chore: Convert to a node style

This commit is contained in:
BluJ
2023-03-01 14:16:18 -07:00
parent 04f185f208
commit d4e0cdfd92
783 changed files with 11054 additions and 135393 deletions

View File

@@ -1,17 +0,0 @@
declare global {
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param o An object.
* @param v A property name.
*/
hasOwn(o: object, v: PropertyKey): boolean;
}
}
export {};
declare global {
interface Error {
cause?: unknown;
}
}
export {};

View File

@@ -1,5 +0,0 @@
import { Deno } from "@deno/shim-deno";
export { Deno } from "@deno/shim-deno";
export declare const dntGlobalThis: Omit<typeof globalThis, "Deno"> & {
Deno: typeof Deno;
};

View File

@@ -1,5 +0,0 @@
import { Deno } from "@deno/shim-deno";
export { Deno } from "@deno/shim-deno";
export declare const dntGlobalThis: Omit<typeof globalThis, "Deno"> & {
Deno: typeof Deno;
};

View File

@@ -1,48 +0,0 @@
import * as T from "./types.js";
export declare const DEFAULT_OPTIONS: T.BackupOptions;
type BackupSet = {
srcPath: string;
srcVolume: string;
dstPath: string;
dstVolume: string;
options?: Partial<T.BackupOptions>;
};
/**
* 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()
* ```
*/
export declare class Backups {
private options;
private backupSet;
static BACKUP: "BACKUP";
constructor(options?: T.BackupOptions, backupSet?: BackupSet[]);
static volumes(...volumeNames: string[]): Backups;
static addSets(...options: BackupSet[]): Backups;
static with_options(options?: Partial<T.BackupOptions>): Backups;
set_options(options?: Partial<T.BackupOptions>): this;
volumes(...volumeNames: string[]): this;
addSets(...options: BackupSet[]): this;
build(): {
createBackup: T.ExpectedExports.createBackup;
restoreBackup: T.ExpectedExports.restoreBackup;
};
}
export {};

View File

@@ -1,23 +0,0 @@
import { Config } from "../config/config.js";
import { matches } from "../dependencies.js";
import { ExpectedExports } from "../types.js";
import { ConfigSpec } from "../types/config-types.js";
import { TypeFromProps } from "../utils/propertiesMatcher.js";
/**
* 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
*/
export declare const getConfig: <A extends ConfigSpec>(spec: Config<A>) => ExpectedExports.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
*/
export declare const getConfigAndMatcher: <Spec extends ConfigSpec>(spec: Config<Spec>) => [ExpectedExports.getConfig, matches.Validator<unknown, TypeFromProps<Spec>>];

View File

@@ -1,18 +0,0 @@
import * as T from "../types.js";
import * as M from "../migrations.js";
import { ConfigSpec } from "../types/config-types.js";
export interface NoRepeat<version extends string, type extends "up" | "down"> {
version: version;
type: type;
}
/**
* @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
*/
export declare function updateConfig<version extends string, type extends "up" | "down">(fn: (config: ConfigSpec, effects: T.Effects) => ConfigSpec | Promise<ConfigSpec>, configured: boolean, noRepeat?: NoRepeat<version, type>, noFail?: boolean): M.MigrationFn<version, type>;
export declare function noRepeatGuard<version extends string, type extends "up" | "down">(effects: T.Effects, noRepeat: NoRepeat<version, type> | undefined, fn: () => Promise<void>): Promise<void>;
export declare function initNoRepeat<versions extends string>(effects: T.Effects, migrations: M.MigrationMapping<versions>, startingVersion: string): Promise<void>;
export declare function fromMapping<versions extends string>(migrations: M.MigrationMapping<versions>, currentVersion: string): T.ExpectedExports.migration;

View File

@@ -1,4 +0,0 @@
export { properties } from "./properties.js";
export { setConfig } from "./setConfig.js";
export { getConfig, getConfigAndMatcher } from "./getConfig.js";
export * as migrations from "./migrations.js";

View File

@@ -1,9 +0,0 @@
import { ExpectedExports } from "../types.js";
/**
* 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
*/
export declare const properties: ExpectedExports.properties;

View File

@@ -1,13 +0,0 @@
import { DependsOn, Effects, SetResult } from "../types.js";
import { ConfigSpec } from "../types/config-types.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
*/
export declare const setConfig: (effects: Effects, newConfig: ConfigSpec, dependsOn?: DependsOn) => Promise<{
result: SetResult;
}>;

171
lib/types/config-types.ts Normal file
View File

@@ -0,0 +1,171 @@
// deno-lint-ignore-file ban-types
export type ConfigSpec = Record<string, ValueSpec>;
export type ValueType =
| "string"
| "number"
| "boolean"
| "enum"
| "list"
| "object"
| "union";
export type ValueSpec = ValueSpecOf<ValueType>;
// core spec types. These types provide the metadata for performing validations
export type ValueSpecOf<T extends ValueType> = T extends "string"
? ValueSpecString
: T extends "number"
? ValueSpecNumber
: T extends "boolean"
? ValueSpecBoolean
: T extends "enum"
? ValueSpecEnum
: T extends "list"
? ValueSpecList
: T extends "object"
? ValueSpecObject
: T extends "union"
? ValueSpecUnion
: never;
export interface ValueSpecString extends ListValueSpecString, WithStandalone {
type: "string";
default: null | DefaultString;
nullable: boolean;
textarea: null | boolean;
}
export interface ValueSpecNumber extends ListValueSpecNumber, WithStandalone {
type: "number";
nullable: boolean;
default: null | number;
}
export interface ValueSpecEnum extends ListValueSpecEnum, WithStandalone {
type: "enum";
default: string;
}
export interface ValueSpecBoolean extends WithStandalone {
type: "boolean";
default: boolean;
}
export interface ValueSpecUnion {
type: "union";
tag: UnionTagSpec;
variants: { [key: string]: ConfigSpec };
default: string;
}
export interface ValueSpecObject extends WithStandalone {
type: "object";
spec: ConfigSpec;
}
export interface WithStandalone {
name: string;
description: null | string;
warning: null | string;
}
// no lists of booleans, lists
export type ListValueSpecType =
| "string"
| "number"
| "enum"
| "object"
| "union";
// represents a spec for the values of a list
export type ListValueSpecOf<T extends ListValueSpecType> = T extends "string"
? ListValueSpecString
: T extends "number"
? ListValueSpecNumber
: T extends "enum"
? ListValueSpecEnum
: T extends "object"
? ListValueSpecObject
: T extends "union"
? ListValueSpecUnion
: never;
// represents a spec for a list
export type ValueSpecList = ValueSpecListOf<ListValueSpecType>;
export interface ValueSpecListOf<T extends ListValueSpecType>
extends WithStandalone {
type: "list";
subtype: T;
spec: ListValueSpecOf<T>;
range: string; // '[0,1]' (inclusive) OR '[0,*)' (right unbounded), normal math rules
default:
| string[]
| number[]
| DefaultString[]
| object[]
| readonly string[]
| readonly number[]
| readonly DefaultString[]
| readonly object[];
}
// sometimes the type checker needs just a little bit of help
export function isValueSpecListOf<S extends ListValueSpecType>(
t: ValueSpecList,
s: S
): t is ValueSpecListOf<S> {
return t.subtype === s;
}
export interface ListValueSpecString {
pattern: null | string;
"pattern-description": null | string;
masked: boolean;
placeholder: null | string;
}
export interface ListValueSpecNumber {
range: string;
integral: boolean;
units: null | string;
placeholder: null | string;
}
export interface ListValueSpecEnum {
values: string[] | readonly string[];
"value-names": { [value: string]: string };
}
export interface ListValueSpecObject {
spec: ConfigSpec; // this is a mapped type of the config object at this level, replacing the object's values with specs on those values
"unique-by": UniqueBy; // indicates whether duplicates can be permitted in the list
"display-as": null | string; // this should be a handlebars template which can make use of the entire config which corresponds to 'spec'
}
export type UniqueBy =
| null
| undefined
| string
| { any: readonly UniqueBy[] | UniqueBy[] }
| { all: readonly UniqueBy[] | UniqueBy[] };
export interface ListValueSpecUnion {
tag: UnionTagSpec;
variants: { [key: string]: ConfigSpec };
"display-as": null | string; // this may be a handlebars template which can conditionally (on tag.id) make use of each union's entries, or if left blank will display as tag.id
"unique-by": UniqueBy;
default: string; // this should be the variantName which one prefers a user to start with by default when creating a new union instance in a list
}
export interface UnionTagSpec {
id: string; // The name of the field containing one of the union variants
"variant-names": {
// the name of each variant
[variant: string]: string;
};
name: string;
description: null | string;
warning: null | string;
}
export type DefaultString = string | { charset: string; len: number };

View File

@@ -1,6 +0,0 @@
export declare class IBuilder<A> {
readonly a: A;
protected constructor(a: A);
build(): A;
}
export type BuilderExtract<A> = A extends IBuilder<infer B> ? B : never;

View File

@@ -1,13 +0,0 @@
import { ConfigSpec, ValueSpec } from "../types/config-types.js";
import { BuilderExtract, IBuilder } from "./builder.js";
import { Value } from "./value.js";
export declare class Config<A extends ConfigSpec> extends IBuilder<A> {
static empty(): Config<{}>;
static withValue<K extends string, B extends ValueSpec>(key: K, value: Value<B>): Config<{ [key in K]: B; }>;
static addValue<K extends string, B extends ValueSpec>(key: K, value: Value<B>): Config<{ [key in K]: B; }>;
static of<B extends {
[key: string]: Value<ValueSpec>;
}>(spec: B): Config<{ [K in keyof B]: BuilderExtract<B[K]>; }>;
withValue<K extends string, B extends ValueSpec>(key: K, value: Value<B>): Config<A & { [key in K]: B; }>;
addValue<K extends string, B extends ValueSpec>(key: K, value: Value<B>): Config<A & { [key in K]: B; }>;
}

View File

@@ -1 +0,0 @@
export {};

View File

@@ -1,87 +0,0 @@
import { BuilderExtract, IBuilder } from "./builder.js";
import { Config } from "./config.js";
import { Default, NumberSpec, StringSpec } from "./value.js";
import { Description } from "./value.js";
import { Variants } from "./variants.js";
import { ConfigSpec, UniqueBy, ValueSpecList, ValueSpecListOf } from "../types/config-types.js";
export declare class List<A extends ValueSpecList> extends IBuilder<A> {
static string<A extends Description & Default<string[]> & {
range: string;
spec: StringSpec;
}>(a: A): List<ValueSpecListOf<"string">>;
static number<A extends Description & Default<number[]> & {
range: string;
spec: NumberSpec;
}>(a: A): List<{
type: "list";
subtype: "number";
} & A>;
static enum<A extends Description & Default<string[]> & {
range: string;
spec: {
values: string[];
"value-names": {
[key: string]: string;
};
};
}>(a: A): List<{
type: "list";
subtype: "enum";
} & A>;
static obj<A extends Description & Default<Record<string, unknown>[]> & {
range: string;
spec: {
spec: Config<ConfigSpec>;
"display-as": null | string;
"unique-by": null | UniqueBy;
};
}>(a: A): List<{
type: "list";
subtype: "object";
} & {
spec: {
spec: BuilderExtract<A["spec"]["spec"]>;
"display-as": null | string;
"unique-by": null | UniqueBy;
};
} & Omit<A, "spec">>;
static union<A extends Description & Default<string[]> & {
range: string;
spec: {
tag: {
id: B;
name: string;
description: null | string;
warning: null | string;
"variant-names": {
[key: string]: string;
};
};
variants: Variants<{
[key: string]: ConfigSpec;
}>;
"display-as": null | string;
"unique-by": UniqueBy;
default: string;
};
}, B extends string>(a: A): List<{
type: "list";
subtype: "union";
} & {
spec: {
variants: BuilderExtract<A["spec"]["variants"]>;
tag: {
id: B;
name: string;
description: null | string;
warning: null | string;
"variant-names": {
[key: string]: string;
};
};
"display-as": null | string;
"unique-by": UniqueBy;
default: string;
};
} & Omit<A, "spec">>;
}

