Skip to content

Commit

Permalink
Export Schema<Id> type in @ethdebug/format
Browse files Browse the repository at this point in the history
... in case any users of this package want to try their luck with
something like json-schema-to-ts.

Specifically, do:

- Update the "yamls.ts" code generation step to output raw JSON objects
  for each schema (in addition to all the raw YAML strings currently
  output)
- Declare raw JSON objects `as const`, to preserve each schema object at
  the type-level
- Define a generic `Schema<Id>` type as a helper for getting the
  type of a schema with a given id
  • Loading branch information
gnidan committed Feb 6, 2024
1 parent 922f85a commit 1864714
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
10 changes: 10 additions & 0 deletions packages/format/bin/generate-schema-yamls.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ const readSchemaYamls = (directory) => {
}

const schemaYamls = readSchemaYamls(schemasRoot);
const rawSchemas = Object.entries(schemaYamls)
.map(([id, yaml]) => ({ [id]: YAML.parse(yaml) }))
.reduce((a, b) => ({ ...a, ...b }), {});

console.log(`export type SchemaYamlsById = {
[id: string]: string;
Expand All @@ -37,4 +40,11 @@ console.log(`export type SchemaYamlsById = {
export const schemaYamls: SchemaYamlsById = ${
JSON.stringify(schemaYamls, undefined, 2)
};
const rawSchemas = ${
JSON.stringify(rawSchemas, undefined, 2)
} as const;
export type Schema<Id extends keyof typeof rawSchemas> =
(typeof rawSchemas)[Id];
`);
2 changes: 1 addition & 1 deletion packages/format/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from "./describe";
export { schemas, schemaIds } from "./schemas";
export { schemas, schemaIds, type Schema } from "./schemas";
3 changes: 2 additions & 1 deletion packages/format/src/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { schemaYamls } from "../yamls";
import { describeSchema } from "./describe";
import { schemaYamls } from "../yamls";
export type { Schema } from "../yamls";

export const schemaIds: string[] = Object.keys(schemaYamls);
export const schemas = schemaIds
Expand Down

0 comments on commit 1864714

Please sign in to comment.