diff --git a/Makefile b/Makefile index d33cbf2..57d065d 100644 --- a/Makefile +++ b/Makefile @@ -12,6 +12,9 @@ bundle: fmt $(TS_FILES) .FORCE node_modules npx tsc-multi npx tsc --emitDeclarationOnly +check: + npm run check + fmt: node_modules npx prettier --write "**/*.ts" diff --git a/README.md b/README.md index f43dcc4..20fcfc9 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ For making the patterns that are wanted in making services for the startOS. -### Generate: Config class from legacy ConfigSpec +### Generate: Config class from legacy InputSpec ```sh cat utils/test/config.json | deno run https://deno.land/x/embassyd_sdk/scripts/oldSpecToBuilder.ts "../../mod" |deno fmt - > utils/test/output.ts diff --git a/lib/backup/index.ts b/lib/backup/index.ts index 3bf642e..e6a4026 100644 --- a/lib/backup/index.ts +++ b/lib/backup/index.ts @@ -1,4 +1,3 @@ -import { ok } from "../util"; import * as T from "../types"; export const DEFAULT_OPTIONS: T.BackupOptions = { @@ -41,7 +40,7 @@ export class Backups { constructor( private options = DEFAULT_OPTIONS, - private backupSet = [] as BackupSet[] + private backupSet = [] as BackupSet[], ) {} static volumes(...volumeNames: string[]) { return new Backups().addSets( @@ -50,7 +49,7 @@ export class Backups { srcPath: "./", dstPath: `./${srcVolume}/`, dstVolume: Backups.BACKUP, - })) + })), ); } static addSets(...options: BackupSet[]) { @@ -73,12 +72,12 @@ export class Backups { srcPath: "./", dstPath: `./${srcVolume}/`, dstVolume: Backups.BACKUP, - })) + })), ); } addSets(...options: BackupSet[]) { options.forEach((x) => - this.backupSet.push({ ...x, options: { ...this.options, ...x.options } }) + this.backupSet.push({ ...x, options: { ...this.options, ...x.options } }), ); return this; } @@ -99,7 +98,7 @@ export class Backups { .map((x) => x.dstPath) .map((x) => x.replace(/\.\/([^]*)\//, "$1")); const filteredItems = previousItems.filter( - (x) => backupPaths.indexOf(x) === -1 + (x) => backupPaths.indexOf(x) === -1, ); for (const itemToRemove of filteredItems) { effects.error(`Trying to remove ${itemToRemove}`); @@ -112,7 +111,7 @@ export class Backups { effects.removeFile({ volumeId: Backups.BACKUP, path: itemToRemove, - }) + }), ) .catch(() => { effects.warn(`Failed to remove ${itemToRemove} from backup volume`); @@ -135,7 +134,7 @@ export class Backups { }) .wait(); } - return ok; + return; }; const restoreBackup: T.ExpectedExports.restoreBackup = async ({ effects, @@ -160,7 +159,7 @@ export class Backups { }) .wait(); } - return ok; + return; }; return { createBackup, restoreBackup }; } diff --git a/lib/config/builder/config.ts b/lib/config/builder/config.ts index 8824759..721248e 100644 --- a/lib/config/builder/config.ts +++ b/lib/config/builder/config.ts @@ -1,4 +1,4 @@ -import { ConfigSpec, ValueSpec } from "../../types/config-types"; +import { InputSpec, ValueSpec } from "../../types/config-types"; import { typeFromProps } from "../../util"; import { BuilderExtract, IBuilder } from "./builder"; import { Value } from "./value"; @@ -483,19 +483,19 @@ import { Value } from "./value"; ``` */ -export class Config extends IBuilder { +export class Config extends IBuilder { static empty() { return new Config({}); } static withValue( key: K, - value: Value + value: Value, ) { return Config.empty().withValue(key, value); } static addValue( key: K, - value: Value + value: Value, ) { return Config.empty().withValue(key, value); } diff --git a/lib/config/builder/list.ts b/lib/config/builder/list.ts index b5e47e5..fdc9878 100644 --- a/lib/config/builder/list.ts +++ b/lib/config/builder/list.ts @@ -4,7 +4,7 @@ import { Default, NumberSpec, StringSpec } from "./value"; import { Description } from "./value"; import { Variants } from "./variants"; import { - ConfigSpec, + InputSpec, UniqueBy, ValueSpecList, ValueSpecListOf, @@ -38,7 +38,7 @@ export class List extends IBuilder { Default & { range: string; spec: StringSpec; - } + }, >(a: A) { return new List({ type: "list" as const, @@ -51,7 +51,7 @@ export class List extends IBuilder { Default & { range: string; spec: NumberSpec; - } + }, >(a: A) { return new List({ type: "list" as const, @@ -69,7 +69,7 @@ export class List extends IBuilder { [key: string]: string; }; }; - } + }, >(a: A) { return new List({ type: "list" as const, @@ -82,11 +82,11 @@ export class List extends IBuilder { Default[]> & { range: string; spec: { - spec: Config; + spec: Config; "display-as": null | string; "unique-by": null | UniqueBy; }; - } + }, >(a: A) { const { spec: previousSpec, ...rest } = a; const { spec: previousSpecSpec, ...restSpec } = previousSpec; @@ -121,13 +121,13 @@ export class List extends IBuilder { [key: string]: string; }; }; - variants: Variants<{ [key: string]: ConfigSpec }>; + variants: Variants<{ [key: string]: InputSpec }>; "display-as": null | string; "unique-by": UniqueBy; default: string; }; }, - B extends string + B extends string, >(a: A) { const { spec: previousSpec, ...rest } = a; const { variants: previousVariants, ...restSpec } = previousSpec; diff --git a/lib/config/builder/value.ts b/lib/config/builder/value.ts index 72c6526..c85335a 100644 --- a/lib/config/builder/value.ts +++ b/lib/config/builder/value.ts @@ -3,7 +3,7 @@ import { Config } from "./config"; import { List } from "./list"; import { Variants } from "./variants"; import { - ConfigSpec, + InputSpec, UniqueBy, ValueSpec, ValueSpecList, @@ -80,7 +80,7 @@ export class Value extends IBuilder { A extends Description & NullableDefault & Nullable & - StringSpec + StringSpec, >(a: A) { return new Value({ type: "string" as const, @@ -88,7 +88,7 @@ export class Value extends IBuilder { } as ValueSpecString); } static number< - A extends Description & NullableDefault & Nullable & NumberSpec + A extends Description & NullableDefault & Nullable & NumberSpec, >(a: A) { return new Value({ type: "number" as const, @@ -100,7 +100,7 @@ export class Value extends IBuilder { Default & { values: readonly string[] | string[]; "value-names": Record; - } + }, >(a: A) { return new Value({ type: "enum" as const, @@ -115,9 +115,9 @@ export class Value extends IBuilder { default: null | { [k: string]: unknown }; "display-as": null | string; "unique-by": null | string; - spec: Config; + spec: Config; "value-names": Record; - } + }, >(a: A) { const { spec: previousSpec, ...rest } = a; const spec = previousSpec.build() as BuilderExtract; @@ -139,11 +139,11 @@ export class Value extends IBuilder { [key: string]: string; }; }; - variants: Variants<{ [key: string]: ConfigSpec }>; + variants: Variants<{ [key: string]: InputSpec }>; "display-as": string | null; "unique-by": UniqueBy; }, - B extends string + B extends string, >(a: A) { const { variants: previousVariants, ...rest } = a; const variants = previousVariants.build() as BuilderExtract; diff --git a/lib/config/builder/variants.ts b/lib/config/builder/variants.ts index 5d7018b..e1a9fb3 100644 --- a/lib/config/builder/variants.ts +++ b/lib/config/builder/variants.ts @@ -1,4 +1,4 @@ -import { ConfigSpec } from "../../types/config-types"; +import { InputSpec } from "../../types/config-types"; import { BuilderExtract, IBuilder } from "./builder"; import { Config } from "."; @@ -39,12 +39,12 @@ import { Config } from "."; ``` */ export class Variants< - A extends { [key: string]: ConfigSpec } + A extends { [key: string]: InputSpec }, > extends IBuilder { static of< A extends { - [key: string]: Config; - } + [key: string]: Config; + }, >(a: A) { const variants: { [K in keyof A]: BuilderExtract } = {} as any; for (const key in a) { @@ -56,17 +56,14 @@ export class Variants< static empty() { return Variants.of({}); } - static withVariant( + static withVariant( key: K, - value: Config + value: Config, ) { return Variants.empty().withVariant(key, value); } - withVariant( - key: K, - value: Config - ) { + withVariant(key: K, value: Config) { return new Variants({ ...this.a, [key]: value.build(), diff --git a/lib/config/setup_config_export.ts b/lib/config/setup_config_export.ts index 5a3d702..bd37820 100644 --- a/lib/config/setup_config_export.ts +++ b/lib/config/setup_config_export.ts @@ -1,7 +1,7 @@ import { Config } from "./builder"; import { DeepPartial, DependsOn, Effects, ExpectedExports } from "../types"; -import { ConfigSpec } from "../types/config-types"; -import { nullIfEmpty, okOf } from "../util"; +import { InputSpec } from "../types/config-types"; +import { nullIfEmpty } from "../util"; import { TypeFromProps } from "../util/propertiesMatcher"; /** @@ -11,7 +11,7 @@ import { TypeFromProps } from "../util/propertiesMatcher"; * @param options * @returns */ -export function setupConfigExports(options: { +export function setupConfigExports(options: { spec: Config; dependsOn: DependsOn; write(effects: Effects, config: TypeFromProps): Promise; @@ -25,16 +25,16 @@ export function setupConfigExports(options: { return { error: "Set config type error for config" }; } await options.write(effects, config); - return okOf({ + return { signal: "SIGTERM", "depends-on": options.dependsOn, - }); + }; }) as ExpectedExports.setConfig, getConfig: (async ({ effects }) => { - return okOf({ + return { spec: options.spec.build(), config: nullIfEmpty(await options.read(effects)), - }); + }; }) as ExpectedExports.getConfig, }; } diff --git a/lib/health/util.ts b/lib/health/util.ts index 78f8216..9f4e6e2 100644 --- a/lib/health/util.ts +++ b/lib/health/util.ts @@ -1,4 +1,4 @@ -import { Effects, ResultType } from "../types"; +import { Effects } from "../types"; import { isKnownError } from "../util"; import { HealthResult } from "./healthRunner"; @@ -10,10 +10,10 @@ import { HealthResult } from "./healthRunner"; */ export const checkWebUrl: ( url: string, - createSuccess?: null | ((response?: string | null) => string) + createSuccess?: null | ((response?: string | null) => string), ) => (effects: Effects, duration: number) => Promise = ( url, - createSuccess = null + createSuccess = null, ) => { return async (effects, duration) => { const errorValue = guardDurationAboveMinimum({ @@ -55,22 +55,12 @@ export const runHealthScript = args: string[]; message: ((result: unknown) => string) | null; }) => - async ( - effects: Effects, - _duration: number - ): Promise> => { + async (effects: Effects, _duration: number): Promise => { const res = await effects.runCommand({ command, args }); - if ("result" in res) { - return { - result: { - success: - message?.(res) ?? - `Have ran script ${command} and the result: ${res.result}`, - }, - }; - } else { - throw res; - } + return { + success: + message?.(res) ?? `Have ran script ${command} and the result: ${res}`, + }; }; // Ensure the starting duration is pass a minimum diff --git a/lib/scripts/oldSpecToBuilder.ts b/lib/scripts/oldSpecToBuilder.ts index d5616d0..b896818 100644 --- a/lib/scripts/oldSpecToBuilder.ts +++ b/lib/scripts/oldSpecToBuilder.ts @@ -4,16 +4,16 @@ import * as fs from "fs"; export async function writeConvertedFile( file: string, inputData: Promise | any, - options: Parameters[1] + options: Parameters[1], ) { await fs.writeFile(file, await makeFileContent(inputData, options), (err) => - console.error(err) + console.error(err), ); } export default async function makeFileContent( inputData: Promise | any, - { startSdk = "start-sdk" } = {} + { startSdk = "start-sdk" } = {}, ) { const outputLines: string[] = []; outputLines.push(` @@ -22,13 +22,13 @@ export default async function makeFileContent( const data = await inputData; const namedConsts = new Set(["Config", "Value", "List"]); - const configName = newConst("configSpec", convertConfigSpec(data)); + const configName = newConst("InputSpec", convertInputSpec(data)); const configMatcherName = newConst( - "matchConfigSpec", - `${configName}.validator()` + "matchInputSpec", + `${configName}.validator()`, ); outputLines.push( - `export type ConfigSpec = typeof ${configMatcherName}._TYPE;` + `export type InputSpec = typeof ${configMatcherName}._TYPE;`, ); return outputLines.join("\n"); @@ -38,7 +38,7 @@ export default async function makeFileContent( outputLines.push(`export const ${variableName} = ${data};`); return variableName; } - function convertConfigSpec(data: any) { + function convertInputSpec(data: any) { let answer = "Config.of({"; for (const [key, value] of Object.entries(data)) { const variableName = newConst(key, convertValueSpec(value)); @@ -64,7 +64,7 @@ export default async function makeFileContent( textarea: value.textarea || null, }, null, - 2 + 2, )})`; } case "number": { @@ -81,7 +81,7 @@ export default async function makeFileContent( placeholder: value.placeholder || null, }, null, - 2 + 2, )})`; } case "boolean": { @@ -93,7 +93,7 @@ export default async function makeFileContent( warning: value.warning || null, }, null, - 2 + 2, )})`; } case "enum": { @@ -107,13 +107,13 @@ export default async function makeFileContent( "value-names": value["value-names"] || null, }, null, - 2 + 2, )})`; } case "object": { const specName = newConst( value.name + "_spec", - convertConfigSpec(value.spec) + convertInputSpec(value.spec), ); return `Value.object({ name: ${JSON.stringify(value.name || null)}, @@ -129,7 +129,7 @@ export default async function makeFileContent( case "union": { const variants = newConst( value.name + "_variants", - convertVariants(value.variants) + convertVariants(value.variants), ); return `Value.union({ name: ${JSON.stringify(value.name || null)}, @@ -147,7 +147,7 @@ export default async function makeFileContent( "display-as": ${JSON.stringify(value["display-as"] || null)}, "unique-by": ${JSON.stringify(value["unique-by"] || null)}, "variant-names": ${JSON.stringify( - (value["variant-names"] as any) || null + (value["variant-names"] as any) || null, )}, })`; } @@ -182,7 +182,7 @@ export default async function makeFileContent( warning: value.warning || null, }, null, - 2 + 2, )})`; } case "number": { @@ -201,7 +201,7 @@ export default async function makeFileContent( warning: value.warning || null, }, null, - 2 + 2, )})`; } case "enum": { @@ -218,13 +218,13 @@ export default async function makeFileContent( warning: value.warning || null, }, null, - 2 + 2, )})`; } case "object": { const specName = newConst( value.name + "_spec", - convertConfigSpec(value.spec.spec) + convertInputSpec(value.spec.spec), ); return `List.obj({ name: ${JSON.stringify(value.name || null)}, @@ -232,7 +232,7 @@ export default async function makeFileContent( spec: { spec: ${specName}, "display-as": ${JSON.stringify( - value?.spec?.["display-as"] || null + value?.spec?.["display-as"] || null, )}, "unique-by": ${JSON.stringify(value?.spec?.["unique-by"] || null)}, }, @@ -244,7 +244,7 @@ export default async function makeFileContent( case "union": { const variants = newConst( value.name + "_variants", - convertConfigSpec(value.spec.variants) + convertInputSpec(value.spec.variants), ); return `List.union( { @@ -254,24 +254,24 @@ export default async function makeFileContent( tag: { "id":${JSON.stringify(value?.spec?.tag?.["id"] || null)}, "name": ${JSON.stringify( - value?.spec?.tag?.["name"] || null + value?.spec?.tag?.["name"] || null, )}, "description": ${JSON.stringify( - value?.spec?.tag?.["description"] || null + value?.spec?.tag?.["description"] || null, )}, "warning": ${JSON.stringify( - value?.spec?.tag?.["warning"] || null + value?.spec?.tag?.["warning"] || null, )}, "variant-names": ${JSON.stringify( - value?.spec?.tag?.["variant-names"] || {} + value?.spec?.tag?.["variant-names"] || {}, )}, }, variants: ${variants}, "display-as": ${JSON.stringify( - value?.spec?.["display-as"] || null + value?.spec?.["display-as"] || null, )}, "unique-by": ${JSON.stringify( - value?.spec?.["unique-by"] || null + value?.spec?.["unique-by"] || null, )}, default: ${JSON.stringify(value?.spec?.["default"] || null)}, }, @@ -288,7 +288,7 @@ export default async function makeFileContent( function convertVariants(variants: any) { let answer = "Variants.of({"; for (const [key, value] of Object.entries(variants)) { - const variableName = newConst(key, convertConfigSpec(value)); + const variableName = newConst(key, convertInputSpec(value)); answer += `"${key}": ${variableName},`; } return `${answer}})`; diff --git a/lib/types.ts b/lib/types.ts index f2ef111..343d495 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -1,5 +1,5 @@ export * as configTypes from "./types/config-types"; -import { ConfigSpec } from "./types/config-types"; +import { InputSpec } from "./types/config-types"; export namespace ExpectedExports { version: 1; @@ -7,25 +7,26 @@ export namespace ExpectedExports { export type setConfig = (options: { effects: Effects; input: Record; - }) => Promise>; + }) => Promise; /** Get configuration returns a shape that describes the format that the embassy ui will generate, and later send to the set config */ export type getConfig = (options: { effects: Effects; - }) => Promise>; + config: unknown; + }) => Promise; /** These are how we make sure the our dependency configurations are valid and if not how to fix them. */ export type dependencies = Dependencies; /** For backing up service data though the embassyOS UI */ export type createBackup = (options: { effects: Effects; - }) => Promise>; + }) => Promise; /** For restoring service data that was previously backed up using the embassyOS UI create backup flow. Backup restores are also triggered via the embassyOS UI, or doing a system restore flow during setup. */ export type restoreBackup = (options: { effects: Effects; - }) => Promise>; + }) => Promise; /** Properties are used to get values from the docker, like a username + password, what ports we are hosting from */ export type properties = (options: { effects: Effects; - }) => Promise>; + }) => Promise; /** Health checks are used to determine if the service is working properly after starting * A good use case is if we are using a web server, seeing if we can get to the web server. @@ -35,7 +36,7 @@ export namespace ExpectedExports { [id: string]: (options: { effects: Effects; input: TimeMs; - }) => Promise>; + }) => Promise; }; /** @@ -47,7 +48,7 @@ export namespace ExpectedExports { [id: string]: (options: { effects: Effects; input?: Record; - }) => Promise>; + }) => Promise; }; /** @@ -56,8 +57,8 @@ export namespace ExpectedExports { */ export type main = (options: { effects: Effects; - started(): null; - }) => Promise>; + started(onTerm: () => void): null; + }) => Promise; /** * Every time a package completes an install, this function is called before the main. @@ -66,14 +67,14 @@ export namespace ExpectedExports { export type init = (options: { effects: Effects; previousVersion: null | string; - }) => Promise>; + }) => Promise; /** This will be ran during any time a package is uninstalled, for example during a update * this will be called. */ export type uninit = (options: { effects: Effects; nextVersion: null | string; - }) => Promise>; + }) => Promise; } export type TimeMs = number; export type VersionString = string; @@ -82,7 +83,7 @@ export type ConfigRes = { /** This should be the previous config, that way during set config we start with the previous */ config?: null | Record; /** Shape that is describing the form in the ui */ - spec: ConfigSpec; + spec: InputSpec; }; /** Used to reach out from the pure js runtime */ export type Effects = { @@ -119,9 +120,9 @@ export type Effects = { command: string; args?: string[]; timeoutMillis?: number; - }): Promise>; + }): Promise; runDaemon(input: { command: string; args?: string[] }): { - wait(): Promise>; + wait(): Promise; term(): Promise; }; @@ -170,7 +171,7 @@ export type Effects = { method?: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "PATCH"; headers?: Record; body?: string; - } + }, ): Promise<{ method: string; ok: boolean; @@ -200,6 +201,12 @@ export type Effects = { progress: () => Promise; }; + getServiceConfig(options?: { + packageId?: string; + path?: string; + callback?: (config: unknown, previousConfig: unknown) => void; + }): Promise; + /** Get the address for another service for local internet*/ getServiceLocalAddress(options: { packageId: string; @@ -249,7 +256,7 @@ export type Effects = { name: string; description: string; id: string; - input: null | ConfigSpec; + input: null | InputSpec; }): Promise; /** * Remove an action that was exported. Used problably during main or during setConfig. @@ -349,7 +356,6 @@ export type KnownError = | { "error-code": [number, string] | readonly [number, string]; }; -export type ResultType = KnownError | { result: T }; export type PackagePropertiesV2 = { [name: string]: PackagePropertyObject | PackagePropertyString; @@ -380,15 +386,9 @@ export type Dependencies = { /** Id is the id of the package, should be the same as the manifest */ [id: string]: { /** Checks are called to make sure that our dependency is in the correct shape. If a known error is returned we know that the dependency needs modification */ - check( - effects: Effects, - input: ConfigSpec - ): Promise>; + check(effects: Effects, input: InputSpec): Promise; /** This is called after we know that the dependency package needs a new configuration, this would be a transform for defaults */ - autoConfigure( - effects: Effects, - input: ConfigSpec - ): Promise>; + autoConfigure(effects: Effects, input: InputSpec): Promise; }; }; diff --git a/lib/types/config-types.ts b/lib/types/config-types.ts index 9a3935b..6d2a824 100644 --- a/lib/types/config-types.ts +++ b/lib/types/config-types.ts @@ -1,4 +1,4 @@ -export type ConfigSpec = Record; +export type InputSpec = Record; export type ValueType = | "string" @@ -53,13 +53,13 @@ export interface ValueSpecBoolean extends WithStandalone { export interface ValueSpecUnion { type: "union"; tag: UnionTagSpec; - variants: { [key: string]: ConfigSpec }; + variants: { [key: string]: InputSpec }; default: string; } export interface ValueSpecObject extends WithStandalone { type: "object"; - spec: ConfigSpec; + spec: InputSpec; } export interface WithStandalone { @@ -111,7 +111,7 @@ export interface ValueSpecListOf // sometimes the type checker needs just a little bit of help export function isValueSpecListOf( t: ValueSpecList, - s: S + s: S, ): t is ValueSpecListOf { return t.subtype === s; } @@ -136,7 +136,7 @@ export interface ListValueSpecEnum { } export interface ListValueSpecObject { - spec: ConfigSpec; // this is a mapped type of the config object at this level, replacing the object's values with specs on those values + spec: InputSpec; // this is a mapped type of the config object at this level, replacing the object's values with specs on those values "unique-by": UniqueBy; // indicates whether duplicates can be permitted in the list "display-as": null | string; // this should be a handlebars template which can make use of the entire config which corresponds to 'spec' } @@ -150,7 +150,7 @@ export type UniqueBy = export interface ListValueSpecUnion { tag: UnionTagSpec; - variants: { [key: string]: ConfigSpec }; + variants: { [key: string]: InputSpec }; "display-as": null | string; // this may be a handlebars template which can conditionally (on tag.id) make use of each union's entries, or if left blank will display as tag.id "unique-by": UniqueBy; default: string; // this should be the variantName which one prefers a user to start with by default when creating a new union instance in a list diff --git a/lib/util/artifacts/output.ts b/lib/util/artifacts/output.ts index ee5e270..de40e99 100644 --- a/lib/util/artifacts/output.ts +++ b/lib/util/artifacts/output.ts @@ -6,6 +6,7 @@ export const enable = Value.boolean({ description: "Allow remote RPC requests.", warning: null, }); + export const username = Value.string({ name: "Username", default: "bitcoin", @@ -438,12 +439,12 @@ export const advanced1 = Value.object({ spec: advancedSpec1, "value-names": {}, }); -export const configSpec = Config.of({ +export const InputSpec = Config.of({ rpc: rpc, "zmq-enabled": zmqEnabled, txindex: txindex, wallet: wallet, advanced: advanced1, }); -export const matchConfigSpec = configSpec.validator(); -export type ConfigSpec = typeof matchConfigSpec._TYPE; +export const matchInputSpec = InputSpec.validator(); +export type InputSpec = typeof matchInputSpec._TYPE; diff --git a/lib/util/fileHelper.ts b/lib/util/fileHelper.ts index 51bbaf0..787caec 100644 --- a/lib/util/fileHelper.ts +++ b/lib/util/fileHelper.ts @@ -12,7 +12,7 @@ const previousPath = /(.+?)\/([^/]*)$/; * to keep the same path on the read and write, and have methods for helping with structured data. * And if we are not using a structured data, we can use the raw method which forces the construction of a BiMap * ```ts - import {configSpec} from './configSpec.ts' + import {InputSpec} from './InputSpec.ts' import {matches, T} from '../deps.ts'; const { object, string, number, boolean, arrayOf, array, anyOf, allOf } = matches const someValidator = object({ @@ -45,7 +45,7 @@ const previousPath = /(.+?)\/([^/]*)$/; } export const getConfig: T.ExpectedExports.getConfig = async (effects, config) => ({ - spec: configSpec, + spec: InputSpec, config: nullIfEmpty({ ...jsonFile.get(effects) }) @@ -56,7 +56,7 @@ export class FileHelper { readonly path: string, readonly volume: string, readonly writeData: (dataIn: A) => string, - readonly readData: (stringValue: string) => A + readonly readData: (stringValue: string) => A, ) {} async write(data: A, effects: T.Effects) { let matched; @@ -86,21 +86,21 @@ export class FileHelper { await effects.readFile({ path: this.path, volumeId: this.volume, - }) + }), ); } static raw( path: string, volume: string, toFile: (dataIn: A) => string, - fromFile: (rawData: string) => A + fromFile: (rawData: string) => A, ) { return new FileHelper(path, volume, toFile, fromFile); } static json( path: string, volume: string, - shape: matches.Validator + shape: matches.Validator, ) { return new FileHelper( path, @@ -110,13 +110,13 @@ export class FileHelper { }, (inString) => { return shape.unsafeCast(JSON.parse(inString)); - } + }, ); } static toml>( path: string, volume: string, - shape: matches.Validator + shape: matches.Validator, ) { return new FileHelper( path, @@ -126,13 +126,13 @@ export class FileHelper { }, (inString) => { return shape.unsafeCast(TOML.parse(inString)); - } + }, ); } static yaml>( path: string, volume: string, - shape: matches.Validator + shape: matches.Validator, ) { return new FileHelper( path, @@ -142,7 +142,7 @@ export class FileHelper { }, (inString) => { return shape.unsafeCast(YAML.parse(inString)); - } + }, ); } } diff --git a/lib/util/index.ts b/lib/util/index.ts index efa9621..3d88ee6 100644 --- a/lib/util/index.ts +++ b/lib/util/index.ts @@ -4,34 +4,15 @@ export { guardAll, typeFromProps } from "./propertiesMatcher"; export { default as nullIfEmpty } from "./nullIfEmpty"; export { FileHelper } from "./fileHelper"; -export function unwrapResultType(res: T.ResultType): T { - if ("error-code" in res) { - throw new Error(res["error-code"][1]); - } else if ("error" in res) { - throw new Error(res["error"]); - } else { - return res.result; - } -} - /** Used to check if the file exists before hand */ export const exists = ( effects: T.Effects, - props: { path: string; volumeId: string } + props: { path: string; volumeId: string }, ) => effects.metadata(props).then( (_) => true, - (_) => false + (_) => false, ); -export const errorCode = (code: number, error: string) => ({ - "error-code": [code, error] as const, -}); -export const error = (error: string) => ({ error }); -export const okOf = (result: A) => ({ - result, -}); -export const ok = { result: null }; - export const isKnownError = (e: unknown): e is T.KnownError => e instanceof Object && ("error" in e || "error-code" in e); diff --git a/lib/util/propertiesMatcher.test.ts b/lib/util/propertiesMatcher.test.ts index e1ee694..74eb789 100644 --- a/lib/util/propertiesMatcher.test.ts +++ b/lib/util/propertiesMatcher.test.ts @@ -4,7 +4,7 @@ describe("Properties Matcher", () => { // import * as PM from "./propertiesMatcher"; // import { expect } from "https://deno.land/x/expect@v0.2.9/mod"; // import * as matches from "ts-matches"; -// import { configSpec as bitcoinPropertiesConfig } from "./test/output"; +// import { InputSpec as bitcoinPropertiesConfig } from "./test/output"; // const randWithSeed = (seed = 1) => { // return function random() { diff --git a/lib/util/propertiesMatcher.ts b/lib/util/propertiesMatcher.ts index 3add1ec..f9e07cd 100644 --- a/lib/util/propertiesMatcher.ts +++ b/lib/util/propertiesMatcher.ts @@ -1,5 +1,5 @@ import * as matches from "ts-matches"; -import { ConfigSpec, ValueSpec as ValueSpecAny } from "../types/config-types"; +import { InputSpec, ValueSpec as ValueSpecAny } from "../types/config-types"; type TypeBoolean = "boolean"; type TypeString = "string"; @@ -107,7 +107,7 @@ function charRange(value = "") { */ export function generateDefault( generate: { charset: string; len: number }, - { random = () => Math.random() } = {} + { random = () => Math.random() } = {}, ) { const validCharSets: number[][] = generate.charset .split(",") @@ -118,7 +118,7 @@ export function generateDefault( } const max = validCharSets.reduce( (acc, x) => x.reduce((x, y) => Math.max(x, y), acc), - 0 + 0, ); let i = 0; const answer: string[] = Array(generate.len); @@ -127,7 +127,7 @@ export function generateDefault( const inRange = validCharSets.reduce( (acc, [lower, upper]) => acc || (nextValue >= lower && nextValue <= upper), - false + false, ); if (!inRange) continue; answer[i] = String.fromCharCode(nextValue); @@ -155,7 +155,7 @@ export function matchNumberWithRange(range: string) { ? "any" : left === "[" ? `greaterThanOrEqualTo${leftValue}` - : `greaterThan${leftValue}` + : `greaterThan${leftValue}`, ) .validate( // prettier-ignore @@ -165,7 +165,7 @@ export function matchNumberWithRange(range: string) { // prettier-ignore rightValue === "*" ? "any" : right === "]" ? `lessThanOrEqualTo${rightValue}` : - `lessThan${rightValue}` + `lessThan${rightValue}`, ); } function withIntegral(parser: matches.Parser, value: unknown) { @@ -186,12 +186,12 @@ const isGenerator = matches.shape({ }).test; function defaultNullable( parser: matches.Parser, - value: unknown + value: unknown, ) { if (matchDefault.test(value)) { if (isGenerator(value.default)) { return parser.defaultTo( - parser.unsafeCast(generateDefault(value.default)) + parser.unsafeCast(generateDefault(value.default)), ); } return parser.defaultTo(value.default); @@ -201,7 +201,7 @@ function defaultNullable( } /** - * ConfigSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec. + * InputSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec. * ValueSpecAny: This is any of the values in a config spec. * * Use this when we want to convert a value spec any into a parser for what a config will look like @@ -209,7 +209,7 @@ function defaultNullable( * @returns */ export function guardAll( - value: A + value: A, ): matches.Parser> { if (!isType.test(value)) { return matches.unknown as any; @@ -224,7 +224,7 @@ export function guardAll( case "number": return defaultNullable( withIntegral(withRange(value), value), - value + value, ) as any; case "object": @@ -244,14 +244,14 @@ export function guardAll( matches .arrayOf(guardAll({ type: subtype, ...spec } as any)) .validate((x) => rangeValidate(x.length), "valid length"), - value + value, ) as any; } case "enum": if (matchValues.test(value)) { return defaultNullable( matches.literals(value.values[0], ...value.values), - value + value, ) as any; } return matches.unknown as any; @@ -261,8 +261,8 @@ export function guardAll( ...Object.entries(value.variants).map(([variant, spec]) => matches .shape({ [value.tag.id]: matches.literal(variant) }) - .concat(typeFromProps(spec)) - ) + .concat(typeFromProps(spec)), + ), ) as any; } return matches.unknown as any; @@ -271,15 +271,15 @@ export function guardAll( return matches.unknown as any; } /** - * ConfigSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec. + * InputSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec. * ValueSpecAny: This is any of the values in a config spec. * * Use this when we want to convert a config spec into a parser for what a config will look like * @param valueDictionary * @returns */ -export function typeFromProps( - valueDictionary: A +export function typeFromProps( + valueDictionary: A, ): matches.Parser> { if (!recordString.test(valueDictionary)) return matches.unknown as any; return matches.shape( @@ -287,7 +287,7 @@ export function typeFromProps( Object.entries(valueDictionary).map(([key, value]) => [ key, guardAll(value), - ]) - ) + ]), + ), ) as any; } diff --git a/package-lock.json b/package-lock.json index 0b654e4..fa104ad 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "start-sdk", - "version": "0.4.0-lib0.alpha4", + "version": "0.4.0-lib0.alpha5", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "start-sdk", - "version": "0.4.0-lib0.alpha4", + "version": "0.4.0-lib0.alpha5", "license": "MIT", "dependencies": { "@iarna/toml": "^2.2.5", diff --git a/package.json b/package.json index 281b909..4771dfc 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,14 @@ { "name": "start-sdk", - "version": "0.4.0-lib0.alpha5", + "version": "0.4.0-lib0.alpha6", "description": "For making the patterns that are wanted in making services for the startOS.", "main": "./index.cjs", "types": "./index.d.ts", "module": "./index.mjs", "scripts": { "test": "jest -c ./jest.config.js", - "buildOutput": "ts-node --esm ./lib/util/artifacts/makeOutput.ts" + "buildOutput": "ts-node --esm ./lib/util/artifacts/makeOutput.ts", + "check": "tsc --noEmit" }, "repository": { "type": "git",