View File

@@ -1,4 +0,0 @@
export { Config } from "./config.js";
export { List } from "./list.js";
export { Value } from "./value.js";
export { Variants } from "./variants.js";

View File

@@ -1,86 +0,0 @@
import { BuilderExtract, IBuilder } from "./builder.js";
import { Config } from "./config.js";
import { List } from "./list.js";
import { Variants } from "./variants.js";
import { ConfigSpec, UniqueBy, ValueSpec, ValueSpecList, ValueSpecNumber, ValueSpecString } from "../types/config-types.js";
export type DefaultString = string | {
charset: string | null | undefined;
len: number;
};
export type Description = {
name: string;
description: string | null;
warning: string | null;
};
export type Default<A> = {
default: A;
};
export type NullableDefault<A> = {
default: null | A;
};
export type StringSpec = {
masked: boolean | null;
placeholder: string | null;
pattern: null | string;
"pattern-description": null | string;
textarea: boolean | null;
};
export type NumberSpec = {
range: string;
integral: boolean;
units: string | null;
placeholder: string | null;
};
export type Nullable = {
nullable: boolean;
};
export declare class Value<A extends ValueSpec> extends IBuilder<A> {
static boolean<A extends Description & Default<boolean>>(a: A): Value<{
type: "boolean";
} & A>;
static string<A extends Description & NullableDefault<DefaultString> & Nullable & StringSpec>(a: A): Value<ValueSpecString>;
static number<A extends Description & NullableDefault<number> & Nullable & NumberSpec>(a: A): Value<ValueSpecNumber>;
static enum<A extends Description & Default<string> & {
values: readonly string[] | string[];
"value-names": Record<string, string>;
}>(a: A): Value<{
type: "enum";
} & A>;
static object<A extends {
name: string;
description: string | null;
warning: string | null;
default: null | {
[k: string]: unknown;
};
"display-as": null | string;
"unique-by": null | string;
spec: Config<ConfigSpec>;
"value-names": Record<string, string>;
}>(a: A): Value<{
type: "object";
} & Omit<A, "spec"> & {
spec: BuilderExtract<A["spec"]>;
}>;
static union<A extends Description & Default<string> & {
tag: {
id: B;
name: string;
description: string | null;
warning: string | null;
"variant-names": {
[key: string]: string;
};
};
variants: Variants<{
[key: string]: ConfigSpec;
}>;
"display-as": string | null;
"unique-by": UniqueBy;
}, B extends string>(a: A): Value<{
type: "union";
} & Omit<A, "variants"> & {
variants: BuilderExtract<A["variants"]>;
}>;
static list<A extends List<ValueSpecList>>(a: A): Value<ValueSpecList>;
}

View File

@@ -1,13 +0,0 @@
import { ConfigSpec } from "../types/config-types.js";
import { BuilderExtract, IBuilder } from "./builder.js";
import { Config } from "./mod.js";
export declare class Variants<A extends {
[key: string]: ConfigSpec;
}> extends IBuilder<A> {
static of<A extends {
[key: string]: Config<ConfigSpec>;
}>(a: A): Variants<{ [K in keyof A]: BuilderExtract<A[K]>; }>;
static empty(): Variants<{}>;
static withVariant<K extends string, B extends ConfigSpec>(key: K, value: Config<B>): Variants<{} & { [key in K]: B; }>;
withVariant<K extends string, B extends ConfigSpec>(key: K, value: Config<B>): Variants<A & { [key in K]: B; }>;
}

View File

@@ -1,2 +0,0 @@
export * as matches from "./deps/deno.land/x/ts_matches@v5.3.0/mod.js";
export * as YAML from "./deps/deno.land/std@0.140.0/encoding/yaml.js";

View File

@@ -1,5 +0,0 @@
export declare class DenoStdInternalError extends Error {
constructor(message: string);
}
/** Make an assertion, if not `true`, then throw. */
export declare function assert(expr: unknown, msg?: string): asserts expr;

View File

@@ -1,41 +0,0 @@
/**
* An abstraction of multiple Uint8Arrays
*/
export declare class BytesList {
private len;
private chunks;
constructor();
/**
* Total size of bytes
*/
size(): number;
/**
* Push bytes with given offset infos
*/
add(value: Uint8Array, start?: number, end?: number): void;
/**
* Drop head `n` bytes.
*/
shift(n: number): void;
/**
* Find chunk index in which `pos` locates by binary-search
* returns -1 if out of range
*/
getChunkIndex(pos: number): number;
/**
* Get indexed byte from chunks
*/
get(i: number): number;
/**
* Iterator of bytes from given position
*/
iterator(start?: number): IterableIterator<number>;
/**
* Returns subset of bytes copied
*/
slice(start: number, end?: number): Uint8Array;
/**
* Concatenate chunks into single Uint8Array copied.
*/
concat(): Uint8Array;
}

View File

@@ -1,17 +0,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
*/
export declare function equalsNaive(a: Uint8Array, b: Uint8Array): boolean;
/** 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
*/
export declare function equalsSimd(a: Uint8Array, b: Uint8Array): boolean;
/** Check whether binary arrays are equal to each other.
* @param a first array to check equality
* @param b second array to check equality
*/
export declare function equals(a: Uint8Array, b: Uint8Array): boolean;

View File

@@ -1,133 +0,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
* ```
*/
export declare function indexOfNeedle(source: Uint8Array, needle: Uint8Array, start?: number): number;
/** 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
* ```
*/
export declare function lastIndexOfNeedle(source: Uint8Array, needle: Uint8Array, start?: number): number;
/** 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
* ```
*/
export declare function startsWith(source: Uint8Array, prefix: Uint8Array): boolean;
/** 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
* ```
*/
export declare function endsWith(source: Uint8Array, suffix: Uint8Array): boolean;
/** 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
* ```
*/
export declare function repeat(source: Uint8Array, count: number): Uint8Array;
/** 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]
*/
export declare function concat(...buf: Uint8Array[]): Uint8Array;
/** 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
* ```
*/
export declare function includesNeedle(source: Uint8Array, needle: Uint8Array, start?: number): boolean;
/** 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]
* ```
*/
export declare function copy(src: Uint8Array, dst: Uint8Array, off?: number): number;
export { equals } from "./equals.js";

View File

@@ -1,5 +0,0 @@
import * as common from "../utils.js";
import { DumperStateOptions } from "./dumper_state.js";
type Any = common.Any;
export declare function dump(input: Any, options?: DumperStateOptions): string;
export {};

View File

@@ -1,72 +0,0 @@
import type { SchemaDefinition } from "../schema.js";
import { State } from "../state.js";
import type { StyleVariant, Type } from "../type.js";
import type { Any, ArrayObject } from "../utils.js";
export interface DumperStateOptions {
/** indentation width to use (in spaces). */
indent?: number;
/** when true, will not add an indentation level to array elements */
noArrayIndent?: boolean;
/**
* do not throw on invalid types (like function in the safe schema)
* and skip pairs and single values with such types.
*/
skipInvalid?: boolean;
/**
* specifies level of nesting, when to switch from
* block to flow style for collections. -1 means block style everywhere
*/
flowLevel?: number;
/** Each tag may have own set of styles. - "tag" => "style" map. */
styles?: ArrayObject<StyleVariant> | null;
/** specifies a schema to use. */
schema?: SchemaDefinition;
/**
* If true, sort keys when dumping YAML in ascending, ASCII character order.
* If a function, use the function to sort the keys. (default: false)
* If a function is specified, the function must return a negative value
* if first argument is less than second argument, zero if they're equal
* and a positive value otherwise.
*/
sortKeys?: boolean | ((a: string, b: string) => number);
/** set max line width. (default: 80) */
lineWidth?: number;
/**
* if true, don't convert duplicate objects
* into references (default: false)
*/
noRefs?: boolean;
/**
* if true don't try to be compatible with older yaml versions.
* Currently: don't quote "yes", "no" and so on,
* as required for YAML 1.1 (default: false)
*/
noCompatMode?: boolean;
/**
* if true flow sequences will be condensed, omitting the
* space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`.
* Can be useful when using yaml for pretty URL query params
* as spaces are %-encoded. (default: false).
*/
condenseFlow?: boolean;
}
export declare class DumperState extends State {
indent: number;
noArrayIndent: boolean;
skipInvalid: boolean;
flowLevel: number;
sortKeys: boolean | ((a: Any, b: Any) => number);
lineWidth: number;
noRefs: boolean;
noCompatMode: boolean;
condenseFlow: boolean;
implicitTypes: Type[];
explicitTypes: Type[];
tag: string | null;
result: string;
duplicates: Any[];
usedDuplicates: Any[];
styleMap: ArrayObject<StyleVariant>;
dump: Any;
constructor({ schema, indent, noArrayIndent, skipInvalid, flowLevel, styles, sortKeys, lineWidth, noRefs, noCompatMode, condenseFlow, }: DumperStateOptions);
}

View File

@@ -1,6 +0,0 @@
import type { Mark } from "./mark.js";
export declare class YAMLError extends Error {
protected mark: Mark | string;
constructor(message?: string, mark?: Mark | string);
toString(_compact: boolean): string;
}

View File

@@ -1,4 +0,0 @@
import { LoaderStateOptions } from "./loader_state.js";
export type CbFunction = (doc: unknown) => void;
export declare function loadAll<T extends CbFunction | LoaderStateOptions>(input: string, iteratorOrOption?: T, options?: LoaderStateOptions): T extends CbFunction ? void : unknown[];
export declare function load(input: string, options?: LoaderStateOptions): unknown;

View File

@@ -1,43 +0,0 @@
import type { YAMLError } from "../error.js";
import type { SchemaDefinition, TypeMap } from "../schema.js";
import { State } from "../state.js";
import type { Type } from "../type.js";
import type { Any, ArrayObject } from "../utils.js";
export interface LoaderStateOptions {
legacy?: boolean;
listener?: ((...args: Any[]) => void) | null;
/** string to be used as a file path in error/warning messages. */
filename?: string;
/** specifies a schema to use. */
schema?: SchemaDefinition;
/** compatibility with JSON.parse behaviour. */
json?: boolean;
/** function to call on warning messages. */
onWarning?(this: null, e?: YAMLError): void;
}
export type ResultType = any[] | Record<string, any> | string;
export declare class LoaderState extends State {
input: string;
documents: Any[];
length: number;
lineIndent: number;
lineStart: number;
position: number;
line: number;
filename?: string;
onWarning?: (...args: Any[]) => void;
legacy: boolean;
json: boolean;
listener?: ((...args: Any[]) => void) | null;
implicitTypes: Type[];
typeMap: TypeMap;
version?: string | null;
checkLineBreaks?: boolean;
tagMap?: ArrayObject;
anchorMap?: ArrayObject;
tag?: string | null;
anchor?: string | null;
kind?: string | null;
result: ResultType | null;
constructor(input: string, { filename, schema, onWarning, legacy, json, listener, }: LoaderStateOptions);
}

