@dedot/codegen 0.0.1-next.9dacef43.1 → 0.0.1-next.a5b1d2fb.22

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.
Files changed (154) hide show
  1. package/{generator → chaintypes/generator}/ApiGen.d.ts +2 -2
  2. package/chaintypes/generator/ConstsGen.d.ts +4 -0
  3. package/{generator → chaintypes/generator}/ConstsGen.js +8 -9
  4. package/chaintypes/generator/ErrorsGen.d.ts +5 -0
  5. package/{generator → chaintypes/generator}/ErrorsGen.js +9 -10
  6. package/chaintypes/generator/EventsGen.d.ts +5 -0
  7. package/{generator → chaintypes/generator}/EventsGen.js +9 -10
  8. package/chaintypes/generator/IndexGen.d.ts +5 -0
  9. package/chaintypes/generator/IndexGen.js +17 -0
  10. package/chaintypes/generator/JsonRpcGen.d.ts +8 -0
  11. package/chaintypes/generator/JsonRpcGen.js +55 -0
  12. package/chaintypes/generator/QueryGen.d.ts +5 -0
  13. package/{generator → chaintypes/generator}/QueryGen.js +24 -16
  14. package/chaintypes/generator/RuntimeApisGen.d.ts +9 -0
  15. package/chaintypes/generator/RuntimeApisGen.js +189 -0
  16. package/chaintypes/generator/TxGen.d.ts +5 -0
  17. package/{generator → chaintypes/generator}/TxGen.js +14 -12
  18. package/chaintypes/generator/TypesGen.d.ts +11 -0
  19. package/chaintypes/generator/TypesGen.js +55 -0
  20. package/chaintypes/generator/index.d.ts +10 -0
  21. package/chaintypes/generator/index.js +10 -0
  22. package/chaintypes/index.d.ts +3 -0
  23. package/chaintypes/index.js +49 -0
  24. package/chaintypes/templates/consts.hbs +7 -0
  25. package/chaintypes/templates/errors.hbs +7 -0
  26. package/chaintypes/templates/events.hbs +7 -0
  27. package/chaintypes/templates/index.hbs +27 -0
  28. package/chaintypes/templates/json-rpc.hbs +5 -0
  29. package/chaintypes/templates/query.hbs +7 -0
  30. package/chaintypes/templates/runtime.hbs +8 -0
  31. package/chaintypes/templates/tx.hbs +9 -0
  32. package/{cjs → chaintypes}/templates/types.hbs +1 -1
  33. package/cjs/{generator → chaintypes/generator}/ConstsGen.js +12 -13
  34. package/cjs/chaintypes/generator/ErrorsGen.js +40 -0
  35. package/cjs/{generator → chaintypes/generator}/EventsGen.js +16 -17
  36. package/cjs/chaintypes/generator/IndexGen.js +21 -0
  37. package/cjs/chaintypes/generator/JsonRpcGen.js +59 -0
  38. package/cjs/{generator → chaintypes/generator}/QueryGen.js +26 -18
  39. package/cjs/chaintypes/generator/RuntimeApisGen.js +193 -0
  40. package/cjs/{generator → chaintypes/generator}/TxGen.js +23 -21
  41. package/cjs/chaintypes/generator/TypesGen.js +59 -0
  42. package/cjs/chaintypes/generator/index.js +26 -0
  43. package/cjs/chaintypes/index.js +76 -0
  44. package/cjs/chaintypes/templates/consts.hbs +7 -0
  45. package/cjs/chaintypes/templates/errors.hbs +7 -0
  46. package/cjs/chaintypes/templates/events.hbs +7 -0
  47. package/cjs/chaintypes/templates/index.hbs +27 -0
  48. package/cjs/chaintypes/templates/json-rpc.hbs +5 -0
  49. package/cjs/chaintypes/templates/query.hbs +7 -0
  50. package/cjs/chaintypes/templates/runtime.hbs +8 -0
  51. package/cjs/chaintypes/templates/tx.hbs +9 -0
  52. package/{templates → cjs/chaintypes/templates}/types.hbs +1 -1
  53. package/cjs/{generator/dirname.js → dirname.js} +0 -1
  54. package/cjs/index.js +4 -62
  55. package/cjs/{generator/TypesGen.js → shared/BaseTypesGen.js} +102 -160
  56. package/cjs/{generator → shared}/TypeImports.js +29 -3
  57. package/cjs/{generator → shared}/index.js +3 -10
  58. package/cjs/shared/known-codecs.js +170 -0
  59. package/cjs/typink/generator/ConstructorQueryGen.js +24 -0
  60. package/cjs/typink/generator/ConstructorTxGen.js +24 -0
  61. package/cjs/typink/generator/IndexGen.js +24 -0
  62. package/cjs/typink/generator/QueryGen.js +72 -0
  63. package/cjs/typink/generator/TxGen.js +25 -0
  64. package/cjs/typink/generator/TypesGen.js +35 -0
  65. package/cjs/typink/generator/index.js +22 -0
  66. package/cjs/typink/index.js +36 -0
  67. package/cjs/typink/templates/constructor-query.hbs +7 -0
  68. package/cjs/typink/templates/constructor-tx.hbs +7 -0
  69. package/cjs/typink/templates/index.hbs +14 -0
  70. package/cjs/typink/templates/query.hbs +7 -0
  71. package/cjs/typink/templates/tx.hbs +7 -0
  72. package/cjs/typink/templates/types.hbs +5 -0
  73. package/cjs/{generator/utils.js → utils.js} +34 -5
  74. package/index.d.ts +2 -4
  75. package/index.js +2 -48
  76. package/package.json +16 -18
  77. package/{generator/TypesGen.d.ts → shared/BaseTypesGen.d.ts} +13 -12
  78. package/{generator/TypesGen.js → shared/BaseTypesGen.js} +89 -147
  79. package/{generator → shared}/TypeImports.d.ts +12 -1
  80. package/{generator → shared}/TypeImports.js +29 -3
  81. package/shared/index.d.ts +3 -0
  82. package/shared/index.js +3 -0
  83. package/shared/known-codecs.d.ts +23 -0
  84. package/shared/known-codecs.js +139 -0
  85. package/typink/generator/ConstructorQueryGen.d.ts +6 -0
  86. package/typink/generator/ConstructorQueryGen.js +20 -0
  87. package/typink/generator/ConstructorTxGen.d.ts +6 -0
  88. package/typink/generator/ConstructorTxGen.js +20 -0
  89. package/typink/generator/IndexGen.d.ts +6 -0
  90. package/typink/generator/IndexGen.js +20 -0
  91. package/typink/generator/QueryGen.d.ts +12 -0
  92. package/typink/generator/QueryGen.js +68 -0
  93. package/typink/generator/TxGen.d.ts +6 -0
  94. package/typink/generator/TxGen.js +21 -0
  95. package/typink/generator/TypesGen.d.ts +8 -0
  96. package/typink/generator/TypesGen.js +31 -0
  97. package/typink/generator/index.d.ts +6 -0
  98. package/typink/generator/index.js +6 -0
  99. package/typink/index.d.ts +2 -0
  100. package/typink/index.js +30 -0
  101. package/typink/templates/constructor-query.hbs +7 -0
  102. package/typink/templates/constructor-tx.hbs +7 -0
  103. package/typink/templates/index.hbs +14 -0
  104. package/typink/templates/query.hbs +7 -0
  105. package/typink/templates/tx.hbs +7 -0
  106. package/typink/templates/types.hbs +5 -0
  107. package/{generator/utils.d.ts → utils.d.ts} +6 -1
  108. package/{generator/utils.js → utils.js} +32 -4
  109. package/cjs/genSupportedChainTypes.js +0 -79
  110. package/cjs/generator/ErrorsGen.js +0 -41
  111. package/cjs/generator/IndexGen.js +0 -18
  112. package/cjs/generator/RpcGen.js +0 -175
  113. package/cjs/generator/RuntimeApisGen.js +0 -115
  114. package/cjs/packageInfo.js +0 -5
  115. package/cjs/templates/consts.hbs +0 -7
  116. package/cjs/templates/errors.hbs +0 -7
  117. package/cjs/templates/events.hbs +0 -7
  118. package/cjs/templates/index.hbs +0 -22
  119. package/cjs/templates/query.hbs +0 -7
  120. package/cjs/templates/rpc.hbs +0 -7
  121. package/cjs/templates/runtime.hbs +0 -8
  122. package/cjs/templates/tx.hbs +0 -9
  123. package/cjs/types.js +0 -2
  124. package/genSupportedChainTypes.d.ts +0 -1
  125. package/genSupportedChainTypes.js +0 -74
  126. package/generator/ConstsGen.d.ts +0 -4
  127. package/generator/ErrorsGen.d.ts +0 -5
  128. package/generator/EventsGen.d.ts +0 -5
  129. package/generator/IndexGen.d.ts +0 -6
  130. package/generator/IndexGen.js +0 -14
  131. package/generator/QueryGen.d.ts +0 -5
  132. package/generator/RpcGen.d.ts +0 -10
  133. package/generator/RpcGen.js +0 -171
  134. package/generator/RuntimeApisGen.d.ts +0 -9
  135. package/generator/RuntimeApisGen.js +0 -111
  136. package/generator/TxGen.d.ts +0 -5
  137. package/generator/index.d.ts +0 -10
  138. package/generator/index.js +0 -10
  139. package/packageInfo.d.ts +0 -4
  140. package/packageInfo.js +0 -2
  141. package/templates/consts.hbs +0 -7
  142. package/templates/errors.hbs +0 -7
  143. package/templates/events.hbs +0 -7
  144. package/templates/index.hbs +0 -22
  145. package/templates/query.hbs +0 -7
  146. package/templates/rpc.hbs +0 -7
  147. package/templates/runtime.hbs +0 -8
  148. package/templates/tx.hbs +0 -9
  149. package/types.d.ts +0 -6
  150. package/types.js +0 -1
  151. /package/{generator → chaintypes/generator}/ApiGen.js +0 -0
  152. /package/cjs/{generator → chaintypes/generator}/ApiGen.js +0 -0
  153. /package/{generator/dirname.d.ts → dirname.d.ts} +0 -0
  154. /package/{generator/dirname.js → dirname.js} +0 -0
