Skip to content

Commit

Permalink
feat: upgrade to latest json schema tools
Browse files Browse the repository at this point in the history
  • Loading branch information
BelfordZ committed Jul 30, 2020
1 parent c0d11ec commit ffe4935
Show file tree
Hide file tree
Showing 14 changed files with 3,524 additions and 1,892 deletions.
2 changes: 1 addition & 1 deletion .node-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
12.14.0
12.18.2
5,050 changes: 3,207 additions & 1,843 deletions package-lock.json

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,18 @@
},
"homepage": "https://github.com/open-rpc/typings#readme",
"dependencies": {
"@etclabscore/json-schema-to-types": "^1.10.1",
"@open-rpc/schema-utils-js": "^1.12.0",
"@json-schema-tools/transpiler": "^1.4.1",
"@open-rpc/schema-utils-js": "^1.14.0",
"commander": "^6.0.0",
"fs-extra": "^9.0.0"
"fs-extra": "^9.0.1"
},
"devDependencies": {
"@open-rpc/meta-schema": "^1.6.0",
"@open-rpc/meta-schema": "^1.12.6",
"@types/commander": "^2.12.2",
"@types/fs-extra": "^9.0.0",
"@types/jest": "^26.0.0",
"jest": "^25.1.0",
"ts-jest": "^25.0.0",
"typescript": "^3.5.1"
"@types/fs-extra": "^9.0.1",
"@types/jest": "^26.0.7",
"jest": "^26.1.0",
"ts-jest": "^26.1.4",
"typescript": "^3.9.7"
}
}
2 changes: 1 addition & 1 deletion src/generate-typings-file.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ensureDir, emptyDir, writeFile } from "fs-extra";
import { ensureDir, writeFile } from "fs-extra";

import MethodTypings, { OpenRPCTypingsSupportedLanguages } from "./";
import { OpenrpcDocument as OpenRPC } from "@open-rpc/meta-schema";
Expand Down
9 changes: 6 additions & 3 deletions src/go.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,23 @@ import {
GetMethodAliasName,
} from "./generator-interface";
import { ContentDescriptorObject, MethodObject } from "@open-rpc/meta-schema";
import { languageSafeName, ensureSchemaTitles } from "@etclabscore/json-schema-to-types/build/utils";

import { languageSafeName, getTitle } from "@json-schema-tools/transpiler/build/utils";
import titleizer from "@json-schema-tools/transpiler/build/titleizer";

export const getMethodAliasName: GetMethodAliasName = (method) => {
return languageSafeName(method.name);
};