View File

@@ -1,10 +0,0 @@
export declare class Mark {
name: string;
buffer: string;
position: number;
line: number;
column: number;
constructor(name: string, buffer: string, position: number, line: number, column: number);
getSnippet(indent?: number, maxLength?: number): string | null;
toString(compact?: boolean): string;
}

View File

@@ -1,16 +0,0 @@
import { CbFunction } from "./loader/loader.js";
import type { LoaderStateOptions } from "./loader/loader_state.js";
export type ParseOptions = LoaderStateOptions;
/**
* 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.
*/
export declare function parse(content: string, options?: ParseOptions): unknown;
/**
* Same as `parse()`, but understands multi-document sources.
* Applies iterator to each document if specified, or returns array of documents.
*/
export declare function parseAll(content: string, iterator: CbFunction, options?: ParseOptions): void;
export declare function parseAll(content: string, options?: ParseOptions): unknown;

View File

@@ -1,22 +0,0 @@
import type { KindType, Type } from "./type.js";
import type { Any, ArrayObject } from "./utils.js";
export type TypeMap = {
[k in KindType | "fallback"]: ArrayObject<Type>;
};
export declare class Schema implements SchemaDefinition {
static SCHEMA_DEFAULT?: Schema;
implicit: Type[];
explicit: Type[];
include: Schema[];
compiledImplicit: Type[];
compiledExplicit: Type[];
compiledTypeMap: TypeMap;
constructor(definition: SchemaDefinition);
extend(definition: SchemaDefinition): Schema;
static create(): void;
}
export interface SchemaDefinition {
implicit?: Any[];
explicit?: Type[];
include?: Schema[];
}

View File

@@ -1,2 +0,0 @@
import { Schema } from "../schema.js";
export declare const core: Schema;

View File

@@ -1,2 +0,0 @@
import { Schema } from "../schema.js";
export declare const def: Schema;

View File

@@ -1,2 +0,0 @@
import { Schema } from "../schema.js";
export declare const extended: Schema;

View File

@@ -1,2 +0,0 @@
import { Schema } from "../schema.js";
export declare const failsafe: Schema;

View File

@@ -1,2 +0,0 @@
import { Schema } from "../schema.js";
export declare const json: Schema;

View File

@@ -1,5 +0,0 @@
export { core as CORE_SCHEMA } from "./core.js";
export { def as DEFAULT_SCHEMA } from "./default.js";
export { extended as EXTENDED_SCHEMA } from "./extended.js";
export { failsafe as FAILSAFE_SCHEMA } from "./failsafe.js";
export { json as JSON_SCHEMA } from "./json.js";

View File

@@ -1,5 +0,0 @@
import type { SchemaDefinition } from "./schema.js";
export declare abstract class State {
schema: SchemaDefinition;
constructor(schema?: SchemaDefinition);
}

View File

@@ -1,8 +0,0 @@
import type { DumperStateOptions } from "./dumper/dumper_state.js";
export type DumpOptions = DumperStateOptions;
/**
* Serializes `object` as a YAML document.
*
* You can disable exceptions by setting the skipInvalid option to true.
*/
export declare function stringify(obj: Record<string, unknown>, options?: DumpOptions): string;

View File

@@ -1,28 +0,0 @@
import type { Any, ArrayObject } from "./utils.js";
export type KindType = "sequence" | "scalar" | "mapping";
export type StyleVariant = "lowercase" | "uppercase" | "camelcase" | "decimal";
export type RepresentFn = (data: Any, style?: StyleVariant) => Any;
interface TypeOptions {
kind: KindType;
resolve?: (data: Any) => boolean;
construct?: (data: string) => Any;
instanceOf?: Any;
predicate?: (data: Record<string, unknown>) => boolean;
represent?: RepresentFn | ArrayObject<RepresentFn>;
defaultStyle?: StyleVariant;
styleAliases?: ArrayObject;
}
export declare class Type {
tag: string;
kind: KindType | null;
instanceOf: Any;
predicate?: (data: Record<string, unknown>) => boolean;
represent?: RepresentFn | ArrayObject<RepresentFn>;
defaultStyle?: StyleVariant;
styleAliases?: ArrayObject;
loadKind?: KindType;
constructor(tag: string, options?: TypeOptions);
resolve: (data?: Any) => boolean;
construct: (data?: Any) => Any;
}
export {};

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const binary: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const bool: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const float: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const func: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const int: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const map: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const merge: Type;

View File

@@ -1,16 +0,0 @@
export { binary } from "./binary.js";
export { bool } from "./bool.js";
export { float } from "./float.js";
export { func } from "./function.js";
export { int } from "./int.js";
export { map } from "./map.js";
export { merge } from "./merge.js";
export { nil } from "./nil.js";
export { omap } from "./omap.js";
export { pairs } from "./pairs.js";
export { regexp } from "./regexp.js";
export { seq } from "./seq.js";
export { set } from "./set.js";
export { str } from "./str.js";
export { timestamp } from "./timestamp.js";
export { undefinedType } from "./undefined.js";

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const nil: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const omap: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const pairs: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const regexp: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const seq: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const set: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const str: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const timestamp: Type;

View File

@@ -1,2 +0,0 @@
import { Type } from "../type.js";
export declare const undefinedType: Type;

View File

@@ -1,19 +0,0 @@
export type Any = any;
export declare function isNothing(subject: unknown): subject is never;
export declare function isArray(value: unknown): value is Any[];
export declare function isBoolean(value: unknown): value is boolean;
export declare function isNull(value: unknown): value is null;
export declare function isNumber(value: unknown): value is number;
export declare function isString(value: unknown): value is string;
export declare function isSymbol(value: unknown): value is symbol;
export declare function isUndefined(value: unknown): value is undefined;
export declare function isObject(value: unknown): value is Record<string, unknown>;
export declare function isError(e: unknown): boolean;
export declare function isFunction(value: unknown): value is () => void;
export declare function isRegExp(value: unknown): value is RegExp;
export declare function toArray<T>(sequence: T): T | [] | [T];
export declare function repeat(str: string, count: number): string;
export declare function isNegativeZero(i: number): boolean;
export interface ArrayObject<T = Any> {
[P: string]: T;
}

View File

@@ -1,8 +0,0 @@
export type { ParseOptions } from "./_yaml/parse.js";
export { parse, parseAll } from "./_yaml/parse.js";
export type { DumpOptions as StringifyOptions } from "./_yaml/stringify.js";
export { stringify } from "./_yaml/stringify.js";
export type { SchemaDefinition } from "./_yaml/schema.js";
export { Type } from "./_yaml/type.js";
export type { KindType, RepresentFn, StyleVariant } from "./_yaml/type.js";
export { CORE_SCHEMA, DEFAULT_SCHEMA, EXTENDED_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, } from "./_yaml/schema/mod.js";

View File

