mirror of
https://github.com/Start9Labs/start-sdk.git
synced 2026-03-26 02:11:56 +00:00
chore: Add tests and fix tests. Remove validation for types not seeable
This commit is contained in:
@@ -41,7 +41,7 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
|
|||||||
maxLength?: number | null;
|
maxLength?: number | null;
|
||||||
patterns: Pattern[];
|
patterns: Pattern[];
|
||||||
/** Default = "text" */
|
/** Default = "text" */
|
||||||
inputmode?: ListValueSpecText["inputmode"];
|
inputMode?: ListValueSpecText["inputMode"];
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const spec = {
|
const spec = {
|
||||||
@@ -50,7 +50,7 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
|
|||||||
minLength: null,
|
minLength: null,
|
||||||
maxLength: null,
|
maxLength: null,
|
||||||
masked: false,
|
masked: false,
|
||||||
inputmode: "text" as const,
|
inputMode: "text" as const,
|
||||||
...aSpec,
|
...aSpec,
|
||||||
};
|
};
|
||||||
return new List({
|
return new List({
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
|
|||||||
maxLength?: number | null;
|
maxLength?: number | null;
|
||||||
patterns?: Pattern[];
|
patterns?: Pattern[];
|
||||||
/** Default = 'text' */
|
/** Default = 'text' */
|
||||||
inputmode?: ValueSpecText["inputmode"];
|
inputMode?: ValueSpecText["inputMode"];
|
||||||
}) {
|
}) {
|
||||||
return new Value({
|
return new Value({
|
||||||
type: "text" as const,
|
type: "text" as const,
|
||||||
@@ -77,7 +77,7 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
|
|||||||
minLength: null,
|
minLength: null,
|
||||||
maxLength: null,
|
maxLength: null,
|
||||||
patterns: [],
|
patterns: [],
|
||||||
inputmode: "text",
|
inputMode: "text",
|
||||||
...a,
|
...a,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -148,17 +148,17 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
|
|||||||
warning?: string | null;
|
warning?: string | null;
|
||||||
required: boolean;
|
required: boolean;
|
||||||
/** Default = 'datetime-local' */
|
/** Default = 'datetime-local' */
|
||||||
inputMode?: ValueSpecDatetime['inputMode']
|
inputMode?: ValueSpecDatetime["inputMode"];
|
||||||
min?: string | null
|
min?: string | null;
|
||||||
max?: string | null
|
max?: string | null;
|
||||||
step?: string | null
|
step?: string | null;
|
||||||
default?: number | null;
|
default?: number | null;
|
||||||
}) {
|
}) {
|
||||||
return new Value({
|
return new Value({
|
||||||
type: "datetime" as const,
|
type: "datetime" as const,
|
||||||
description: null,
|
description: null,
|
||||||
warning: null,
|
warning: null,
|
||||||
inputMode: 'datetime-local',
|
inputMode: "datetime-local",
|
||||||
min: null,
|
min: null,
|
||||||
max: null,
|
max: null,
|
||||||
step: null,
|
step: null,
|
||||||
|
|||||||
@@ -56,17 +56,17 @@ export interface ValueSpecNumber extends ListValueSpecNumber, WithStandalone {
|
|||||||
default: number | null;
|
default: number | null;
|
||||||
}
|
}
|
||||||
export interface ValueSpecColor extends WithStandalone {
|
export interface ValueSpecColor extends WithStandalone {
|
||||||
type: "color"
|
type: "color";
|
||||||
required: boolean;
|
required: boolean;
|
||||||
default: string | null;
|
default: string | null;
|
||||||
}
|
}
|
||||||
export interface ValueSpecDatetime extends WithStandalone {
|
export interface ValueSpecDatetime extends WithStandalone {
|
||||||
type: "datetime"
|
type: "datetime";
|
||||||
required: boolean;
|
required: boolean;
|
||||||
inputMode: 'date' | 'time' | 'datetime-local'
|
inputMode: "date" | "time" | "datetime-local";
|
||||||
min: string | null
|
min: string | null;
|
||||||
max: string | null
|
max: string | null;
|
||||||
step: string | null
|
step: string | null;
|
||||||
default: string | null;
|
default: string | null;
|
||||||
}
|
}
|
||||||
export interface ValueSpecSelect extends SelectBase, WithStandalone {
|
export interface ValueSpecSelect extends SelectBase, WithStandalone {
|
||||||
@@ -141,16 +141,16 @@ export interface ValueSpecListOf<T extends ListValueSpecType>
|
|||||||
| readonly Record<string, unknown>[];
|
| readonly Record<string, unknown>[];
|
||||||
}
|
}
|
||||||
export interface Pattern {
|
export interface Pattern {
|
||||||
regex: string
|
regex: string;
|
||||||
description: string
|
description: string;
|
||||||
}
|
}
|
||||||
export interface ListValueSpecText {
|
export interface ListValueSpecText {
|
||||||
type: "text";
|
type: "text";
|
||||||
patterns: Pattern[]
|
patterns: Pattern[];
|
||||||
minLength: number | null
|
minLength: number | null;
|
||||||
maxLength: 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 {
|
||||||
|
|||||||
@@ -1,10 +1,5 @@
|
|||||||
import { Config } from "./builder";
|
import { Config } from "./builder";
|
||||||
import {
|
import { DeepPartial, Dependencies, Effects, ExpectedExports } from "../types";
|
||||||
DeepPartial,
|
|
||||||
Dependencies,
|
|
||||||
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";
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ export async function specToBuilder(
|
|||||||
masked: spec?.masked || false,
|
masked: spec?.masked || false,
|
||||||
placeholder: spec?.placeholder || null,
|
placeholder: spec?.placeholder || null,
|
||||||
pattern: spec?.patterns || [],
|
pattern: spec?.patterns || [],
|
||||||
inputMode: spec?.inputmode || 'text',
|
inputMode: spec?.inputMode || "text",
|
||||||
})})`;
|
})})`;
|
||||||
}
|
}
|
||||||
case "number": {
|
case "number": {
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ describe("builder tests", () => {
|
|||||||
"minLength": null,
|
"minLength": null,
|
||||||
"maxLength": null,
|
"maxLength": null,
|
||||||
"patterns": [],
|
"patterns": [],
|
||||||
"inputmode":"text",
|
"inputMode":"text",
|
||||||
"name": "Peer tor address",
|
"name": "Peer tor address",
|
||||||
"required": true
|
"required": true
|
||||||
}}`
|
}}`
|
||||||
@@ -67,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",
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
import {
|
import { ListValueSpecOf, isValueSpecListOf } from "../config/configTypes";
|
||||||
ListValueSpecOf,
|
|
||||||
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";
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
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
|
||||||
@@ -15,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);
|
||||||
@@ -135,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" } },
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -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) =>
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ unknown
|
|||||||
type GuardColor<A> =
|
type GuardColor<A> =
|
||||||
A extends { type: TypeColor } ? GuardDefaultRequired<A, string> :
|
A extends { type: TypeColor } ? GuardDefaultRequired<A, string> :
|
||||||
unknown
|
unknown
|
||||||
// prettier-ignore
|
// prettier-ignore
|
||||||
type GuardDatetime<A> =
|
type GuardDatetime<A> =
|
||||||
A extends { type: TypeDatetime } ? GuardDefaultRequired<A, string> :
|
A extends { type: TypeDatetime } ? GuardDefaultRequired<A, string> :
|
||||||
unknown
|
unknown
|
||||||
@@ -121,8 +121,6 @@ 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 matchRange = object({ range: string });
|
|
||||||
const matchInteger = object({ integer: literals(true) });
|
const matchInteger = object({ integer: literals(true) });
|
||||||
const matchSpec = object({ spec: recordString });
|
const matchSpec = object({ spec: recordString });
|
||||||
const matchUnion = object({
|
const matchUnion = object({
|
||||||
@@ -132,107 +130,13 @@ const matchValues = object({
|
|||||||
values: dictionary([string, string]),
|
values: dictionary([string, string]),
|
||||||
});
|
});
|
||||||
|
|
||||||
function charRange(value = "") {
|
|
||||||
const split = 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 withInteger(parser: Parser<unknown, number>, value: unknown) {
|
function withInteger(parser: Parser<unknown, number>, value: unknown) {
|
||||||
if (matchInteger.test(value)) {
|
if (matchInteger.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;
|
||||||
}
|
}
|
||||||
@@ -253,49 +157,41 @@ export function guardAll<A extends ValueSpecAny>(
|
|||||||
}
|
}
|
||||||
switch (value.type) {
|
switch (value.type) {
|
||||||
case "toggle":
|
case "toggle":
|
||||||
return defaultRequired(boolean, value) as any;
|
return requiredParser(boolean, value) as any;
|
||||||
|
|
||||||
case "text":
|
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":
|
case "color":
|
||||||
return defaultRequired(string, value) as any;
|
return requiredParser(string, value) as any;
|
||||||
|
|
||||||
case "datetime":
|
case "datetime":
|
||||||
return defaultRequired(string, value) as any;
|
return requiredParser(string, value) as any;
|
||||||
|
|
||||||
case "number":
|
case "number":
|
||||||
return defaultRequired(
|
return requiredParser(withInteger(number, value), value) as any;
|
||||||
withInteger(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;
|
||||||
@@ -304,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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,19 @@ 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";
|
||||||
|
|
||||||
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" } = {},
|
||||||
) {
|
) {
|
||||||
@@ -52,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,
|
||||||
@@ -64,7 +68,7 @@ export default async function makeFileContent(
|
|||||||
2,
|
2,
|
||||||
)})`;
|
)})`;
|
||||||
}
|
}
|
||||||
return `Value.text(${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,
|
||||||
@@ -73,9 +77,14 @@ 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,
|
||||||
patterns: value.pattern ?
|
patterns: value.pattern
|
||||||
[{ regex: value.pattern, description: value["pattern-description"] }] :
|
? [
|
||||||
[],
|
{
|
||||||
|
regex: value.pattern,
|
||||||
|
description: value["pattern-description"],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
minLength: null,
|
minLength: null,
|
||||||
maxLength: null,
|
maxLength: null,
|
||||||
},
|
},
|
||||||
@@ -84,7 +93,9 @@ export default async function makeFileContent(
|
|||||||
)})`;
|
)})`;
|
||||||
}
|
}
|
||||||
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,
|
||||||
@@ -176,7 +187,7 @@ 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.text(${JSON.stringify(
|
return `${rangeToTodoComment(value?.range)}List.text(${JSON.stringify(
|
||||||
{
|
{
|
||||||
name: value.name || null,
|
name: value.name || null,
|
||||||
minLength: null,
|
minLength: null,
|
||||||
@@ -190,15 +201,20 @@ 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,
|
||||||
patterns: value?.spec?.pattern ?
|
patterns: value?.spec?.pattern
|
||||||
[{ regex: value.spec.pattern, description: value?.spec?.["pattern-description"] }] :
|
? [
|
||||||
[],
|
{
|
||||||
|
regex: value.spec.pattern,
|
||||||
|
description: value?.spec?.["pattern-description"],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
minLength: null,
|
minLength: null,
|
||||||
maxLength: 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,
|
||||||
minLength: null,
|
minLength: null,
|
||||||
@@ -230,7 +246,9 @@ 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,
|
||||||
minLength: null,
|
minLength: null,
|
||||||
@@ -249,7 +267,7 @@ 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)},
|
||||||
minLength: ${JSON.stringify(null)},
|
minLength: ${JSON.stringify(null)},
|
||||||
maxLength: ${JSON.stringify(null)},
|
maxLength: ${JSON.stringify(null)},
|
||||||
@@ -272,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(
|
||||||
@@ -292,7 +310,7 @@ 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)},
|
||||||
minLength:${JSON.stringify(null)},
|
minLength:${JSON.stringify(null)},
|
||||||
maxLength:${JSON.stringify(null)},
|
maxLength:${JSON.stringify(null)},
|
||||||
@@ -332,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})*/`;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user