mirror of
https://github.com/Start9Labs/start-os.git
synced 2026-03-30 20:14:49 +00:00
chore: migrate from ts-matches to zod across all TypeScript packages
This commit is contained in:
@@ -1,12 +1,12 @@
|
||||
PACKAGE_TS_FILES := $(shell git ls-files package/lib) package/lib/test/output.ts
|
||||
BASE_TS_FILES := $(shell git ls-files base/lib) package/lib/test/output.ts
|
||||
PACKAGE_TS_FILES := $(shell git ls-files package/lib)
|
||||
BASE_TS_FILES := $(shell git ls-files base/lib)
|
||||
version = $(shell git tag --sort=committerdate | tail -1)
|
||||
|
||||
.PHONY: test base/test package/test clean bundle fmt buildOutput check
|
||||
|
||||
all: bundle
|
||||
|
||||
package/test: $(PACKAGE_TS_FILES) package/lib/test/output.ts package/node_modules base/node_modules
|
||||
package/test: $(PACKAGE_TS_FILES) package/node_modules base/node_modules
|
||||
cd package && npm test
|
||||
|
||||
base/test: $(BASE_TS_FILES) base/node_modules
|
||||
@@ -21,9 +21,6 @@ clean:
|
||||
rm -f package/lib/test/output.ts
|
||||
rm -rf package/node_modules
|
||||
|
||||
package/lib/test/output.ts: package/node_modules package/lib/test/makeOutput.ts package/scripts/oldSpecToBuilder.ts
|
||||
cd package && npm run buildOutput
|
||||
|
||||
bundle: baseDist dist | test fmt
|
||||
touch dist
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ValueSpec } from '../inputSpecTypes'
|
||||
import { Value } from './value'
|
||||
import { _ } from '../../../util'
|
||||
import { Effects } from '../../../Effects'
|
||||
import { Parser, object } from 'ts-matches'
|
||||
import { z } from 'zod'
|
||||
import { DeepPartial } from '../../../types'
|
||||
import { InputSpecTools, createInputSpecTools } from './inputSpecTools'
|
||||
|
||||
@@ -96,7 +96,7 @@ export class InputSpec<
|
||||
private readonly spec: {
|
||||
[K in keyof Type]: Value<Type[K]>
|
||||
},
|
||||
public readonly validator: Parser<unknown, StaticValidatedAs>,
|
||||
public readonly validator: z.ZodType<StaticValidatedAs>,
|
||||
) {}
|
||||
public _TYPE: Type = null as any as Type
|
||||
public _PARTIAL: DeepPartial<Type> = null as any as DeepPartial<Type>
|
||||
@@ -104,13 +104,13 @@ export class InputSpec<
|
||||
spec: {
|
||||
[K in keyof Type]: ValueSpec
|
||||
}
|
||||
validator: Parser<unknown, Type>
|
||||
validator: z.ZodType<Type>
|
||||
}> {
|
||||
const answer = {} as {
|
||||
[K in keyof Type]: ValueSpec
|
||||
}
|
||||
const validator = {} as {
|
||||
[K in keyof Type]: Parser<unknown, any>
|
||||
[K in keyof Type]: z.ZodType<any>
|
||||
}
|
||||
for (const k in this.spec) {
|
||||
const built = await this.spec[k].build(options as any)
|
||||
@@ -119,7 +119,7 @@ export class InputSpec<
|
||||
}
|
||||
return {
|
||||
spec: answer,
|
||||
validator: object(validator) as any,
|
||||
validator: z.object(validator) as any,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ export class InputSpec<
|
||||
const value =
|
||||
build instanceof Function ? build(createInputSpecTools<Type>()) : build
|
||||
const newSpec = { ...this.spec, [key]: value } as any
|
||||
const newValidator = object(
|
||||
const newValidator = z.object(
|
||||
Object.fromEntries(
|
||||
Object.entries(newSpec).map(([k, v]) => [
|
||||
k,
|
||||
@@ -163,7 +163,7 @@ export class InputSpec<
|
||||
const addedValues =
|
||||
build instanceof Function ? build(createInputSpecTools<Type>()) : build
|
||||
const newSpec = { ...this.spec, ...addedValues } as any
|
||||
const newValidator = object(
|
||||
const newValidator = z.object(
|
||||
Object.fromEntries(
|
||||
Object.entries(newSpec).map(([k, v]) => [
|
||||
k,
|
||||
@@ -175,7 +175,7 @@ export class InputSpec<
|
||||
}
|
||||
|
||||
static of<Spec extends Record<string, Value<any, any>>>(spec: Spec) {
|
||||
const validator = object(
|
||||
const validator = z.object(
|
||||
Object.fromEntries(
|
||||
Object.entries(spec).map(([k, v]) => [k, v.validator]),
|
||||
),
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
ValueSpecText,
|
||||
} from '../inputSpecTypes'
|
||||
import { DefaultString } from '../inputSpecTypes'
|
||||
import { Parser } from 'ts-matches'
|
||||
import { z } from 'zod'
|
||||
import { ListValueSpecText } from '../inputSpecTypes'
|
||||
|
||||
export interface InputSpecTools<OuterType> {
|
||||
@@ -224,7 +224,7 @@ export interface BoundValue<OuterType> {
|
||||
},
|
||||
OuterType
|
||||
>,
|
||||
validator: Parser<unknown, UnionResStaticValidatedAs<StaticVariantValues>>,
|
||||
validator: z.ZodType<UnionResStaticValidatedAs<StaticVariantValues>>,
|
||||
): Value<
|
||||
UnionRes<VariantValues>,
|
||||
UnionResStaticValidatedAs<StaticVariantValues>,
|
||||
@@ -232,7 +232,7 @@ export interface BoundValue<OuterType> {
|
||||
>
|
||||
|
||||
dynamicHidden<T>(
|
||||
getParser: LazyBuild<Parser<unknown, T>, OuterType>,
|
||||
getParser: LazyBuild<z.ZodType<T>, OuterType>,
|
||||
): Value<T, T, OuterType>
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
ValueSpecList,
|
||||
ValueSpecListOf,
|
||||
} from '../inputSpecTypes'
|
||||
import { Parser, arrayOf, string } from 'ts-matches'
|
||||
import { z } from 'zod'
|
||||
|
||||
export class List<
|
||||
Type extends StaticValidatedAs,
|
||||
@@ -18,11 +18,11 @@ export class List<
|
||||
public build: LazyBuild<
|
||||
{
|
||||
spec: ValueSpecList
|
||||
validator: Parser<unknown, Type>
|
||||
validator: z.ZodType<Type>
|
||||
},
|
||||
OuterType
|
||||
>,
|
||||
public readonly validator: Parser<unknown, StaticValidatedAs>,
|
||||
public readonly validator: z.ZodType<StaticValidatedAs>,
|
||||
) {}
|
||||
readonly _TYPE: Type = null as any
|
||||
|
||||
@@ -69,7 +69,7 @@ export class List<
|
||||
generate?: null | RandomString
|
||||
},
|
||||
) {
|
||||
const validator = arrayOf(string)
|
||||
const validator = z.array(z.string())
|
||||
return new List<string[]>(() => {
|
||||
const spec = {
|
||||
type: 'text' as const,
|
||||
@@ -120,7 +120,7 @@ export class List<
|
||||
OuterType
|
||||
>,
|
||||
) {
|
||||
const validator = arrayOf(string)
|
||||
const validator = z.array(z.string())
|
||||
return new List<string[], string[], OuterType>(async (options) => {
|
||||
const { spec: aSpec, ...a } = await getA(options)
|
||||
const spec = {
|
||||
@@ -193,8 +193,8 @@ export class List<
|
||||
disabled: false,
|
||||
...value,
|
||||
},
|
||||
validator: arrayOf(built.validator),
|
||||
validator: z.array(built.validator),
|
||||
}
|
||||
}, arrayOf(aSpec.spec.validator))
|
||||
}, z.array(aSpec.spec.validator))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,37 +12,27 @@ import {
|
||||
} from '../inputSpecTypes'
|
||||
import { DefaultString } from '../inputSpecTypes'
|
||||
import { _, once } from '../../../util'
|
||||
import {
|
||||
Parser,
|
||||
any,
|
||||
anyOf,
|
||||
arrayOf,
|
||||
boolean,
|
||||
literal,
|
||||
literals,
|
||||
number,
|
||||
object,
|
||||
string,
|
||||
} from 'ts-matches'
|
||||
import { z } from 'zod'
|
||||
import { DeepPartial } from '../../../types'
|
||||
|
||||
export const fileInfoParser = object({
|
||||
path: string,
|
||||
commitment: object({ hash: string, size: number }),
|
||||
export const fileInfoParser = z.object({
|
||||
path: z.string(),
|
||||
commitment: z.object({ hash: z.string(), size: z.number() }),
|
||||
})
|
||||
export type FileInfo = typeof fileInfoParser._TYPE
|
||||
export type FileInfo = z.infer<typeof fileInfoParser>
|
||||
|
||||
export type AsRequired<T, Required extends boolean> = Required extends true
|
||||
? T
|
||||
: T | null
|
||||
|
||||
const testForAsRequiredParser = once(
|
||||
() => object({ required: literal(true) }).test,
|
||||
() => (v: unknown) =>
|
||||
z.object({ required: z.literal(true) }).safeParse(v).success,
|
||||
)
|
||||
function asRequiredParser<Type, Input extends { required: boolean }>(
|
||||
parser: Parser<unknown, Type>,
|
||||
parser: z.ZodType<Type>,
|
||||
input: Input,
|
||||
): Parser<unknown, AsRequired<Type, Input['required']>> {
|
||||
): z.ZodType<AsRequired<Type, Input['required']>> {
|
||||
if (testForAsRequiredParser()(input)) return parser as any
|
||||
return parser.nullable() as any
|
||||
}
|
||||
@@ -56,11 +46,11 @@ export class Value<
|
||||
public build: LazyBuild<
|
||||
{
|
||||
spec: ValueSpec
|
||||
validator: Parser<unknown, Type>
|
||||
validator: z.ZodType<Type>
|
||||
},
|
||||
OuterType
|
||||
>,
|
||||
public readonly validator: Parser<unknown, StaticValidatedAs>,
|
||||
public readonly validator: z.ZodType<StaticValidatedAs>,
|
||||
) {}
|
||||
public _TYPE: Type = null as any as Type
|
||||
public _PARTIAL: DeepPartial<Type> = null as any as DeepPartial<Type>
|
||||
@@ -93,7 +83,7 @@ export class Value<
|
||||
*/
|
||||
immutable?: boolean
|
||||
}) {
|
||||
const validator = boolean
|
||||
const validator = z.boolean()
|
||||
return new Value<boolean>(
|
||||
async () => ({
|
||||
spec: {
|
||||
@@ -121,7 +111,7 @@ export class Value<
|
||||
OuterType
|
||||
>,
|
||||
) {
|
||||
const validator = boolean
|
||||
const validator = z.boolean()
|
||||
return new Value<boolean, boolean, OuterType>(
|
||||
async (options) => ({
|
||||
spec: {
|
||||
@@ -212,7 +202,7 @@ export class Value<
|
||||
*/
|
||||
generate?: RandomString | null
|
||||
}) {
|
||||
const validator = asRequiredParser(string, a)
|
||||
const validator = asRequiredParser(z.string(), a)
|
||||
return new Value<AsRequired<string, Required>>(
|
||||
async () => ({
|
||||
spec: {
|
||||
@@ -274,10 +264,10 @@ export class Value<
|
||||
generate: a.generate ?? null,
|
||||
...a,
|
||||
},
|
||||
validator: asRequiredParser(string, a),
|
||||
validator: asRequiredParser(z.string(), a),
|
||||
}
|
||||
},
|
||||
string.nullable(),
|
||||
z.string().nullable(),
|
||||
)
|
||||
}
|
||||
/**
|
||||
@@ -336,7 +326,7 @@ export class Value<
|
||||
*/
|
||||
immutable?: boolean
|
||||
}) {
|
||||
const validator = asRequiredParser(string, a)
|
||||
const validator = asRequiredParser(z.string(), a)
|
||||
return new Value<AsRequired<string, Required>>(async () => {
|
||||
const built: ValueSpecTextarea = {
|
||||
description: null,
|
||||
@@ -392,10 +382,10 @@ export class Value<
|
||||
immutable: false,
|
||||
...a,
|
||||
},
|
||||
validator: asRequiredParser(string, a),
|
||||
validator: asRequiredParser(z.string(), a),
|
||||
}
|
||||
},
|
||||
string.nullable(),
|
||||
z.string().nullable(),
|
||||
)
|
||||
}
|
||||
/**
|
||||
@@ -456,7 +446,7 @@ export class Value<
|
||||
*/
|
||||
immutable?: boolean
|
||||
}) {
|
||||
const validator = asRequiredParser(number, a)
|
||||
const validator = asRequiredParser(z.number(), a)
|
||||
return new Value<AsRequired<number, Required>>(
|
||||
() => ({
|
||||
spec: {
|
||||
@@ -513,10 +503,10 @@ export class Value<
|
||||
immutable: false,
|
||||
...a,
|
||||
},
|
||||
validator: asRequiredParser(number, a),
|
||||
validator: asRequiredParser(z.number(), a),
|
||||
}
|
||||
},
|
||||
number.nullable(),
|
||||
z.number().nullable(),
|
||||
)
|
||||
}
|
||||
/**
|
||||
@@ -555,7 +545,7 @@ export class Value<
|
||||
*/
|
||||
immutable?: boolean
|
||||
}) {
|
||||
const validator = asRequiredParser(string, a)
|
||||
const validator = asRequiredParser(z.string(), a)
|
||||
return new Value<AsRequired<string, Required>>(
|
||||
() => ({
|
||||
spec: {
|
||||
@@ -597,10 +587,10 @@ export class Value<
|
||||
immutable: false,
|
||||
...a,
|
||||
},
|
||||
validator: asRequiredParser(string, a),
|
||||
validator: asRequiredParser(z.string(), a),
|
||||
}
|
||||
},
|
||||
string.nullable(),
|
||||
z.string().nullable(),
|
||||
)
|
||||
}
|
||||
/**
|
||||
@@ -649,7 +639,7 @@ export class Value<
|
||||
*/
|
||||
immutable?: boolean
|
||||
}) {
|
||||
const validator = asRequiredParser(string, a)
|
||||
const validator = asRequiredParser(z.string(), a)
|
||||
return new Value<AsRequired<string, Required>>(
|
||||
() => ({
|
||||
spec: {
|
||||
@@ -700,10 +690,10 @@ export class Value<
|
||||
immutable: false,
|
||||
...a,
|
||||
},
|
||||
validator: asRequiredParser(string, a),
|
||||
validator: asRequiredParser(z.string(), a),
|
||||
}
|
||||
},
|
||||
string.nullable(),
|
||||
z.string().nullable(),
|
||||
)
|
||||
}
|
||||
/**
|
||||
@@ -757,8 +747,12 @@ export class Value<
|
||||
*/
|
||||
immutable?: boolean
|
||||
}) {
|
||||
const validator = anyOf(
|
||||
...Object.keys(a.values).map((x: keyof Values & string) => literal(x)),
|
||||
const validator = z.union(
|
||||
Object.keys(a.values).map((x: keyof Values & string) => z.literal(x)) as [
|
||||
z.ZodLiteral<string>,
|
||||
z.ZodLiteral<string>,
|
||||
...z.ZodLiteral<string>[],
|
||||
],
|
||||
)
|
||||
return new Value<keyof Values & string>(
|
||||
() => ({
|
||||
@@ -803,14 +797,18 @@ export class Value<
|
||||
immutable: false,
|
||||
...a,
|
||||
},
|
||||
validator: anyOf(
|
||||
...Object.keys(a.values).map((x: keyof Values & string) =>
|
||||
literal(x),
|
||||
),
|
||||
validator: z.union(
|
||||
Object.keys(a.values).map((x: keyof Values & string) =>
|
||||
z.literal(x),
|
||||
) as [
|
||||
z.ZodLiteral<string>,
|
||||
z.ZodLiteral<string>,
|
||||
...z.ZodLiteral<string>[],
|
||||
],
|
||||
),
|
||||
}
|
||||
},
|
||||
string,
|
||||
z.string(),
|
||||
)
|
||||
}
|
||||
/**
|
||||
@@ -865,8 +863,14 @@ export class Value<
|
||||
*/
|
||||
immutable?: boolean
|
||||
}) {
|
||||
const validator = arrayOf(
|
||||
literals(...(Object.keys(a.values) as any as [keyof Values & string])),
|
||||
const validator = z.array(
|
||||
z.union(
|
||||
Object.keys(a.values).map((x) => z.literal(x)) as [
|
||||
z.ZodLiteral<string>,
|
||||
z.ZodLiteral<string>,
|
||||
...z.ZodLiteral<string>[],
|
||||
],
|
||||
),
|
||||
)
|
||||
return new Value<(keyof Values & string)[]>(
|
||||
() => ({
|
||||
@@ -920,13 +924,17 @@ export class Value<
|
||||
immutable: false,
|
||||
...a,
|
||||
},
|
||||
validator: arrayOf(
|
||||
literals(
|
||||
...(Object.keys(a.values) as any as [keyof Values & string]),
|
||||
validator: z.array(
|
||||
z.union(
|
||||
Object.keys(a.values).map((x) => z.literal(x)) as [
|
||||
z.ZodLiteral<string>,
|
||||
z.ZodLiteral<string>,
|
||||
...z.ZodLiteral<string>[],
|
||||
],
|
||||
),
|
||||
),
|
||||
}
|
||||
}, arrayOf(string))
|
||||
}, z.array(z.string()))
|
||||
}
|
||||
/**
|
||||
* @description Display a collapsable grouping of additional fields, a "sub form". The second value is the inputSpec spec for the sub form.
|
||||
@@ -1077,7 +1085,7 @@ export class Value<
|
||||
}) {
|
||||
return new Value<
|
||||
typeof a.variants._TYPE,
|
||||
typeof a.variants.validator._TYPE
|
||||
typeof a.variants.validator._output
|
||||
>(async (options) => {
|
||||
const built = await a.variants.build(options as any)
|
||||
return {
|
||||
@@ -1136,7 +1144,7 @@ export class Value<
|
||||
},
|
||||
OuterType
|
||||
>,
|
||||
validator: Parser<unknown, UnionResStaticValidatedAs<StaticVariantValues>>,
|
||||
validator: z.ZodType<UnionResStaticValidatedAs<StaticVariantValues>>,
|
||||
): Value<
|
||||
UnionRes<VariantValues>,
|
||||
UnionResStaticValidatedAs<StaticVariantValues>,
|
||||
@@ -1162,11 +1170,11 @@ export class Value<
|
||||
},
|
||||
OuterType
|
||||
>,
|
||||
validator: Parser<unknown, unknown> = any,
|
||||
validator: z.ZodType<unknown> = z.any(),
|
||||
) {
|
||||
return new Value<
|
||||
UnionRes<VariantValues>,
|
||||
typeof validator._TYPE,
|
||||
z.infer<typeof validator>,
|
||||
OuterType
|
||||
>(async (options) => {
|
||||
const newValues = await getA(options)
|
||||
@@ -1259,9 +1267,9 @@ export class Value<
|
||||
* ```
|
||||
*/
|
||||
static hidden<T>(): Value<T>
|
||||
static hidden<T>(parser: Parser<unknown, T>): Value<T>
|
||||
static hidden<T>(parser: Parser<unknown, T> = any) {
|
||||
return new Value<T, typeof parser._TYPE>(async () => {
|
||||
static hidden<T>(parser: z.ZodType<T>): Value<T>
|
||||
static hidden<T>(parser: z.ZodType<T> = z.any()) {
|
||||
return new Value<T, z.infer<typeof parser>>(async () => {
|
||||
return {
|
||||
spec: {
|
||||
type: 'hidden' as const,
|
||||
@@ -1279,7 +1287,7 @@ export class Value<
|
||||
* ```
|
||||
*/
|
||||
static dynamicHidden<T, OuterType = unknown>(
|
||||
getParser: LazyBuild<Parser<unknown, T>, OuterType>,
|
||||
getParser: LazyBuild<z.ZodType<T>, OuterType>,
|
||||
) {
|
||||
return new Value<T, T, OuterType>(async (options) => {
|
||||
const validator = await getParser(options)
|
||||
@@ -1289,7 +1297,7 @@ export class Value<
|
||||
} as ValueSpecHidden,
|
||||
validator,
|
||||
}
|
||||
}, any)
|
||||
}, z.any())
|
||||
}
|
||||
|
||||
map<U>(fn: (value: StaticValidatedAs) => U): Value<U, U, OuterType> {
|
||||
@@ -1297,8 +1305,8 @@ export class Value<
|
||||
const built = await this.build(options)
|
||||
return {
|
||||
spec: built.spec,
|
||||
validator: built.validator.map(fn),
|
||||
validator: built.validator.transform(fn),
|
||||
}
|
||||
}, this.validator.map(fn))
|
||||
}, this.validator.transform(fn))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
ExtractInputSpecType,
|
||||
ExtractInputSpecStaticValidatedAs,
|
||||
} from './inputSpec'
|
||||
import { Parser, any, anyOf, literal, object } from 'ts-matches'
|
||||
import { z } from 'zod'
|
||||
|
||||
export type UnionRes<
|
||||
VariantValues extends {
|
||||
@@ -109,12 +109,11 @@ export class Variants<
|
||||
public build: LazyBuild<
|
||||
{
|
||||
spec: ValueSpecUnion['variants']
|
||||
validator: Parser<unknown, UnionRes<VariantValues>>
|
||||
validator: z.ZodType<UnionRes<VariantValues>>
|
||||
},
|
||||
OuterType
|
||||
>,
|
||||
public readonly validator: Parser<
|
||||
unknown,
|
||||
public readonly validator: z.ZodType<
|
||||
UnionResStaticValidatedAs<VariantValues>
|
||||
>,
|
||||
) {}
|
||||
@@ -128,8 +127,7 @@ export class Variants<
|
||||
},
|
||||
>(a: VariantValues) {
|
||||
const staticValidators = {} as {
|
||||
[K in keyof VariantValues]: Parser<
|
||||
unknown,
|
||||
[K in keyof VariantValues]: z.ZodType<
|
||||
ExtractInputSpecStaticValidatedAs<VariantValues[K]['spec']>
|
||||
>
|
||||
}
|
||||
@@ -137,16 +135,20 @@ export class Variants<
|
||||
const value = a[key]
|
||||
staticValidators[key] = value.spec.validator
|
||||
}
|
||||
const other = object(
|
||||
Object.fromEntries(
|
||||
Object.entries(staticValidators).map(([k, v]) => [k, any.optional()]),
|
||||
),
|
||||
).optional()
|
||||
const other = z
|
||||
.object(
|
||||
Object.fromEntries(
|
||||
Object.entries(staticValidators).map(([k, v]) => [
|
||||
k,
|
||||
z.any().optional(),
|
||||
]),
|
||||
),
|
||||
)
|
||||
.optional()
|
||||
return new Variants<VariantValues>(
|
||||
async (options) => {
|
||||
const validators = {} as {
|
||||
[K in keyof VariantValues]: Parser<
|
||||
unknown,
|
||||
[K in keyof VariantValues]: z.ZodType<
|
||||
ExtractInputSpecType<VariantValues[K]['spec']>
|
||||
>
|
||||
}
|
||||
@@ -165,32 +167,37 @@ export class Variants<
|
||||
}
|
||||
validators[key] = built.validator
|
||||
}
|
||||
const other = object(
|
||||
Object.fromEntries(
|
||||
Object.entries(validators).map(([k, v]) => [k, any.optional()]),
|
||||
),
|
||||
).optional()
|
||||
const other = z
|
||||
.object(
|
||||
Object.fromEntries(
|
||||
Object.entries(validators).map(([k, v]) => [
|
||||
k,
|
||||
z.any().optional(),
|
||||
]),
|
||||
),
|
||||
)
|
||||
.optional()
|
||||
return {
|
||||
spec: variants,
|
||||
validator: anyOf(
|
||||
...Object.entries(validators).map(([k, v]) =>
|
||||
object({
|
||||
selection: literal(k),
|
||||
validator: z.union(
|
||||
Object.entries(validators).map(([k, v]) =>
|
||||
z.object({
|
||||
selection: z.literal(k),
|
||||
value: v,
|
||||
other,
|
||||
}),
|
||||
),
|
||||
) as [z.ZodObject<any>, z.ZodObject<any>, ...z.ZodObject<any>[]],
|
||||
) as any,
|
||||
}
|
||||
},
|
||||
anyOf(
|
||||
...Object.entries(staticValidators).map(([k, v]) =>
|
||||
object({
|
||||
selection: literal(k),
|
||||
z.union(
|
||||
Object.entries(staticValidators).map(([k, v]) =>
|
||||
z.object({
|
||||
selection: z.literal(k),
|
||||
value: v,
|
||||
other,
|
||||
}),
|
||||
),
|
||||
) as [z.ZodObject<any>, z.ZodObject<any>, ...z.ZodObject<any>[]],
|
||||
) as any,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ExtractInputSpecType } from './input/builder/inputSpec'
|
||||
import * as T from '../types'
|
||||
import { once } from '../util'
|
||||
import { InitScript } from '../inits'
|
||||
import { Parser } from 'ts-matches'
|
||||
import { z } from 'zod'
|
||||
|
||||
type MaybeInputSpec<Type> = {} extends Type ? null : InputSpec<Type>
|
||||
export type Run<A extends Record<string, any>> = (options: {
|
||||
@@ -52,7 +52,7 @@ export class Action<Id extends T.ActionId, Type extends Record<string, any>>
|
||||
readonly _INPUT: Type = null as any as Type
|
||||
private prevInputSpec: Record<
|
||||
string,
|
||||
{ spec: T.inputSpecTypes.InputSpec; validator: Parser<unknown, Type> }
|
||||
{ spec: T.inputSpecTypes.InputSpec; validator: z.ZodType<Type> }
|
||||
> = {}
|
||||
private constructor(
|
||||
readonly id: Id,
|
||||
@@ -137,7 +137,7 @@ export class Action<Id extends T.ActionId, Type extends Record<string, any>>
|
||||
`getActionInput has not been called for EventID ${options.effects.eventId}`,
|
||||
)
|
||||
}
|
||||
options.input = prevInputSpec.validator.unsafeCast(options.input)
|
||||
options.input = prevInputSpec.validator.parse(options.input)
|
||||
spec = prevInputSpec.spec
|
||||
}
|
||||
return (
|
||||
|
||||
@@ -8,6 +8,6 @@ export * as types from './types'
|
||||
export * as T from './types'
|
||||
export * as yaml from 'yaml'
|
||||
export * as inits from './inits'
|
||||
export * as matches from 'ts-matches'
|
||||
export { z } from 'zod'
|
||||
|
||||
export * as utils from './util'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { object, string } from 'ts-matches'
|
||||
import { z } from 'zod'
|
||||
import { Effects } from '../Effects'
|
||||
import { Origin } from './Origin'
|
||||
import { AddSslOptions, BindParams } from '../osBindings'
|
||||
@@ -69,9 +69,8 @@ export type BindOptionsByProtocol =
|
||||
| BindOptionsByKnownProtocol
|
||||
| (BindOptions & { protocol: null })
|
||||
|
||||
const hasStringProtocol = object({
|
||||
protocol: string,
|
||||
}).test
|
||||
const hasStringProtocol = (v: unknown): v is { protocol: string } =>
|
||||
z.object({ protocol: z.string() }).safeParse(v).success
|
||||
|
||||
export class MultiHost {
|
||||
constructor(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { object } from 'ts-matches'
|
||||
|
||||
export function deepEqual(...args: unknown[]) {
|
||||
const objects = args.filter(object.test)
|
||||
const objects = args.filter(
|
||||
(x): x is object => typeof x === 'object' && x !== null,
|
||||
)
|
||||
if (objects.length === 0) {
|
||||
for (const x of args) if (x !== args[0]) return false
|
||||
return true
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { boolean } from 'ts-matches'
|
||||
import { ExtendedVersion } from '../exver'
|
||||
|
||||
export type Vertex<VMetadata = null, EMetadata = null> = {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { arrayOf, string } from 'ts-matches'
|
||||
|
||||
export const splitCommand = (
|
||||
command: string | [string, ...string[]],
|
||||
): string[] => {
|
||||
if (arrayOf(string).test(command)) return command
|
||||
if (Array.isArray(command)) return command
|
||||
return ['sh', '-c', command]
|
||||
}
|
||||
|
||||
19
sdk/base/package-lock.json
generated
19
sdk/base/package-lock.json
generated
@@ -13,8 +13,8 @@
|
||||
"deep-equality-data-structures": "^1.5.0",
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"mime": "^4.0.7",
|
||||
"ts-matches": "^6.3.2",
|
||||
"yaml": "^2.7.1"
|
||||
"yaml": "^2.7.1",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.4.0",
|
||||
@@ -4626,12 +4626,6 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-matches": {
|
||||
"version": "6.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ts-matches/-/ts-matches-6.3.2.tgz",
|
||||
"integrity": "sha512-UhSgJymF8cLd4y0vV29qlKVCkQpUtekAaujXbQVc729FezS8HwqzepqvtjzQ3HboatIqN/Idor85O2RMwT7lIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ts-morph": {
|
||||
"version": "18.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-morph/-/ts-morph-18.0.0.tgz",
|
||||
@@ -5006,6 +5000,15 @@
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
|
||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,11 +24,11 @@
|
||||
"@iarna/toml": "^3.0.0",
|
||||
"@noble/curves": "^1.8.2",
|
||||
"@noble/hashes": "^1.7.2",
|
||||
"deep-equality-data-structures": "^1.5.0",
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"mime": "^4.0.7",
|
||||
"ts-matches": "^6.3.2",
|
||||
"yaml": "^2.7.1",
|
||||
"deep-equality-data-structures": "^1.5.0"
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"prettier": {
|
||||
"trailingComma": "all",
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Trigger } from '../trigger'
|
||||
import { TriggerInput } from '../trigger/TriggerInput'
|
||||
import { defaultTrigger } from '../trigger/defaultTrigger'
|
||||
import { once, asError, Drop } from '../util'
|
||||
import { object, unknown } from 'ts-matches'
|
||||
|
||||
export type HealthCheckParams = {
|
||||
id: HealthCheckId
|
||||
@@ -109,7 +108,8 @@ export class HealthCheck extends Drop {
|
||||
}
|
||||
|
||||
function asMessage(e: unknown) {
|
||||
if (object({ message: unknown }).test(e)) return String(e.message)
|
||||
if (typeof e === 'object' && e !== null && 'message' in e)
|
||||
return String((e as any).message)
|
||||
const value = String(e)
|
||||
if (value.length == null) return null
|
||||
return value
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
ISB,
|
||||
IST,
|
||||
types,
|
||||
matches,
|
||||
z,
|
||||
utils,
|
||||
} from '../../base/lib'
|
||||
|
||||
@@ -20,7 +20,7 @@ export {
|
||||
ISB,
|
||||
IST,
|
||||
types,
|
||||
matches,
|
||||
z,
|
||||
utils,
|
||||
}
|
||||
export { setupI18n } from './i18n'
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { testOutput } from './output.test'
|
||||
import { InputSpec } from '../../../base/lib/actions/input/builder/inputSpec'
|
||||
import { List } from '../../../base/lib/actions/input/builder/list'
|
||||
import { Value } from '../../../base/lib/actions/input/builder/value'
|
||||
@@ -7,6 +6,12 @@ import { ValueSpec } from '../../../base/lib/actions/input/inputSpecTypes'
|
||||
import { setupManifest } from '../manifest/setupManifest'
|
||||
import { StartSdk } from '../StartSdk'
|
||||
|
||||
export type IfEquals<T, U, Y = unknown, N = never> =
|
||||
(<G>() => G extends T ? 1 : 2) extends <G>() => G extends U ? 1 : 2 ? Y : N
|
||||
export function testOutput<A, B>(): (c: IfEquals<A, B>) => null {
|
||||
return () => null
|
||||
}
|
||||
|
||||
describe('builder tests', () => {
|
||||
test('text', async () => {
|
||||
const bitcoinPropertiesBuilt: {
|
||||
@@ -50,8 +55,8 @@ describe('values', () => {
|
||||
default: false,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast(false)
|
||||
testOutput<typeof validator._TYPE, boolean>()(null)
|
||||
validator.parse(false)
|
||||
testOutput<typeof validator._output, boolean>()(null)
|
||||
})
|
||||
test('text', async () => {
|
||||
const value = await Value.text({
|
||||
@@ -61,9 +66,9 @@ describe('values', () => {
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
const rawIs = value.spec
|
||||
validator.unsafeCast('test text')
|
||||
expect(() => validator.unsafeCast(null)).toThrowError()
|
||||
testOutput<typeof validator._TYPE, string>()(null)
|
||||
validator.parse('test text')
|
||||
expect(() => validator.parse(null)).toThrowError()
|
||||
testOutput<typeof validator._output, string>()(null)
|
||||
})
|
||||
test('text with default', async () => {
|
||||
const value = await Value.text({
|
||||
@@ -73,9 +78,9 @@ describe('values', () => {
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
const rawIs = value.spec
|
||||
validator.unsafeCast('test text')
|
||||
expect(() => validator.unsafeCast(null)).toThrowError()
|
||||
testOutput<typeof validator._TYPE, string>()(null)
|
||||
validator.parse('test text')
|
||||
expect(() => validator.parse(null)).toThrowError()
|
||||
testOutput<typeof validator._output, string>()(null)
|
||||
})
|
||||
test('optional text', async () => {
|
||||
const value = await Value.text({
|
||||
@@ -85,9 +90,9 @@ describe('values', () => {
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
const rawIs = value.spec
|
||||
validator.unsafeCast('test text')
|
||||
validator.unsafeCast(null)
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('test text')
|
||||
validator.parse(null)
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
})
|
||||
test('color', async () => {
|
||||
const value = await Value.color({
|
||||
@@ -98,8 +103,8 @@ describe('values', () => {
|
||||
warning: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('#000000')
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('#000000')
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
})
|
||||
test('datetime', async () => {
|
||||
const value = await Value.datetime({
|
||||
@@ -113,8 +118,8 @@ describe('values', () => {
|
||||
max: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('2021-01-01')
|
||||
testOutput<typeof validator._TYPE, string>()(null)
|
||||
validator.parse('2021-01-01')
|
||||
testOutput<typeof validator._output, string>()(null)
|
||||
})
|
||||
test('optional datetime', async () => {
|
||||
const value = await Value.datetime({
|
||||
@@ -128,8 +133,8 @@ describe('values', () => {
|
||||
max: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('2021-01-01')
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('2021-01-01')
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
})
|
||||
test('textarea', async () => {
|
||||
const value = await Value.textarea({
|
||||
@@ -145,8 +150,8 @@ describe('values', () => {
|
||||
placeholder: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('test text')
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('test text')
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
})
|
||||
test('number', async () => {
|
||||
const value = await Value.number({
|
||||
@@ -163,8 +168,8 @@ describe('values', () => {
|
||||
placeholder: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast(2)
|
||||
testOutput<typeof validator._TYPE, number>()(null)
|
||||
validator.parse(2)
|
||||
testOutput<typeof validator._output, number>()(null)
|
||||
})
|
||||
test('optional number', async () => {
|
||||
const value = await Value.number({
|
||||
@@ -181,8 +186,8 @@ describe('values', () => {
|
||||
placeholder: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast(2)
|
||||
testOutput<typeof validator._TYPE, number | null>()(null)
|
||||
validator.parse(2)
|
||||
testOutput<typeof validator._output, number | null>()(null)
|
||||
})
|
||||
test('select', async () => {
|
||||
const value = await Value.select({
|
||||
@@ -196,10 +201,10 @@ describe('values', () => {
|
||||
warning: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('a')
|
||||
validator.unsafeCast('b')
|
||||
expect(() => validator.unsafeCast('c')).toThrowError()
|
||||
testOutput<typeof validator._TYPE, 'a' | 'b'>()(null)
|
||||
validator.parse('a')
|
||||
validator.parse('b')
|
||||
expect(() => validator.parse('c')).toThrowError()
|
||||
testOutput<typeof validator._output, 'a' | 'b'>()(null)
|
||||
})
|
||||
test('nullable select', async () => {
|
||||
const value = await Value.select({
|
||||
@@ -213,9 +218,9 @@ describe('values', () => {
|
||||
warning: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('a')
|
||||
validator.unsafeCast('b')
|
||||
testOutput<typeof validator._TYPE, 'a' | 'b'>()(null)
|
||||
validator.parse('a')
|
||||
validator.parse('b')
|
||||
testOutput<typeof validator._output, 'a' | 'b'>()(null)
|
||||
})
|
||||
test('multiselect', async () => {
|
||||
const value = await Value.multiselect({
|
||||
@@ -231,12 +236,12 @@ describe('values', () => {
|
||||
maxLength: null,
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast([])
|
||||
validator.unsafeCast(['a', 'b'])
|
||||
validator.parse([])
|
||||
validator.parse(['a', 'b'])
|
||||
|
||||
expect(() => validator.unsafeCast(['e'])).toThrowError()
|
||||
expect(() => validator.unsafeCast([4])).toThrowError()
|
||||
testOutput<typeof validator._TYPE, Array<'a' | 'b'>>()(null)
|
||||
expect(() => validator.parse(['e'])).toThrowError()
|
||||
expect(() => validator.parse([4])).toThrowError()
|
||||
testOutput<typeof validator._output, Array<'a' | 'b'>>()(null)
|
||||
})
|
||||
test('object', async () => {
|
||||
const value = await Value.object(
|
||||
@@ -254,8 +259,8 @@ describe('values', () => {
|
||||
}),
|
||||
).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ a: true })
|
||||
testOutput<typeof validator._TYPE, { a: boolean }>()(null)
|
||||
validator.parse({ a: true })
|
||||
testOutput<typeof validator._output, { a: boolean }>()(null)
|
||||
})
|
||||
test('union', async () => {
|
||||
const value = await Value.union({
|
||||
@@ -278,8 +283,8 @@ describe('values', () => {
|
||||
}),
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ selection: 'a', value: { b: false } })
|
||||
type Test = typeof validator._TYPE
|
||||
validator.parse({ selection: 'a', value: { b: false } })
|
||||
type Test = typeof validator._output
|
||||
testOutput<
|
||||
Test,
|
||||
{
|
||||
@@ -306,9 +311,9 @@ describe('values', () => {
|
||||
default: false,
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast(false)
|
||||
expect(() => validator.unsafeCast(null)).toThrowError()
|
||||
testOutput<typeof validator._TYPE, boolean>()(null)
|
||||
validator.parse(false)
|
||||
expect(() => validator.parse(null)).toThrowError()
|
||||
testOutput<typeof validator._output, boolean>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
description: null,
|
||||
@@ -324,9 +329,9 @@ describe('values', () => {
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
const rawIs = value.spec
|
||||
validator.unsafeCast('test text')
|
||||
validator.unsafeCast(null)
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('test text')
|
||||
validator.parse(null)
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
required: false,
|
||||
@@ -340,9 +345,9 @@ describe('values', () => {
|
||||
default: 'this is a default value',
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('test text')
|
||||
validator.unsafeCast(null)
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('test text')
|
||||
validator.parse(null)
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
required: false,
|
||||
@@ -357,9 +362,9 @@ describe('values', () => {
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
const rawIs = value.spec
|
||||
validator.unsafeCast('test text')
|
||||
validator.unsafeCast(null)
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('test text')
|
||||
validator.parse(null)
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
required: false,
|
||||
@@ -375,9 +380,9 @@ describe('values', () => {
|
||||
warning: null,
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('#000000')
|
||||
validator.unsafeCast(null)
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('#000000')
|
||||
validator.parse(null)
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
required: false,
|
||||
@@ -432,9 +437,9 @@ describe('values', () => {
|
||||
}
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('2021-01-01')
|
||||
validator.unsafeCast(null)
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('2021-01-01')
|
||||
validator.parse(null)
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
required: false,
|
||||
@@ -458,8 +463,8 @@ describe('values', () => {
|
||||
placeholder: null,
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('test text')
|
||||
testOutput<typeof validator._TYPE, string | null>()(null)
|
||||
validator.parse('test text')
|
||||
testOutput<typeof validator._output, string | null>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
required: false,
|
||||
@@ -480,10 +485,10 @@ describe('values', () => {
|
||||
placeholder: null,
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast(2)
|
||||
validator.unsafeCast(null)
|
||||
expect(() => validator.unsafeCast('null')).toThrowError()
|
||||
testOutput<typeof validator._TYPE, number | null>()(null)
|
||||
validator.parse(2)
|
||||
validator.parse(null)
|
||||
expect(() => validator.parse('null')).toThrowError()
|
||||
testOutput<typeof validator._output, number | null>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
required: false,
|
||||
@@ -501,9 +506,9 @@ describe('values', () => {
|
||||
warning: null,
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast('a')
|
||||
validator.unsafeCast('b')
|
||||
testOutput<typeof validator._TYPE, 'a' | 'b'>()(null)
|
||||
validator.parse('a')
|
||||
validator.parse('b')
|
||||
testOutput<typeof validator._output, 'a' | 'b'>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
})
|
||||
@@ -522,12 +527,12 @@ describe('values', () => {
|
||||
maxLength: null,
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast([])
|
||||
validator.unsafeCast(['a', 'b'])
|
||||
validator.parse([])
|
||||
validator.parse(['a', 'b'])
|
||||
|
||||
expect(() => validator.unsafeCast([4])).toThrowError()
|
||||
expect(() => validator.unsafeCast(null)).toThrowError()
|
||||
testOutput<typeof validator._TYPE, Array<'a' | 'b'>>()(null)
|
||||
expect(() => validator.parse([4])).toThrowError()
|
||||
expect(() => validator.parse(null)).toThrowError()
|
||||
testOutput<typeof validator._output, Array<'a' | 'b'>>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'Testing',
|
||||
default: [],
|
||||
@@ -568,8 +573,8 @@ describe('values', () => {
|
||||
}),
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ selection: 'a', value: { b: false } })
|
||||
type Test = typeof validator._TYPE
|
||||
validator.parse({ selection: 'a', value: { b: false } })
|
||||
type Test = typeof validator._output
|
||||
testOutput<
|
||||
Test,
|
||||
| {
|
||||
@@ -653,8 +658,8 @@ describe('values', () => {
|
||||
}),
|
||||
})).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ selection: 'a', value: { b: false } })
|
||||
type Test = typeof validator._TYPE
|
||||
validator.parse({ selection: 'a', value: { b: false } })
|
||||
type Test = typeof validator._output
|
||||
testOutput<
|
||||
Test,
|
||||
| {
|
||||
@@ -726,8 +731,8 @@ describe('Builder List', () => {
|
||||
),
|
||||
).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast([{ test: true }])
|
||||
testOutput<typeof validator._TYPE, { test: boolean }[]>()(null)
|
||||
validator.parse([{ test: true }])
|
||||
testOutput<typeof validator._output, { test: boolean }[]>()(null)
|
||||
})
|
||||
test('text', async () => {
|
||||
const value = await Value.list(
|
||||
@@ -741,8 +746,8 @@ describe('Builder List', () => {
|
||||
),
|
||||
).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast(['test', 'text'])
|
||||
testOutput<typeof validator._TYPE, string[]>()(null)
|
||||
validator.parse(['test', 'text'])
|
||||
testOutput<typeof validator._output, string[]>()(null)
|
||||
})
|
||||
describe('dynamic', () => {
|
||||
test('text', async () => {
|
||||
@@ -753,10 +758,10 @@ describe('Builder List', () => {
|
||||
})),
|
||||
).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast(['test', 'text'])
|
||||
expect(() => validator.unsafeCast([3, 4])).toThrowError()
|
||||
expect(() => validator.unsafeCast(null)).toThrowError()
|
||||
testOutput<typeof validator._TYPE, string[]>()(null)
|
||||
validator.parse(['test', 'text'])
|
||||
expect(() => validator.parse([3, 4])).toThrowError()
|
||||
expect(() => validator.parse(null)).toThrowError()
|
||||
testOutput<typeof validator._output, string[]>()(null)
|
||||
expect(value.spec).toMatchObject({
|
||||
name: 'test',
|
||||
spec: { patterns: [] },
|
||||
@@ -777,10 +782,10 @@ describe('Nested nullable values', () => {
|
||||
}),
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ a: null })
|
||||
validator.unsafeCast({ a: 'test' })
|
||||
expect(() => validator.unsafeCast({ a: 4 })).toThrowError()
|
||||
testOutput<typeof validator._TYPE, { a: string | null }>()(null)
|
||||
validator.parse({ a: null })
|
||||
validator.parse({ a: 'test' })
|
||||
expect(() => validator.parse({ a: 4 })).toThrowError()
|
||||
testOutput<typeof validator._output, { a: string | null }>()(null)
|
||||
})
|
||||
test('Testing number', async () => {
|
||||
const value = await InputSpec.of({
|
||||
@@ -800,10 +805,10 @@ describe('Nested nullable values', () => {
|
||||
}),
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ a: null })
|
||||
validator.unsafeCast({ a: 5 })
|
||||
expect(() => validator.unsafeCast({ a: '4' })).toThrowError()
|
||||
testOutput<typeof validator._TYPE, { a: number | null }>()(null)
|
||||
validator.parse({ a: null })
|
||||
validator.parse({ a: 5 })
|
||||
expect(() => validator.parse({ a: '4' })).toThrowError()
|
||||
testOutput<typeof validator._output, { a: number | null }>()(null)
|
||||
})
|
||||
test('Testing color', async () => {
|
||||
const value = await InputSpec.of({
|
||||
@@ -817,10 +822,10 @@ describe('Nested nullable values', () => {
|
||||
}),
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ a: null })
|
||||
validator.unsafeCast({ a: '5' })
|
||||
expect(() => validator.unsafeCast({ a: 4 })).toThrowError()
|
||||
testOutput<typeof validator._TYPE, { a: string | null }>()(null)
|
||||
validator.parse({ a: null })
|
||||
validator.parse({ a: '5' })
|
||||
expect(() => validator.parse({ a: 4 })).toThrowError()
|
||||
testOutput<typeof validator._output, { a: string | null }>()(null)
|
||||
})
|
||||
test('Testing select', async () => {
|
||||
const value = await InputSpec.of({
|
||||
@@ -847,9 +852,9 @@ describe('Nested nullable values', () => {
|
||||
}).build({} as any)
|
||||
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ a: 'a' })
|
||||
expect(() => validator.unsafeCast({ a: '4' })).toThrowError()
|
||||
testOutput<typeof validator._TYPE, { a: 'a' }>()(null)
|
||||
validator.parse({ a: 'a' })
|
||||
expect(() => validator.parse({ a: '4' })).toThrowError()
|
||||
testOutput<typeof validator._output, { a: 'a' }>()(null)
|
||||
})
|
||||
test('Testing multiselect', async () => {
|
||||
const value = await InputSpec.of({
|
||||
@@ -868,10 +873,10 @@ describe('Nested nullable values', () => {
|
||||
}),
|
||||
}).build({} as any)
|
||||
const validator = value.validator
|
||||
validator.unsafeCast({ a: [] })
|
||||
validator.unsafeCast({ a: ['a'] })
|
||||
expect(() => validator.unsafeCast({ a: ['4'] })).toThrowError()
|
||||
expect(() => validator.unsafeCast({ a: '4' })).toThrowError()
|
||||
testOutput<typeof validator._TYPE, { a: 'a'[] }>()(null)
|
||||
validator.parse({ a: [] })
|
||||
validator.parse({ a: ['a'] })
|
||||
expect(() => validator.parse({ a: ['4'] })).toThrowError()
|
||||
expect(() => validator.parse({ a: '4' })).toThrowError()
|
||||
testOutput<typeof validator._output, { a: 'a'[] }>()(null)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,428 +0,0 @@
|
||||
import { oldSpecToBuilder } from '../../scripts/oldSpecToBuilder'
|
||||
|
||||
oldSpecToBuilder(
|
||||
// Make the location
|
||||
'./lib/test/output.ts',
|
||||
// Put the inputSpec here
|
||||
{
|
||||
mediasources: {
|
||||
type: 'list',
|
||||
subtype: 'enum',
|
||||
name: 'Media Sources',
|
||||
description: 'List of Media Sources to use with Jellyfin',
|
||||
range: '[1,*)',
|
||||
default: ['nextcloud'],
|
||||
spec: {
|
||||
values: ['nextcloud', 'filebrowser'],
|
||||
'value-names': {
|
||||
nextcloud: 'NextCloud',
|
||||
filebrowser: 'File Browser',
|
||||
},
|
||||
},
|
||||
},
|
||||
testListUnion: {
|
||||
type: 'list',
|
||||
subtype: 'union',
|
||||
name: 'Lightning Nodes',
|
||||
description: 'List of Lightning Network node instances to manage',
|
||||
range: '[1,*)',
|
||||
default: ['lnd'],
|
||||
spec: {
|
||||
type: 'string',
|
||||
'display-as': '{{name}}',
|
||||
'unique-by': 'name',
|
||||
name: 'Node Implementation',
|
||||
tag: {
|
||||
id: 'type',
|
||||
name: 'Type',
|
||||
description:
|
||||
'- LND: Lightning Network Daemon from Lightning Labs\n- CLN: Core Lightning from Blockstream\n',
|
||||
'variant-names': {
|
||||
lnd: 'Lightning Network Daemon (LND)',
|
||||
'c-lightning': 'Core Lightning (CLN)',
|
||||
},
|
||||
},
|
||||
default: 'lnd',
|
||||
variants: {
|
||||
lnd: {
|
||||
name: {
|
||||
type: 'string',
|
||||
name: 'Node Name',
|
||||
description: 'Name of this node in the list',
|
||||
default: 'LND Wrapper',
|
||||
nullable: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
rpc: {
|
||||
type: 'object',
|
||||
name: 'RPC Settings',
|
||||
description: 'RPC configuration options.',
|
||||
spec: {
|
||||
enable: {
|
||||
type: 'boolean',
|
||||
name: 'Enable',
|
||||
description: 'Allow remote RPC requests.',
|
||||
default: true,
|
||||
},
|
||||
username: {
|
||||
type: 'string',
|
||||
nullable: false,
|
||||
name: 'Username',
|
||||
description: 'The username for connecting to Bitcoin over RPC.',
|
||||
default: 'bitcoin',
|
||||
masked: true,
|
||||
pattern: '^[a-zA-Z0-9_]+$',
|
||||
'pattern-description':
|
||||
'Must be alphanumeric (can contain underscore).',
|
||||
},
|
||||
password: {
|
||||
type: 'string',
|
||||
nullable: false,
|
||||
name: 'RPC Password',
|
||||
description: 'The password for connecting to Bitcoin over RPC.',
|
||||
default: {
|
||||
charset: 'a-z,2-7',
|
||||
len: 20,
|
||||
},
|
||||
pattern: '^[^\\n"]*$',
|
||||
'pattern-description':
|
||||
'Must not contain newline or quote characters.',
|
||||
copyable: true,
|
||||
masked: true,
|
||||
},
|
||||
bio: {
|
||||
type: 'string',
|
||||
nullable: false,
|
||||
name: 'Username',
|
||||
description: 'The username for connecting to Bitcoin over RPC.',
|
||||
default: 'bitcoin',
|
||||
masked: true,
|
||||
pattern: '^[a-zA-Z0-9_]+$',
|
||||
'pattern-description':
|
||||
'Must be alphanumeric (can contain underscore).',
|
||||
textarea: true,
|
||||
},
|
||||
advanced: {
|
||||
type: 'object',
|
||||
name: 'Advanced',
|
||||
description: 'Advanced RPC Settings',
|
||||
spec: {
|
||||
auth: {
|
||||
name: 'Authorization',
|
||||
description:
|
||||
'Username and hashed password for JSON-RPC connections. RPC clients connect using the usual http basic authentication.',
|
||||
type: 'list',
|
||||
subtype: 'string',
|
||||
default: [],
|
||||
spec: {
|
||||
pattern:
|
||||
'^[a-zA-Z0-9_-]+:([0-9a-fA-F]{2})+\\$([0-9a-fA-F]{2})+$',
|
||||
'pattern-description':
|
||||
'Each item must be of the form "<USERNAME>:<SALT>$<HASH>".',
|
||||
masked: false,
|
||||
},
|
||||
range: '[0,*)',
|
||||
},
|
||||
serialversion: {
|
||||
name: 'Serialization Version',
|
||||
description:
|
||||
'Return raw transaction or block hex with Segwit or non-SegWit serialization.',
|
||||
type: 'enum',
|
||||
values: ['non-segwit', 'segwit'],
|
||||
'value-names': {},
|
||||
default: 'segwit',
|
||||
},
|
||||
servertimeout: {
|
||||
name: 'Rpc Server Timeout',
|
||||
description:
|
||||
'Number of seconds after which an uncompleted RPC call will time out.',
|
||||
type: 'number',
|
||||
nullable: false,
|
||||
range: '[5,300]',
|
||||
integral: true,
|
||||
units: 'seconds',
|
||||
default: 30,
|
||||
},
|
||||
threads: {
|
||||
name: 'Threads',
|
||||
description:
|
||||
'Set the number of threads for handling RPC calls. You may wish to increase this if you are making lots of calls via an integration.',
|
||||
type: 'number',
|
||||
nullable: false,
|
||||
default: 16,
|
||||
range: '[1,64]',
|
||||
integral: true,
|
||||
},
|
||||
workqueue: {
|
||||
name: 'Work Queue',
|
||||
description:
|
||||
'Set the depth of the work queue to service RPC calls. Determines how long the backlog of RPC requests can get before it just rejects new ones.',
|
||||
type: 'number',
|
||||
nullable: false,
|
||||
default: 128,
|
||||
range: '[8,256]',
|
||||
integral: true,
|
||||
units: 'requests',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'zmq-enabled': {
|
||||
type: 'boolean',
|
||||
name: 'ZeroMQ Enabled',
|
||||
description: 'Enable the ZeroMQ interface',
|
||||
default: true,
|
||||
},
|
||||
txindex: {
|
||||
type: 'boolean',
|
||||
name: 'Transaction Index',
|
||||
description: 'Enable the Transaction Index (txindex)',
|
||||
default: true,
|
||||
},
|
||||
wallet: {
|
||||
type: 'object',
|
||||
name: 'Wallet',
|
||||
description: 'Wallet Settings',
|
||||
spec: {
|
||||
enable: {
|
||||
name: 'Enable Wallet',
|
||||
description: 'Load the wallet and enable wallet RPC calls.',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
},
|
||||
avoidpartialspends: {
|
||||
name: 'Avoid Partial Spends',
|
||||
description:
|
||||
'Group outputs by address, selecting all or none, instead of selecting on a per-output basis. This improves privacy at the expense of higher transaction fees.',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
},
|
||||
discardfee: {
|
||||
name: 'Discard Change Tolerance',
|
||||
description:
|
||||
'The fee rate (in BTC/kB) that indicates your tolerance for discarding change by adding it to the fee.',
|
||||
type: 'number',
|
||||
nullable: false,
|
||||
default: 0.0001,
|
||||
range: '[0,.01]',
|
||||
integral: false,
|
||||
units: 'BTC/kB',
|
||||
},
|
||||
},
|
||||
},
|
||||
advanced: {
|
||||
type: 'object',
|
||||
name: 'Advanced',
|
||||
description: 'Advanced Settings',
|
||||
spec: {
|
||||
mempool: {
|
||||
type: 'object',
|
||||
name: 'Mempool',
|
||||
description: 'Mempool Settings',
|
||||
spec: {
|
||||
mempoolfullrbf: {
|
||||
name: 'Enable Full RBF',
|
||||
description:
|
||||
'Policy for your node to use for relaying and mining unconfirmed transactions. For details, see https://github.com/bitcoin/bitcoin/blob/master/doc/release-notes/release-notes-24.0.md#notice-of-new-option-for-transaction-replacement-policies',
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
persistmempool: {
|
||||
type: 'boolean',
|
||||
name: 'Persist Mempool',
|
||||
description: 'Save the mempool on shutdown and load on restart.',
|
||||
default: true,
|
||||
},
|
||||
maxmempool: {
|
||||
type: 'number',
|
||||
nullable: false,
|
||||
name: 'Max Mempool Size',
|
||||
description:
|
||||
'Keep the transaction memory pool below <n> megabytes.',
|
||||
range: '[1,*)',
|
||||
integral: true,
|
||||
units: 'MiB',
|
||||
default: 300,
|
||||
},
|
||||
mempoolexpiry: {
|
||||
type: 'number',
|
||||
nullable: false,
|
||||
name: 'Mempool Expiration',
|
||||
description:
|
||||
'Do not keep transactions in the mempool longer than <n> hours.',
|
||||
range: '[1,*)',
|
||||
integral: true,
|
||||
units: 'Hr',
|
||||
default: 336,
|
||||
},
|
||||
},
|
||||
},
|
||||
peers: {
|
||||
type: 'object',
|
||||
name: 'Peers',
|
||||
description: 'Peer Connection Settings',
|
||||
spec: {
|
||||
listen: {
|
||||
type: 'boolean',
|
||||
name: 'Make Public',
|
||||
description:
|
||||
'Allow other nodes to find your server on the network.',
|
||||
default: true,
|
||||
},
|
||||
onlyconnect: {
|
||||
type: 'boolean',
|
||||
name: 'Disable Peer Discovery',
|
||||
description: 'Only connect to specified peers.',
|
||||
default: false,
|
||||
},
|
||||
onlyonion: {
|
||||
type: 'boolean',
|
||||
name: 'Disable Clearnet',
|
||||
description: 'Only connect to peers over Tor.',
|
||||
default: false,
|
||||
},
|
||||
addnode: {
|
||||
name: 'Add Nodes',
|
||||
description: 'Add addresses of nodes to connect to.',
|
||||
type: 'list',
|
||||
subtype: 'object',
|
||||
range: '[0,*)',
|
||||
default: [],
|
||||
spec: {
|
||||
'unique-by': null,
|
||||
spec: {
|
||||
hostname: {
|
||||
type: 'string',
|
||||
nullable: true,
|
||||
name: 'Hostname',
|
||||
description: 'Domain or IP address of bitcoin peer',
|
||||
pattern:
|
||||
'(^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)|((^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$)|(^[a-z2-7]{16}\\.onion$)|(^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$))',
|
||||
'pattern-description':
|
||||
"Must be either a domain name, or an IPv4 or IPv6 address. Do not include protocol scheme (eg 'http://') or port.",
|
||||
masked: false,
|
||||
},
|
||||
port: {
|
||||
type: 'number',
|
||||
nullable: true,
|
||||
name: 'Port',
|
||||
description:
|
||||
'Port that peer is listening on for inbound p2p connections',
|
||||
range: '[0,65535]',
|
||||
integral: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
dbcache: {
|
||||
type: 'number',
|
||||
nullable: true,
|
||||
name: 'Database Cache',
|
||||
description:
|
||||
"How much RAM to allocate for caching the TXO set. Higher values improve syncing performance, but increase your chance of using up all your system's memory or corrupting your database in the event of an ungraceful shutdown. Set this high but comfortably below your system's total RAM during IBD, then turn down to 450 (or leave blank) once the sync completes.",
|
||||
warning:
|
||||
'WARNING: Increasing this value results in a higher chance of ungraceful shutdowns, which can leave your node unusable if it happens during the initial block download. Use this setting with caution. Be sure to set this back to the default (450 or leave blank) once your node is synced. DO NOT press the STOP button if your dbcache is large. Instead, set this number back to the default, hit save, and wait for bitcoind to restart on its own.',
|
||||
range: '(0,*)',
|
||||
integral: true,
|
||||
units: 'MiB',
|
||||
},
|
||||
pruning: {
|
||||
type: 'union',
|
||||
name: 'Pruning Settings',
|
||||
description:
|
||||
'Blockchain Pruning Options\nReduce the blockchain size on disk\n',
|
||||
warning:
|
||||
'If you set pruning to Manual and your disk is smaller than the total size of the blockchain, you MUST have something running that prunes these blocks or you may overfill your disk!\nDisabling pruning will convert your node into a full archival node. This requires a resync of the entire blockchain, a process that may take several days. Make sure you have enough free disk space or you may fill up your disk.\n',
|
||||
tag: {
|
||||
id: 'mode',
|
||||
name: 'Pruning Mode',
|
||||
description:
|
||||
'- Disabled: Disable pruning\n- Automatic: Limit blockchain size on disk to a certain number of megabytes\n- Manual: Prune blockchain with the "pruneblockchain" RPC\n',
|
||||
'variant-names': {
|
||||
disabled: 'Disabled',
|
||||
automatic: 'Automatic',
|
||||
manual: 'Manual',
|
||||
},
|
||||
},
|
||||
variants: {
|
||||
disabled: {},
|
||||
automatic: {
|
||||
size: {
|
||||
type: 'number',
|
||||
nullable: false,
|
||||
name: 'Max Chain Size',
|
||||
description: 'Limit of blockchain size on disk.',
|
||||
warning:
|
||||
'Increasing this value will require re-syncing your node.',
|
||||
default: 550,
|
||||
range: '[550,1000000)',
|
||||
integral: true,
|
||||
units: 'MiB',
|
||||
},
|
||||
},
|
||||
manual: {
|
||||
size: {
|
||||
type: 'number',
|
||||
nullable: false,
|
||||
name: 'Failsafe Chain Size',
|
||||
description: 'Prune blockchain if size expands beyond this.',
|
||||
default: 65536,
|
||||
range: '[550,1000000)',
|
||||
integral: true,
|
||||
units: 'MiB',
|
||||
},
|
||||
},
|
||||
},
|
||||
default: 'disabled',
|
||||
},
|
||||
blockfilters: {
|
||||
type: 'object',
|
||||
name: 'Block Filters',
|
||||
description: 'Settings for storing and serving compact block filters',
|
||||
spec: {
|
||||
blockfilterindex: {
|
||||
type: 'boolean',
|
||||
name: 'Compute Compact Block Filters (BIP158)',
|
||||
description:
|
||||
"Generate Compact Block Filters during initial sync (IBD) to enable 'getblockfilter' RPC. This is useful if dependent services need block filters to efficiently scan for addresses/transactions etc.",
|
||||
default: true,
|
||||
},
|
||||
peerblockfilters: {
|
||||
type: 'boolean',
|
||||
name: 'Serve Compact Block Filters to Peers (BIP157)',
|
||||
description:
|
||||
"Serve Compact Block Filters as a peer service to other nodes on the network. This is useful if you wish to connect an SPV client to your node to make it efficient to scan transactions without having to download all block data. 'Compute Compact Block Filters (BIP158)' is required.",
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
bloomfilters: {
|
||||
type: 'object',
|
||||
name: 'Bloom Filters (BIP37)',
|
||||
description: 'Setting for serving Bloom Filters',
|
||||
spec: {
|
||||
peerbloomfilters: {
|
||||
type: 'boolean',
|
||||
name: 'Serve Bloom Filters to Peers',
|
||||
description:
|
||||
'Peers have the option of setting filters on each connection they make after the version handshake has completed. Bloom filters are for clients implementing SPV (Simplified Payment Verification) that want to check that block headers connect together correctly, without needing to verify the full blockchain. The client must trust that the transactions in the chain are in fact valid. It is highly recommended AGAINST using for anything except Bisq integration.',
|
||||
warning:
|
||||
'This is ONLY for use with Bisq integration, please use Block Filters for all other applications.',
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
// convert this to `start-sdk/lib` for conversions
|
||||
StartSdk: './output.sdk',
|
||||
},
|
||||
)
|
||||
@@ -1,148 +0,0 @@
|
||||
import { inputSpecSpec, InputSpecSpec } from './output'
|
||||
import * as _I from '../index'
|
||||
import { camelCase } from '../../scripts/oldSpecToBuilder'
|
||||
import { deepMerge } from '../../../base/lib/util'
|
||||
|
||||
export type IfEquals<T, U, Y = unknown, N = never> =
|
||||
(<G>() => G extends T ? 1 : 2) extends <G>() => G extends U ? 1 : 2 ? Y : N
|
||||
export function testOutput<A, B>(): (c: IfEquals<A, B>) => null {
|
||||
return () => null
|
||||
}
|
||||
|
||||
/// Testing the types of the input spec
|
||||
testOutput<InputSpecSpec['rpc']['enable'], boolean>()(null)
|
||||
testOutput<InputSpecSpec['rpc']['username'], string>()(null)
|
||||
testOutput<InputSpecSpec['rpc']['username'], string>()(null)
|
||||
|
||||
testOutput<InputSpecSpec['rpc']['advanced']['auth'], string[]>()(null)
|
||||
testOutput<
|
||||
InputSpecSpec['rpc']['advanced']['serialversion'],
|
||||
'segwit' | 'non-segwit'
|
||||
>()(null)
|
||||
testOutput<InputSpecSpec['rpc']['advanced']['servertimeout'], number>()(null)
|
||||
testOutput<
|
||||
InputSpecSpec['advanced']['peers']['addnode'][0]['hostname'],
|
||||
string | null
|
||||
>()(null)
|
||||
testOutput<
|
||||
InputSpecSpec['testListUnion'][0]['union']['value']['name'],
|
||||
string
|
||||
>()(null)
|
||||
testOutput<InputSpecSpec['testListUnion'][0]['union']['selection'], 'lnd'>()(
|
||||
null,
|
||||
)
|
||||
testOutput<InputSpecSpec['mediasources'], Array<'filebrowser' | 'nextcloud'>>()(
|
||||
null,
|
||||
)
|
||||
|
||||
// @ts-expect-error Because enable should be a boolean
|
||||
testOutput<InputSpecSpec['rpc']['enable'], string>()(null)
|
||||
// prettier-ignore
|
||||
// @ts-expect-error Expect that the string is the one above
|
||||
testOutput<InputSpecSpec["testListUnion"][0]['selection']['selection'], "selection">()(null);
|
||||
|
||||
/// Here we test the output of the matchInputSpecSpec function
|
||||
describe('Inputs', () => {
|
||||
const validInput: InputSpecSpec = {
|
||||
mediasources: ['filebrowser'],
|
||||
testListUnion: [
|
||||
{
|
||||
union: { selection: 'lnd', value: { name: 'string' } },
|
||||
},
|
||||
],
|
||||
rpc: {
|
||||
enable: true,
|
||||
bio: 'This is a bio',
|
||||
username: 'test',
|
||||
password: 'test',
|
||||
advanced: {
|
||||
auth: ['test'],
|
||||
serialversion: 'segwit',
|
||||
servertimeout: 6,
|
||||
threads: 3,
|
||||
workqueue: 9,
|
||||
},
|
||||
},
|
||||
'zmq-enabled': false,
|
||||
txindex: false,
|
||||
wallet: { enable: false, avoidpartialspends: false, discardfee: 0.0001 },
|
||||
advanced: {
|
||||
mempool: {
|
||||
maxmempool: 1,
|
||||
persistmempool: true,
|
||||
mempoolexpiry: 23,
|
||||
mempoolfullrbf: true,
|
||||
},
|
||||
peers: {
|
||||
listen: true,
|
||||
onlyconnect: true,
|
||||
onlyonion: true,
|
||||
addnode: [
|
||||
{
|
||||
hostname: 'test',
|
||||
port: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
dbcache: 5,
|
||||
pruning: {
|
||||
selection: 'disabled',
|
||||
value: { disabled: {} },
|
||||
},
|
||||
blockfilters: {
|
||||
blockfilterindex: false,
|
||||
peerblockfilters: false,
|
||||
},
|
||||
bloomfilters: { peerbloomfilters: false },
|
||||
},
|
||||
}
|
||||
|
||||
test('test valid input', async () => {
|
||||
const { validator } = await inputSpecSpec.build({} as any)
|
||||
const output = validator.unsafeCast(validInput)
|
||||
expect(output).toEqual(validInput)
|
||||
})
|
||||
test('test no longer care about the conversion of min/max and validating', async () => {
|
||||
const { validator } = await inputSpecSpec.build({} as any)
|
||||
validator.unsafeCast(
|
||||
deepMerge({}, validInput, { rpc: { advanced: { threads: 0 } } }),
|
||||
)
|
||||
})
|
||||
test('test errors should throw for number in string', async () => {
|
||||
const { validator } = await inputSpecSpec.build({} as any)
|
||||
expect(() =>
|
||||
validator.unsafeCast(deepMerge({}, validInput, { rpc: { enable: 2 } })),
|
||||
).toThrowError()
|
||||
})
|
||||
test('Test that we set serialversion to something not segwit or non-segwit', async () => {
|
||||
const { validator } = await inputSpecSpec.build({} as any)
|
||||
expect(() =>
|
||||
validator.unsafeCast(
|
||||
deepMerge({}, validInput, {
|
||||
rpc: { advanced: { serialversion: 'testing' } },
|
||||
}),
|
||||
),
|
||||
).toThrowError()
|
||||
})
|
||||
})
|
||||
|
||||
describe('camelCase', () => {
|
||||
test("'EquipmentClass name'", () => {
|
||||
expect(camelCase('EquipmentClass name')).toEqual('equipmentClassName')
|
||||
})
|
||||
test("'Equipment className'", () => {
|
||||
expect(camelCase('Equipment className')).toEqual('equipmentClassName')
|
||||
})
|
||||
test("'equipment class name'", () => {
|
||||
expect(camelCase('equipment class name')).toEqual('equipmentClassName')
|
||||
})
|
||||
test("'Equipment Class Name'", () => {
|
||||
expect(camelCase('Equipment Class Name')).toEqual('equipmentClassName')
|
||||
})
|
||||
test("'hyphen-name-format'", () => {
|
||||
expect(camelCase('hyphen-name-format')).toEqual('hyphenNameFormat')
|
||||
})
|
||||
test("'underscore_name_format'", () => {
|
||||
expect(camelCase('underscore_name_format')).toEqual('underscoreNameFormat')
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as matches from 'ts-matches'
|
||||
import { z } from 'zod'
|
||||
import * as YAML from 'yaml'
|
||||
import * as TOML from '@iarna/toml'
|
||||
import * as INI from 'ini'
|
||||
@@ -97,7 +97,7 @@ function toPath(path: ToPath): string {
|
||||
return path.base.subpath(path.subpath)
|
||||
}
|
||||
|
||||
type Validator<T, U> = matches.Validator<T, U> | matches.Validator<unknown, U>
|
||||
type Validator<_T, U> = z.ZodType<U>
|
||||
|
||||
type ReadType<A> = {
|
||||
once: () => Promise<A | null>
|
||||
@@ -499,7 +499,7 @@ export class FileHelper<A> {
|
||||
(inData) => inData,
|
||||
(inString) => inString,
|
||||
(data) =>
|
||||
(shape || (matches.string as Validator<Transformed, A>)).unsafeCast(
|
||||
(shape || (z.string() as unknown as Validator<Transformed, A>)).parse(
|
||||
data,
|
||||
),
|
||||
transformers,
|
||||
@@ -518,7 +518,7 @@ export class FileHelper<A> {
|
||||
path,
|
||||
(inData) => JSON.stringify(inData, null, 2),
|
||||
(inString) => JSON.parse(inString),
|
||||
(data) => shape.unsafeCast(data),
|
||||
(data) => shape.parse(data),
|
||||
transformers,
|
||||
)
|
||||
}
|
||||
@@ -544,7 +544,7 @@ export class FileHelper<A> {
|
||||
path,
|
||||
(inData) => YAML.stringify(inData, null, 2),
|
||||
(inString) => YAML.parse(inString),
|
||||
(data) => shape.unsafeCast(data),
|
||||
(data) => shape.parse(data),
|
||||
transformers,
|
||||
)
|
||||
}
|
||||
@@ -570,7 +570,7 @@ export class FileHelper<A> {
|
||||
path,
|
||||
(inData) => TOML.stringify(inData as TOML.JsonMap),
|
||||
(inString) => TOML.parse(inString),
|
||||
(data) => shape.unsafeCast(data),
|
||||
(data) => shape.parse(data),
|
||||
transformers,
|
||||
)
|
||||
}
|
||||
@@ -596,7 +596,7 @@ export class FileHelper<A> {
|
||||
path,
|
||||
(inData) => INI.stringify(filterUndefined(inData), options),
|
||||
(inString) => INI.parse(inString, options),
|
||||
(data) => shape.unsafeCast(data),
|
||||
(data) => shape.parse(data),
|
||||
transformers,
|
||||
)
|
||||
}
|
||||
@@ -632,7 +632,7 @@ export class FileHelper<A> {
|
||||
return [line.slice(0, pos), line.slice(pos + 1)]
|
||||
}),
|
||||
),
|
||||
(data) => shape.unsafeCast(data),
|
||||
(data) => shape.parse(data),
|
||||
transformers,
|
||||
)
|
||||
}
|
||||
|
||||
23
sdk/package/package-lock.json
generated
23
sdk/package/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@start9labs/start-sdk",
|
||||
"version": "0.4.0-beta.50",
|
||||
"version": "0.4.0-beta.51",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@start9labs/start-sdk",
|
||||
"version": "0.4.0-beta.50",
|
||||
"version": "0.4.0-beta.51",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@iarna/toml": "^3.0.0",
|
||||
@@ -17,8 +17,8 @@
|
||||
"ini": "^5.0.0",
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"mime": "^4.0.7",
|
||||
"ts-matches": "^6.3.2",
|
||||
"yaml": "^2.7.1"
|
||||
"yaml": "^2.7.1",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.4.0",
|
||||
@@ -4815,12 +4815,6 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-matches": {
|
||||
"version": "6.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ts-matches/-/ts-matches-6.3.2.tgz",
|
||||
"integrity": "sha512-UhSgJymF8cLd4y0vV29qlKVCkQpUtekAaujXbQVc729FezS8HwqzepqvtjzQ3HboatIqN/Idor85O2RMwT7lIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ts-morph": {
|
||||
"version": "18.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-morph/-/ts-morph-18.0.0.tgz",
|
||||
@@ -5232,6 +5226,15 @@
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
|
||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@start9labs/start-sdk",
|
||||
"version": "0.4.0-beta.50",
|
||||
"version": "0.4.0-beta.51",
|
||||
"description": "Software development kit to facilitate packaging services for StartOS",
|
||||
"main": "./package/lib/index.js",
|
||||
"types": "./package/lib/index.d.ts",
|
||||
@@ -31,16 +31,16 @@
|
||||
},
|
||||
"homepage": "https://github.com/Start9Labs/start-os#readme",
|
||||
"dependencies": {
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"mime": "^4.0.7",
|
||||
"ts-matches": "^6.3.2",
|
||||
"yaml": "^2.7.1",
|
||||
"deep-equality-data-structures": "^2.0.0",
|
||||
"ini": "^5.0.0",
|
||||
"@types/ini": "^4.1.1",
|
||||
"@iarna/toml": "^3.0.0",
|
||||
"@noble/curves": "^1.8.2",
|
||||
"@noble/hashes": "^1.7.2"
|
||||
"@noble/hashes": "^1.7.2",
|
||||
"@types/ini": "^4.1.1",
|
||||
"deep-equality-data-structures": "^2.0.0",
|
||||
"ini": "^5.0.0",
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"mime": "^4.0.7",
|
||||
"yaml": "^2.7.1",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"prettier": {
|
||||
"trailingComma": "all",
|
||||
|
||||
@@ -1,384 +0,0 @@
|
||||
import * as fs from 'fs'
|
||||
|
||||
// https://stackoverflow.com/questions/2970525/converting-any-string-into-camel-case
|
||||
export function camelCase(value: string) {
|
||||
return value
|
||||
.replace(/([\(\)\[\]])/g, '')
|
||||
.replace(/^([A-Z])|[\s-_](\w)/g, function (match, p1, p2, offset) {
|
||||
if (p2) return p2.toUpperCase()
|
||||
return p1.toLowerCase()
|
||||
})
|
||||
}
|
||||
|
||||
export async function oldSpecToBuilder(
|
||||
file: string,
|
||||
inputData: Promise<any> | any,
|
||||
options?: Parameters<typeof makeFileContentFromOld>[1],
|
||||
) {
|
||||
await fs.writeFile(
|
||||
file,
|
||||
await makeFileContentFromOld(inputData, options),
|
||||
(err) => console.error(err),
|
||||
)
|
||||
}
|
||||
|
||||
function isString(x: unknown): x is string {
|
||||
return typeof x === 'string'
|
||||
}
|
||||
|
||||
export default async function makeFileContentFromOld(
|
||||
inputData: Promise<any> | any,
|
||||
{ StartSdk = 'start-sdk', nested = true } = {},
|
||||
) {
|
||||
const outputLines: string[] = []
|
||||
outputLines.push(`
|
||||
import { sdk } from "${StartSdk}"
|
||||
const {InputSpec, List, Value, Variants} = sdk
|
||||
`)
|
||||
const data = await inputData
|
||||
|
||||
const namedConsts = new Set(['InputSpec', 'Value', 'List'])
|
||||
const inputSpecName = newConst('inputSpecSpec', convertInputSpec(data))
|
||||
outputLines.push(`export type InputSpecSpec = typeof ${inputSpecName}._TYPE;`)
|
||||
|
||||
return outputLines.join('\n')
|
||||
|
||||
function newConst(key: string, data: string, type?: string) {
|
||||
const variableName = getNextConstName(camelCase(key))
|
||||
outputLines.push(
|
||||
`export const ${variableName}${!type ? '' : `: ${type}`} = ${data};`,
|
||||
)
|
||||
return variableName
|
||||
}
|
||||
function maybeNewConst(key: string, data: string) {
|
||||
if (nested) return data
|
||||
return newConst(key, data)
|
||||
}
|
||||
function convertInputSpecInner(data: any) {
|
||||
let answer = '{'
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
const variableName = maybeNewConst(key, convertValueSpec(value))
|
||||
|
||||
answer += `${JSON.stringify(key)}: ${variableName},`
|
||||
}
|
||||
return `${answer}}`
|
||||
}
|
||||
|
||||
function convertInputSpec(data: any) {
|
||||
return `InputSpec.of(${convertInputSpecInner(data)})`
|
||||
}
|
||||
function convertValueSpec(value: any): string {
|
||||
switch (value.type) {
|
||||
case 'string': {
|
||||
if (value.textarea) {
|
||||
return `${rangeToTodoComment(
|
||||
value?.range,
|
||||
)}Value.textarea(${JSON.stringify(
|
||||
{
|
||||
name: value.name || null,
|
||||
description: value.description || null,
|
||||
warning: value.warning || null,
|
||||
required: !(value.nullable || false),
|
||||
default: value.default,
|
||||
placeholder: value.placeholder || null,
|
||||
minLength: null,
|
||||
maxLength: null,
|
||||
minRows: 3,
|
||||
maxRows: 6,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)})`
|
||||
}
|
||||
return `${rangeToTodoComment(value?.range)}Value.text(${JSON.stringify(
|
||||
{
|
||||
name: value.name || null,
|
||||
default: value.default || null,
|
||||
required: !value.nullable,
|
||||
description: value.description || null,
|
||||
warning: value.warning || null,
|
||||
masked: value.masked || false,
|
||||
placeholder: value.placeholder || null,
|
||||
inputmode: 'text',
|
||||
patterns: value.pattern
|
||||
? [
|
||||
{
|
||||
regex: value.pattern,
|
||||
description: value['pattern-description'],
|
||||
},
|
||||
]
|
||||
: [],
|
||||
minLength: null,
|
||||
maxLength: null,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)})`
|
||||
}
|
||||
case 'number': {
|
||||
return `${rangeToTodoComment(
|
||||
value?.range,
|
||||
)}Value.number(${JSON.stringify(
|
||||
{
|
||||
name: value.name || null,
|
||||
description: value.description || null,
|
||||
warning: value.warning || null,
|
||||
default: value.default || null,
|
||||
required: !value.nullable,
|
||||
min: null,
|
||||
max: null,
|
||||
step: null,
|
||||
integer: value.integral || false,
|
||||
units: value.units || null,
|
||||
placeholder: value.placeholder || null,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)})`
|
||||
}
|
||||
case 'boolean': {
|
||||
return `Value.toggle(${JSON.stringify(
|
||||
{
|
||||
name: value.name || null,
|
||||
default: value.default || false,
|
||||
description: value.description || null,
|
||||
warning: value.warning || null,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)})`
|
||||
}
|
||||
case 'enum': {
|
||||
const allValueNames = new Set([
|
||||
...(value?.['values'] || []),
|
||||
...Object.keys(value?.['value-names'] || {}),
|
||||
])
|
||||
const values = Object.fromEntries(
|
||||
Array.from(allValueNames)
|
||||
.filter(isString)
|
||||
.map((key) => [key, value?.spec?.['value-names']?.[key] || key]),
|
||||
)
|
||||
return `Value.select(${JSON.stringify(
|
||||
{
|
||||
name: value.name || null,
|
||||
description: value.description || null,
|
||||
warning: value.warning || null,
|
||||
default: value.default,
|
||||
values,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)} as const)`
|
||||
}
|
||||
case 'object': {
|
||||
const specName = maybeNewConst(
|
||||
value.name + '_spec',
|
||||
convertInputSpec(value.spec),
|
||||
)
|
||||
return `Value.object({
|
||||
name: ${JSON.stringify(value.name || null)},
|
||||
description: ${JSON.stringify(value.description || null)},
|
||||
}, ${specName})`
|
||||
}
|
||||
case 'union': {
|
||||
const variants = maybeNewConst(
|
||||
value.name + '_variants',
|
||||
convertVariants(value.variants, value.tag['variant-names'] || {}),
|
||||
)
|
||||
|
||||
return `Value.union({
|
||||
name: ${JSON.stringify(value.name || null)},
|
||||
description: ${JSON.stringify(value.tag.description || null)},
|
||||
warning: ${JSON.stringify(value.tag.warning || null)},
|
||||
default: ${JSON.stringify(value.default)},
|
||||
variants: ${variants},
|
||||
})`
|
||||
}
|
||||
case 'list': {
|
||||
if (value.subtype === 'enum') {
|
||||
const allValueNames = new Set([
|
||||
...(value?.spec?.['values'] || []),
|
||||
...Object.keys(value?.spec?.['value-names'] || {}),
|
||||
])
|
||||
const values = Object.fromEntries(
|
||||
Array.from(allValueNames)
|
||||
.filter(isString)
|
||||
.map((key: string) => [
|
||||
key,
|
||||
value?.spec?.['value-names']?.[key] ?? key,
|
||||
]),
|
||||
)
|
||||
return `Value.multiselect(${JSON.stringify(
|
||||
{
|
||||
name: value.name || null,
|
||||
minLength: null,
|
||||
maxLength: null,
|
||||
default: value.default ?? null,
|
||||
description: value.description || null,
|
||||
warning: value.warning || null,
|
||||
values,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)})`
|
||||
}
|
||||
const list = maybeNewConst(value.name + '_list', convertList(value))
|
||||
return `Value.list(${list})`
|
||||
}
|
||||
case 'pointer': {
|
||||
return `/* TODO deal with point removed point "${value.name}" */null as any`
|
||||
}
|
||||
}
|
||||
throw Error(`Unknown type "${value.type}"`)
|
||||
}
|
||||
|
||||
function convertList(value: any) {
|
||||
switch (value.subtype) {
|
||||
case 'string': {
|
||||
return `${rangeToTodoComment(value?.range)}List.text(${JSON.stringify(
|
||||
{
|
||||
name: value.name || null,
|
||||
minLength: null,
|
||||
maxLength: null,
|
||||
default: value.default || null,
|
||||
description: value.description || null,
|
||||
warning: value.warning || null,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}, ${JSON.stringify({
|
||||
masked: value?.spec?.masked || false,
|
||||
placeholder: value?.spec?.placeholder || null,
|
||||
patterns: value?.spec?.pattern
|
||||
? [
|
||||
{
|
||||
regex: value.spec.pattern,
|
||||
description: value?.spec?.['pattern-description'],
|
||||
},
|
||||
]
|
||||
: [],
|
||||
minLength: null,
|
||||
maxLength: null,
|
||||
})})`
|
||||
}
|
||||
// case "number": {
|
||||
// return `${rangeToTodoComment(value?.range)}List.number(${JSON.stringify(
|
||||
// {
|
||||
// name: value.name || null,
|
||||
// minLength: null,
|
||||
// maxLength: null,
|
||||
// default: value.default || null,
|
||||
// description: value.description || null,
|
||||
// warning: value.warning || null,
|
||||
// },
|
||||
// null,
|
||||
// 2,
|
||||
// )}, ${JSON.stringify({
|
||||
// integer: value?.spec?.integral || false,
|
||||
// min: null,
|
||||
// max: null,
|
||||
// units: value?.spec?.units || null,
|
||||
// placeholder: value?.spec?.placeholder || null,
|
||||
// })})`
|
||||
// }
|
||||
case 'enum': {
|
||||
return '/* error!! list.enum */'
|
||||
}
|
||||
case 'object': {
|
||||
const specName = maybeNewConst(
|
||||
value.name + '_spec',
|
||||
convertInputSpec(value.spec.spec),
|
||||
)
|
||||
return `${rangeToTodoComment(value?.range)}List.obj({
|
||||
name: ${JSON.stringify(value.name || null)},
|
||||
minLength: ${JSON.stringify(null)},
|
||||
maxLength: ${JSON.stringify(null)},
|
||||
default: ${JSON.stringify(value.default || null)},
|
||||
description: ${JSON.stringify(value.description || null)},
|
||||
}, {
|
||||
spec: ${specName},
|
||||
displayAs: ${JSON.stringify(value?.spec?.['display-as'] || null)},
|
||||
uniqueBy: ${JSON.stringify(value?.spec?.['unique-by'] || null)},
|
||||
})`
|
||||
}
|
||||
case 'union': {
|
||||
const variants = maybeNewConst(
|
||||
value.name + '_variants',
|
||||
convertVariants(
|
||||
value.spec.variants,
|
||||
value.spec['variant-names'] || {},
|
||||
),
|
||||
)
|
||||
const unionValueName = maybeNewConst(
|
||||
value.name + '_union',
|
||||
`${rangeToTodoComment(value?.range)}
|
||||
Value.union({
|
||||
name: ${JSON.stringify(value?.spec?.tag?.name || null)},
|
||||
description: ${JSON.stringify(
|
||||
value?.spec?.tag?.description || null,
|
||||
)},
|
||||
warning: ${JSON.stringify(value?.spec?.tag?.warning || null)},
|
||||
default: ${JSON.stringify(value?.spec?.default || null)},
|
||||
variants: ${variants},
|
||||
})
|
||||
`,
|
||||
)
|
||||
const listInputSpec = maybeNewConst(
|
||||
value.name + '_list_inputSpec',
|
||||
`
|
||||
InputSpec.of({
|
||||
"union": ${unionValueName}
|
||||
})
|
||||
`,
|
||||
)
|
||||
return `${rangeToTodoComment(value?.range)}List.obj({
|
||||
name:${JSON.stringify(value.name || null)},
|
||||
minLength:${JSON.stringify(null)},
|
||||
maxLength:${JSON.stringify(null)},
|
||||
default: [],
|
||||
description: ${JSON.stringify(value.description || null)},
|
||||
warning: ${JSON.stringify(value.warning || null)},
|
||||
}, {
|
||||
spec: ${listInputSpec},
|
||||
displayAs: ${JSON.stringify(value?.spec?.['display-as'] || null)},
|
||||
uniqueBy: ${JSON.stringify(value?.spec?.['unique-by'] || null)},
|
||||
})`
|
||||
}
|
||||
}
|
||||
throw new Error(`Unknown subtype "${value.subtype}"`)
|
||||
}
|
||||
|
||||
function convertVariants(
|
||||
variants: Record<string, unknown>,
|
||||
variantNames: Record<string, string>,
|
||||
): string {
|
||||
let answer = 'Variants.of({'
|
||||
for (const [key, value] of Object.entries(variants)) {
|
||||
const variantSpec = maybeNewConst(key, convertInputSpec(value))
|
||||
answer += `"${key}": {name: "${
|
||||
variantNames[key] || key
|
||||
}", spec: ${variantSpec}},`
|
||||
}
|
||||
return `${answer}})`
|
||||
}
|
||||
|
||||
function getNextConstName(name: string, i = 0): string {
|
||||
const newName = !i ? name : name + i
|
||||
if (namedConsts.has(newName)) {
|
||||
return getNextConstName(name, i + 1)
|
||||
}
|
||||
namedConsts.add(newName)
|
||||
return newName
|
||||
}
|
||||
}
|
||||
|
||||
function rangeToTodoComment(range: string | undefined) {
|
||||
if (!range) return ''
|
||||
return `/* TODO: Convert range for this value (${range})*/`
|
||||
}
|
||||
|
||||
// oldSpecToBuilder(
|
||||
// "./inputSpec.ts",
|
||||
// // Put inputSpec here
|
||||
// {},
|
||||
// )
|
||||
@@ -16,5 +16,5 @@
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["lib/**/*"],
|
||||
"exclude": ["lib/**/*.spec.ts", "lib/**/*.gen.ts", "list", "node_modules"]
|
||||
"exclude": ["lib/**/*.spec.ts", "lib/**/*.test.ts", "lib/**/*.gen.ts", "list", "node_modules"]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user