@@ -1,279 +0,0 @@
import type { Reader, ReaderSync, Writer, WriterSync } from "./types";
/** A variable-sized buffer of bytes with `read()` and `write()` methods.
*
* Buffer is almost always used with some I/O like files and sockets. It allows
* one to buffer up a download from a socket. Buffer grows and shrinks as
* necessary.
*
* Buffer is NOT the same thing as Node's Buffer. Node's Buffer was created in
* 2009 before JavaScript had the concept of ArrayBuffers. It's simply a
* non-standard ArrayBuffer.
*
* ArrayBuffer is a fixed memory allocation. Buffer is implemented on top of
* ArrayBuffer.
*
* Based on [Go Buffer](https://golang.org/pkg/bytes/#Buffer). */
export declare class Buffer {
#private;
constructor(ab?: ArrayBufferLike | ArrayLike<number>);
/** Returns a slice holding the unread portion of the buffer.
*
* The slice is valid for use only until the next buffer modification (that
* is, only until the next call to a method like `read()`, `write()`,
* `reset()`, or `truncate()`). If `options.copy` is false the slice aliases the buffer content at
* least until the next buffer modification, so immediate changes to the
* slice will affect the result of future reads.
* @param options Defaults to `{ copy: true }`
*/
bytes(options?: {
copy: boolean;
}): Uint8Array;
/** Returns whether the unread portion of the buffer is empty. */
empty(): boolean;
/** A read only number of bytes of the unread portion of the buffer. */
get length(): number;
/** The read only capacity of the buffer's underlying byte slice, that is,
* the total space allocated for the buffer's data. */
get capacity(): number;
/** Discards all but the first `n` unread bytes from the buffer but
* continues to use the same allocated storage. It throws if `n` is
* negative or greater than the length of the buffer. */
truncate(n: number): void;
reset(): void;
/** Reads the next `p.length` bytes from the buffer or until the buffer is
* drained. Returns the number of bytes read. If the buffer has no data to
* return, the return is EOF (`null`). */
readSync(p: Uint8Array): number | null;
/** Reads the next `p.length` bytes from the buffer or until the buffer is
* drained. Resolves to the number of bytes read. If the buffer has no
* data to return, resolves to EOF (`null`).
*
* NOTE: This methods reads bytes synchronously; it's provided for
* compatibility with `Reader` interfaces.
*/
read(p: Uint8Array): Promise<number | null>;
writeSync(p: Uint8Array): number;
/** NOTE: This methods writes bytes synchronously; it's provided for
* compatibility with `Writer` interface. */
write(p: Uint8Array): Promise<number>;
/** Grows the buffer's capacity, if necessary, to guarantee space for
* another `n` bytes. After `.grow(n)`, at least `n` bytes can be written to
* the buffer without another allocation. If `n` is negative, `.grow()` will
* throw. If the buffer can't grow it will throw an error.
*
* Based on Go Lang's
* [Buffer.Grow](https://golang.org/pkg/bytes/#Buffer.Grow). */
grow(n: number): void;
/** Reads data from `r` until EOF (`null`) and appends it to the buffer,
* growing the buffer as needed. It resolves to the number of bytes read.
* If the buffer becomes too large, `.readFrom()` will reject with an error.
*
* Based on Go Lang's
* [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */
readFrom(r: Reader): Promise<number>;
/** Reads data from `r` until EOF (`null`) and appends it to the buffer,
* growing the buffer as needed. It returns the number of bytes read. If the
* buffer becomes too large, `.readFromSync()` will throw an error.
*
* Based on Go Lang's
* [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */
readFromSync(r: ReaderSync): number;
}
export declare class BufferFullError extends Error {
partial: Uint8Array;
name: string;
constructor(partial: Uint8Array);
}
export declare class PartialReadError extends Error {
name: string;
partial?: Uint8Array;
constructor();
}
/** Result type returned by of BufReader.readLine(). */
export interface ReadLineResult {
line: Uint8Array;
more: boolean;
}
/** BufReader implements buffering for a Reader object. */
export declare class BufReader implements Reader {
#private;
/** return new BufReader unless r is BufReader */
static create(r: Reader, size?: number): BufReader;
constructor(rd: Reader, size?: number);
/** Returns the size of the underlying buffer in bytes. */
size(): number;
buffered(): number;
/** Discards any buffered data, resets all state, and switches
* the buffered reader to read from r.
*/
reset(r: Reader): void;
/** reads data into p.
* It returns the number of bytes read into p.
* The bytes are taken from at most one Read on the underlying Reader,
* hence n may be less than len(p).
* To read exactly len(p) bytes, use io.ReadFull(b, p).
*/
read(p: Uint8Array): Promise<number | null>;
/** reads exactly `p.length` bytes into `p`.
*
* If successful, `p` is returned.
*
* If the end of the underlying stream has been reached, and there are no more
* bytes available in the buffer, `readFull()` returns `null` instead.
*
* An error is thrown if some bytes could be read, but not enough to fill `p`
* entirely before the underlying stream reported an error or EOF. Any error
* thrown will have a `partial` property that indicates the slice of the
* buffer that has been successfully filled with data.
*
* Ported from https://golang.org/pkg/io/#ReadFull
*/
readFull(p: Uint8Array): Promise<Uint8Array | null>;
/** Returns the next byte [0, 255] or `null`. */
readByte(): Promise<number | null>;
/** readString() reads until the first occurrence of delim in the input,
* returning a string containing the data up to and including the delimiter.
* If ReadString encounters an error before finding a delimiter,
* it returns the data read before the error and the error itself
* (often `null`).
* ReadString returns err != nil if and only if the returned data does not end
* in delim.
* For simple uses, a Scanner may be more convenient.
*/
readString(delim: string): Promise<string | null>;
/** `readLine()` is a low-level line-reading primitive. Most callers should
* use `readString('\n')` instead or use a Scanner.
*
* `readLine()` tries to return a single line, not including the end-of-line
* bytes. If the line was too long for the buffer then `more` is set and the
* beginning of the line is returned. The rest of the line will be returned
* from future calls. `more` will be false when returning the last fragment
* of the line. The returned buffer is only valid until the next call to
* `readLine()`.
*
* The text returned from ReadLine does not include the line end ("\r\n" or
* "\n").
*
* When the end of the underlying stream is reached, the final bytes in the
* stream are returned. No indication or error is given if the input ends
* without a final line end. When there are no more trailing bytes to read,
* `readLine()` returns `null`.
*
* Calling `unreadByte()` after `readLine()` will always unread the last byte
* read (possibly a character belonging to the line end) even if that byte is
* not part of the line returned by `readLine()`.
*/
readLine(): Promise<ReadLineResult | null>;
/** `readSlice()` reads until the first occurrence of `delim` in the input,
* returning a slice pointing at the bytes in the buffer. The bytes stop
* being valid at the next read.
*
* If `readSlice()` encounters an error before finding a delimiter, or the
* buffer fills without finding a delimiter, it throws an error with a
* `partial` property that contains the entire buffer.
*
* If `readSlice()` encounters the end of the underlying stream and there are
* any bytes left in the buffer, the rest of the buffer is returned. In other
* words, EOF is always treated as a delimiter. Once the buffer is empty,
* it returns `null`.
*
* Because the data returned from `readSlice()` will be overwritten by the
* next I/O operation, most clients should use `readString()` instead.
*/
readSlice(delim: number): Promise<Uint8Array | null>;
/** `peek()` returns the next `n` bytes without advancing the reader. The
* bytes stop being valid at the next read call.
*
* When the end of the underlying stream is reached, but there are unread
* bytes left in the buffer, those bytes are returned. If there are no bytes
* left in the buffer, it returns `null`.
*
* If an error is encountered before `n` bytes are available, `peek()` throws
* an error with the `partial` property set to a slice of the buffer that
* contains the bytes that were available before the error occurred.
*/
peek(n: number): Promise<Uint8Array | null>;
}
declare abstract class AbstractBufBase {
buf: Uint8Array;
usedBufferBytes: number;
err: Error | null;
constructor(buf: Uint8Array);
/** Size returns the size of the underlying buffer in bytes. */
size(): number;
/** Returns how many bytes are unused in the buffer. */
available(): number;
/** buffered returns the number of bytes that have been written into the
* current buffer.
*/
buffered(): number;
}
/** BufWriter implements buffering for an deno.Writer object.
* If an error occurs writing to a Writer, no more data will be
* accepted and all subsequent writes, and flush(), will return the error.
* After all data has been written, the client should call the
* flush() method to guarantee all data has been forwarded to
* the underlying deno.Writer.
*/
export declare class BufWriter extends AbstractBufBase implements Writer {
#private;
/** return new BufWriter unless writer is BufWriter */
static create(writer: Writer, size?: number): BufWriter;
constructor(writer: Writer, size?: number);
/** Discards any unflushed buffered data, clears any error, and
* resets buffer to write its output to w.
*/
reset(w: Writer): void;
/** Flush writes any buffered data to the underlying io.Writer. */
flush(): Promise<void>;
/** Writes the contents of `data` into the buffer. If the contents won't fully
* fit into the buffer, those bytes that can are copied into the buffer, the
* buffer is the flushed to the writer and the remaining bytes are copied into
* the now empty buffer.
*
* @return the number of bytes written to the buffer.
*/
write(data: Uint8Array): Promise<number>;
}
/** BufWriterSync implements buffering for a deno.WriterSync object.
* If an error occurs writing to a WriterSync, no more data will be
* accepted and all subsequent writes, and flush(), will return the error.
* After all data has been written, the client should call the
* flush() method to guarantee all data has been forwarded to
* the underlying deno.WriterSync.
*/
export declare class BufWriterSync extends AbstractBufBase implements WriterSync {
#private;
/** return new BufWriterSync unless writer is BufWriterSync */
static create(writer: WriterSync, size?: number): BufWriterSync;
constructor(writer: WriterSync, size?: number);
/** Discards any unflushed buffered data, clears any error, and
* resets buffer to write its output to w.
*/
reset(w: WriterSync): void;
/** Flush writes any buffered data to the underlying io.WriterSync. */
flush(): void;
/** Writes the contents of `data` into the buffer. If the contents won't fully
* fit into the buffer, those bytes that can are copied into the buffer, the
* buffer is the flushed to the writer and the remaining bytes are copied into
* the now empty buffer.
*
* @return the number of bytes written to the buffer.
*/
writeSync(data: Uint8Array): number;
}
/** Read delimited bytes from a Reader. */
export declare function readDelim(reader: Reader, delim: Uint8Array): AsyncIterableIterator<Uint8Array>;
/** Read delimited strings from a Reader. */
export declare function readStringDelim(reader: Reader, delim: string, decoderOpts?: {
encoding?: string;
fatal?: boolean;
ignoreBOM?: boolean;
}): AsyncIterableIterator<string>;
/** Read strings line-by-line from a Reader. */
export declare function readLines(reader: Reader, decoderOpts?: {
encoding?: string;
fatal?: boolean;
ignoreBOM?: boolean;
}): AsyncIterableIterator<string>;
export {};

View File

@@ -1,264 +0,0 @@
/** RGB 8-bits per channel. Each in range `0->255` or `0x00->0xff` */
interface Rgb {
r: number;
g: number;
b: number;
}
/**
* Set changing text color to enabled or disabled
* @param value
*/
export declare function setColorEnabled(value: boolean): void;
/** Get whether text color change is enabled or disabled. */
export declare function getColorEnabled(): boolean;
/**
* Reset the text modified
* @param str text to reset
*/
export declare function reset(str: string): string;
/**
* Make the text bold.
* @param str text to make bold
*/
export declare function bold(str: string): string;
/**
* The text emits only a small amount of light.
* @param str text to dim
*/
export declare function dim(str: string): string;
/**
* Make the text italic.
* @param str text to make italic
*/
export declare function italic(str: string): string;
/**
* Make the text underline.
* @param str text to underline
*/
export declare function underline(str: string): string;
/**
* Invert background color and text color.
* @param str text to invert its color
*/
export declare function inverse(str: string): string;
/**
* Make the text hidden.
* @param str text to hide
*/
export declare function hidden(str: string): string;
/**
* Put horizontal line through the center of the text.
* @param str text to strike through
*/
export declare function strikethrough(str: string): string;
/**
* Set text color to black.
* @param str text to make black
*/
export declare function black(str: string): string;
/**
* Set text color to red.
* @param str text to make red
*/
export declare function red(str: string): string;
/**
* Set text color to green.
* @param str text to make green
*/
export declare function green(str: string): string;
/**
* Set text color to yellow.
* @param str text to make yellow
*/
export declare function yellow(str: string): string;
/**
* Set text color to blue.
* @param str text to make blue
*/
export declare function blue(str: string): string;
/**
* Set text color to magenta.
* @param str text to make magenta
*/
export declare function magenta(str: string): string;
/**
* Set text color to cyan.
* @param str text to make cyan
*/
export declare function cyan(str: string): string;
/**
* Set text color to white.
* @param str text to make white
*/
export declare function white(str: string): string;
/**
* Set text color to gray.
* @param str text to make gray
*/
export declare function gray(str: string): string;
/**
* Set text color to bright black.
* @param str text to make bright-black
*/
export declare function brightBlack(str: string): string;
/**
* Set text color to bright red.
* @param str text to make bright-red
*/
export declare function brightRed(str: string): string;
/**
* Set text color to bright green.
* @param str text to make bright-green
*/
export declare function brightGreen(str: string): string;
/**
* Set text color to bright yellow.
* @param str text to make bright-yellow
*/
export declare function brightYellow(str: string): string;
/**
* Set text color to bright blue.
* @param str text to make bright-blue
*/
export declare function brightBlue(str: string): string;
/**
* Set text color to bright magenta.
* @param str text to make bright-magenta
*/
export declare function brightMagenta(str: string): string;
/**
* Set text color to bright cyan.
* @param str text to make bright-cyan
*/
export declare function brightCyan(str: string): string;
/**
* Set text color to bright white.
* @param str text to make bright-white
*/
export declare function brightWhite(str: string): string;
/**
* Set background color to black.
* @param str text to make its background black
*/
export declare function bgBlack(str: string): string;
/**
* Set background color to red.
* @param str text to make its background red
*/
export declare function bgRed(str: string): string;
/**
* Set background color to green.
* @param str text to make its background green
*/
export declare function bgGreen(str: string): string;
/**
* Set background color to yellow.
* @param str text to make its background yellow
*/
export declare function bgYellow(str: string): string;
/**
* Set background color to blue.
* @param str text to make its background blue
*/
export declare function bgBlue(str: string): string;
/**
* Set background color to magenta.
* @param str text to make its background magenta
*/
export declare function bgMagenta(str: string): string;
/**
* Set background color to cyan.
* @param str text to make its background cyan
*/
export declare function bgCyan(str: string): string;
/**
* Set background color to white.
* @param str text to make its background white
*/
export declare function bgWhite(str: string): string;
/**
* Set background color to bright black.
* @param str text to make its background bright-black
*/
export declare function bgBrightBlack(str: string): string;
/**
* Set background color to bright red.
* @param str text to make its background bright-red
*/
export declare function bgBrightRed(str: string): string;
/**
* Set background color to bright green.
* @param str text to make its background bright-green
*/
export declare function bgBrightGreen(str: string): string;
/**
* Set background color to bright yellow.
* @param str text to make its background bright-yellow
*/
export declare function bgBrightYellow(str: string): string;
/**
* Set background color to bright blue.
* @param str text to make its background bright-blue
*/
export declare function bgBrightBlue(str: string): string;
/**
* Set background color to bright magenta.
* @param str text to make its background bright-magenta
*/
export declare function bgBrightMagenta(str: string): string;
/**
* Set background color to bright cyan.
* @param str text to make its background bright-cyan
*/
export declare function bgBrightCyan(str: string): string;
/**
* Set background color to bright white.
* @param str text to make its background bright-white
*/
export declare function bgBrightWhite(str: string): string;
/**
* 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
*/
export declare function rgb8(str: string, color: number): string;
/**
* 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
*/
export declare function bgRgb8(str: string, color: number): string;
/**
* 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
*/
export declare function rgb24(str: string, color: number | Rgb): string;
/**
* 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
*/
export declare function bgRgb24(str: string, color: number | Rgb): string;
/**
* Remove ANSI escape codes from the string.
* @param string to remove ANSI escape codes from
*/
export declare function stripColor(string: string): string;
export {};