const getMethodTyping = (method: MethodObject): string => {
const mResult = method.result as ContentDescriptorObject;
const resultName = languageSafeName(ensureSchemaTitles({ ...mResult.schema }).title as string);
const mutableSchema = (mResult.schema === true || mResult.schema === false) ? mResult.schema : { ...mResult.schema };
const resultName = languageSafeName(getTitle(titleizer(mutableSchema)));

const methodAliasName = getMethodAliasName(method);

const params = (method.params as ContentDescriptorObject[]).map(
(param) => `${param.name} ${languageSafeName(ensureSchemaTitles(param.schema).title as string)}`,
(param) => `${param.name} ${languageSafeName(getTitle(titleizer(param.schema)))}`,
).join(", ");

return `\t${methodAliasName}(${params}) (${resultName}, error)`;
Expand Down
183 changes: 170 additions & 13 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import MethodTypings, { OpenRPCTypingsSupportedLanguages } from ".";
import MethodTypings from ".";
import { OpenrpcDocument as OpenRPC } from "@open-rpc/meta-schema";

const getTestOpenRPCDocument = () => ({
Expand Down Expand Up @@ -27,6 +27,8 @@ const getTestOpenRPCDocument = () => ({
properties: {
reepadoop: { type: "number" },
skeepadeep: { title: "skeepadeep", type: "integer" },
aboolT: true,
aboolF: false,
},
title: "ripslip",
type: "object",
Expand All @@ -51,14 +53,18 @@ const expectedRipSlipTypescript = [
"export interface Ripslip {",
" reepadoop?: NumberHo1ClIqD;",
" skeepadeep?: Skeepadeep;",
" aboolT?: AlwaysTrue;",
" aboolF?: AlwaysFalse;",
" [k: string]: any;",
"}",
].join("\n");
const expectedJibberTypescript = "export type Jibber = (jibberNiptip: Niptip) => Promise<Ripslip>;";
const expectedTypescript = [
expectedNipTipTypescript,
expectedReepadoopTypescript,
expectedSkeepadeepTypescript,
"type AlwaysTrue = any;",
"type AlwaysFalse = any;",
expectedNipTipTypescript,
expectedRipSlipTypescript,
"/**",
" *",
Expand All @@ -75,17 +81,21 @@ const expectedRipSlipRust = [
"use std::collections::HashMap;",
"extern crate serde_json;",
"",
"pub type NumberHo1ClIqD = f64;",
"pub type Skeepadeep = i64;",
"type AlwaysTrue = serde_json::Value;",
"type AlwaysFalse = serde_json::Value;",
"/// Niptip",
"///",
"/// a really cool niptip",
"///",
"pub type Niptip = f64;",
"pub type NumberHo1ClIqD = f64;",
"pub type Skeepadeep = i64;",
"#[derive(Serialize, Deserialize)]",
"pub struct Ripslip {",
" pub(crate) reepadoop: Option<NumberHo1ClIqD>,",
" pub(crate) skeepadeep: Option<Skeepadeep>,",
" pub(crate) aboolT: Option<AlwaysTrue>,",
" pub(crate) aboolF: Option<AlwaysFalse>,",
"}",
].join("\n");

Expand All @@ -107,24 +117,59 @@ const expectedRipSlipGo = [
"type Ripslip struct {",
"\tReepadoop *NumberHo1ClIqD `json:\"reepadoop,omitempty\"`",
"\tSkeepadeep *Skeepadeep `json:\"skeepadeep,omitempty\"`",
"\tAboolT *AlwaysTrue `json:\"aboolT,omitempty\"`",
"\tAboolF *AlwaysFalse `json:\"aboolF,omitempty\"`",
"}",
].join("\n");
const expectedJibberGo = [
"type Jipperjobber interface {",
"\tJibber(jibberNiptip Niptip) (Ripslip, error)",
"}",
].join("\n");

const expectedExtraGo = [
"func (a *AnyOfNiptipRipslip) UnmarshalJSON(bytes []byte) error {",
"\tvar ok bool",
"\tvar myNiptip Niptip",
"\tif err := json.Unmarshal(bytes, &myNiptip); err == nil {",
"\t\tok = true",
"\t\ta.Niptip = &myNiptip",
"\t}",
"\tvar myRipslip Ripslip",
"\tif err := json.Unmarshal(bytes, &myRipslip); err == nil {",
"\t\tok = true",
"\t\ta.Ripslip = &myRipslip",
"\t}",
"\tif ok {",
"\t\treturn nil",
"\t}",
"\treturn errors.New(\"failed to unmarshal any of the object properties\")",
"}",
"func (o AnyOfNiptipRipslip) MarshalJSON() ([]byte, error) {",
"\tout := []interface{}",
"\tif o.Niptip != nil {",
"\t\tout = append(out, o.Niptip)",
"\t}",
"\tif o.Ripslip != nil {",
"\t\tout = append(out, o.Ripslip)",
"\t}",
"\treturn json.Marshal(out)",
"}"
].join("\n");
const expectedGo = [
expectedNipTipGo,
expectedReepadoopGo,
expectedSkeepadeepGo,
"type AlwaysTrue interface{}",
"type AlwaysFalse interface{}",
expectedNipTipGo,
expectedRipSlipGo,
"// Generated! Represents an alias to any of the provided schemas",
"type AnyOfNiptipRipslip struct {",
"\tNiptip *Niptip",
"\tRipslip *Ripslip",
"}",
expectedJibberGo,
expectedExtraGo,
expectedJibberGo
].join("\n");

const expectedNipTipPython = ["// a really cool niptip", "type Niptip float64"].join("\n");
Expand Down Expand Up @@ -351,12 +396,8 @@ describe("MethodTypings", () => {
use std::collections::HashMap;
extern crate serde_json;
pub type StringDoaGddGA = String;
pub type BooleanVyG3AETh = bool;
#[derive(Serialize, Deserialize)]
pub struct ObjectOfBooleanVyG3AETh5PX0GXMY {
pub(crate) ripslip: Option<BooleanVyG3AETh>,
}
pub type StringDoaGddGA = String;
/// UnorderedSetOfStringDoaGddGAmrf5BlCm
///
/// array of strings is all...
Expand All @@ -365,6 +406,10 @@ pub type UnorderedSetOfStringDoaGddGAmrf5BlCm = Vec<StringDoaGddGA>;
pub type IntegerXZTmW7Mv = i64;
pub type UnorderedSetOfIntegerXZTmW7MvjsBS3XxD = (IntegerXZTmW7Mv);
#[derive(Serialize, Deserialize)]
pub struct ObjectOfBooleanVyG3AETh5PX0GXMY {
pub(crate) ripslip: Option<BooleanVyG3AETh>,
}
#[derive(Serialize, Deserialize)]
pub enum OneOfUnorderedSetOfIntegerXZTmW7MvjsBS3XxDUnorderedSetOfStringDoaGddGAmrf5BlCm9HEAgL2M {
UnorderedSetOfStringDoaGddGAmrf5BlCm,
UnorderedSetOfIntegerXZTmW7MvjsBS3XxD
Expand Down Expand Up @@ -478,11 +523,9 @@ pub enum AnyOfStringDoaGddGAStringDoaGddGAObjectOfBooleanVyG3AETh5PX0GXMYOneOfUn
export type Bee = number;
export type A = string;
export type Ceee = boolean;
export type AnyOfABeeCeeePpSBogg4 = Bee | A | Ceee;
export type X = number;
export type Y = string;
export type Z = boolean;
export type OneOfXYZCMfJwVAI = X | Y | Z;
export type Baz = number;
export interface WithBaz {
baz?: Baz;
Expand All @@ -498,6 +541,8 @@ export interface WithFoo {
foo?: Foo;
[k: string]: any;
}
export type AnyOfABeeCeeePpSBogg4 = Bee | A | Ceee;
export type OneOfXYZCMfJwVAI = X | Y | Z;
export type AllOfWithBarWithBazWithFooVAQmhFhX = WithBaz & WithBar & WithFoo;
export type StringDoaGddGA = string;
/**
Expand All @@ -508,4 +553,116 @@ export type StringDoaGddGA = string;
export type AnyOfAnyOfABeeCeeePpSBogg4OneOfXYZCMfJwVAIAllOfWithBarWithBazWithFooVAQmhFhXStringDoaGddGAStringDoaGddGA = AnyOfABeeCeeePpSBogg4 | OneOfXYZCMfJwVAI | AllOfWithBarWithBazWithFooVAQmhFhX | StringDoaGddGA;
export type Jobber = (ripslip: AnyOfABeeCeeePpSBogg4, biperbopper: OneOfXYZCMfJwVAI, slippyslopper: AllOfWithBarWithBazWithFooVAQmhFhX, ripper?: StringDoaGddGA) => Promise<StringDoaGddGA>;`); //tslint:disable-line
});


it("boolean schemas", () => {
const doc = {
info: {
title: "abc",
version: "3.2.1",
},
methods: [
{
name: "jobber",
params: [
{
name: "isTrue",
schema: true,
}
],
result: {
name: "isFalse",
schema: false,
},
},
],
openrpc: "1.0.0",
} as OpenRPC;

const methodTypings = new MethodTypings(doc);
expect(methodTypings.toString("typescript"))
.toBe([
"type AlwaysTrue = any;",
"type AlwaysFalse = any;",
"/**",
" *",
" * Generated! Represents an alias to any of the provided schemas",
" *",
" */",
"export type AnyOfAlwaysTrueAlwaysFalse = AlwaysTrue | AlwaysFalse;",
"export type Jobber = (isTrue: AlwaysTrue) => Promise<AlwaysFalse>;"
].join("\n"));

expect(methodTypings.toString("rust"))
.toBe([
"use serde::{Serialize, Deserialize};",
"use std::collections::HashMap;",
"extern crate serde_json;",
"",
"type AlwaysTrue = serde_json::Value;",
"type AlwaysFalse = serde_json::Value;",
"#[derive(Serialize, Deserialize)]",
"pub enum AnyOfAlwaysTrueAlwaysFalse {",
" AlwaysTrue,",
" AlwaysFalse",
"}",
"pub fn Jobber(&mut self, isTrue: AlwaysTrue) -> RpcRequest<AlwaysFalse>;"
].join("\n"));

expect(methodTypings.toString("python"))
.toBe([
"from typing import Any, NewType",
"",
"AlwaysTrue = NewType(\"AlwaysTrue\", Any)",
"from typing import Any, NewType",
"",
"AlwaysFalse = NewType(\"AlwaysFalse\", Any)",
"from typing import NewType, Union",
'"""Generated! Represents an alias to any of the provided schemas',
'"""',
"AnyOfAlwaysTrueAlwaysFalse = NewType(\"AnyOfAlwaysTrueAlwaysFalse\", Union[AlwaysTrue, AlwaysFalse])",
""
].join("\n"));

expect(methodTypings.toString("go"))
.toBe([
"type AlwaysTrue interface{}",
"type AlwaysFalse interface{}",
"// Generated! Represents an alias to any of the provided schemas",
"type AnyOfAlwaysTrueAlwaysFalse struct {",
"\tAlwaysTrue *AlwaysTrue",
"\tAlwaysFalse *AlwaysFalse",
"}",
"func (a *AnyOfAlwaysTrueAlwaysFalse) UnmarshalJSON(bytes []byte) error {",
"\tvar ok bool",
"\tvar myAlwaysTrue AlwaysTrue",
"\tif err := json.Unmarshal(bytes, &myAlwaysTrue); err == nil {",
"\t\tok = true",
"\t\ta.AlwaysTrue = &myAlwaysTrue",
"\t}",
"\tvar myAlwaysFalse AlwaysFalse",
"\tif err := json.Unmarshal(bytes, &myAlwaysFalse); err == nil {",
"\t\tok = true",
"\t\ta.AlwaysFalse = &myAlwaysFalse",
"\t}",
"\tif ok {",
"\t\treturn nil",
"\t}",
"\treturn errors.New(\"failed to unmarshal any of the object properties\")",
"}",
"func (o AnyOfAlwaysTrueAlwaysFalse) MarshalJSON() ([]byte, error) {",
"\tout := []interface{}",
"\tif o.AlwaysTrue != nil {",
"\t\tout = append(out, o.AlwaysTrue)",
"\t}",
"\tif o.AlwaysFalse != nil {",
"\t\tout = append(out, o.AlwaysFalse)",
"\t}",
"\treturn json.Marshal(out)",
"}",
"type Abc interface {",
"\tJobber(isTrue AlwaysTrue) (AlwaysFalse, error)",
"}",
].join("\n"));
});
});
15 changes: 8 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import go from "./go";
import python from "./python";
import { Generator } from "./generator-interface";
import { OpenrpcDocument as OpenRPC, MethodObject, ContentDescriptorObject } from "@open-rpc/meta-schema";
import { getSchemasForOpenRPCDocument } from "./utils";
import JsonSchemaToTypes from "@etclabscore/json-schema-to-types";
import { languageSafeName, ensureSchemaTitles } from "@etclabscore/json-schema-to-types/build/utils";
import { getSchemasForOpenRPCDocument, deepClone } from "./utils";
import Transpiler from "@json-schema-tools/transpiler";
import { languageSafeName, getTitle } from "@json-schema-tools/transpiler/build/utils";
import titleizer from "@json-schema-tools/transpiler/build/titleizer";

interface Generators {
typescript: Generator;
Expand Down Expand Up @@ -49,7 +50,7 @@ export interface OpenRPCTypingsToStringOptions {
* A class to handle all the tasks relating to types for the OpenRPC Document.
*/
export default class MethodTypings {
private transpiler: JsonSchemaToTypes;
private transpiler: Transpiler;

private toStringOptionsDefaults: OpenRPCTypingsToStringOptions = {
includeMethodAliasTypings: true,
Expand All @@ -58,7 +59,7 @@ export default class MethodTypings {

constructor(private openrpcDocument: OpenRPC) {
const schemas = getSchemasForOpenRPCDocument(openrpcDocument);
this.transpiler = new JsonSchemaToTypes(schemas);
this.transpiler = new Transpiler(deepClone(schemas));
}

/**
Expand Down Expand Up @@ -99,8 +100,8 @@ export default class MethodTypings {

return {
method: gen.getMethodAliasName(defaultedMethod),
params: methodParams.map(({ schema }) => languageSafeName(ensureSchemaTitles(schema).title as string)),
result: languageSafeName(ensureSchemaTitles(methodResult.schema).title as string),
params: methodParams.map(({ schema }) => languageSafeName(getTitle(titleizer(schema)))),
result: languageSafeName(getTitle(titleizer(methodResult.schema))),
};
}

Expand Down
1 change: 1 addition & 0 deletions src/openrpc.fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const testOpenRPCDocument = {
result: {
name: "ripslip",
schema: {
type: "object",
properties: {
reepadoop: { type: "number" },
},
Expand Down
Loading

0 comments on commit ffe4935

Please sign in to comment.