Merge pull request #4 from Start9Labs/feat/update-types

rename things and add new value spec types
This commit is contained in:
J H
2023-04-20 14:58:48 -06:00
committed by GitHub
14 changed files with 350 additions and 337 deletions

View File

@@ -2,8 +2,8 @@ import { BuilderExtract, IBuilder } from "./builder";
import { Config } from "./config"; import { Config } from "./config";
import { import {
InputSpec, InputSpec,
ListValueSpecNumber, ListValueSpecText,
ListValueSpecString, Pattern,
UniqueBy, UniqueBy,
ValueSpecList, ValueSpecList,
} from "../configTypes"; } from "../configTypes";
@@ -22,33 +22,34 @@ export const auth = Value.list(authorizationList);
``` ```
*/ */
export class List<A extends ValueSpecList> extends IBuilder<A> { export class List<A extends ValueSpecList> extends IBuilder<A> {
static string( static text(
a: { a: {
name: string; name: string;
description?: string | null; description?: string | null;
warning?: string | null; warning?: string | null;
/** Default = [] */ /** Default = [] */
default?: string[]; default?: string[];
/** Default = "(\*,\*)" */ minLength?: number | null;
range?: string; maxLength?: number | null;
}, },
aSpec: { aSpec: {
/** Default = false */ /** Default = false */
masked?: boolean; masked?: boolean;
placeholder?: string | null; placeholder?: string | null;
pattern?: string | null; minLength?: number | null;
patternDescription?: string | null; maxLength?: number | null;
patterns: Pattern[];
/** Default = "text" */ /** Default = "text" */
inputmode?: ListValueSpecString["inputmode"]; inputMode?: ListValueSpecText["inputMode"];
}, },
) { ) {
const spec = { const spec = {
type: "string" as const, type: "text" as const,
placeholder: null, placeholder: null,
pattern: null, minLength: null,
patternDescription: null, maxLength: null,
masked: false, masked: false,
inputmode: "text" as const, inputMode: "text" as const,
...aSpec, ...aSpec,
}; };
return new List({ return new List({
@@ -56,7 +57,8 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
warning: null, warning: null,
default: [], default: [],
type: "list" as const, type: "list" as const,
range: "(*,*)", minLength: null,
maxLength: null,
...a, ...a,
spec, spec,
}); });
@@ -68,13 +70,14 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
warning?: string | null; warning?: string | null;
/** Default = [] */ /** Default = [] */
default?: string[]; default?: string[];
/** Default = "(\*,\*)" */ minLength?: number | null;
range?: string; maxLength?: number | null;
}, },
aSpec: { aSpec: {
integral: boolean; integer: boolean;
/** Default = "(\*,\*)" */ min?: number | null;
range?: string; max?: number | null;
step?: string | null;
units?: string | null; units?: string | null;
placeholder?: string | null; placeholder?: string | null;
}, },
@@ -82,15 +85,17 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
const spec = { const spec = {
type: "number" as const, type: "number" as const,
placeholder: null, placeholder: null,
range: "(*,*)", min: null,
max: null,
step: null,
units: null, units: null,
...aSpec, ...aSpec,
}; };
return new List({ return new List({
description: null, description: null,
warning: null, warning: null,
units: null, minLength: null,
range: "(*,*)", maxLength: null,
default: [], default: [],
type: "list" as const, type: "list" as const,
...a, ...a,
@@ -104,8 +109,8 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
warning?: string | null; warning?: string | null;
/** Default [] */ /** Default [] */
default?: []; default?: [];
/** Default = "(\*,\*)" */ minLength?: number | null;
range?: string; maxLength?: number | null;
}, },
aSpec: { aSpec: {
spec: Spec; spec: Spec;
@@ -130,7 +135,8 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
return new List({ return new List({
description: null, description: null,
warning: null, warning: null,
range: "(*,*)", minLength: null,
maxLength: null,
type: "list" as const, type: "list" as const,
...value, ...value,
}); });

View File

@@ -4,10 +4,13 @@ import { List } from "./list";
import { Variants } from "./variants"; import { Variants } from "./variants";
import { import {
InputSpec, InputSpec,
ListValueSpecString, Pattern,
ValueSpec, ValueSpec,
ValueSpecColor,
ValueSpecDatetime,
ValueSpecList, ValueSpecList,
ValueSpecNumber, ValueSpecNumber,
ValueSpecText,
ValueSpecTextarea, ValueSpecTextarea,
} from "../configTypes"; } from "../configTypes";
import { guardAll } from "../../util"; import { guardAll } from "../../util";
@@ -35,7 +38,7 @@ const username = Value.string({
``` ```
*/ */
export class Value<A extends ValueSpec> extends IBuilder<A> { export class Value<A extends ValueSpec> extends IBuilder<A> {
static boolean(a: { static toggle(a: {
name: string; name: string;
description?: string | null; description?: string | null;
warning?: string | null; warning?: string | null;
@@ -45,11 +48,11 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
description: null, description: null,
warning: null, warning: null,
default: null, default: null,
type: "boolean" as const, type: "toggle" as const,
...a, ...a,
}); });
} }
static string(a: { static text(a: {
name: string; name: string;
description?: string | null; description?: string | null;
warning?: string | null; warning?: string | null;
@@ -58,21 +61,23 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
/** Default = false */ /** Default = false */
masked?: boolean; masked?: boolean;
placeholder?: string | null; placeholder?: string | null;
pattern?: string | null; minLength?: number | null;
patternDescription?: string | null; maxLength?: number | null;
patterns?: Pattern[];
/** Default = 'text' */ /** Default = 'text' */
inputmode?: ListValueSpecString["inputmode"]; inputMode?: ValueSpecText["inputMode"];
}) { }) {
return new Value({ return new Value({
type: "string" as const, type: "text" as const,
default: null, default: null,
description: null, description: null,
warning: null, warning: null,
masked: false, masked: false,
placeholder: null, placeholder: null,
pattern: null, minLength: null,
patternDescription: null, maxLength: null,
inputmode: "text", patterns: [],
inputMode: "text",
...a, ...a,
}); });
} }
@@ -81,11 +86,15 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
description?: string | null; description?: string | null;
warning?: string | null; warning?: string | null;
required: boolean; required: boolean;
minLength?: number | null;
maxLength?: number | null;
placeholder?: string | null; placeholder?: string | null;
}) { }) {
return new Value({ return new Value({
description: null, description: null,
warning: null, warning: null,
minLength: null,
maxLength: null,
placeholder: null, placeholder: null,
type: "textarea" as const, type: "textarea" as const,
...a, ...a,
@@ -97,9 +106,11 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
warning?: string | null; warning?: string | null;
required: boolean; required: boolean;
default?: number | null; default?: number | null;
/** default = "(\*,\*)" */ min?: number | null;
range?: string; max?: number | null;
integral: boolean; /** Default = '1' */
step?: string | null;
integer: boolean;
units?: string | null; units?: string | null;
placeholder?: string | null; placeholder?: string | null;
}) { }) {
@@ -108,12 +119,53 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
description: null, description: null,
warning: null, warning: null,
default: null, default: null,
range: "(*,*)", min: null,
max: null,
step: null,
units: null, units: null,
placeholder: null, placeholder: null,
...a, ...a,
} as ValueSpecNumber); } as ValueSpecNumber);
} }
static color(a: {
name: string;
description?: string | null;
warning?: string | null;
required: boolean;
default?: number | null;
}) {
return new Value({
type: "color" as const,
description: null,
warning: null,
default: null,
...a,
} as ValueSpecColor);
}
static datetime(a: {
name: string;
description?: string | null;
warning?: string | null;
required: boolean;
/** Default = 'datetime-local' */
inputMode?: ValueSpecDatetime["inputMode"];
min?: string | null;
max?: string | null;
step?: string | null;
default?: number | null;
}) {
return new Value({
type: "datetime" as const,
description: null,
warning: null,
inputMode: "datetime-local",
min: null,
max: null,
step: null,
default: null,
...a,
} as ValueSpecDatetime);
}
static select<B extends Record<string, string>>(a: { static select<B extends Record<string, string>>(a: {
name: string; name: string;
description?: string | null; description?: string | null;
@@ -134,16 +186,16 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
name: string; name: string;
description?: string | null; description?: string | null;
warning?: string | null; warning?: string | null;
default?: string[]; default: string[];
values: Values; values: Values;
/** default = "(\*,\*)" */ minLength?: number | null;
range?: string; maxLength?: number | null;
}) { }) {
return new Value({ return new Value({
type: "multiselect" as const, type: "multiselect" as const,
range: "(*,*)", minLength: null,
maxLength: null,
warning: null, warning: null,
default: [],
description: null, description: null,
...a, ...a,
}); });

View File

@@ -1,9 +1,11 @@
export type InputSpec = Record<string, ValueSpec>; export type InputSpec = Record<string, ValueSpec>;
export type ValueType = export type ValueType =
| "string" | "text"
| "textarea" | "textarea"
| "number" | "number"
| "boolean" | "color"
| "datetime"
| "toggle"
| "select" | "select"
| "multiselect" | "multiselect"
| "list" | "list"
@@ -12,14 +14,18 @@ export type ValueType =
| "union"; | "union";
export type ValueSpec = ValueSpecOf<ValueType>; export type ValueSpec = ValueSpecOf<ValueType>;
/** core spec types. These types provide the metadata for performing validations */ /** core spec types. These types provide the metadata for performing validations */
export type ValueSpecOf<T extends ValueType> = T extends "string" export type ValueSpecOf<T extends ValueType> = T extends "text"
? ValueSpecString ? ValueSpecText
: T extends "number"
? ValueSpecTextarea
: T extends "textarea" : T extends "textarea"
? ValueSpecTextarea
: T extends "number"
? ValueSpecNumber ? ValueSpecNumber
: T extends "boolean" : T extends "color"
? ValueSpecBoolean ? ValueSpecColor
: T extends "datetime"
? ValueSpecDatetime
: T extends "toggle"
? ValueSpecToggle
: T extends "select" : T extends "select"
? ValueSpecSelect ? ValueSpecSelect
: T extends "multiselect" : T extends "multiselect"
@@ -34,19 +40,35 @@ export type ValueSpecOf<T extends ValueType> = T extends "string"
? ValueSpecUnion ? ValueSpecUnion
: never; : never;
export interface ValueSpecString extends ListValueSpecString, WithStandalone { export interface ValueSpecText extends ListValueSpecText, WithStandalone {
required: boolean; required: boolean;
default: DefaultString | null; default: DefaultString | null;
} }
export interface ValueSpecTextarea extends WithStandalone { export interface ValueSpecTextarea extends WithStandalone {
type: "textarea"; type: "textarea";
placeholder: string | null; placeholder: string | null;
minLength: number | null;
maxLength: number | null;
required: boolean; required: boolean;
} }
export interface ValueSpecNumber extends ListValueSpecNumber, WithStandalone { export interface ValueSpecNumber extends ListValueSpecNumber, WithStandalone {
required: boolean; required: boolean;
default: number | null; default: number | null;
} }
export interface ValueSpecColor extends WithStandalone {
type: "color";
required: boolean;
default: string | null;
}
export interface ValueSpecDatetime extends WithStandalone {
type: "datetime";
required: boolean;
inputMode: "date" | "time" | "datetime-local";
min: string | null;
max: string | null;
step: string | null;
default: string | null;
}
export interface ValueSpecSelect extends SelectBase, WithStandalone { export interface ValueSpecSelect extends SelectBase, WithStandalone {
type: "select"; type: "select";
required: boolean; required: boolean;
@@ -54,12 +76,12 @@ export interface ValueSpecSelect extends SelectBase, WithStandalone {
} }
export interface ValueSpecMultiselect extends SelectBase, WithStandalone { export interface ValueSpecMultiselect extends SelectBase, WithStandalone {
type: "multiselect"; type: "multiselect";
/**'[0,1]' (inclusive) OR '[0,*)' (right unbounded), normal math rules */ minLength: number | null;
range: string; maxLength: number | null;
default: string[]; default: string[];
} }
export interface ValueSpecBoolean extends WithStandalone { export interface ValueSpecToggle extends WithStandalone {
type: "boolean"; type: "toggle";
default: boolean | null; default: boolean | null;
} }
export interface ValueSpecUnion extends WithStandalone { export interface ValueSpecUnion extends WithStandalone {
@@ -91,10 +113,10 @@ export interface WithStandalone {
export interface SelectBase { export interface SelectBase {
values: Record<string, string>; values: Record<string, string>;
} }
export type ListValueSpecType = "string" | "number" | "object"; export type ListValueSpecType = "text" | "number" | "object";
/** represents a spec for the values of a list */ /** represents a spec for the values of a list */
export type ListValueSpecOf<T extends ListValueSpecType> = T extends "string" export type ListValueSpecOf<T extends ListValueSpecType> = T extends "text"
? ListValueSpecString ? ListValueSpecText
: T extends "number" : T extends "number"
? ListValueSpecNumber ? ListValueSpecNumber
: T extends "object" : T extends "object"
@@ -106,7 +128,8 @@ export interface ValueSpecListOf<T extends ListValueSpecType>
extends WithStandalone { extends WithStandalone {
type: "list"; type: "list";
spec: ListValueSpecOf<T>; spec: ListValueSpecOf<T>;
range: string; minLength: number | null;
maxLength: number | null;
default: default:
| string[] | string[]
| number[] | number[]
@@ -117,18 +140,25 @@ export interface ValueSpecListOf<T extends ListValueSpecType>
| readonly DefaultString[] | readonly DefaultString[]
| readonly Record<string, unknown>[]; | readonly Record<string, unknown>[];
} }
export interface ListValueSpecString { export interface Pattern {
type: "string"; regex: string;
pattern: string | null; description: string;
patternDescription: string | null; }
export interface ListValueSpecText {
type: "text";
patterns: Pattern[];
minLength: number | null;
maxLength: number | null;
masked: boolean; masked: boolean;
inputmode: "text" | "email" | "tel" | "url"; inputMode: "text" | "email" | "tel" | "url";
placeholder: string | null; placeholder: string | null;
} }
export interface ListValueSpecNumber { export interface ListValueSpecNumber {
type: "number"; type: "number";
range: string; min: number | null;
integral: boolean; max: number | null;
integer: boolean;
step: string | null;
units: string | null; units: string | null;
placeholder: string | null; placeholder: string | null;
} }

View File

@@ -1,11 +1,5 @@
import { Config } from "./builder"; import { Config } from "./builder";
import { import { DeepPartial, Dependencies, Effects, ExpectedExports } from "../types";
DeepPartial,
Dependencies,
DependsOn,
Effects,
ExpectedExports,
} from "../types";
import { InputSpec } from "./configTypes"; import { InputSpec } from "./configTypes";
import { nullIfEmpty } from "../util"; import { nullIfEmpty } from "../util";
import { TypeFromProps } from "../util/propertiesMatcher"; import { TypeFromProps } from "../util/propertiesMatcher";

View File

@@ -50,10 +50,12 @@ export async function specToBuilder(
} }
function convertValueSpec(value: C.ValueSpec): string { function convertValueSpec(value: C.ValueSpec): string {
switch (value.type) { switch (value.type) {
case "string": case "text":
case "textarea": case "textarea":
case "number": case "number":
case "boolean": case "color":
case "datetime":
case "toggle":
case "select": case "select":
case "multiselect": { case "multiselect": {
const { type, ...rest } = value; const { type, ...rest } = value;
@@ -91,11 +93,12 @@ export async function specToBuilder(
function convertList(valueSpecList: C.ValueSpecList) { function convertList(valueSpecList: C.ValueSpecList) {
const { spec, ...value } = valueSpecList; const { spec, ...value } = valueSpecList;
switch (spec.type) { switch (spec.type) {
case "string": { case "text": {
return `List.string(${JSON.stringify( return `List.text(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
range: value.range || null, minLength: value.minLength || null,
maxLength: value.maxLength || null,
default: value.default || null, default: value.default || null,
description: value.description || null, description: value.description || null,
warning: value.warning || null, warning: value.warning || null,
@@ -105,16 +108,16 @@ export async function specToBuilder(
)}, ${JSON.stringify({ )}, ${JSON.stringify({
masked: spec?.masked || false, masked: spec?.masked || false,
placeholder: spec?.placeholder || null, placeholder: spec?.placeholder || null,
pattern: spec?.pattern || null, pattern: spec?.patterns || [],
patternDescription: spec?.patternDescription || null, inputMode: spec?.inputMode || "text",
inputMode: spec?.inputmode || null,
})})`; })})`;
} }
case "number": { case "number": {
return `List.number(${JSON.stringify( return `List.number(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
range: value.range || null, minLength: value.minLength || null,
maxLength: value.maxLength || null,
default: value.default || null, default: value.default || null,
description: value.description || null, description: value.description || null,
warning: value.warning || null, warning: value.warning || null,
@@ -122,8 +125,10 @@ export async function specToBuilder(
null, null,
2, 2,
)}, ${JSON.stringify({ )}, ${JSON.stringify({
range: spec?.range || null, integer: spec?.integer || false,
integral: spec?.integral || false, min: spec?.min || null,
max: spec?.max || null,
step: spec?.step || null,
units: spec?.units || null, units: spec?.units || null,
placeholder: spec?.placeholder || null, placeholder: spec?.placeholder || null,
})})`; })})`;
@@ -135,7 +140,8 @@ export async function specToBuilder(
); );
return `List.obj({ return `List.obj({
name: ${JSON.stringify(value.name || null)}, name: ${JSON.stringify(value.name || null)},
range: ${JSON.stringify(value.range || null)}, minLength: ${JSON.stringify(value.minLength || null)},
maxLength: ${JSON.stringify(value.maxLength || null)},
default: ${JSON.stringify(value.default || null)}, default: ${JSON.stringify(value.default || null)},
description: ${JSON.stringify(value.description || null)}, description: ${JSON.stringify(value.description || null)},
warning: ${JSON.stringify(value.warning || null)}, warning: ${JSON.stringify(value.warning || null)},

View File

@@ -3,41 +3,42 @@ import { Config } from "../config/builder/config";
import { List } from "../config/builder/list"; import { List } from "../config/builder/list";
import { Value } from "../config/builder/value"; import { Value } from "../config/builder/value";
import { Variants } from "../config/builder/variants"; import { Variants } from "../config/builder/variants";
import { Parser } from "ts-matches";
describe("builder tests", () => { describe("builder tests", () => {
test("String", () => { test("text", () => {
const bitcoinPropertiesBuilt: { const bitcoinPropertiesBuilt: {
"peer-tor-address": { "peer-tor-address": {
name: string; name: string;
description: string | null; description: string | null;
type: "string"; type: "text";
}; };
} = Config.of({ } = Config.of({
"peer-tor-address": Value.string({ "peer-tor-address": Value.text({
name: "Peer tor address", name: "Peer tor address",
default: "", default: null,
description: "The Tor address of the peer interface", description: "The Tor address of the peer interface",
warning: null, warning: null,
required: true, required: true,
masked: true, masked: true,
placeholder: null, placeholder: null,
pattern: null, minLength: null,
patternDescription: null, maxLength: null,
patterns: [],
}), }),
}).build(); }).build();
expect(JSON.stringify(bitcoinPropertiesBuilt)).toEqual( expect(JSON.stringify(bitcoinPropertiesBuilt)).toEqual(
/*json*/ `{ /*json*/ `{
"peer-tor-address": { "peer-tor-address": {
"type": "string", "type": "text",
"default": "", "default": null,
"description": "The Tor address of the peer interface", "description": "The Tor address of the peer interface",
"warning": null, "warning": null,
"masked": true, "masked": true,
"placeholder": null, "placeholder": null,
"pattern": null, "minLength": null,
"patternDescription": null, "maxLength": null,
"inputmode":"text", "patterns": [],
"inputMode":"text",
"name": "Peer tor address", "name": "Peer tor address",
"required": true "required": true
}}` }}`
@@ -49,16 +50,16 @@ describe("builder tests", () => {
}); });
describe("values", () => { describe("values", () => {
test("boolean", () => { test("toggle", () => {
const value = Value.boolean({ const value = Value.toggle({
name: "Testing", name: "Testing",
}); });
const validator = value.validator(); const validator = value.validator();
validator.unsafeCast(false); validator.unsafeCast(false);
testOutput<typeof validator._TYPE, boolean>()(null); testOutput<typeof validator._TYPE, boolean>()(null);
}); });
test("string", () => { test("text", () => {
const value = Value.string({ const value = Value.text({
name: "Testing", name: "Testing",
required: false, required: false,
}); });
@@ -66,6 +67,24 @@ describe("values", () => {
validator.unsafeCast("test text"); validator.unsafeCast("test text");
testOutput<typeof validator._TYPE, string>()(null); testOutput<typeof validator._TYPE, string>()(null);
}); });
test("color", () => {
const value = Value.color({
name: "Testing",
required: false,
});
const validator = value.validator();
validator.unsafeCast("#000000");
testOutput<typeof validator._TYPE, string>()(null);
});
test("datetime", () => {
const value = Value.datetime({
name: "Testing",
required: false,
});
const validator = value.validator();
validator.unsafeCast("2021-01-01");
testOutput<typeof validator._TYPE, string>()(null);
});
test("textarea", () => { test("textarea", () => {
const value = Value.textarea({ const value = Value.textarea({
name: "Testing", name: "Testing",
@@ -79,7 +98,7 @@ describe("values", () => {
const value = Value.number({ const value = Value.number({
name: "Testing", name: "Testing",
required: false, required: false,
integral: false, integer: false,
}); });
const validator = value.validator(); const validator = value.validator();
validator.unsafeCast(2); validator.unsafeCast(2);
@@ -106,6 +125,7 @@ describe("values", () => {
a: "A", a: "A",
b: "B", b: "B",
}, },
default: [],
}); });
const validator = value.validator(); const validator = value.validator();
validator.unsafeCast([]); validator.unsafeCast([]);
@@ -118,7 +138,7 @@ describe("values", () => {
name: "Testing", name: "Testing",
}, },
Config.of({ Config.of({
a: Value.boolean({ a: Value.toggle({
name: "test", name: "test",
}), }),
}), }),
@@ -136,7 +156,7 @@ describe("values", () => {
Variants.of({ Variants.of({
a: { a: {
name: "a", name: "a",
spec: Config.of({ b: Value.boolean({ name: "b" }) }), spec: Config.of({ b: Value.toggle({ name: "b" }) }),
}, },
}), }),
); );
@@ -155,7 +175,7 @@ describe("values", () => {
name: "test", name: "test",
}, },
{ {
integral: false, integer: false,
}, },
), ),
); );
@@ -173,7 +193,7 @@ describe("Builder List", () => {
name: "test", name: "test",
}, },
{ {
spec: Config.of({ test: Value.boolean({ name: "test" }) }), spec: Config.of({ test: Value.toggle({ name: "test" }) }),
}, },
), ),
); );
@@ -181,13 +201,15 @@ describe("Builder List", () => {
validator.unsafeCast([{ test: true }]); validator.unsafeCast([{ test: true }]);
testOutput<typeof validator._TYPE, { test: boolean }[]>()(null); testOutput<typeof validator._TYPE, { test: boolean }[]>()(null);
}); });
test("string", () => { test("text", () => {
const value = Value.list( const value = Value.list(
List.string( List.text(
{ {
name: "test", name: "test",
}, },
{}, {
patterns: [],
},
), ),
); );
const validator = value.validator(); const validator = value.validator();
@@ -200,7 +222,7 @@ describe("Builder List", () => {
{ {
name: "test", name: "test",
}, },
{ integral: true }, { integer: true },
), ),
); );
const validator = value.validator(); const validator = value.validator();

View File

@@ -1,20 +1,16 @@
import { import { ListValueSpecOf, isValueSpecListOf } from "../config/configTypes";
ListValueSpecOf,
ValueSpecList,
isValueSpecListOf,
} from "../config/configTypes";
import { Config } from "../config/builder/config"; import { Config } from "../config/builder/config";
import { List } from "../config/builder/list"; import { List } from "../config/builder/list";
import { Value } from "../config/builder/value"; import { Value } from "../config/builder/value";
describe("Config Types", () => { describe("Config Types", () => {
test("isValueSpecListOf", () => { test("isValueSpecListOf", () => {
const options = [List.obj, List.string, List.number]; const options = [List.obj, List.text, List.number];
for (const option of options) { for (const option of options) {
const test = option({} as any, { spec: Config.of({}) } as any) as any; const test = option({} as any, { spec: Config.of({}) } as any) as any;
const someList = Value.list(test).build(); const someList = Value.list(test).build();
if (isValueSpecListOf(someList, "string")) { if (isValueSpecListOf(someList, "text")) {
someList.spec satisfies ListValueSpecOf<"string">; someList.spec satisfies ListValueSpecOf<"text">;
} else if (isValueSpecListOf(someList, "number")) { } else if (isValueSpecListOf(someList, "number")) {
someList.spec satisfies ListValueSpecOf<"number">; someList.spec satisfies ListValueSpecOf<"number">;
} else if (isValueSpecListOf(someList, "object")) { } else if (isValueSpecListOf(someList, "object")) {

View File

@@ -1,6 +1,6 @@
import { writeConvertedFile } from "../../scripts/oldSpecToBuilder"; import { writeConvertedFileFromOld } from "../../scripts/oldSpecToBuilder";
writeConvertedFile( writeConvertedFileFromOld(
"./lib/test/output.ts", // Make the location "./lib/test/output.ts", // Make the location
{ {
// Put the config here // Put the config here

View File

@@ -1,10 +1,10 @@
import { Parser } from "ts-matches";
import { import {
UnionSelectKey, UnionSelectKey,
unionSelectKey, unionSelectKey,
UnionValueKey, UnionValueKey,
unionValueKey, unionValueKey,
} from "../config/configTypes"; } from "../config/configTypes";
import { deepMerge } from "../util";
import { InputSpec, matchInputSpec, testListUnion } from "./output"; import { InputSpec, matchInputSpec, testListUnion } from "./output";
export type IfEquals<T, U, Y = unknown, N = never> = (<G>() => G extends T export type IfEquals<T, U, Y = unknown, N = never> = (<G>() => G extends T
@@ -16,42 +16,10 @@ export function testOutput<A, B>(): (c: IfEquals<A, B>) => null {
return () => null; return () => null;
} }
function isObject(item: unknown): item is object {
return !!(item && typeof item === "object" && !Array.isArray(item));
}
type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (
x: infer R,
) => any
? R
: never;
export function mergeDeep<A extends unknown[]>(...sources: A) {
return _mergeDeep({}, ...sources);
}
function _mergeDeep<A extends unknown[]>(
target: UnionToIntersection<A[number]> | {},
...sources: A
): UnionToIntersection<A[number]> | {} {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject((source as any)[key])) {
if (!(target as any)[key]) Object.assign(target, { [key]: {} });
_mergeDeep((target as any)[key], (source as any)[key]);
} else {
Object.assign(target, { [key]: (source as any)[key] });
}
}
}
return _mergeDeep(target, ...sources);
}
/// Testing the types of the input spec /// Testing the types of the input spec
testOutput<InputSpec["rpc"]["enable"], boolean>()(null);
// @ts-expect-error Because enable should be a boolean // @ts-expect-error Because enable should be a boolean
testOutput<InputSpec["rpc"]["enable"], string>()(null); testOutput<InputSpec["rpc"]["enable"], string>()(null);
testOutput<InputSpec["rpc"]["enable"], boolean>()(null);
testOutput<InputSpec["rpc"]["username"], string>()(null); testOutput<InputSpec["rpc"]["username"], string>()(null);
testOutput<InputSpec["rpc"]["advanced"]["auth"], string[]>()(null); testOutput<InputSpec["rpc"]["advanced"]["auth"], string[]>()(null);
@@ -136,19 +104,22 @@ describe("Inputs", () => {
const output = matchInputSpec.unsafeCast(validInput); const output = matchInputSpec.unsafeCast(validInput);
expect(output).toEqual(validInput); expect(output).toEqual(validInput);
}); });
test("test errors", () => { test("test no longer care about the conversion of min/max and validating", () => {
matchInputSpec.unsafeCast(
deepMerge({}, validInput, { rpc: { advanced: { threads: 0 } } }),
);
});
test("test errors should throw for number in string", () => {
expect(() => expect(() =>
matchInputSpec.unsafeCast( matchInputSpec.unsafeCast(
mergeDeep(validInput, { rpc: { advanced: { threads: 0 } } }), deepMerge({}, validInput, { rpc: { enable: 2 } }),
), ),
).toThrowError(); ).toThrowError();
expect(() => });
matchInputSpec.unsafeCast(mergeDeep(validInput, { rpc: { enable: 2 } })), test("Test that we set serialversion to something not segwit or non-segwit", () => {
).toThrowError();
expect(() => expect(() =>
matchInputSpec.unsafeCast( matchInputSpec.unsafeCast(
mergeDeep(validInput, { deepMerge({}, validInput, {
rpc: { advanced: { serialversion: "testing" } }, rpc: { advanced: { serialversion: "testing" } },
}), }),
), ),

View File

@@ -5,6 +5,7 @@ export function deepMerge(...args: unknown[]): unknown {
if (!object.test(lastItem)) return lastItem; if (!object.test(lastItem)) return lastItem;
const objects = args.filter(object.test).filter((x) => !Array.isArray(x)); const objects = args.filter(object.test).filter((x) => !Array.isArray(x));
if (objects.length === 0) return lastItem as any; if (objects.length === 0) return lastItem as any;
if (objects.length === 1) objects.unshift({});
const allKeys = new Set(objects.flatMap((x) => Object.keys(x))); const allKeys = new Set(objects.flatMap((x) => Object.keys(x)));
for (const key of allKeys) { for (const key of allKeys) {
const filteredValues = objects.flatMap((x) => const filteredValues = objects.flatMap((x) =>

View File

@@ -1,4 +1,4 @@
import { Parser, string } from "ts-matches"; import { Parser } from "ts-matches";
import * as T from "../types"; import * as T from "../types";
import FileHelper from "./fileHelper"; import FileHelper from "./fileHelper";
import nullIfEmpty from "./nullIfEmpty"; import nullIfEmpty from "./nullIfEmpty";

View File

@@ -19,14 +19,16 @@ const {
boolean, boolean,
} = matches; } = matches;
type TypeBoolean = "boolean"; type TypeToggle = "toggle";
type TypeString = "string"; type TypeText = "text";
type TypeTextarea = "textarea"; type TypeTextarea = "textarea";
type TypeNumber = "number"; type TypeNumber = "number";
type TypeObject = "object"; type TypeObject = "object";
type TypeList = "list"; type TypeList = "list";
type TypeSelect = "select"; type TypeSelect = "select";
type TypeMultiselect = "multiselect"; type TypeMultiselect = "multiselect";
type TypeColor = "color";
type TypeDatetime = "datetime";
type TypeUnion = "union"; type TypeUnion = "union";
// prettier-ignore // prettier-ignore
@@ -41,19 +43,17 @@ type GuardNumber<A> =
A extends { type: TypeNumber } ? GuardDefaultRequired<A, number> : A extends { type: TypeNumber } ? GuardDefaultRequired<A, number> :
unknown unknown
// prettier-ignore // prettier-ignore
type GuardString<A> = type GuardText<A> =
A extends { type: TypeString } ? GuardDefaultRequired<A, string> : A extends { type: TypeText } ? GuardDefaultRequired<A, string> :
unknown unknown
// prettier-ignore // prettier-ignore
type GuardTextarea<A> = type GuardTextarea<A> =
A extends { type: TypeTextarea } ? GuardDefaultRequired<A, string> : A extends { type: TypeTextarea } ? GuardDefaultRequired<A, string> :
unknown unknown
// prettier-ignore // prettier-ignore
type GuardBoolean<A> = type GuardToggle<A> =
A extends { type: TypeBoolean } ? GuardDefaultRequired<A, boolean> : A extends { type: TypeToggle } ? GuardDefaultRequired<A, boolean> :
unknown unknown
// prettier-ignore // prettier-ignore
type GuardObject<A> = type GuardObject<A> =
A extends { type: TypeObject, spec: infer B } ? ( A extends { type: TypeObject, spec: infer B } ? (
@@ -72,11 +72,18 @@ type GuardSelect<A> =
B extends Record<string, string> ? keyof B : never B extends Record<string, string> ? keyof B : never
) : ) :
unknown unknown
// prettier-ignore // prettier-ignore
type GuardMultiselect<A> = type GuardMultiselect<A> =
A extends { type: TypeMultiselect, values: infer B} ?(keyof B)[] : A extends { type: TypeMultiselect, values: infer B} ?(keyof B)[] :
unknown unknown
// prettier-ignore
type GuardColor<A> =
A extends { type: TypeColor } ? GuardDefaultRequired<A, string> :
unknown
// prettier-ignore
type GuardDatetime<A> =
A extends { type: TypeDatetime } ? GuardDefaultRequired<A, string> :
unknown
// prettier-ignore // prettier-ignore
type VariantValue<A> = type VariantValue<A> =
@@ -91,14 +98,16 @@ type GuardUnion<A> =
type _<T> = T; type _<T> = T;
export type GuardAll<A> = GuardNumber<A> & export type GuardAll<A> = GuardNumber<A> &
GuardString<A> & GuardText<A> &
GuardTextarea<A> & GuardTextarea<A> &
GuardBoolean<A> & GuardToggle<A> &
GuardObject<A> & GuardObject<A> &
GuardList<A> & GuardList<A> &
GuardUnion<A> & GuardUnion<A> &
GuardSelect<A> & GuardSelect<A> &
GuardMultiselect<A>; GuardMultiselect<A> &
GuardColor<A> &
GuardDatetime<A>;
// prettier-ignore // prettier-ignore
export type TypeFromProps<A> = export type TypeFromProps<A> =
A extends Record<string, unknown> ? { [K in keyof A & string]: _<GuardAll<A[K]>> } : A extends Record<string, unknown> ? { [K in keyof A & string]: _<GuardAll<A[K]>> } :
@@ -112,9 +121,7 @@ const matchVariant = object({
const recordString = dictionary([string, unknown]); const recordString = dictionary([string, unknown]);
const matchDefault = object({ default: unknown }); const matchDefault = object({ default: unknown });
const matchRequired = object({ required: literals(false) }); const matchRequired = object({ required: literals(false) });
const rangeRegex = /(\[|\()(\*|(\d|\.)+),(\*|(\d|\.)+)(\]|\))/; const matchInteger = object({ integer: literals(true) });
const matchRange = object({ range: string });
const matchIntegral = object({ integral: literals(true) });
const matchSpec = object({ spec: recordString }); const matchSpec = object({ spec: recordString });
const matchUnion = object({ const matchUnion = object({
variants: dictionary([string, matchVariant]), variants: dictionary([string, matchVariant]),
@@ -123,107 +130,13 @@ const matchValues = object({
values: dictionary([string, string]), values: dictionary([string, string]),
}); });
function charRange(value = "") { function withInteger(parser: Parser<unknown, number>, value: unknown) {
const split = value if (matchInteger.test(value)) {
.split("-")
.filter(Boolean)
.map((x) => x.charCodeAt(0));
if (split.length < 1) return null;
if (split.length === 1) return [split[0], split[0]];
return [split[0], split[1]];
}
/**
* @param generate.charset Pattern like "a-z" or "a-z,1-5"
* @param generate.len Length to make random variable
* @param param1
* @returns
*/
export function generateDefault(
generate: { charset: string; len: number },
{ random = () => Math.random() } = {},
) {
const validCharSets: number[][] = generate.charset
.split(",")
.map(charRange)
.filter(Array.isArray);
if (validCharSets.length === 0) {
throw new Error("Expecing that we have a valid charset");
}
const max = validCharSets.reduce(
(acc, x) => x.reduce((x, y) => Math.max(x, y), acc),
0,
);
let i = 0;
const answer: string[] = Array(generate.len);
while (i < generate.len) {
const nextValue = Math.round(random() * max);
const inRange = validCharSets.reduce(
(acc, [lower, upper]) =>
acc || (nextValue >= lower && nextValue <= upper),
false,
);
if (!inRange) continue;
answer[i] = String.fromCharCode(nextValue);
i++;
}
return answer.join("");
}
export function matchNumberWithRange(range: string) {
const matched = rangeRegex.exec(range);
if (!matched) return number;
const [, left, leftValue, , rightValue, , right] = matched;
return number
.validate(
leftValue === "*"
? (_) => true
: left === "["
? (x) => x >= Number(leftValue)
: (x) => x > Number(leftValue),
leftValue === "*"
? "any"
: left === "["
? `greaterThanOrEqualTo${leftValue}`
: `greaterThan${leftValue}`,
)
.validate(
// prettier-ignore
rightValue === "*" ? (_) => true :
right === "]" ? (x) => x <= Number(rightValue) :
(x) => x < Number(rightValue),
// prettier-ignore
rightValue === "*" ? "any" :
right === "]" ? `lessThanOrEqualTo${rightValue}` :
`lessThan${rightValue}`,
);
}
function withIntegral(parser: Parser<unknown, number>, value: unknown) {
if (matchIntegral.test(value)) {
return parser.validate(Number.isInteger, "isIntegral"); return parser.validate(Number.isInteger, "isIntegral");
} }
return parser; return parser;
} }
function withRange(value: unknown) { function requiredParser<A>(parser: Parser<unknown, A>, value: unknown) {
if (matchRange.test(value)) {
return matchNumberWithRange(value.range);
}
return number;
}
const isGenerator = object({
charset: string,
len: number,
}).test;
function defaultRequired<A>(parser: Parser<unknown, A>, value: unknown) {
if (matchDefault.test(value)) {
if (isGenerator(value.default)) {
return parser.defaultTo(
parser.unsafeCast(generateDefault(value.default)),
);
}
return parser.defaultTo(value.default);
}
if (!matchRequired.test(value)) return parser.optional(); if (!matchRequired.test(value)) return parser.optional();
return parser; return parser;
} }
@@ -243,44 +156,42 @@ export function guardAll<A extends ValueSpecAny>(
return unknown as any; return unknown as any;
} }
switch (value.type) { switch (value.type) {
case "boolean": case "toggle":
return defaultRequired(boolean, value) as any; return requiredParser(boolean, value) as any;
case "string": case "text":
return defaultRequired(string, value) as any; return requiredParser(string, value) as any;
case "textarea": case "textarea":
return defaultRequired(string, value) as any; return requiredParser(string, value) as any;
case "color":
return requiredParser(string, value) as any;
case "datetime":
return requiredParser(string, value) as any;
case "number": case "number":
return defaultRequired( return requiredParser(withInteger(number, value), value) as any;
withIntegral(withRange(value), value),
value,
) as any;
case "object": case "object":
if (matchSpec.test(value)) { if (matchSpec.test(value)) {
return defaultRequired(typeFromProps(value.spec), value) as any; return requiredParser(typeFromProps(value.spec), value) as any;
} }
return unknown as any; return unknown as any;
case "list": { case "list": {
const spec = (matchSpec.test(value) && value.spec) || {}; const spec = (matchSpec.test(value) && value.spec) || {};
const rangeValidate =
(matchRange.test(value) && matchNumberWithRange(value.range).test) ||
(() => true);
return defaultRequired( return requiredParser(
matches matches.arrayOf(guardAll(spec as any)),
.arrayOf(guardAll(spec as any))
.validate((x) => rangeValidate(x.length), "valid length"),
value, value,
) as any; ) as any;
} }
case "select": case "select":
if (matchValues.test(value)) { if (matchValues.test(value)) {
const valueKeys = Object.keys(value.values); const valueKeys = Object.keys(value.values);
return defaultRequired( return requiredParser(
literals(valueKeys[0], ...valueKeys), literals(valueKeys[0], ...valueKeys),
value, value,
) as any; ) as any;
@@ -289,19 +200,9 @@ export function guardAll<A extends ValueSpecAny>(
case "multiselect": case "multiselect":
if (matchValues.test(value)) { if (matchValues.test(value)) {
const maybeAddRangeValidate = <X extends Validator<unknown, B[]>, B>(
x: X,
) => {
if (!matchRange.test(value)) return x;
return x.validate(
(x) => matchNumberWithRange(value.range).test(x.length),
"validLength",
);
};
const valueKeys = Object.keys(value.values); const valueKeys = Object.keys(value.values);
return defaultRequired( return requiredParser(
maybeAddRangeValidate(arrayOf(literals(valueKeys[0], ...valueKeys))), arrayOf(literals(valueKeys[0], ...valueKeys)),
value, value,
) as any; ) as any;
} }

View File

@@ -1,19 +1,20 @@
import camelCase from "lodash/camelCase"; import camelCase from "lodash/camelCase";
import * as fs from "fs"; import * as fs from "fs";
import { string } from "ts-matches"; import { string } from "ts-matches";
import { unionSelectKey } from "../lib/config/configTypes";
export async function writeConvertedFile( export async function writeConvertedFileFromOld(
file: string, file: string,
inputData: Promise<any> | any, inputData: Promise<any> | any,
options: Parameters<typeof makeFileContent>[1], options: Parameters<typeof makeFileContentFromOld>[1],
) { ) {
await fs.writeFile(file, await makeFileContent(inputData, options), (err) => await fs.writeFile(
console.error(err), file,
await makeFileContentFromOld(inputData, options),
(err) => console.error(err),
); );
} }
export default async function makeFileContent( export default async function makeFileContentFromOld(
inputData: Promise<any> | any, inputData: Promise<any> | any,
{ startSdk = "start-sdk" } = {}, { startSdk = "start-sdk" } = {},
) { ) {
@@ -53,7 +54,9 @@ export default async function makeFileContent(
switch (value.type) { switch (value.type) {
case "string": { case "string": {
if (value.textarea) { if (value.textarea) {
return `Value.textarea(${JSON.stringify( return `${rangeToTodoComment(
value?.range,
)}Value.textarea(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
description: value.description || null, description: value.description || null,
@@ -65,7 +68,7 @@ export default async function makeFileContent(
2, 2,
)})`; )})`;
} }
return `Value.string(${JSON.stringify( return `${rangeToTodoComment(value?.range)}Value.text(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
default: value.default || null, default: value.default || null,
@@ -74,23 +77,35 @@ export default async function makeFileContent(
required: !(value.nullable || false), required: !(value.nullable || false),
masked: value.masked || false, masked: value.masked || false,
placeholder: value.placeholder || null, placeholder: value.placeholder || null,
pattern: value.pattern || null, patterns: value.pattern
patternDescription: value["pattern-description"] || null, ? [
{
regex: value.pattern,
description: value["pattern-description"],
},
]
: [],
minLength: null,
maxLength: null,
}, },
null, null,
2, 2,
)})`; )})`;
} }
case "number": { case "number": {
return `Value.number(${JSON.stringify( return `${rangeToTodoComment(
value?.range,
)}Value.number(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
default: value.default || null, default: value.default || null,
description: value.description || null, description: value.description || null,
warning: value.warning || null, warning: value.warning || null,
required: !(value.nullable || false), required: !(value.nullable || false),
range: value.range || null, min: null,
integral: value.integral || false, max: null,
step: null,
integer: value.integral || false,
units: value.units || null, units: value.units || null,
placeholder: value.placeholder || null, placeholder: value.placeholder || null,
}, },
@@ -99,7 +114,7 @@ export default async function makeFileContent(
)})`; )})`;
} }
case "boolean": { case "boolean": {
return `Value.boolean(${JSON.stringify( return `Value.toggle(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
default: value.default || false, default: value.default || false,
@@ -172,12 +187,11 @@ export default async function makeFileContent(
function convertList(value: any) { function convertList(value: any) {
switch (value.subtype) { switch (value.subtype) {
case "string": { case "string": {
return `List.${ return `${rangeToTodoComment(value?.range)}List.text(${JSON.stringify(
value?.spec?.textarea === true ? "textarea" : "string"
}(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
range: value.range || null, minLength: null,
maxLength: null,
default: value.default || null, default: value.default || null,
description: value.description || null, description: value.description || null,
warning: value.warning || null, warning: value.warning || null,
@@ -187,15 +201,24 @@ export default async function makeFileContent(
)}, ${JSON.stringify({ )}, ${JSON.stringify({
masked: value?.spec?.masked || false, masked: value?.spec?.masked || false,
placeholder: value?.spec?.placeholder || null, placeholder: value?.spec?.placeholder || null,
pattern: value?.spec?.pattern || null, patterns: value?.spec?.pattern
patternDescription: value?.spec?.["pattern-description"] || null, ? [
{
regex: value.spec.pattern,
description: value?.spec?.["pattern-description"],
},
]
: [],
minLength: null,
maxLength: null,
})})`; })})`;
} }
case "number": { case "number": {
return `List.number(${JSON.stringify( return `${rangeToTodoComment(value?.range)}List.number(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
range: value.range || null, minLength: null,
maxLength: null,
default: value.default || null, default: value.default || null,
description: value.description || null, description: value.description || null,
warning: value.warning || null, warning: value.warning || null,
@@ -203,8 +226,9 @@ export default async function makeFileContent(
null, null,
2, 2,
)}, ${JSON.stringify({ )}, ${JSON.stringify({
range: value?.spec?.range || null, integer: value?.spec?.integral || false,
integral: value?.spec?.integral || false, min: null,
max: null,
units: value?.spec?.units || null, units: value?.spec?.units || null,
placeholder: value?.spec?.placeholder || null, placeholder: value?.spec?.placeholder || null,
})})`; })})`;
@@ -222,10 +246,13 @@ export default async function makeFileContent(
value?.spec?.["value-names"]?.[key] || key, value?.spec?.["value-names"]?.[key] || key,
]), ]),
); );
return `Value.multiselect(${JSON.stringify( return `${rangeToTodoComment(
value?.range,
)}Value.multiselect(${JSON.stringify(
{ {
name: value.name || null, name: value.name || null,
range: value.range || null, minLength: null,
maxLength: null,
default: value.default || null, default: value.default || null,
description: value.description || null, description: value.description || null,
warning: value.warning || null, warning: value.warning || null,
@@ -240,9 +267,10 @@ export default async function makeFileContent(
value.name + "_spec", value.name + "_spec",
convertInputSpec(value.spec.spec), convertInputSpec(value.spec.spec),
); );
return `List.obj({ return `${rangeToTodoComment(value?.range)}List.obj({
name: ${JSON.stringify(value.name || null)}, name: ${JSON.stringify(value.name || null)},
range: ${JSON.stringify(value.range || null)}, minLength: ${JSON.stringify(null)},
maxLength: ${JSON.stringify(null)},
default: ${JSON.stringify(value.default || null)}, default: ${JSON.stringify(value.default || null)},
description: ${JSON.stringify(value.description || null)}, description: ${JSON.stringify(value.description || null)},
warning: ${JSON.stringify(value.warning || null)}, warning: ${JSON.stringify(value.warning || null)},
@@ -262,7 +290,7 @@ export default async function makeFileContent(
); );
const unionValueName = newConst( const unionValueName = newConst(
value.name + "_union", value.name + "_union",
` `${rangeToTodoComment(value?.range)}
Value.union({ Value.union({
name: ${JSON.stringify(value?.spec?.tag?.name || null)}, name: ${JSON.stringify(value?.spec?.tag?.name || null)},
description: ${JSON.stringify( description: ${JSON.stringify(
@@ -282,9 +310,10 @@ export default async function makeFileContent(
}) })
`, `,
); );
return `List.obj({ return `${rangeToTodoComment(value?.range)}List.obj({
name:${JSON.stringify(value.name || null)}, name:${JSON.stringify(value.name || null)},
range:${JSON.stringify(value.range || null)}, minLength:${JSON.stringify(null)},
maxLength:${JSON.stringify(null)},
default: [], default: [],
description: ${JSON.stringify(value.description || null)}, description: ${JSON.stringify(value.description || null)},
warning: ${JSON.stringify(value.warning || null)}, warning: ${JSON.stringify(value.warning || null)},
@@ -321,3 +350,8 @@ export default async function makeFileContent(
return newName; return newName;
} }
} }
function rangeToTodoComment(range: string | undefined) {
if (!range) return "";
return `/* TODO: Convert range for this value (${range})*/`;
}