View File

@@ -1,15 +0,0 @@
export declare enum DiffType {
removed = "removed",
common = "common",
added = "added"
}
export interface DiffResult<T> {
type: DiffType;
value: T;
}
/**
* Renders the differences between the actual and expected values
* @param A Actual value
* @param B Expected value
*/
export declare function diff<T>(A: T[], B: T[]): Array<DiffResult<T>>;

View File

@@ -1,120 +0,0 @@
interface Constructor {
new (...args: any[]): any;
}
export declare class AssertionError extends Error {
constructor(message: string);
}
/**
* 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
*/
export declare function _format(v: unknown): string;
/**
* Deep equality comparison used in assertions
* @param c actual value
* @param d expected value
*/
export declare function equal(c: unknown, d: unknown): boolean;
/** Make an assertion, error will be thrown if `expr` does not have truthy value. */
export declare function assert(expr: unknown, msg?: string): asserts expr;
/**
* Make an assertion that `actual` and `expected` are equal, deeply. If not
* deeply equal, then throw.
*
* Type parameter can be specified to ensure values under comparison have the same type.
* For example:
*```ts
*assertEquals<number>(1, 2)
*```
*/
export declare function assertEquals(actual: unknown, expected: unknown, msg?: string): void;
export declare function assertEquals<T>(actual: T, expected: T, msg?: string): void;
/**
* Make an assertion that `actual` and `expected` are not equal, deeply.
* If not then throw.
*
* Type parameter can be specified to ensure values under comparison have the same type.
* For example:
*```ts
*assertNotEquals<number>(1, 2)
*```
*/
export declare function assertNotEquals(actual: unknown, expected: unknown, msg?: string): void;
export declare function assertNotEquals<T>(actual: T, expected: T, msg?: string): void;
/**
* Make an assertion that `actual` and `expected` are strictly equal. If
* not then throw.
* ```ts
* assertStrictEquals(1, 2)
* ```
*/
export declare function assertStrictEquals(actual: unknown, expected: unknown, msg?: string): void;
export declare function assertStrictEquals<T>(actual: T, expected: T, msg?: string): void;
/**
* Make an assertion that `actual` and `expected` are not strictly equal.
* If the values are strictly equal then throw.
* ```ts
* assertNotStrictEquals(1, 1)
* ```
*/
export declare function assertNotStrictEquals(actual: unknown, expected: unknown, msg?: string): void;
export declare function assertNotStrictEquals<T>(actual: T, expected: T, msg?: string): void;
/**
* Make an assertion that actual is not null or undefined. If not
* then thrown.
*/
export declare function assertExists(actual: unknown, msg?: string): void;
/**
* Make an assertion that actual includes expected. If not
* then thrown.
*/
export declare function assertStringIncludes(actual: string, expected: string, msg?: string): void;
/**
* Make an assertion that `actual` includes the `expected` values.
* If not then an error will be thrown.
*
* Type parameter can be specified to ensure values under comparison have the same type.
* For example:
*```ts
*assertArrayIncludes<number>([1, 2], [2])
*```
*/
export declare function assertArrayIncludes(actual: ArrayLike<unknown>, expected: ArrayLike<unknown>, msg?: string): void;
export declare function assertArrayIncludes<T>(actual: ArrayLike<T>, expected: ArrayLike<T>, msg?: string): void;
/**
* Make an assertion that `actual` match RegExp `expected`. If not
* then thrown
*/
export declare function assertMatch(actual: string, expected: RegExp, msg?: string): void;
/**
* Make an assertion that `actual` not match RegExp `expected`. If match
* then thrown
*/
export declare function assertNotMatch(actual: string, expected: RegExp, msg?: string): void;
/**
* Make an assertion that `actual` object is a subset of `expected` object, deeply.
* If not, then throw.
*/
export declare function assertObjectMatch(actual: Record<PropertyKey, any>, expected: Record<PropertyKey, unknown>): void;
/**
* Forcefully throws a failed assertion
*/
export declare function fail(msg?: string): void;
/**
* 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.
*/
export declare function assertThrows<T = void>(fn: () => T, ErrorClass?: Constructor, msgIncludes?: string, msg?: string): Error;
/**
* 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.
*/
export declare function assertThrowsAsync<T = void>(fn: () => Promise<T>, ErrorClass?: Constructor, msgIncludes?: string, msg?: string): Promise<Error>;
/** Use this to stub out methods that will throw when invoked. */
export declare function unimplemented(msg?: string): never;
/** Use this to assert unreachable code. */
export declare function unreachable(): never;
export {};

View File

@@ -1,37 +0,0 @@
import type { Matchers } from "./matchers.js";
interface Expected {
toBe(candidate: any): void;
toEqual(candidate: any): void;
toBeTruthy(): void;
toBeFalsy(): void;
toBeDefined(): void;
toBeInstanceOf(clazz: any): void;
toBeUndefined(): void;
toBeNull(): void;
toBeNaN(): void;
toMatch(pattern: RegExp | string): void;
toHaveProperty(propName: string): void;
toHaveLength(length: number): void;
toContain(item: any): void;
toThrow(error?: RegExp | string): void;
toBeGreaterThan(number: number): void;
toBeGreaterThanOrEqual(number: number): void;
toBeLessThan(number: number): void;
toBeLessThanOrEqual(number: number): void;
toHaveBeenCalled(): void;
toHaveBeenCalledTimes(number: number): void;
toHaveBeenCalledWith(...args: any[]): void;
toHaveBeenLastCalledWith(...args: any[]): void;
toHaveBeenNthCalledWith(nthCall: number, ...args: any[]): void;
toHaveReturned(): void;
toHaveReturnedTimes(number: number): void;
toHaveReturnedWith(value: any): void;
toHaveLastReturnedWith(value: any): void;
toHaveNthReturnedWith(nthCall: number, value: any): void;
not: Expected;
resolves: Expected;
rejects: Expected;
}
export declare function expect(value: any): Expected;
export declare function addMatchers(newMatchers: Matchers): void;
export {};

View File

@@ -1,36 +0,0 @@
export type Matcher = (value: any, ...args: any[]) => MatchResult;
export type Matchers = {
[key: string]: Matcher;
};
export type MatchResult = {
pass: boolean;
message?: string;
};
export declare function toBe(actual: any, expected: any): MatchResult;
export declare function toEqual(actual: any, expected: any): MatchResult;
export declare function toBeGreaterThan(actual: any, comparison: number): MatchResult;
export declare function toBeLessThan(actual: any, comparison: number): MatchResult;
export declare function toBeGreaterThanOrEqual(actual: any, comparison: number): MatchResult;
export declare function toBeLessThanOrEqual(actual: any, comparison: number): MatchResult;
export declare function toBeTruthy(value: any): MatchResult;
export declare function toBeFalsy(value: any): MatchResult;
export declare function toBeDefined(value: unknown): MatchResult;
export declare function toBeUndefined(value: unknown): MatchResult;
export declare function toBeNull(value: unknown): MatchResult;
export declare function toBeNaN(value: unknown): MatchResult;
export declare function toBeInstanceOf(value: any, expected: Function): MatchResult;
export declare function toMatch(value: any, pattern: RegExp | string): MatchResult;
export declare function toHaveProperty(value: any, propName: string): MatchResult;
export declare function toHaveLength(value: any, length: number): MatchResult;
export declare function toContain(value: any, item: any): MatchResult;
export declare function toThrow(value: any, error?: RegExp | string): MatchResult;
export declare function toHaveBeenCalled(value: any): MatchResult;
export declare function toHaveBeenCalledTimes(value: any, times: number): MatchResult;
export declare function toHaveBeenCalledWith(value: any, ...args: any[]): MatchResult;
export declare function toHaveBeenLastCalledWith(value: any, ...args: any[]): MatchResult;
export declare function toHaveBeenNthCalledWith(value: any, nth: number, ...args: any[]): MatchResult;
export declare function toHaveReturnedWith(value: any, result: any): MatchResult;
export declare function toHaveReturned(value: any): MatchResult;
export declare function toHaveLastReturnedWith(value: any, expected: any): MatchResult;
export declare function toHaveReturnedTimes(value: any, times: number): MatchResult;
export declare function toHaveNthReturnedWith(value: any, nth: number, expected: any): MatchResult;

View File

@@ -1,10 +0,0 @@
export type MockCall = {
args: any[];
returned?: any;
thrown?: any;
timestamp: number;
returns: boolean;
throws: boolean;
};
export declare function fn(...stubs: Function[]): (...args: any[]) => any;
export declare function calls(f: Function): MockCall[];

View File

@@ -1,4 +0,0 @@
import * as m from "./mock.js";
export declare const mock: typeof m;
export * from "./expect.js";
export declare function it(name: string, fn: () => void | Promise<void>): void;

View File

@@ -1,20 +0,0 @@
export * from "./src/matches.js";
import matches from "./src/matches.js";
export { AnyParser } from "./src/parsers/any-parser.js";
export { ArrayParser } from "./src/parsers/array-parser.js";
export { BoolParser } from "./src/parsers/bool-parser.js";
export { FunctionParser } from "./src/parsers/function-parser.js";
export { GuardParser } from "./src/parsers/guard-parser.js";
export { NilParser } from "./src/parsers/nill-parser.js";
export { NumberParser } from "./src/parsers/number-parser.js";
export { ObjectParser } from "./src/parsers/object-parser.js";
export { OrParsers } from "./src/parsers/or-parser.js";
export { ShapeParser } from "./src/parsers/shape-parser.js";
export { StringParser } from "./src/parsers/string-parser.js";
export { saferStringify } from "./src/utils.js";
export { NamedParser } from "./src/parsers/named.js";
export { ArrayOfParser } from "./src/parsers/array-of-parser.js";
export { LiteralsParser } from "./src/parsers/literal-parser.js";
export { ConcatParsers } from "./src/parsers/concat-parser.js";
export { MappedAParser } from "./src/parsers/mapped-parser.js";
export default matches;