@@ -1,115 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RuntimeApisGen = void 0;
4
- const specs_1 = require("@dedot/specs");
5
- const utils_1 = require("./utils");
6
- const utils_2 = require("@dedot/utils");
7
- const RpcGen_1 = require("./RpcGen");
8
- const util_1 = require("@polkadot/util");
9
- class RuntimeApisGen extends RpcGen_1.RpcGen {
10
- typesGen;
11
- runtimeApis;
12
- constructor(typesGen, runtimeApis) {
13
- super(typesGen, []);
14
- this.typesGen = typesGen;
15
- this.runtimeApis = runtimeApis;
16
- }
17
- generate() {
18
- this.typesGen.clearCache();
19
- this.typesGen.typeImports.addKnownType('GenericRuntimeApis', 'GenericRuntimeApiMethod');
20
- let runtimeCallsOut = '';
21
- if (this.metadata.apis.length > 0) {
22
- this.metadata.apis.forEach((runtimeApi) => {
23
- const { name: runtimeApiName, methods } = runtimeApi;
24
- runtimeCallsOut += (0, utils_1.commentBlock)(`@runtimeapi: ${runtimeApiName} - ${(0, utils_2.calculateRuntimeApiHash)(runtimeApiName)}`);
25
- runtimeCallsOut += `${(0, util_1.stringCamelCase)(runtimeApiName)}: {
26
- ${methods.map((method) => this.#generateMethodDef(runtimeApiName, method)).join('\n')}
27
-
28
- ${(0, utils_1.commentBlock)('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
29
- }`;
30
- });
31
- }
32
- else {
33
- const specs = this.#targetRuntimeApiSpecs();
34
- specs.forEach(({ methods, runtimeApiName, runtimeApiHash, version }) => {
35
- runtimeCallsOut += (0, utils_1.commentBlock)(`@runtimeapi: ${runtimeApiName} - ${runtimeApiHash}`, `@version: ${version}`);
36
- runtimeCallsOut += `${(0, util_1.stringCamelCase)(runtimeApiName)}: {
37
- ${Object.keys(methods)
38
- .map((methodName) => this.#generateMethodDefFromSpec({
39
- ...methods[methodName],
40
- runtimeApiName,
41
- methodName,
42
- }))
43
- .join('\n')}
44
-
45
- ${(0, utils_1.commentBlock)('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
46
- }`;
47
- });
48
- }
49
- const importTypes = this.typesGen.typeImports.toImports();
50
- const template = (0, utils_1.compileTemplate)('runtime.hbs');
51
- return (0, utils_1.beautifySourceCode)(template({ importTypes, runtimeCallsOut }));
52
- }
53
- #isOptionalType(type) {
54
- return type.startsWith('Option<') || type.endsWith('| undefined');
55
- }
56
- #isOptionalParam(params, type, idx) {
57
- return this.#isOptionalType(type) && params.slice(idx + 1).every(({ type }) => this.#isOptionalType(type));
58
- }
59
- #generateMethodDefFromSpec(spec) {
60
- const { docs = [], params, type, runtimeApiName, methodName } = spec;
61
- const callName = `${runtimeApiName}_${(0, utils_2.stringSnakeCase)(methodName)}`;
62
- const defaultDocs = [`@callname: ${callName}`];
63
- this.addTypeImport(type, false);
64
- params.forEach(({ type }) => this.addTypeImport(type));
65
- const typedParams = params.map((param, idx) => ({
66
- ...param,
67
- isOptional: this.#isOptionalParam(params, param.type, idx),
68
- plainType: this.getGeneratedTypeName(param.type),
69
- }));
70
- const paramsOut = typedParams
71
- .map(({ name, isOptional, plainType }) => `${(0, util_1.stringCamelCase)(name)}${isOptional ? '?' : ''}: ${plainType}`)
72
- .join(', ');
73
- const typeOut = this.getGeneratedTypeName(type, false);
74
- return `${(0, utils_1.commentBlock)(docs, '\n', defaultDocs, typedParams.map(({ plainType, name }) => `@param {${plainType}} ${name}`))}${methodName}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
75
- }
76
- #generateMethodDef(runtimeApiName, methodDef) {
77
- const { name: methodName, inputs, output, docs } = methodDef;
78
- const callName = `${runtimeApiName}_${(0, utils_2.stringSnakeCase)(methodName)}`;
79
- const defaultDocs = [`@callname: ${callName}`];
80
- const typeOut = this.typesGen.generateType(output, 1, true);
81
- this.addTypeImport(typeOut, false);
82
- const typedInputs = inputs
83
- .map((input, idx) => ({
84
- ...input,
85
- type: this.typesGen.generateType(input.typeId, 1),
86
- }))
87
- .map((input, idx, inputs) => ({
88
- ...input,
89
- isOptional: this.#isOptionalParam(inputs, input.type, idx),
90
- }));
91
- this.addTypeImport(typedInputs.map((t) => t.type));
92
- const paramsOut = typedInputs
93
- .map(({ name, type, isOptional }) => `${(0, util_1.stringCamelCase)(name)}${isOptional ? '?' : ''}: ${type}`)
94
- .join(', ');
95
- return `${(0, utils_1.commentBlock)(docs, '\n', defaultDocs, typedInputs.map(({ type, name }) => `@param {${type}} ${name}`))}${(0, util_1.stringCamelCase)(methodName)}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
96
- }
97
- #targetRuntimeApiSpecs() {
98
- const specs = this.runtimeApis.map(([runtimeApiHash, version]) => {
99
- const runtimeApiSpec = (0, specs_1.findRuntimeApiSpec)(runtimeApiHash, version);
100
- if (!runtimeApiSpec)
101
- return;
102
- return {
103
- ...runtimeApiSpec,
104
- runtimeApiHash,
105
- };
106
- });
107
- return specs.reduce((o, spec) => {
108
- if (!spec) {
109
- return o;
110
- }
111
- return [...o, spec];
112
- }, []);
113
- }
114
- }
115
- exports.RuntimeApisGen = RuntimeApisGen;
@@ -1,5 +0,0 @@
1
- "use strict";
2
- // THIS FILE IS AUTO-GENERATED, DO NOT EDIT!
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.packageInfo = void 0;
5
- exports.packageInfo = { name: '@dedot/codegen', version: '0.0.1-alpha.26' };
@@ -1,7 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- {{{ importTypes }}}
4
-
5
- export interface ChainConsts extends GenericChainConsts {
6
- {{{ defTypeOut }}}
7
- }
@@ -1,7 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- {{{ importTypes }}}
4
-
5
- export interface ChainErrors extends GenericChainErrors {
6
- {{{ defTypeOut }}}
7
- }
@@ -1,7 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- {{{ importTypes }}}
4
-
5
- export interface ChainEvents extends GenericChainEvents {
6
- {{{ defTypeOut }}}
7
- }
@@ -1,22 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- import { GenericSubstrateApi } from '@dedot/types';
4
- import { ChainConsts } from './consts';
5
- import { ChainStorage } from './query';
6
- import { RpcCalls } from './rpc';
7
- import { ChainErrors } from './errors';
8
- import { ChainEvents } from './events';
9
- import { RuntimeApis } from './runtime';
10
- import { ChainTx } from './tx';
11
-
12
- export * from './types';
13
-
14
- export interface {{{interfaceName}}}Api extends GenericSubstrateApi {
15
- rpc: RpcCalls;
16
- consts: ChainConsts;
17
- query: ChainStorage;
18
- errors: ChainErrors;
19
- events: ChainEvents;
20
- call: RuntimeApis;
21
- tx: ChainTx;
22
- }
@@ -1,7 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- {{{ importTypes }}}
4
-
5
- export interface ChainStorage extends GenericChainStorage {
6
- {{{ defTypeOut }}}
7
- }
@@ -1,7 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- {{{ importTypes }}}
4
-
5
- export interface RpcCalls extends GenericRpcCalls {
6
- {{{rpcCallsOut}}}
7
- }
@@ -1,8 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- {{{ importTypes }}}
4
-
5
- export interface RuntimeApis extends GenericRuntimeApis {
6
- {{{ runtimeCallsOut }}}
7
- }
8
-
@@ -1,9 +0,0 @@
1
- // Generated by @dedot/codegen
2
-
3
- {{{ importTypes }}}
4
-
5
- {{{ defTypes }}}
6
-
7
- export interface ChainTx extends GenericChainTx<TxCall> {
8
- {{{ txDefsOut }}}
9
- }
package/cjs/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1 +0,0 @@
1
- export {};
@@ -1,74 +0,0 @@
1
- import { generateTypes, generateTypesFromChain } from './index';
2
- import { rpc } from '@polkadot/types-support/metadata/static-substrate';
3
- import staticSubstrate from '@polkadot/types-support/metadata/v15/substrate-hex';
4
- import { $Metadata, CodecRegistry } from '@dedot/codecs';
5
- import { ConstantExecutor } from 'dedot';
6
- const NETWORKS = [
7
- {
8
- chain: 'substrate',
9
- metadataHex: staticSubstrate,
10
- rpcMethods: rpc.methods,
11
- },
12
- {
13
- chain: 'polkadot',
14
- endpoint: 'wss://rpc.polkadot.io',
15
- },
16
- {
17
- chain: 'kusama',
18
- endpoint: 'wss://kusama-rpc.polkadot.io',
19
- },
20
- {
21
- chain: 'astar',
22
- endpoint: 'wss://rpc.astar.network',
23
- },
24
- {
25
- chain: 'moonbeam',
26
- endpoint: 'wss://moonbeam.api.onfinality.io/public-ws',
27
- },
28
- {
29
- chain: 'polkadotAssetHub',
30
- endpoint: 'wss://polkadot-asset-hub-rpc.polkadot.io/',
31
- },
32
- {
33
- chain: 'kusamaAssetHub',
34
- endpoint: 'wss://kusama-asset-hub-rpc.polkadot.io/',
35
- },
36
- {
37
- chain: 'rococoAssetHub',
38
- endpoint: 'wss://rococo-asset-hub-rpc.polkadot.io/',
39
- },
40
- {
41
- chain: 'aleph',
42
- endpoint: 'wss://aleph-zero.api.onfinality.io/public-ws',
43
- },
44
- {
45
- chain: 'westendAssetHub',
46
- endpoint: 'wss://westend-asset-hub-rpc.polkadot.io',
47
- },
48
- ];
49
- const OUT_DIR = 'packages/chaintypes/src';
50
- async function run() {
51
- for (const network of NETWORKS) {
52
- const { chain, endpoint, metadataHex, rpcMethods } = network;
53
- if (endpoint) {
54
- console.log(`Generate types for ${chain} via endpoint ${endpoint}`);
55
- await generateTypesFromChain(network, endpoint, OUT_DIR);
56
- }
57
- else if (metadataHex && rpcMethods) {
58
- console.log(`Generate types for ${chain} via raw data`);
59
- const metadata = $Metadata.tryDecode(metadataHex);
60
- const runtimeVersion = getRuntimeVersion(metadata);
61
- await generateTypes(network, metadata.latest, rpcMethods, runtimeVersion.apis, OUT_DIR);
62
- }
63
- }
64
- console.log('DONE!');
65
- }
66
- const getRuntimeVersion = (metadata) => {
67
- const registry = new CodecRegistry(metadata.latest);
68
- const executor = new ConstantExecutor({
69
- registry,
70
- metadataLatest: metadata.latest,
71
- });
72
- return executor.execute('system', 'version');
73
- };
74
- run().catch(console.log);
@@ -1,4 +0,0 @@
1
- import { ApiGen } from '../generator';
2
- export declare class ConstsGen extends ApiGen {
3
- generate(): Promise<string>;
4
- }
@@ -1,5 +0,0 @@
1
- import { ApiGen } from './ApiGen';
2
- export declare class ErrorsGen extends ApiGen {
3
- #private;
4
- generate(): Promise<string>;
5
- }
@@ -1,5 +0,0 @@
1
- import { ApiGen } from './ApiGen';
2
- export declare class EventsGen extends ApiGen {
3
- #private;
4
- generate(): Promise<string>;
5
- }
@@ -1,6 +0,0 @@
1
- import { NetworkInfo } from '../types';
2
- export declare class IndexGen {
3
- readonly networkInfo: NetworkInfo;
4
- constructor(networkInfo: NetworkInfo);
5
- generate(): Promise<string>;
6
- }
@@ -1,14 +0,0 @@
1
- import { beautifySourceCode, compileTemplate } from './utils';
2
- import { stringPascalCase } from '@polkadot/util';
3
- export class IndexGen {
4
- networkInfo;
5
- constructor(networkInfo) {
6
- this.networkInfo = networkInfo;
7
- }
8
- async generate() {
9
- const { chain } = this.networkInfo;
10
- const interfaceName = stringPascalCase(chain);
11
- const template = compileTemplate('index.hbs');
12
- return beautifySourceCode(template({ interfaceName }));
13
- }
14
- }
@@ -1,5 +0,0 @@
1
- import { ApiGen } from '../generator';
2
- export declare class QueryGen extends ApiGen {
3
- #private;
4
- generate(): Promise<string>;
5
- }
@@ -1,10 +0,0 @@
1
- import { ApiGen, TypesGen } from '../generator';
2
- export declare class RpcGen extends ApiGen {
3
- #private;
4
- readonly typesGen: TypesGen;
5
- readonly rpcMethods: string[];
6
- constructor(typesGen: TypesGen, rpcMethods: string[]);
7
- generate(): Promise<string>;
8
- addTypeImport(type: string | string[], toTypeIn?: boolean): void;
9
- getGeneratedTypeName(type: string, toTypeIn?: boolean): string;
10
- }
@@ -1,171 +0,0 @@
1
- import { findAliasRpcSpec, findRpcSpec, isUnsubscribeMethod } from '@dedot/specs';
2
- import { isNativeType } from '@dedot/utils';
3
- import { ApiGen } from '../generator';
4
- import { beautifySourceCode, commentBlock, compileTemplate, TUPLE_TYPE_REGEX, WRAPPER_TYPE_REGEX } from './utils';
5
- const HIDDEN_RPCS = [
6
- // Ref: https://github.com/paritytech/polkadot-sdk/blob/43415ef58c143b985e09015cd000dbd65f6d3997/substrate/client/rpc-servers/src/lib.rs#L152C9-L158
7
- 'rpc_methods',
8
- ];
9
- export class RpcGen extends ApiGen {
10
- typesGen;
11
- rpcMethods;
12
- constructor(typesGen, rpcMethods) {
13
- super(typesGen);
14
- this.typesGen = typesGen;
15
- this.rpcMethods = rpcMethods;
16
- HIDDEN_RPCS.filter((one) => !rpcMethods.includes(one)).forEach((one) => rpcMethods.push(one));
17
- rpcMethods.sort();
18
- }
19
- generate() {
20
- this.typesGen.clearCache();
21
- this.typesGen.typeImports.addKnownType('GenericRpcCalls', 'Unsub', 'Callback', 'GenericRpcCall');
22
- const specsByModule = this.rpcMethods
23
- .filter((one) => !findAliasRpcSpec(one)) // we'll ignore alias rpc for now if defined in the specs! TODO should we generate alias rpc as well?
24
- .filter((one) => !isUnsubscribeMethod(one)) // we'll ignore unsubscribe method as well
25
- .map((one) => {
26
- const spec = findRpcSpec(one);
27
- if (spec) {
28
- return spec;
29
- }
30
- const [module, ...methodParts] = one.split('_');
31
- const method = methodParts.join('_');
32
- return {
33
- params: [],
34
- type: 'GenericRpcCall',
35
- module,
36
- method,
37
- };
38
- })
39
- .reduce((o, spec) => {
40
- const { module, method } = spec;
41
- // ignore if rpc name does not confront with the general convention
42
- if (!module || !method) {
43
- return o;
44
- }
45
- return {
46
- ...o,
47
- [module]: o[module] ? [...o[module], spec] : [spec],
48
- };
49
- }, {});
50
- let rpcCallsOut = '';
51
- Object.keys(specsByModule).forEach((module) => {
52
- const specs = specsByModule[module];
53
- // TODO add alias info to docs block!
54
- rpcCallsOut += `${module}: {
55
- ${specs.map((spec) => this.#generateMethodDef(spec)).join(',\n')},
56
-
57
- [method: string]: GenericRpcCall,
58
- },`;
59
- });
60
- // TODO include & define external types
61
- const importTypes = this.typesGen.typeImports.toImports();
62
- const template = compileTemplate('rpc.hbs');
63
- return beautifySourceCode(template({ importTypes, rpcCallsOut }));
64
- }
65
- #generateMethodDef(spec) {
66
- const { name, type, module, method, docs = [], params, pubsub, deprecated } = spec;
67
- const rpcName = name || `${module}_${method}`;
68
- let defaultDocs = [`@rpcname: ${rpcName}`];
69
- if (deprecated) {
70
- defaultDocs.push(`@deprecated: ${deprecated}`);
71
- }
72
- if (type === 'GenericRpcCall' && params.length === 0) {
73
- return `${commentBlock(defaultDocs)}${method}: GenericRpcCall`;
74
- }
75
- this.addTypeImport(type, false);
76
- params.forEach(({ type, isScale }) => {
77
- this.addTypeImport(type, !!isScale);
78
- });
79
- const typedParams = params.map((param) => ({
80
- ...param,
81
- plainType: this.getGeneratedTypeName(param.type, !!param.isScale),
82
- }));
83
- const isSubscription = !!pubsub;
84
- const paramsOut = typedParams.map(({ name, type, isOptional, isScale, plainType }) => `${name}${isOptional ? '?' : ''}: ${plainType}`);
85
- const paramsDoc = typedParams.map(({ name, plainType }) => `@param {${plainType}} ${name}`);
86
- const typeOut = this.getGeneratedTypeName(type, false);
87
- if (isSubscription) {
88
- defaultDocs.shift();
89
- defaultDocs.unshift(`@pubsub: ${pubsub?.join(', ')}`);
90
- paramsOut.push(`callback: Callback<${typeOut}>`);
91
- return `${commentBlock(docs, '\n', defaultDocs, paramsDoc)}${method}: GenericRpcCall<(${paramsOut.join(', ')}) => Promise<Unsub>>`;
92
- }
93
- else {
94
- return `${commentBlock(docs, '\n', defaultDocs, paramsDoc)}${method}: GenericRpcCall<(${paramsOut.join(', ')}) => Promise<${typeOut}>>`;
95
- }
96
- }
97
- // TODO check typeIn, typeOut if param type, or rpc type isScale
98
- addTypeImport(type, toTypeIn = true) {
99
- if (Array.isArray(type)) {
100
- type.forEach((one) => this.addTypeImport(one, toTypeIn));
101
- return;
102
- }
103
- type = type.trim();
104
- if (isNativeType(type)) {
105
- return;
106
- }
107
- // Handle generic wrapper types
108
- const matchArray = type.match(WRAPPER_TYPE_REGEX);
109
- if (matchArray) {
110
- const [_, $1, $2] = matchArray;
111
- this.addTypeImport($1, toTypeIn);
112
- if ($2.match(WRAPPER_TYPE_REGEX) || $2.match(TUPLE_TYPE_REGEX)) {
113
- this.addTypeImport($2, toTypeIn);
114
- }
115
- else {
116
- this.addTypeImport($2.split(','), toTypeIn);
117
- }
118
- return;
119
- }
120
- // Check tuple type
121
- if (type.match(TUPLE_TYPE_REGEX)) {
122
- this.addTypeImport(type.slice(1, -1).split(','), toTypeIn);
123
- return;
124
- }
125
- if (type.includes(' | ')) {
126
- this.addTypeImport(type.split(' | ').map((one) => one.trim()), toTypeIn);
127
- return;
128
- }
129
- try {
130
- const codecType = this.#getCodecType(type, toTypeIn);
131
- if (isNativeType(codecType))
132
- return;
133
- this.typesGen.typeImports.addCodecType(codecType);
134
- return;
135
- }
136
- catch (e) { }
137
- this.typesGen.addTypeImport(type);
138
- }
139
- getGeneratedTypeName(type, toTypeIn = true) {
140
- try {
141
- const matchArray = type.match(WRAPPER_TYPE_REGEX);
142
- if (matchArray) {
143
- const [_, $1, $2] = matchArray;
144
- const wrapperTypeName = this.#getCodecType($1, toTypeIn);
145
- if ($2.match(WRAPPER_TYPE_REGEX) || $2.match(TUPLE_TYPE_REGEX)) {
146
- return `${wrapperTypeName}<${this.getGeneratedTypeName($2, toTypeIn)}>`;
147
- }
148
- const innerTypeNames = $2
149
- .split(',')
150
- .map((one) => this.getGeneratedTypeName(one.trim(), toTypeIn))
151
- .join(', ');
152
- return `${wrapperTypeName}<${innerTypeNames}>`;
153
- }
154
- else if (type.match(TUPLE_TYPE_REGEX)) {
155
- const innerTypeNames = type
156
- .slice(1, -1)
157
- .split(',')
158
- .map((one) => this.getGeneratedTypeName(one.trim(), toTypeIn))
159
- .join(', ');
160
- return `[${innerTypeNames}]`;
161
- }
162
- return this.#getCodecType(type, toTypeIn);
163
- }
164
- catch (e) { }
165
- return type;
166
- }
167
- #getCodecType(type, toTypeIn = true) {
168
- const { typeIn, typeOut } = this.registry.findCodecType(type);
169
- return toTypeIn ? typeIn : typeOut;
170
- }
171
- }
@@ -1,9 +0,0 @@
1
- import { TypesGen } from './TypesGen';
2
- import { RpcGen } from './RpcGen';
3
- export declare class RuntimeApisGen extends RpcGen {
4
- #private;
5
- readonly typesGen: TypesGen;
6
- readonly runtimeApis: [string, number][];
7
- constructor(typesGen: TypesGen, runtimeApis: [string, number][]);
8
- generate(): Promise<string>;
9
- }
@@ -1,111 +0,0 @@
1
- import { findRuntimeApiSpec } from '@dedot/specs';
2
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils';
3
- import { calculateRuntimeApiHash, stringSnakeCase } from '@dedot/utils';
4
- import { RpcGen } from './RpcGen';
5
- import { stringCamelCase } from '@polkadot/util';
6
- export class RuntimeApisGen extends RpcGen {
7
- typesGen;
8
- runtimeApis;
9
- constructor(typesGen, runtimeApis) {
10
- super(typesGen, []);
11
- this.typesGen = typesGen;
12
- this.runtimeApis = runtimeApis;
13
- }
14
- generate() {
15
- this.typesGen.clearCache();
16
- this.typesGen.typeImports.addKnownType('GenericRuntimeApis', 'GenericRuntimeApiMethod');
17
- let runtimeCallsOut = '';
18
- if (this.metadata.apis.length > 0) {
19
- this.metadata.apis.forEach((runtimeApi) => {
20
- const { name: runtimeApiName, methods } = runtimeApi;
21
- runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${calculateRuntimeApiHash(runtimeApiName)}`);
22
- runtimeCallsOut += `${stringCamelCase(runtimeApiName)}: {
23
- ${methods.map((method) => this.#generateMethodDef(runtimeApiName, method)).join('\n')}
24
-
25
- ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
26
- }`;
27
- });
28
- }
29
- else {
30
- const specs = this.#targetRuntimeApiSpecs();
31
- specs.forEach(({ methods, runtimeApiName, runtimeApiHash, version }) => {
32
- runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${runtimeApiHash}`, `@version: ${version}`);
33
- runtimeCallsOut += `${stringCamelCase(runtimeApiName)}: {
34
- ${Object.keys(methods)
35
- .map((methodName) => this.#generateMethodDefFromSpec({
36
- ...methods[methodName],
37
- runtimeApiName,
38
- methodName,
39
- }))
40
- .join('\n')}
41
-
42
- ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
43
- }`;
44
- });
45
- }
46
- const importTypes = this.typesGen.typeImports.toImports();
47
- const template = compileTemplate('runtime.hbs');
48
- return beautifySourceCode(template({ importTypes, runtimeCallsOut }));
49
- }
50
- #isOptionalType(type) {
51
- return type.startsWith('Option<') || type.endsWith('| undefined');
52
- }
53
- #isOptionalParam(params, type, idx) {
54
- return this.#isOptionalType(type) && params.slice(idx + 1).every(({ type }) => this.#isOptionalType(type));
55
- }
56
- #generateMethodDefFromSpec(spec) {
57
- const { docs = [], params, type, runtimeApiName, methodName } = spec;
58
- const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
59
- const defaultDocs = [`@callname: ${callName}`];
60
- this.addTypeImport(type, false);
61
- params.forEach(({ type }) => this.addTypeImport(type));
62
- const typedParams = params.map((param, idx) => ({
63
- ...param,
64
- isOptional: this.#isOptionalParam(params, param.type, idx),
65
- plainType: this.getGeneratedTypeName(param.type),
66
- }));
67
- const paramsOut = typedParams
68
- .map(({ name, isOptional, plainType }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${plainType}`)
69
- .join(', ');
70
- const typeOut = this.getGeneratedTypeName(type, false);
71
- return `${commentBlock(docs, '\n', defaultDocs, typedParams.map(({ plainType, name }) => `@param {${plainType}} ${name}`))}${methodName}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
72
- }
73
- #generateMethodDef(runtimeApiName, methodDef) {
74
- const { name: methodName, inputs, output, docs } = methodDef;
75
- const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
76
- const defaultDocs = [`@callname: ${callName}`];
77
- const typeOut = this.typesGen.generateType(output, 1, true);
78
- this.addTypeImport(typeOut, false);
79
- const typedInputs = inputs
80
- .map((input, idx) => ({
81
- ...input,
82
- type: this.typesGen.generateType(input.typeId, 1),
83
- }))
84
- .map((input, idx, inputs) => ({
85
- ...input,
86
- isOptional: this.#isOptionalParam(inputs, input.type, idx),
87
- }));
88
- this.addTypeImport(typedInputs.map((t) => t.type));
89
- const paramsOut = typedInputs
90
- .map(({ name, type, isOptional }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${type}`)
91
- .join(', ');
92
- return `${commentBlock(docs, '\n', defaultDocs, typedInputs.map(({ type, name }) => `@param {${type}} ${name}`))}${stringCamelCase(methodName)}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
93
- }
94
- #targetRuntimeApiSpecs() {
95
- const specs = this.runtimeApis.map(([runtimeApiHash, version]) => {
96
- const runtimeApiSpec = findRuntimeApiSpec(runtimeApiHash, version);
97
- if (!runtimeApiSpec)
98
- return;
99
- return {
100
- ...runtimeApiSpec,
101
- runtimeApiHash,
102
- };
103
- });
104
- return specs.reduce((o, spec) => {
105
- if (!spec) {
106
- return o;
107
- }
108
- return [...o, spec];
109
- }, []);
110
- }
111
- }
@@ -1,5 +0,0 @@
1
- import { ApiGen } from '../generator';
2
- export declare class TxGen extends ApiGen {
3
- #private;
4
- generate(): Promise<string>;
5
- }
@@ -1,10 +0,0 @@
1
- export * from './TypesGen';
2
- export * from './ApiGen';
3
- export * from './ConstsGen';
4
- export * from './QueryGen';
5
- export * from './RpcGen';
6
- export * from './IndexGen';
7
- export * from './ErrorsGen';
8
- export * from './EventsGen';
9
- export * from './TxGen';
10
- export * from './RuntimeApisGen';