@sdkgen/node-runtime 1.5.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,19 +18,19 @@ const axios_1 = __importDefault(require("axios"));
18
18
  const form_data_1 = __importDefault(require("form-data"));
19
19
  const src_1 = require("../../src");
20
20
  const ast = new parser_1.Parser(`${__dirname}/api.sdkgen`).parse();
21
- fs_1.writeFileSync(`${__dirname}/api.ts`, typescript_generator_1.generateNodeServerSource(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
21
+ (0, fs_1.writeFileSync)(`${__dirname}/api.ts`, (0, typescript_generator_1.generateNodeServerSource)(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
22
22
  const { api, TestError } = require(`${__dirname}/api.ts`);
23
- fs_1.unlinkSync(`${__dirname}/api.ts`);
24
- api.fn.add = async (ctx, { first, second }) => {
23
+ (0, fs_1.unlinkSync)(`${__dirname}/api.ts`);
24
+ api.fn.add = async (_ctx, { first, second }) => {
25
25
  return `${first}${second}`;
26
26
  };
27
- api.fn.maybe = async (ctx, { bin }) => {
27
+ api.fn.maybe = async (_ctx, { bin }) => {
28
28
  return bin === null ? null : Buffer.from(bin, "hex");
29
29
  };
30
- api.fn.hex = async (ctx, { bin }) => {
30
+ api.fn.hex = async (_ctx, { bin }) => {
31
31
  return bin.toString("hex");
32
32
  };
33
- api.fn.obj = async (ctx, { obj }) => {
33
+ api.fn.obj = async (_ctx, { obj }) => {
34
34
  if (obj.val === 0) {
35
35
  throw new Error("Value is zero ~ Fatal");
36
36
  }
@@ -39,13 +39,13 @@ api.fn.obj = async (ctx, { obj }) => {
39
39
  }
40
40
  return obj;
41
41
  };
42
- api.fn.returnArg = async (ctx, { arg }) => {
42
+ api.fn.returnArg = async (_ctx, { arg }) => {
43
43
  return arg;
44
44
  };
45
- api.fn.returnNoArg = async () => {
45
+ api.fn.returnNoArg = async (_ctx) => {
46
46
  return "no-arg";
47
47
  };
48
- api.fn.returnArgConcat = async (ctx, { arg, arg2 }) => {
48
+ api.fn.returnArgConcat = async (_ctx, { arg, arg2 }) => {
49
49
  return `${arg}${arg2}`;
50
50
  };
51
51
  async function readAllStream(stream) {
@@ -68,9 +68,9 @@ api.fn.getHtml = async () => {
68
68
  api.fn.getXml = async () => {
69
69
  return "<h1>Hello world!</h1>";
70
70
  };
71
- fs_1.writeFileSync(`${__dirname}/nodeClient.ts`, typescript_generator_1.generateNodeClientSource(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
71
+ (0, fs_1.writeFileSync)(`${__dirname}/nodeClient.ts`, (0, typescript_generator_1.generateNodeClientSource)(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
72
72
  const { ApiClient: NodeApiClient } = require(`${__dirname}/nodeClient.ts`);
73
- fs_1.unlinkSync(`${__dirname}/nodeClient.ts`);
73
+ (0, fs_1.unlinkSync)(`${__dirname}/nodeClient.ts`);
74
74
  const nodeClient = new NodeApiClient("http://localhost:8001");
75
75
  const server = new src_1.SdkgenHttpServer(api, {});
76
76
  describe("Rest API", () => {
@@ -13,15 +13,15 @@ const parser_1 = require("@sdkgen/parser");
13
13
  const typescript_generator_1 = require("@sdkgen/typescript-generator");
14
14
  const src_1 = require("../../src");
15
15
  const ast = new parser_1.Parser(`${__dirname}/api.sdkgen`).parse();
16
- fs_1.writeFileSync(`${__dirname}/errors-api.ts`, typescript_generator_1.generateNodeServerSource(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
16
+ (0, fs_1.writeFileSync)(`${__dirname}/errors-api.ts`, (0, typescript_generator_1.generateNodeServerSource)(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
17
17
  const { api, CustomError } = require(`${__dirname}/errors-api.ts`);
18
- fs_1.unlinkSync(`${__dirname}/errors-api.ts`);
19
- api.fn.throwCustomError = async (ctx, args) => {
18
+ (0, fs_1.unlinkSync)(`${__dirname}/errors-api.ts`);
19
+ api.fn.throwCustomError = async (_ctx, args) => {
20
20
  throw new CustomError("Some message", args);
21
21
  };
22
- fs_1.writeFileSync(`${__dirname}/errors-nodeClient.ts`, typescript_generator_1.generateNodeClientSource(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
22
+ (0, fs_1.writeFileSync)(`${__dirname}/errors-nodeClient.ts`, (0, typescript_generator_1.generateNodeClientSource)(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
23
23
  const { ApiClient: NodeApiClient } = require(`${__dirname}/errors-nodeClient.ts`);
24
- fs_1.unlinkSync(`${__dirname}/errors-nodeClient.ts`);
24
+ (0, fs_1.unlinkSync)(`${__dirname}/errors-nodeClient.ts`);
25
25
  const nodeClient = new NodeApiClient("http://localhost:35437");
26
26
  const server = new src_1.SdkgenHttpServer(api, {});
27
27
  describe("Errors", () => {
@@ -13,18 +13,18 @@ const parser_1 = require("@sdkgen/parser");
13
13
  const typescript_generator_1 = require("@sdkgen/typescript-generator");
14
14
  const src_1 = require("../../src");
15
15
  const ast = new parser_1.Parser(`${__dirname}/api.sdkgen`).parse();
16
- fs_1.writeFileSync(`${__dirname}/middleware-api.ts`, typescript_generator_1.generateNodeServerSource(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
16
+ (0, fs_1.writeFileSync)(`${__dirname}/middleware-api.ts`, (0, typescript_generator_1.generateNodeServerSource)(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
17
17
  const { api } = require(`${__dirname}/middleware-api.ts`);
18
- fs_1.unlinkSync(`${__dirname}/middleware-api.ts`);
18
+ (0, fs_1.unlinkSync)(`${__dirname}/middleware-api.ts`);
19
19
  api.fn.identity = async (_ctx, args) => {
20
20
  return args.value;
21
21
  };
22
22
  api.fn.sum = async (_ctx, args) => {
23
23
  return args.a + args.b;
24
24
  };
25
- fs_1.writeFileSync(`${__dirname}/middleware-nodeClient.ts`, typescript_generator_1.generateNodeClientSource(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
25
+ (0, fs_1.writeFileSync)(`${__dirname}/middleware-nodeClient.ts`, (0, typescript_generator_1.generateNodeClientSource)(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
26
26
  const { ApiClient: NodeApiClient } = require(`${__dirname}/middleware-nodeClient.ts`);
27
- fs_1.unlinkSync(`${__dirname}/middleware-nodeClient.ts`);
27
+ (0, fs_1.unlinkSync)(`${__dirname}/middleware-nodeClient.ts`);
28
28
  const nodeClient = new NodeApiClient("http://localhost:32542");
29
29
  const server = new src_1.SdkgenHttpServer(api, {});
30
30
  describe("Middleware", () => {
@@ -51,24 +51,6 @@ describe("Middleware", () => {
51
51
  expect(await nodeClient.identity(null, { value: 3 })).toBe(3);
52
52
  api.middlewares.pop();
53
53
  });
54
- test("onRequestStart still work as expected", async () => {
55
- const previous = api.hook.onRequestStart;
56
- expect(await nodeClient.identity(null, { value: 1 })).toBe(1);
57
- expect(await nodeClient.identity(null, { value: 2 })).toBe(2);
58
- expect(await nodeClient.identity(null, { value: 3 })).toBe(3);
59
- api.hook.onRequestStart = async (ctx) => {
60
- if (ctx.request.args.value === 2) {
61
- return {
62
- result: 17,
63
- };
64
- }
65
- return null;
66
- };
67
- expect(await nodeClient.identity(null, { value: 1 })).toBe(1);
68
- expect(await nodeClient.identity(null, { value: 2 })).toBe(17);
69
- expect(await nodeClient.identity(null, { value: 3 })).toBe(3);
70
- api.hook.onRequestStart = previous;
71
- });
72
54
  test("Multiple middlewares stack", async () => {
73
55
  expect(await nodeClient.identity(null, { value: 1 })).toBe(1);
74
56
  expect(await nodeClient.identity(null, { value: 2 })).toBe(2);
@@ -99,14 +99,14 @@ class ApiClient {
99
99
  }
100
100
  catch (e) {
101
101
  console.error(e);
102
- reject({ type: "Fatal", message: e.toString() });
102
+ reject({ type: "Fatal", message: `${e}` });
103
103
  }
104
104
  }
105
105
  catch (e) {
106
106
  console.error(e);
107
107
  reject({
108
108
  type: "BadFormattedResponse",
109
- message: `Response couldn't be parsed as JSON (${data}):\n${e.toString()}`,
109
+ message: `Response couldn't be parsed as JSON (${data}):\n${e}`,
110
110
  });
111
111
  }
112
112
  });
@@ -18,9 +18,9 @@ const typescript_generator_1 = require("@sdkgen/typescript-generator");
18
18
  const axios_1 = __importDefault(require("axios"));
19
19
  const src_1 = require("../../src");
20
20
  const ast = new parser_1.Parser(`${__dirname}/api.sdkgen`).parse();
21
- fs_1.writeFileSync(`${__dirname}/api.ts`, typescript_generator_1.generateNodeServerSource(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
21
+ (0, fs_1.writeFileSync)(`${__dirname}/api.ts`, (0, typescript_generator_1.generateNodeServerSource)(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
22
22
  const { api, SomeError } = require(`${__dirname}/api.ts`);
23
- fs_1.unlinkSync(`${__dirname}/api.ts`);
23
+ (0, fs_1.unlinkSync)(`${__dirname}/api.ts`);
24
24
  let lastCallCtx = null;
25
25
  api.fn.getUser = async (ctx, { id }) => {
26
26
  lastCallCtx = ctx;
@@ -39,9 +39,9 @@ api.fn.throwsError = async () => {
39
39
  // ExecSync(`../../cubos/sdkgen/sdkgen ${__dirname + "/api.sdkgen"} -o ${__dirname + "/legacyNodeClient.ts"} -t typescript_nodeclient`);
40
40
  const { ApiClient: NodeLegacyApiClient } = require(`${__dirname}/legacyNodeClient.ts`);
41
41
  const nodeLegacyClient = new NodeLegacyApiClient("http://localhost:34367");
42
- fs_1.writeFileSync(`${__dirname}/nodeClient.ts`, typescript_generator_1.generateNodeClientSource(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
42
+ (0, fs_1.writeFileSync)(`${__dirname}/nodeClient.ts`, (0, typescript_generator_1.generateNodeClientSource)(ast).replace(/@sdkgen\/node-runtime/gu, "../../src"));
43
43
  const { ApiClient: NodeApiClient } = require(`${__dirname}/nodeClient.ts`);
44
- fs_1.unlinkSync(`${__dirname}/nodeClient.ts`);
44
+ (0, fs_1.unlinkSync)(`${__dirname}/nodeClient.ts`);
45
45
  const nodeClient = new NodeApiClient("http://localhost:34367");
46
46
  const server = new src_1.SdkgenHttpServer(api, { aaa: true });
47
47
  describe("Simple API", () => {
@@ -56,7 +56,7 @@ describe("Simple API", () => {
56
56
  await expect(axios_1.default.get("http://localhost:34367/egesg")).rejects.toThrowError();
57
57
  });
58
58
  test("Can get ast.json at runtime", async () => {
59
- expect(await axios_1.default.get("http://localhost:34367/ast.json")).toMatchObject({ data: parser_1.astToJson(ast) });
59
+ expect(await axios_1.default.get("http://localhost:34367/ast.json")).toMatchObject({ data: (0, parser_1.astToJson)(ast) });
60
60
  server.introspection = false;
61
61
  await expect(axios_1.default.get("http://localhost:34367/ast.json")).rejects.toThrowError();
62
62
  });
@@ -77,7 +77,7 @@ describe("Simple API", () => {
77
77
  arrayOfOptionals: [1, null, 3],
78
78
  base64: "SGVsbG8K",
79
79
  bool: true,
80
- bytes: crypto_1.randomBytes(23),
80
+ bytes: (0, crypto_1.randomBytes)(23),
81
81
  date: new Date(2019, 12, 3),
82
82
  datetime: new Date(),
83
83
  enum: "aa",
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const spec_ts_1 = require("spec.ts");
4
+ const src_1 = require("../src");
5
+ {
6
+ const typeTable = {};
7
+ const encoded = (0, src_1.encode)(typeTable, "", "string", "");
8
+ const decoded = (0, src_1.decode)(typeTable, "", "string", "");
9
+ (0, spec_ts_1.assert)(encoded, spec_ts_1._);
10
+ (0, spec_ts_1.assert)(decoded, spec_ts_1._);
11
+ }
12
+ {
13
+ const typeTable = {};
14
+ const encoded = (0, src_1.encode)(typeTable, "", "bigint", "");
15
+ const decoded = (0, src_1.decode)(typeTable, "", "bigint", "");
16
+ (0, spec_ts_1.assert)(encoded, spec_ts_1._);
17
+ (0, spec_ts_1.assert)(decoded, spec_ts_1._);
18
+ }
19
+ {
20
+ const typeTable = {
21
+ Foo: "string?",
22
+ };
23
+ const encoded = (0, src_1.encode)(typeTable, "", "Foo", "");
24
+ const decoded = (0, src_1.decode)(typeTable, "", "Foo", "");
25
+ (0, spec_ts_1.assert)(encoded, spec_ts_1._);
26
+ (0, spec_ts_1.assert)(decoded, spec_ts_1._);
27
+ }
28
+ {
29
+ const typeTable = {
30
+ Foo: "string?",
31
+ Bar: {
32
+ a: "string",
33
+ b: "Foo[]",
34
+ },
35
+ };
36
+ const encoded = (0, src_1.encode)(typeTable, "", "Bar", "");
37
+ const decoded = (0, src_1.decode)(typeTable, "", "Bar", "");
38
+ (0, spec_ts_1.assert)(encoded, spec_ts_1._);
39
+ (0, spec_ts_1.assert)(decoded, spec_ts_1._);
40
+ }
41
+ {
42
+ const typeTable = {
43
+ Foo: "string?",
44
+ Bar: ["a", "b"],
45
+ };
46
+ const encoded = (0, src_1.encode)(typeTable, "", "Bar", "");
47
+ const decoded = (0, src_1.decode)(typeTable, "", "Bar", "");
48
+ (0, spec_ts_1.assert)(encoded, spec_ts_1._);
49
+ (0, spec_ts_1.assert)(decoded, spec_ts_1._);
50
+ }
51
+ {
52
+ const typeTable = {
53
+ Foo: { x: "string?" },
54
+ Bar: ["a", ["b", "Foo"]],
55
+ };
56
+ const encoded = (0, src_1.encode)(typeTable, "", "Bar", "");
57
+ const decoded = (0, src_1.decode)(typeTable, "", "Bar", "");
58
+ (0, spec_ts_1.assert)(encoded, spec_ts_1._);
59
+ (0, spec_ts_1.assert)(decoded, spec_ts_1._);
60
+ }
@@ -5,108 +5,124 @@ Object.defineProperty(exports, "__esModule", { value: true });
5
5
  const src_1 = require("../src");
6
6
  describe("Encode/Decode", () => {
7
7
  test("Process CPF", () => {
8
- expect(src_1.encode({}, "", "cpf", "067.183.145-36")).toBe("06718314536");
9
- expect(src_1.decode({}, "", "cpf", "06718314536")).toBe("067.183.145-36");
8
+ expect((0, src_1.encode)({}, "", "cpf", "067.183.145-36")).toBe("06718314536");
9
+ expect((0, src_1.decode)({}, "", "cpf", "06718314536")).toBe("067.183.145-36");
10
10
  expect(() => {
11
- src_1.encode({}, "", "cpf", "067.183.145-35");
11
+ (0, src_1.encode)({}, "", "cpf", "067.183.145-35");
12
12
  }).toThrow();
13
13
  expect(() => {
14
- src_1.decode({}, "", "cpf", "06718314535");
14
+ (0, src_1.decode)({}, "", "cpf", "06718314535");
15
15
  }).toThrow();
16
16
  });
17
17
  test("Process CNPJ", () => {
18
- expect(src_1.encode({}, "", "cnpj", "18.571.767/0001-36")).toBe("18571767000136");
19
- expect(src_1.decode({}, "", "cnpj", "18571767000136")).toBe("18.571.767/0001-36");
18
+ expect((0, src_1.encode)({}, "", "cnpj", "18.571.767/0001-36")).toBe("18571767000136");
19
+ expect((0, src_1.decode)({}, "", "cnpj", "18571767000136")).toBe("18.571.767/0001-36");
20
20
  expect(() => {
21
- src_1.encode({}, "", "cnpj", "18.571.767/0001-35");
21
+ (0, src_1.encode)({}, "", "cnpj", "18.571.767/0001-35");
22
22
  }).toThrow();
23
23
  expect(() => {
24
- src_1.decode({}, "", "cnpj", "18571767000135");
24
+ (0, src_1.decode)({}, "", "cnpj", "18571767000135");
25
25
  }).toThrow();
26
26
  });
27
27
  test("Process URL", () => {
28
- expect(src_1.encode({}, "", "url", "https://cubos.io/")).toBe("https://cubos.io/");
29
- expect(src_1.decode({}, "", "url", "https://cubos.io/")).toBe("https://cubos.io/");
30
- expect(src_1.encode({}, "", "url", " https:cubos.io/ ")).toBe("https://cubos.io/");
31
- expect(src_1.encode({}, "", "url", " https:cubos.io ")).toBe("https://cubos.io/");
28
+ expect((0, src_1.encode)({}, "", "url", "https://cubos.io/")).toBe("https://cubos.io/");
29
+ expect((0, src_1.decode)({}, "", "url", "https://cubos.io/")).toBe("https://cubos.io/");
30
+ expect((0, src_1.encode)({}, "", "url", " https:cubos.io/ ")).toBe("https://cubos.io/");
31
+ expect((0, src_1.encode)({}, "", "url", " https:cubos.io ")).toBe("https://cubos.io/");
32
32
  expect(() => {
33
- src_1.encode({}, "", "url", "dfbdfb");
33
+ (0, src_1.encode)({}, "", "url", "dfbdfb");
34
34
  }).toThrow();
35
35
  expect(() => {
36
- src_1.decode({}, "", "url", "hhh.com");
36
+ (0, src_1.decode)({}, "", "url", "hhh.com");
37
37
  }).toThrow();
38
38
  });
39
39
  test("Process Base64", () => {
40
- expect(src_1.encode({}, "", "base64", "c3VyZS4=")).toBe("c3VyZS4=");
41
- expect(src_1.encode({}, "", "base64", "")).toBe("");
40
+ expect((0, src_1.encode)({}, "", "base64", "c3VyZS4=")).toBe("c3VyZS4=");
41
+ expect((0, src_1.encode)({}, "", "base64", "")).toBe("");
42
42
  expect(() => {
43
- src_1.encode({}, "", "base64", "c3VyZS4");
43
+ (0, src_1.encode)({}, "", "base64", "c3VyZS4");
44
44
  }).toThrow();
45
45
  expect(() => {
46
- src_1.encode({}, "", "base64", " c3VyZS4=");
46
+ (0, src_1.encode)({}, "", "base64", " c3VyZS4=");
47
47
  }).toThrow();
48
- expect(src_1.decode({}, "", "base64", "c3VyZS4=")).toBe("c3VyZS4=");
49
- expect(src_1.decode({}, "", "base64", "")).toBe("");
48
+ expect((0, src_1.decode)({}, "", "base64", "c3VyZS4=")).toBe("c3VyZS4=");
49
+ expect((0, src_1.decode)({}, "", "base64", "")).toBe("");
50
50
  expect(() => {
51
- src_1.decode({}, "", "base64", "c3VyZS4");
51
+ (0, src_1.decode)({}, "", "base64", "c3VyZS4");
52
52
  }).toThrow();
53
53
  expect(() => {
54
- src_1.decode({}, "", "base64", " c3VyZS4=");
54
+ (0, src_1.decode)({}, "", "base64", " c3VyZS4=");
55
55
  }).toThrow();
56
56
  });
57
57
  test("Process Date", () => {
58
- expect(src_1.encode({}, "", "date", new Date("2020-11-10T00:00:00Z"))).toBe("2020-11-10");
59
- expect(src_1.encode({}, "", "date", new Date("2020-11-10T15:34:50Z"))).toBe("2020-11-10");
60
- expect(src_1.encode({}, "", "date", "2020-11-10")).toBe("2020-11-10");
58
+ expect((0, src_1.encode)({}, "", "date", new Date("2020-11-10T00:00:00Z"))).toBe("2020-11-10");
59
+ expect((0, src_1.encode)({}, "", "date", new Date("2020-11-10T15:34:50Z"))).toBe("2020-11-10");
60
+ expect((0, src_1.encode)({}, "", "date", "2020-11-10")).toBe("2020-11-10");
61
61
  expect(() => {
62
- src_1.encode({}, "", "date", "2020-11-10T15:34:50Z");
62
+ (0, src_1.encode)({}, "", "date", "2020-11-10T15:34:50Z");
63
63
  }).toThrow();
64
64
  expect(() => {
65
- src_1.encode({}, "", "date", "hello world");
65
+ (0, src_1.encode)({}, "", "date", "hello world");
66
66
  }).toThrow();
67
67
  expect(() => {
68
- src_1.decode({}, "", "date", "2020-02-30");
68
+ (0, src_1.decode)({}, "", "date", "2020-02-30");
69
69
  }).toThrow();
70
70
  expect(() => {
71
- src_1.encode({}, "", "date", new Date(""));
71
+ (0, src_1.encode)({}, "", "date", new Date(""));
72
72
  }).toThrow();
73
73
  });
74
74
  test("Process Datetime", () => {
75
- expect(src_1.encode({}, "", "datetime", new Date("2020-11-10T15:34:50Z"))).toBe("2020-11-10T15:34:50.000");
76
- expect(src_1.encode({}, "", "datetime", "2020-11-10T15:34:50Z")).toBe("2020-11-10T15:34:50.000");
77
- expect(src_1.encode({}, "", "datetime", "2020-11-10T15:34:50.999")).toBe("2020-11-10T15:34:50.999");
78
- expect(src_1.encode({}, "", "datetime", "2020-11-10T15:34:50+01:00")).toBe("2020-11-10T14:34:50.000");
79
- expect(src_1.encode({}, "", "datetime", "2020-11-10T15:34:50.999+01:00")).toBe("2020-11-10T14:34:50.999");
75
+ expect((0, src_1.encode)({}, "", "datetime", new Date("2020-11-10T15:34:50Z"))).toBe("2020-11-10T15:34:50.000");
76
+ expect((0, src_1.encode)({}, "", "datetime", "2020-11-10T15:34:50Z")).toBe("2020-11-10T15:34:50.000");
77
+ expect((0, src_1.encode)({}, "", "datetime", "2020-11-10T15:34:50.999")).toBe("2020-11-10T15:34:50.999");
78
+ expect((0, src_1.encode)({}, "", "datetime", "2020-11-10T15:34:50+01:00")).toBe("2020-11-10T14:34:50.000");
79
+ expect((0, src_1.encode)({}, "", "datetime", "2020-11-10T15:34:50.999+01:00")).toBe("2020-11-10T14:34:50.999");
80
80
  expect(() => {
81
- src_1.encode({}, "", "datetime", "2020-11-10");
81
+ (0, src_1.encode)({}, "", "datetime", "2020-11-10");
82
82
  }).toThrow();
83
83
  expect(() => {
84
- src_1.encode({}, "", "datetime", "hello world");
84
+ (0, src_1.encode)({}, "", "datetime", "hello world");
85
85
  }).toThrow();
86
86
  expect(() => {
87
- src_1.encode({}, "", "datetime", "2020-11-10T15:34:50.999$01:00");
87
+ (0, src_1.encode)({}, "", "datetime", "2020-11-10T15:34:50.999$01:00");
88
88
  }).toThrow();
89
89
  expect(() => {
90
- src_1.decode({}, "", "datetime", "2020-11-10T15:34:50.999$01:00");
90
+ (0, src_1.decode)({}, "", "datetime", "2020-11-10T15:34:50.999$01:00");
91
91
  }).toThrow();
92
- expect(src_1.decode({}, "", "datetime", "2020-11-10T15:34:50Z").getTime()).toBe(new Date("2020-11-10T15:34:50Z").getTime());
93
- expect(src_1.decode({}, "", "datetime", "2020-11-10T15:34:50.000").getTime()).toBe(new Date("2020-11-10T15:34:50Z").getTime());
92
+ expect((0, src_1.decode)({}, "", "datetime", "2020-11-10T15:34:50Z").getTime()).toBe(new Date("2020-11-10T15:34:50Z").getTime());
93
+ expect((0, src_1.decode)({}, "", "datetime", "2020-11-10T15:34:50.000").getTime()).toBe(new Date("2020-11-10T15:34:50Z").getTime());
94
94
  expect(() => {
95
- src_1.encode({}, "", "datetime", new Date(""));
95
+ (0, src_1.encode)({}, "", "datetime", new Date(""));
96
96
  }).toThrow();
97
97
  });
98
98
  test("Process BigInt", () => {
99
- expect(src_1.encode({}, "", "bigint", BigInt(10))).toBe("10");
99
+ expect((0, src_1.encode)({}, "", "bigint", BigInt(10))).toBe("10");
100
100
  expect(() => {
101
- src_1.encode({}, "", "bigint", 10);
101
+ (0, src_1.encode)({}, "", "bigint", 10);
102
102
  }).toThrow();
103
103
  expect(() => {
104
- src_1.encode({}, "", "bigint", "10");
104
+ (0, src_1.encode)({}, "", "bigint", "10");
105
105
  }).toThrow();
106
- expect(src_1.decode({}, "", "bigint", 10)).toBe(BigInt(10));
107
- expect(src_1.decode({}, "", "bigint", "10")).toBe(BigInt(10));
106
+ expect((0, src_1.decode)({}, "", "bigint", 10)).toBe(BigInt(10));
107
+ expect((0, src_1.decode)({}, "", "bigint", "10")).toBe(BigInt(10));
108
108
  expect(() => {
109
- src_1.decode({}, "", "bigint", "hello world");
109
+ (0, src_1.decode)({}, "", "bigint", "hello world");
110
110
  }).toThrow();
111
111
  });
112
+ test("Process Enum", () => {
113
+ for (const func of [src_1.encode, src_1.decode]) {
114
+ expect(func({}, "", ["a", "b"], "a")).toBe("a");
115
+ expect(func({}, "", ["a", "b"], "b")).toBe("b");
116
+ expect(() => {
117
+ func({}, "", ["a", "b"], "c");
118
+ }).toThrow();
119
+ expect(() => {
120
+ func({ X: { v: "int" } }, "", ["a", ["b", "X"]], "b");
121
+ }).toThrow();
122
+ }
123
+ expect((0, src_1.encode)({ X: { v: "int" } }, "", ["a", ["b", "X"]], { tag: "a" })).toBe("a");
124
+ expect((0, src_1.encode)({ X: { v: "int" } }, "", ["a", ["b", "X"]], { tag: "b", v: 4 })).toEqual(["b", { v: 4 }]);
125
+ expect((0, src_1.decode)({ X: { v: "int" } }, "", ["a", ["b", "X"]], "a")).toEqual({ tag: "a" });
126
+ expect((0, src_1.decode)({ X: { v: "int" } }, "", ["a", ["b", "X"]], ["b", { v: 4 }])).toEqual({ tag: "b", v: 4 });
127
+ });
112
128
  });
@@ -3,24 +3,12 @@ import type { Context, ContextReply } from "./context";
3
3
  import type { DeepReadonly } from "./utils";
4
4
  declare type Middleware<ExtraContextT> = (ctx: Context & ExtraContextT, next: () => Promise<ContextReply>) => Promise<ContextReply>;
5
5
  export declare abstract class BaseApiConfig<ExtraContextT = unknown> {
6
- constructor();
7
6
  private _ast;
8
7
  get ast(): AstRoot;
9
8
  astJson: DeepReadonly<AstJson>;
10
9
  fn: {
11
10
  [name: string]: ((ctx: Context & ExtraContextT, args: any) => Promise<any>) | undefined;
12
11
  };
13
- err: {
14
- [name: string]: (message?: string) => never;
15
- };
16
- hook: {
17
- /** @deprecated Use server.registerHealthCheck() instead. */
18
- onHealthCheck(): Promise<boolean>;
19
- /** @deprecated Use middlewares with api.use() instead. */
20
- onRequestEnd(ctx: Context & ExtraContextT, reply: ContextReply): Promise<null | ContextReply>;
21
- /** @deprecated Use middlewares with api.use() instead. */
22
- onRequestStart(ctx: Context & ExtraContextT): Promise<null | ContextReply>;
23
- };
24
12
  readonly middlewares: Array<Middleware<ExtraContextT>>;
25
13
  use(middleware: Middleware<ExtraContextT>): void;
26
14
  }
@@ -5,22 +5,11 @@ const parser_1 = require("@sdkgen/parser");
5
5
  class BaseApiConfig {
6
6
  constructor() {
7
7
  this.fn = {};
8
- this.err = {};
9
- this.hook = {
10
- onHealthCheck: async () => Promise.resolve(true),
11
- onRequestEnd: async () => Promise.resolve(null),
12
- onRequestStart: async () => Promise.resolve(null),
13
- };
14
8
  this.middlewares = [];
15
- this.use(async (ctx, next) => {
16
- var _a, _b;
17
- const reply = (_a = (await this.hook.onRequestStart(ctx))) !== null && _a !== void 0 ? _a : (await next());
18
- return (_b = (await this.hook.onRequestEnd(ctx, reply))) !== null && _b !== void 0 ? _b : reply;
19
- });
20
9
  }
21
10
  get ast() {
22
11
  var _a;
23
- return ((_a = this._ast) !== null && _a !== void 0 ? _a : (this._ast = parser_1.jsonToAst(this.astJson)));
12
+ return ((_a = this._ast) !== null && _a !== void 0 ? _a : (this._ast = (0, parser_1.jsonToAst)(this.astJson)));
24
13
  }
25
14
  use(middleware) {
26
15
  this.middlewares.push(middleware);
@@ -2,18 +2,30 @@
2
2
  import type { AstJson, TypeDescription } from "@sdkgen/parser";
3
3
  import type { DeepReadonly } from "./utils";
4
4
  declare type TypeTable = AstJson["typeTable"];
5
+ declare type ExpandRecursively<T> = T extends object ? (T extends infer O ? {
6
+ [K in keyof O]: ExpandRecursively<O[K]>;
7
+ } : never) : T;
5
8
  declare type JsonType = number | string | boolean | null | JsonType[] | {
6
9
  [Key in string]: JsonType;
7
10
  };
8
11
  declare type AnyDecodedType = number | string | boolean | null | bigint | Buffer | Date | AnyDecodedType[] | {
9
12
  [Key in string]: AnyDecodedType;
10
13
  };
11
- declare type DecodedType<Type, Table extends object> = TypeDescription extends Type ? AnyDecodedType : Type extends "string" | "email" | "html" | "xml" | "url" | "hex" | "uuid" | "base64" | "cpf" | "cnpj" ? string : Type extends "json" ? JsonType : Type extends "bool" ? boolean : Type extends "void" ? null : Type extends "int" | "uint" | "float" | "money" ? number : Type extends "bigint" ? bigint : Type extends "bytes" ? Buffer : Type extends "date" | "datetime" ? Date : Type extends `${infer X}?` ? DecodedType<X, Table> | null : Type extends `${infer X}[]` ? Array<DecodedType<X, Table>> : Type extends string[] ? Type[number] : Type extends readonly string[] ? Type[number] : Type extends object ? {
14
+ declare type DecodedType<Type, Table extends object> = TypeDescription extends Type ? AnyDecodedType : Type extends "string" | "email" | "html" | "xml" | "url" | "hex" | "uuid" | "base64" | "cpf" | "cnpj" ? string : Type extends "json" ? JsonType : Type extends "bool" ? boolean : Type extends "void" ? null : Type extends "int" | "uint" | "float" | "money" ? number : Type extends "bigint" ? bigint : Type extends "bytes" ? Buffer : Type extends "date" | "datetime" ? Date : Type extends `${infer X}?` ? DecodedType<X, Table> | null : Type extends `${infer X}[]` ? Array<DecodedType<X, Table>> : Type extends Array<string | [string, string]> ? DecodedEnumType<Type, Table> : Type extends ReadonlyArray<string | readonly [string, string]> ? DecodedEnumType<Type, Table> : Type extends object ? {
12
15
  -readonly [Key in keyof Type]: DecodedType<Type[Key], Table>;
13
16
  } : object extends Table ? never : Type extends keyof Table ? DecodedType<Table[Type], Table> : never;
14
- declare type EncodedType<Type, Table extends object> = TypeDescription extends Type ? JsonType : Type extends "string" | "email" | "html" | "xml" | "url" | "hex" | "uuid" | "base64" | "cpf" | "cnpj" ? string : Type extends "json" ? JsonType : Type extends "bool" ? boolean : Type extends "void" ? null : Type extends "int" | "uint" | "float" | "money" ? number : Type extends "bigint" | "bytes" | "date" | "datetime" ? string : Type extends `${infer X}?` ? EncodedType<X, Table> | null : Type extends `${infer X}[]` ? Array<EncodedType<X, Table>> : Type extends string[] ? Type[number] : Type extends readonly string[] ? Type[number] : Type extends object ? {
17
+ declare type DecodedEnumType<Type extends Array<string | [string, string]> | ReadonlyArray<string | readonly [string, string]>, Table extends object> = Type[number] extends string ? Type[number] : DecodeTaggedEnumValueType<Type[number], Table>;
18
+ declare type DecodeTaggedEnumValueType<ValueType extends string | [string, string] | readonly [string, string], Table extends object> = ValueType extends string ? {
19
+ tag: ValueType;
20
+ } : ValueType extends [infer Tag, infer Struct] ? ExpandRecursively<{
21
+ tag: Tag;
22
+ } & DecodedType<Struct, Table>> : ValueType extends readonly [infer Tag, infer Struct] ? ExpandRecursively<{
23
+ tag: Tag;
24
+ } & DecodedType<Struct, Table>> : never;
25
+ declare type EncodedType<Type, Table extends object> = TypeDescription extends Type ? JsonType : Type extends "string" | "email" | "html" | "xml" | "url" | "hex" | "uuid" | "base64" | "cpf" | "cnpj" ? string : Type extends "json" ? JsonType : Type extends "bool" ? boolean : Type extends "void" ? null : Type extends "int" | "uint" | "float" | "money" ? number : Type extends "bigint" | "bytes" | "date" | "datetime" ? string : Type extends `${infer X}?` ? EncodedType<X, Table> | null : Type extends `${infer X}[]` ? Array<EncodedType<X, Table>> : Type extends Array<string | [string, string]> ? EnumEncodedValueType<Type[number], Table> : Type extends ReadonlyArray<string | readonly [string, string]> ? EnumEncodedValueType<Type[number], Table> : Type extends object ? {
15
26
  -readonly [Key in keyof Type]: EncodedType<Type[Key], Table>;
16
27
  } : object extends Table ? never : Type extends keyof Table ? EncodedType<Table[Type], Table> : never;
28
+ declare type EnumEncodedValueType<ValueType extends string | [string, string] | readonly [string, string], Table extends object> = ValueType extends string ? ValueType : ValueType extends [infer Tag, infer Struct] ? [Tag, EncodedType<Struct, Table>] : ValueType extends readonly [infer Tag, infer Struct] ? [Tag, EncodedType<Struct, Table>] : never;
17
29
  export declare function encode<Table extends DeepReadonly<TypeTable>, Type extends DeepReadonly<TypeDescription>>(typeTable: Table, path: string, type: Type, value: unknown): EncodedType<Type, Table>;
18
30
  export declare function decode<Table extends DeepReadonly<TypeTable>, Type extends DeepReadonly<TypeDescription>>(typeTable: Table, path: string, type: Type, value: unknown): DecodedType<Type, Table>;
19
31
  export {};
@@ -18,6 +18,17 @@ var __importStar = (this && this.__importStar) || function (mod) {
18
18
  __setModuleDefault(result, mod);
19
19
  return result;
20
20
  };
21
+ var __rest = (this && this.__rest) || function (s, e) {
22
+ var t = {};
23
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
24
+ t[p] = s[p];
25
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
26
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
27
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
28
+ t[p[i]] = s[p[i]];
29
+ }
30
+ return t;
31
+ };
21
32
  Object.defineProperty(exports, "__esModule", { value: true });
22
33
  exports.decode = exports.encode = void 0;
23
34
  const CNPJ = __importStar(require("@fnando/cnpj"));
@@ -122,10 +133,35 @@ function encode(typeTable, path, type, value) {
122
133
  throw new Error(`Invalid type at '${path}', cannot be null`);
123
134
  }
124
135
  else if (Array.isArray(type)) {
125
- if (typeof value !== "string" || !type.includes(value)) {
126
- throw new ParseError(path, type, value);
136
+ if (type.every(tag => typeof tag === "string")) {
137
+ for (const tag of type) {
138
+ if (tag === value) {
139
+ return tag;
140
+ }
141
+ }
127
142
  }
128
- return value;
143
+ else if (typeof value === "object" && value && "tag" in value) {
144
+ const _a = value, { tag: tagValue } = _a, restValue = __rest(_a, ["tag"]);
145
+ for (const entry of type) {
146
+ if (typeof entry === "string") {
147
+ if (entry === tagValue) {
148
+ return entry;
149
+ }
150
+ }
151
+ else {
152
+ const [tag, valueType] = entry;
153
+ if (tag === tagValue) {
154
+ const encodedValues = encode(typeTable, `${path}.${tag}`, valueType, restValue);
155
+ // eslint-disable-next-line max-depth
156
+ if (Object.values(encodedValues).every(v => v === null)) {
157
+ return tag;
158
+ }
159
+ return [tag, encodedValues];
160
+ }
161
+ }
162
+ }
163
+ }
164
+ throw new ParseError(path, type, value);
129
165
  }
130
166
  else if (typeof type === "object") {
131
167
  if (typeof value !== "object") {
@@ -191,6 +227,7 @@ function encode(typeTable, path, type, value) {
191
227
  return (typeof value === "string" ? new Date(value) : value).toISOString().replace("Z", "");
192
228
  }
193
229
  else {
230
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
194
231
  const resolved = typeTable[type];
195
232
  if (resolved) {
196
233
  return encode(typeTable, path, resolved, value);
@@ -204,10 +241,34 @@ function decode(typeTable, path, type, value) {
204
241
  throw new Error(`Invalid type at '${path}', cannot be null`);
205
242
  }
206
243
  else if (Array.isArray(type)) {
207
- if (typeof value !== "string" || !type.includes(value)) {
208
- throw new ParseError(path, type, value);
244
+ if (type.every(tag => typeof tag === "string")) {
245
+ for (const tag of type) {
246
+ if (tag === value) {
247
+ return tag;
248
+ }
249
+ }
209
250
  }
210
- return value;
251
+ else {
252
+ for (const entry of type) {
253
+ if (typeof entry === "string") {
254
+ if (entry === value) {
255
+ return { tag: entry };
256
+ }
257
+ }
258
+ else {
259
+ const [tag, valueType] = entry;
260
+ if (tag === value) {
261
+ const decodedValues = decode(typeTable, `${path}.${tag}`, valueType, {});
262
+ return Object.assign(Object.assign({}, decodedValues), { tag });
263
+ }
264
+ else if (Array.isArray(value) && value.length === 2 && tag === value[0]) {
265
+ const decodedValues = decode(typeTable, `${path}.${tag}`, valueType, value[1]);
266
+ return Object.assign(Object.assign({}, decodedValues), { tag });
267
+ }
268
+ }
269
+ }
270
+ }
271
+ throw new ParseError(path, type, value);
211
272
  }
212
273
  else if (typeof type === "object") {
213
274
  if (typeof value !== "object") {
@@ -282,6 +343,7 @@ function decode(typeTable, path, type, value) {
282
343
  return new Date(`${value.endsWith("Z") ? value : value.concat("Z")}`);
283
344
  }
284
345
  else {
346
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
285
347
  const resolved = typeTable[type];
286
348
  if (resolved) {
287
349
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return