View File

@@ -1,80 +0,0 @@
import { any, arrayOf, boolean, deferred, dictionary, every, guard, instanceOf, isFunction, literal, literals, natural, number, object, Parser, partial, recursive, regex, shape, some, string, tuple, ValidatorError } from "./parsers/index.js";
import { parserName } from "./parsers/named.js";
import { unknown } from "./parsers/simple-parsers.js";
export type { IParser, ParserNames } from "./parsers/interfaces.js";
export { Parser as Validator };
export type { ValidatorError };
export type Fn<A, B> = (a: A) => B;
export type ValueOrFunction<In, Out> = ((a: In) => Out) | Out;
export type ParserOrLiteral<A> = ExtendsSimple<A> | Parser<unknown, A>;
export type Primative = string | number | boolean | null | undefined;
export type ExtendsSimple<A> = A extends string | number | boolean | null | undefined ? A : never;
export type WhenArgsExclude<A> = A extends [ValueOrFunction<infer T, infer V>] ? (T extends unknown ? any : T) : A extends [...ParserOrLiteral<infer In>[], ValueOrFunction<infer In, infer Out>] ? In : never;
type _<A> = A;
type ExcludePrimative<A, B> = Exclude<A, Exclude<B, Exclude<A, B>>>;
export type WhenArgs<In, Out> = [ValueOrFunction<In, Out>] | [...ParserOrLiteral<In>[], ValueOrFunction<In, Out>];
interface _WhenFn<In, Out> {
<A, B>(...args: WhenArgs<A, B>): _<ChainMatches<ExcludePrimative<In, A>, Out | B>>;
}
export type WhenFn<In, Out> = [In] extends [never] ? never : _WhenFn<In, Out>;
export type WhenArgsOutput<A> = A extends [ValueOrFunction<infer T, infer V>] ? V : A extends [...ParserOrLiteral<infer In>[], ValueOrFunction<infer In, infer Out>] ? Out : never;
export type UnwrapFn<In, OutcomeType> = [In] extends [never] ? () => OutcomeType : never;
export interface ChainMatches<In, OutcomeType = never> {
when: WhenFn<In, OutcomeType>;
defaultTo<B>(value: B): B | OutcomeType;
defaultToLazy<B>(getValue: () => B): B | OutcomeType;
unwrap: UnwrapFn<In, OutcomeType>;
}
declare class MatchMore<Ins, OutcomeType> implements ChainMatches<Ins, OutcomeType> {
private a;
constructor(a: unknown);
when: WhenFn<Ins, OutcomeType>;
defaultTo<B>(value: B): B;
defaultToLazy<B>(getValue: () => B): B;
unwrap: UnwrapFn<Ins, OutcomeType>;
}
/**
* 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')
*/
export declare const matches: (<Ins extends unknown>(value: Ins) => MatchMore<Ins, never>) & {
array: Parser<unknown, unknown[]>;
arrayOf: typeof arrayOf;
some: typeof some;
tuple: typeof tuple;
regex: (tester: RegExp) => Parser<unknown, string>;
number: Parser<unknown, number>;
natural: Parser<unknown, number>;
isFunction: Parser<unknown, Function>;
object: Parser<unknown, object>;
string: Parser<unknown, string>;
shape: typeof shape;
partial: <A extends {}>(testShape: { [key in keyof A]: Parser<unknown, A[key]>; }) => Parser<unknown, Partial<A>>;
literal: typeof literal;
every: typeof every;
guard: typeof guard;
unknown: Parser<unknown, unknown>;
any: Parser<unknown, any>;
boolean: Parser<unknown, boolean>;
dictionary: <ParserSets extends [Parser<unknown, unknown>, Parser<unknown, unknown>][]>(...parsers: ParserSets) => Parser<unknown, import("./parsers/dictionary-parser.js").DictionaryShaped<[...ParserSets]>>;
literals: typeof literals;
nill: Parser<unknown, null | undefined>;
instanceOf: <C>(classCreator: new (...args: any[]) => C) => Parser<unknown, C>;
Parse: typeof Parser;
parserName: typeof parserName;
recursive: typeof recursive;
deferred: typeof deferred;
};
declare const array: Parser<unknown, unknown[]>;
declare const nill: Parser<unknown, null | undefined>;
declare const Parse: typeof Parser;
declare const oneOf: typeof some;
declare const anyOf: typeof some;
declare const allOf: typeof every;
export { allOf, any, anyOf, array, arrayOf, boolean, deferred, dictionary, every, guard, instanceOf, isFunction, literal, literals, natural, nill, number, object, oneOf, Parse, Parser, parserName, partial, recursive, regex, shape, some, string, tuple, unknown, };
export default matches;

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class AnyParser implements IParser<unknown, any> {
readonly description: {
readonly name: "Any";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "Any";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, any, C, D>): C | D;
}

View File

@@ -1,26 +0,0 @@
import { Parser } from "./index.js";
import { IParser, OnParse } from "./interfaces.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
*/
export declare class ArrayOfParser<B> implements IParser<unknown, B[]> {
readonly parser: Parser<unknown, B>;
readonly description: {
readonly name: "ArrayOf";
readonly children: readonly [Parser<unknown, B>];
readonly extras: readonly [];
};
constructor(parser: Parser<unknown, B>, description?: {
readonly name: "ArrayOf";
readonly children: readonly [Parser<unknown, B>];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, B[], C, D>): C | D;
}
/**
* 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
*/
export declare function arrayOf<A>(validator: Parser<unknown, A>): Parser<unknown, A[]>;

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class ArrayParser implements IParser<unknown, Array<unknown>> {
readonly description: {
readonly name: "Array";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "Array";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, Array<unknown>, C, D>): C | D;
}

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class BoolParser implements IParser<unknown, boolean> {
readonly description: {
readonly name: "Boolean";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "Boolean";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, boolean, C, D>): C | D;
}

View File

@@ -1,14 +0,0 @@
import { Parser } from "./index.js";
import { IParser, OnParse } from "./interfaces.js";
export declare class ConcatParsers<A, B, B2> implements IParser<A, B2> {
readonly parent: Parser<A, B>;
readonly otherParser: Parser<B, B2>;
readonly description: {
readonly name: "Concat";
readonly children: readonly [Parser<A, B>, Parser<B, B2>];
readonly extras: readonly [];
};
private constructor();
static of<A, B, B2>(parent: Parser<A, B>, otherParser: Parser<B, B2>): Parser<A, B> | Parser<B, B2> | ConcatParsers<A, B, B2>;
parse<C, D>(a: A, onParse: OnParse<A, B2, C, D>): C | D;
}

View File

@@ -1,17 +0,0 @@
import { Parser } from "./index.js";
import { IParser, NonNull, OnParse, Optional } from "./interfaces.js";
export declare class DefaultParser<A, B, B2> implements IParser<Optional<A>, NonNull<B, B2>> {
readonly parent: Parser<A, B>;
readonly defaultValue: B2;
readonly description: {
readonly name: "Default";
readonly children: readonly [Parser<A, B>];
readonly extras: readonly [B2];
};
constructor(parent: Parser<A, B>, defaultValue: B2, description?: {
readonly name: "Default";
readonly children: readonly [Parser<A, B>];
readonly extras: readonly [B2];
});
parse<C, D>(a: A, onParse: OnParse<Optional<A>, NonNull<B, B2>, C, D>): C | D;
}

View File

@@ -1,25 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
import { Parser } from "./parser.js";
/**
* This is needed when the typescript has a recursive, mutual types
* type Things = string | [OtherThings]
* type OtherThings = {type: 'other', value:Things }
*/
export declare class DeferredParser<B> implements IParser<unknown, B> {
readonly description: {
readonly name: "Deferred";
readonly children: readonly [];
readonly extras: readonly [];
};
private parser?;
static create<B>(): DeferredParser<B>;
private constructor();
setParser(parser: IParser<unknown, B>): this;
parse<C, D>(a: unknown, onParse: OnParse<unknown, B, C, D>): C | D;
}
/**
* 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
*/
export declare function deferred<B = never>(): readonly [Parser<unknown, B>, (parser: IParser<unknown, B>) => void];

View File

@@ -1,24 +0,0 @@
import { Parser } from "./index.js";
import { _, IParser, OnParse } from "./interfaces.js";
export type DictionaryTuple<A> = A extends [
Parser<unknown, infer Keys>,
Parser<unknown, infer Values>
] ? Keys extends string | number ? {
[key in Keys]: Values;
} : never : never;
export type DictionaryShaped<T> = T extends [] | readonly [] ? IParser<unknown, any> : T extends [infer A] | readonly [infer A] ? DictionaryTuple<A> : T extends [infer A, ...infer B] | readonly [infer A, ...infer B] ? DictionaryTuple<A> & DictionaryShaped<B> : never;
export declare class DictionaryParser<A extends object | {}, Parsers extends Array<[Parser<unknown, unknown>, Parser<unknown, unknown>]>> implements IParser<A, DictionaryShaped<Parsers>> {
readonly parsers: Parsers;
readonly description: {
readonly name: "Dictionary";
readonly children: IParser<unknown, unknown>[];
readonly extras: readonly [];
};
constructor(parsers: Parsers, description?: {
readonly name: "Dictionary";
readonly children: IParser<unknown, unknown>[];
readonly extras: readonly [];
});
parse<C, D>(a: A, onParse: OnParse<A, DictionaryShaped<Parsers>, C, D>): C | D;
}
export declare const dictionary: <ParserSets extends [Parser<unknown, unknown>, Parser<unknown, unknown>][]>(...parsers: ParserSets) => Parser<unknown, DictionaryShaped<[...ParserSets]>>;

View File

@@ -1,9 +0,0 @@
import { Parser } from "./index.js";
import { AndParser, EnsureParser, IParser } from "./interfaces.js";
export type EveryParser<T> = T extends [] | readonly [] ? IParser<unknown, any> : T extends [infer A] | readonly [infer A] ? EnsureParser<A> : T extends [infer A, ...infer B] | readonly [infer A, ...infer B] ? AndParser<A, EveryParser<B>> : never;
/**
* 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
*/
export declare function every<RestParsers extends Parser<unknown, unknown>[]>(...parsers: RestParsers): EveryParser<RestParsers>;

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class FunctionParser implements IParser<unknown, Function> {
readonly description: {
readonly name: "Function";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "Function";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, Function, C, D>): C | D;
}

View File

@@ -1,16 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class GuardParser<A, B> implements IParser<A, B> {
readonly checkIsA: (value: A) => value is A & B;
readonly typeName: string;
readonly description: {
readonly name: "Guard";
readonly children: readonly [];
readonly extras: readonly [string];
};
constructor(checkIsA: (value: A) => value is A & B, typeName: string, description?: {
readonly name: "Guard";
readonly children: readonly [];
readonly extras: readonly [string];
});
parse<C, D>(a: A, onParse: OnParse<A, B, C, D>): C | D;
}

View File

@@ -1,16 +0,0 @@
import { ValidatorError } from "./interfaces.js";
import { isNumber } from "./utils.js";
import { GuardParser } from "./guard-parser.js";
import { Parser } from "./parser.js";
import { any, boolean, guard, instanceOf, isArray, isFunction, isNill, natural, number, object, regex, string } from "./simple-parsers.js";
import { some } from "./some-parser.js";
import { every } from "./every-parser.js";
import { dictionary } from "./dictionary-parser.js";
import { partial, shape } from "./shape-parser.js";
import { tuple } from "./tuple-parser.js";
import { arrayOf } from "./array-of-parser.js";
import { literal, literals } from "./literal-parser.js";
import { recursive } from "./recursive-parser.js";
import { deferred } from "./deferred-parser.js";
export type { ValidatorError };
export { any, arrayOf, boolean, deferred, dictionary, every, guard, GuardParser as IsAParser, instanceOf, isArray, isFunction, isNill, isNumber, literal, literals, natural, number, object, Parser, partial, recursive, regex, shape, some, string, tuple, };

View File

@@ -1,101 +0,0 @@
import { Parser } from "./index.js";
export type NonNull<A, B> = A extends null | undefined ? B : A;
export type EnsureParser<P> = P extends IParser<any, any> ? P : never;
export type ParserInto<P> = P extends IParser<any, infer A> ? A : never;
export type ParserFrom<P> = P extends IParser<infer A, any> ? A : never;
export type Nil = null | undefined;
export type Optional<A> = A | null | undefined;
export type _<T> = T;
export type SomeParser = IParser<unknown, unknown>;
export type ISimpleParsedError = {
parser: SomeParser;
value: any;
keys: string[];
};
export type ValidatorError = ISimpleParsedError;
export type IParser<A, B> = {
readonly description: Readonly<Description & {}>;
parse<C, D>(this: IParser<A, B>, a: A, onParse: OnParse<A, B, C, D>): C | D;
};
export type Description = {
readonly name: ParserNames;
readonly extras: ReadonlyArray<unknown>;
readonly children: ReadonlyArray<SomeParser>;
} & ({
readonly name: "ArrayOf";
readonly children: readonly [SomeParser];
readonly extras: readonly [];
} | {
readonly name: "Named";
readonly children: readonly [SomeParser];
readonly extras: readonly [string];
} | {
readonly name: "Concat";
readonly children: readonly [SomeParser, SomeParser];
readonly extras: readonly [];
} | {
readonly name: "Default";
readonly children: readonly [SomeParser];
readonly extras: readonly [unknown];
} | {
readonly name: "Tuple";
readonly children: ReadonlyArray<SomeParser>;
readonly extras: readonly [];
} | {
readonly name: "Dictionary";
readonly children: ReadonlyArray<SomeParser>;
readonly extras: readonly [];
} | {
readonly name: "Deferred";
readonly children: readonly [];
readonly extras: readonly [];
} | {
readonly name: "Guard";
readonly children: readonly [];
readonly extras: readonly [unknown];
} | {
readonly name: "Literal";
readonly children: readonly [];
readonly extras: ReadonlyArray<unknown>;
} | {
readonly name: "Mapped";
readonly children: readonly [SomeParser];
readonly extras: readonly [string];
} | {
readonly name: "Maybe";
readonly children: readonly [SomeParser];
readonly extras: readonly [];
} | {
readonly name: "Recursive";
readonly children: readonly [];
readonly extras: readonly [Function];
} | {
readonly name: "Or";
readonly children: readonly [SomeParser, SomeParser];
readonly extras: readonly [];
} | {
readonly name: "Wrapper";
readonly children: readonly [SomeParser];
readonly extras: readonly [];
} | {
readonly name: "Shape" | "Partial";
readonly children: ReadonlyArray<SomeParser>;
readonly extras: ReadonlyArray<string | number>;
} | {
readonly name: "Any" | "Unknown" | "Null" | "Number" | "Boolean" | "Function" | "String" | "Object" | "Array";
readonly children: readonly [];
readonly extras: readonly [];
});
export type ParserNames = "Any" | "Array" | "ArrayOf" | "Boolean" | "Concat" | "Default" | "Deferred" | "Named" | "Dictionary" | "Function" | "Guard" | "Literal" | "Mapped" | "Maybe" | "Named" | "Null" | "Number" | "Partial" | "Object" | "Or" | "Recursive" | "Shape" | "String" | "Tuple" | "Unknown" | "Wrapper";
export type OnParse<A, B, C, D> = {
parsed(b: B): C;
invalid(error: ISimpleParsedError): D;
};
export type AndParser<P1, P2> = [P1, P2] extends [
Parser<infer A1, infer B1>,
Parser<infer A2, infer B2>
] ? Parser<A1 & A2, B1 & B2> : never;
export type OrParser<P1, P2> = [P1, P2] extends [
Parser<infer A1, infer B1>,
Parser<infer A2, infer B2>
] ? Parser<A1 | A2, B1 | B2> : never;

View File

@@ -1,19 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
import { Parser } from "./parser.js";
import { OneOf } from "./utils.js";
export declare class LiteralsParser<B extends unknown[]> implements IParser<unknown, OneOf<B>> {
readonly values: B;
readonly description: {
readonly name: "Literal";
readonly children: readonly [];
readonly extras: B;
};
constructor(values: B, description?: {
readonly name: "Literal";
readonly children: readonly [];
readonly extras: B;
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, OneOf<B>, C, D>): C | D;
}
export declare function literal<A extends string | number | boolean | null | undefined>(isEqualToValue: A): Parser<unknown, A>;
export declare function literals<A extends string | number | boolean | null | undefined, Rest extends Array<string | number | boolean | null | undefined>>(firstValue: A, ...restValues: Rest): Parser<unknown, A | OneOf<Rest>>;

View File

@@ -1,18 +0,0 @@
import { Parser } from "./index.js";
import { IParser, OnParse } from "./interfaces.js";
export declare class MappedAParser<A, B, B2> implements IParser<A, B2> {
readonly parent: Parser<A, B>;
readonly map: (value: B) => B2;
readonly mappingName: string;
readonly description: {
readonly name: "Mapped";
readonly children: readonly [Parser<A, B>];
readonly extras: readonly [string];
};
constructor(parent: Parser<A, B>, map: (value: B) => B2, mappingName?: string, description?: {
readonly name: "Mapped";
readonly children: readonly [Parser<A, B>];
readonly extras: readonly [string];
});
parse<C, D>(a: A, onParse: OnParse<A, B2, C, D>): C | D;
}

View File

@@ -1,16 +0,0 @@
import { Parser } from "./index.js";
import { IParser, OnParse, Optional } from "./interfaces.js";
export declare class MaybeParser<A, B> implements IParser<Optional<A>, Optional<B>> {
readonly parent: Parser<A, B>;
readonly description: {
readonly name: "Maybe";
readonly children: readonly [Parser<A, B>];
readonly extras: readonly [];
};
constructor(parent: Parser<A, B>, description?: {
readonly name: "Maybe";
readonly children: readonly [Parser<A, B>];
readonly extras: readonly [];
});
parse<C, D>(a: A, onParse: OnParse<Optional<A>, Optional<B>, C, D>): C | D;
}

View File

@@ -1,18 +0,0 @@
import { Parser } from "./index.js";
import { IParser, OnParse } from "./interfaces.js";
export declare class NamedParser<A, B> implements IParser<A, B> {
readonly parent: Parser<A, B>;
readonly name: string;
readonly description: {
readonly name: "Named";
readonly children: readonly [Parser<A, B>];
readonly extras: readonly [string];
};
constructor(parent: Parser<A, B>, name: string, description?: {
readonly name: "Named";
readonly children: readonly [Parser<A, B>];
readonly extras: readonly [string];
});
parse<C, D>(a: A, onParse: OnParse<A, B, C, D>): C | D;
}
export declare function parserName<A, B>(name: string, parent: Parser<A, B>): Parser<A, B>;

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class NilParser implements IParser<unknown, null | undefined> {
readonly description: {
readonly name: "Null";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "Null";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, null | undefined, C, D>): C | D;
}

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class NumberParser implements IParser<unknown, number> {
readonly description: {
readonly name: "Number";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "Number";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, number, C, D>): C | D;
}

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class ObjectParser implements IParser<unknown, object> {
readonly description: {
readonly name: "Object";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "Object";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, object, C, D>): C | D;
}

View File

@@ -1,17 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
import { Parser } from "./parser.js";
export declare class OrParsers<A, A2, B, B2> implements IParser<A | A2, B | B2> {
readonly parent: Parser<A, B>;
readonly otherParser: Parser<A2, B2>;
readonly description: {
readonly name: "Or";
readonly children: readonly [Parser<A, B>, Parser<A2, B2>];
readonly extras: readonly [];
};
constructor(parent: Parser<A, B>, otherParser: Parser<A2, B2>, description?: {
readonly name: "Or";
readonly children: readonly [Parser<A, B>, Parser<A2, B2>];
readonly extras: readonly [];
});
parse<C, D>(a: A & A2, onParse: OnParse<A | A2, B | B2, C, D>): C | D;
}

View File

@@ -1,140 +0,0 @@
import { IParser, ISimpleParsedError, NonNull, OnParse, Optional } from "./interfaces.js";
export type EnumType<A> = {
error: ISimpleParsedError;
} | {
value: A;
};
/**
* 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.
*/
export declare class Parser<A, B> implements IParser<A, B> {
readonly parser: IParser<A, B>;
readonly description: {
readonly name: "Wrapper";
readonly children: readonly [IParser<A, B>];
readonly extras: readonly [];
};
readonly _TYPE: B;
constructor(parser: IParser<A, B>, description?: {
readonly name: "Wrapper";
readonly children: readonly [IParser<A, B>];
readonly extras: readonly [];
});
/**
* Use this when you want to decide what happens on the succes and failure cases of parsing
* @param a
* @param onParse
* @returns
*/
parse<C, D>(a: A, onParse: OnParse<A, B, C, D>): C | D;
/**
* 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<A, B extends A>(checkIsA: (value: A) => value is B, name: string): Parser<A, B>;
/**
* This is the line of code that could be over written if
* One would like to have a custom error as any shape
*/
static validatorErrorAsString: <A_1, B_1>(error: ISimpleParsedError) => string;
/**
* Trying to convert the parser into a string representation
* @param parserComingIn
* @returns
*/
static parserAsString(parserComingIn: IParser<unknown, unknown>): string;
/**
* This is the most useful parser, it assumes the happy path and will throw an error if it fails.
* @param value
* @returns
*/
unsafeCast(value: A): B;
/**
* 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: A): Promise<B>;
/**
* 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: A): void | string;
/**
* 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<C>(fn: (apply: B) => C, mappingName?: string): Parser<A, C>;
/**
* 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<C>(otherParser: IParser<B, C>): Parser<A, C>;
/**
* 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<C>(otherParser: IParser<A, C>): Parser<A, B | C>;
/**
* 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
*/
test: (value: A) => value is A & B;
/**
* 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?: string): Parser<Optional<A>, Optional<B>>;
/**
* 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<C>(defaultValue: C): Parser<Optional<A>, C | NonNull<B, C>>;
/**
* We want to test value with a test eg isEven
*/
validate(isValid: (value: B) => boolean, otherName: string): Parser<A, B>;
/**
* We want to refine to a new type given an original type, like isEven, or casting to a more
* specific type
*/
refine<C = B>(refinementTest: (value: B) => value is B & C, otherName?: string): Parser<A, B & C>;
/**
* 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: string): Parser<A, B>;
/**
* 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: A): EnumType<B>;
/**
* Return the unwrapped parser/ IParser
* @returns
*/
unwrappedParser(): IParser<any, any>;
}

View File

@@ -1,30 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
import { Parser } from "./parser.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;
* }
*/
export declare class RecursiveParser<B> implements IParser<unknown, B> {
readonly recursive: (parser: Parser<unknown, any>) => Parser<unknown, unknown>;
readonly description: {
readonly name: "Recursive";
readonly children: readonly [];
readonly extras: readonly [(parser: Parser<unknown, any>) => Parser<unknown, unknown>];
};
private parser?;
static create<B>(fn: (parser: Parser<unknown, any>) => Parser<unknown, unknown>): RecursiveParser<B>;
private constructor();
parse<C, D>(a: unknown, onParse: OnParse<unknown, B, C, D>): C | D;
}
type EnsurredType<A, B = A> = (A extends never ? never : unknown) & ((parser: Parser<unknown, any>) => Parser<unknown, B>);
/**
* 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
*/
export declare function recursive<B = never>(fn: EnsurredType<B>): Parser<unknown, B>;
export {};

View File

@@ -1,63 +0,0 @@
import { Parser } from "./index.js";
import { IParser, OnParse } from "./interfaces.js";
type _<T> = T;
export type MergeAll<T> = T extends ReadonlyArray<infer U> ? ReadonlyArray<MergeAll<U>> : T extends object ? T extends null | undefined | never ? T : _<{
[k in keyof T]: MergeAll<T[k]>;
}> : T;
/**
* Given an object, we want to make sure the key exists and that the value on
* the key matches the parser
*/
export declare class ShapeParser<A extends unknown, Key extends string | number | symbol, B> implements IParser<A, B> {
readonly parserMap: {
[key in keyof B]: Parser<unknown, B[key]>;
};
readonly isPartial: boolean;
readonly parserKeys: (string & keyof B)[];
readonly description: {
readonly name: "Partial" | "Shape";
readonly children: { [key in keyof B]: Parser<unknown, B[key]>; }[string & keyof B][];
readonly extras: (string & keyof B)[];
};
constructor(parserMap: {
[key in keyof B]: Parser<unknown, B[key]>;
}, isPartial: boolean, parserKeys?: (string & keyof B)[], description?: {
readonly name: "Partial" | "Shape";
readonly children: { [key in keyof B]: Parser<unknown, B[key]>; }[string & keyof B][];
readonly extras: (string & keyof B)[];
});
parse<C, D>(a: A, onParse: OnParse<A, B, C, D>): C | D;
}
export declare const isPartial: <A extends {}>(testShape: { [key in keyof A]: Parser<unknown, A[key]>; }) => Parser<unknown, Partial<A>>;
/**
* Good for duck typing an object, with optional values
* @param testShape Shape of validators, to ensure we match the shape
*/
export declare const partial: <A extends {}>(testShape: { [key in keyof A]: Parser<unknown, A[key]>; }) => Parser<unknown, Partial<A>>;
/**
* Good for duck typing an object
* @param testShape Shape of validators, to ensure we match the shape
*/
export declare const isShape: <A extends {}>(testShape: { [key in keyof A]: Parser<unknown, A[key]>; }) => Parser<unknown, A>;
export declare function shape<A extends {}, Overwrites extends keyof A>(testShape: {
[key in keyof A]: Parser<unknown, A[key]>;
}, optionals: Overwrites[]): Parser<unknown, MergeAll<{
[K in keyof Omit<A, Overwrites>]: A[K];
} & {
[K in keyof Pick<A, Overwrites>]?: A[K];
}>>;
export declare function shape<A extends {}, Overwrites extends keyof A, Defaults extends {
[K in Overwrites]?: A[K];
}>(testShape: {
[key in keyof A]: Parser<unknown, A[key]>;
}, optionals: Overwrites[], defaults: Defaults): Parser<unknown, MergeAll<{
[K in keyof Omit<A, Overwrites>]: A[K];
} & {
[K in keyof Omit<Pick<A, Overwrites>, keyof Defaults>]?: A[K];
} & {
[K in keyof Pick<Pick<A, Overwrites>, keyof Defaults & Overwrites>]: A[K];
}>>;
export declare function shape<A extends {}>(testShape: {
[key in keyof A]: Parser<unknown, A[key]>;
}): Parser<unknown, A>;
export {};

View File

@@ -1,19 +0,0 @@
import { Parser } from "./index.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
*/
export declare function guard<A, B extends A>(test: (value: A) => value is B, testName?: string): Parser<A, B>;
export declare const any: Parser<unknown, any>;
export declare const unknown: Parser<unknown, unknown>;
export declare const number: Parser<unknown, number>;
export declare const isNill: Parser<unknown, null | undefined>;
export declare const natural: Parser<unknown, number>;
export declare const isFunction: Parser<unknown, Function>;
export declare const boolean: Parser<unknown, boolean>;
export declare const object: Parser<unknown, object>;
export declare const isArray: Parser<unknown, unknown[]>;
export declare const string: Parser<unknown, string>;
export declare const instanceOf: <C>(classCreator: new (...args: any[]) => C) => Parser<unknown, C>;
export declare const regex: (tester: RegExp) => Parser<unknown, string>;

View File

@@ -1,9 +0,0 @@
import { Parser } from "./index.js";
import { EnsureParser, IParser, OrParser } from "./interfaces.js";
export type SomeParsers<T> = T extends [] | readonly [] ? IParser<unknown, any> : T extends [infer A] | readonly [infer A] ? EnsureParser<A> : T extends [infer A, ...infer B] | readonly [infer A, ...infer B] ? OrParser<A, SomeParsers<B>> : T extends Array<infer A> | ReadonlyArray<infer A> ? A : never;
/**
* 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.
*/
export declare function some<RestParsers extends Parser<unknown, unknown>[]>(...parsers: RestParsers): SomeParsers<RestParsers>;

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class StringParser implements IParser<unknown, string> {
readonly description: {
readonly name: "String";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "String";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, string, C, D>): C | D;
}

View File

@@ -1,19 +0,0 @@
import { Parser } from "./index.js";
import { IParser, OnParse, ParserInto } from "./interfaces.js";
export type TupleParserInto<T> = T extends [infer A] | readonly [infer A] ? [ParserInto<A>] : T extends [infer A, ...infer B] | readonly [infer A, ...infer B] ? [ParserInto<A>, ...TupleParserInto<B>] : never;
export declare class TupleParser<A extends Parser<unknown, unknown>[]> implements IParser<unknown, TupleParserInto<A>> {
readonly parsers: A;
readonly lengthMatcher: Parser<unknown, number>;
readonly description: {
readonly name: "Tuple";
readonly children: A;
readonly extras: readonly [];
};
constructor(parsers: A, lengthMatcher?: Parser<unknown, number>, description?: {
readonly name: "Tuple";
readonly children: A;
readonly extras: readonly [];
});
parse<C, D>(input: unknown, onParse: OnParse<unknown, TupleParserInto<A>, C, D>): C | D;
}
export declare function tuple<A extends Parser<unknown, unknown>[]>(...parsers: A): Parser<unknown, TupleParserInto<A>>;

View File

@@ -1,14 +0,0 @@
import { IParser, OnParse } from "./interfaces.js";
export declare class UnknownParser implements IParser<unknown, unknown> {
readonly description: {
readonly name: "Unknown";
readonly children: readonly [];
readonly extras: readonly [];
};
constructor(description?: {
readonly name: "Unknown";
readonly children: readonly [];
readonly extras: readonly [];
});
parse<C, D>(a: unknown, onParse: OnParse<unknown, unknown, C, D>): C | D;
}

View File

@@ -1,8 +0,0 @@
import { OnParse } from "./interfaces.js";
export declare const isObject: (x: unknown) => x is object;
export declare const isFunctionTest: (x: unknown) => x is Function;
export declare const isNumber: (x: unknown) => x is number;
export declare const isString: (x: unknown) => x is string;
export declare const empty: any[];
export declare const booleanOnParse: OnParse<unknown, unknown, true, false>;
export type OneOf<T> = T extends [infer A] | readonly [infer A] ? A : T extends [infer A, ...infer B] | readonly [infer A, ...infer B] ? A | OneOf<B> : never;

View File

@@ -1,5 +0,0 @@
/**
* Tries and run the stringify, if that fails just return the toString
* @param x Could be anything, including a recursive object
*/
export declare function saferStringify(x: unknown): string;

View File

@@ -1,102 +0,0 @@
/**
* 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
*/
export declare function rangeOf(range: string | Checker): Checker;
/**
* Used to create a checker that will `and` all the ranges passed in
* @param ranges
* @returns
*/
export declare function rangeAnd(...ranges: (string | Checker)[]): Checker;
/**
* Used to create a checker that will `or` all the ranges passed in
* @param ranges
* @returns
*/
export declare function rangeOr(...ranges: (string | Checker)[]): Checker;
/**
* 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
*/
export declare function notRange(range: string | Checker): Checker;
/**
* EmVer is a set of versioning of any pattern like 1 or 1.2 or 1.2.3 or 1.2.3.4 or ..
*/
export declare class EmVer {
readonly values: number[];
/**
* Convert the range, should be 1.2.* or * into a emver
* Or an already made emver
* IsUnsafe
*/
static from(range: string | EmVer): EmVer;
/**
* Convert the range, should be 1.2.* or * into a emver
* IsUnsafe
*/
static parse(range: string): EmVer;
private constructor();
/**
* Used when we need a new emver that has the last number incremented, used in the 1.* like things
*/
withLastIncremented(): EmVer;
greaterThan(other: EmVer): boolean;
equals(other: EmVer): boolean;
greaterThanOrEqual(other: EmVer): boolean;
lessThanOrEqual(other: EmVer): boolean;
lessThan(other: EmVer): boolean;
/**
* Return a enum string that describes (used for switching/iffs)
* to know comparison
* @param other
* @returns
*/
compare(other: EmVer): "equal" | "greater" | "less";
/**
* Used when sorting emver's in a list using the sort method
* @param other
* @returns
*/
compareForSort(other: EmVer): 0 | 1 | -1;
}
/**
* 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
*/
export declare class Checker {
/**
* Check is the function that will be given a emver or unparsed emver and should give if it follows
* a pattern
*/
readonly check: (value: string | EmVer) => boolean;
/**
* 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: string | Checker): Checker;
constructor(
/**
* Check is the function that will be given a emver or unparsed emver and should give if it follows
* a pattern
*/
check: (value: string | EmVer) => boolean);
/**
* Used when we want the `and` condition with another checker
*/
and(...others: (Checker | string)[]): Checker;
/**
* Used when we want the `or` condition with another checker
*/
or(...others: (Checker | string)[]): Checker;
/**
* A useful example is making sure we don't match an exact version, like !=1.2.3
* @returns
*/
not(): Checker;
}

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