wasm-ast-types 0.0.3

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.
package/main/wasm.js ADDED
@@ -0,0 +1,304 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ var _typeof = require("@babel/runtime/helpers/typeof");
6
+
7
+ Object.defineProperty(exports, "__esModule", {
8
+ value: true
9
+ });
10
+ exports.propertySignature = exports.createWasmQueryMethod = exports.createWasmExecMethod = exports.createTypeOrInterface = exports.createTypeInterface = exports.createQueryInterface = exports.createQueryClass = exports.createExecuteInterface = exports.createExecuteClass = void 0;
11
+
12
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
13
+
14
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
15
+
16
+ var t = _interopRequireWildcard(require("@babel/types"));
17
+
18
+ var _case = require("case");
19
+
20
+ var _utils = require("./utils");
21
+
22
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
23
+
24
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
25
+
26
+ var getTypeFromRef = function getTypeFromRef($ref) {
27
+ switch ($ref) {
28
+ case '#/definitions/Binary':
29
+ return t.tsTypeReference(t.identifier('BinaryType'));
30
+
31
+ case '#/definitions/Expiration':
32
+ return t.tsTypeReference(t.identifier('Expiration'));
33
+
34
+ default:
35
+ if ($ref.startsWith('#/definitions/')) {
36
+ return t.tsTypeReference(t.identifier($ref.replace('#/definitions/', '')));
37
+ }
38
+
39
+ throw new Error('what is $ref: ' + $ref);
40
+ }
41
+ };
42
+
43
+ var getArrayTypeFromRef = function getArrayTypeFromRef($ref) {
44
+ return t.tsArrayType(getTypeFromRef($ref));
45
+ };
46
+
47
+ var getArrayTypeFromType = function getArrayTypeFromType(type) {
48
+ return t.tsArrayType(getType(type));
49
+ };
50
+
51
+ var getType = function getType(type) {
52
+ switch (type) {
53
+ case 'string':
54
+ return t.tsStringKeyword();
55
+
56
+ case 'boolean':
57
+ return t.tSBooleanKeyword();
58
+
59
+ case 'integer':
60
+ return t.tsNumberKeyword();
61
+
62
+ default:
63
+ throw new Error('what is type: ' + type);
64
+ }
65
+ };
66
+
67
+ var getPropertyType = function getPropertyType(schema, prop) {
68
+ var _schema$properties, _schema$required;
69
+
70
+ var props = (_schema$properties = schema.properties) !== null && _schema$properties !== void 0 ? _schema$properties : {};
71
+ var info = props[prop];
72
+ var type = null;
73
+ var optional = (_schema$required = schema.required) === null || _schema$required === void 0 ? void 0 : _schema$required.includes(prop);
74
+
75
+ if (info.allOf && info.allOf.length === 1) {
76
+ info = info.allOf[0];
77
+ }
78
+
79
+ if (typeof info.$ref === 'string') {
80
+ type = getTypeFromRef(info.$ref);
81
+ }
82
+
83
+ if (Array.isArray(info.anyOf)) {
84
+ // assuming 2nd is null, but let's check to ensure
85
+ if (info.anyOf.length !== 2) {
86
+ throw new Error('case not handled by transpiler. contact maintainers.');
87
+ }
88
+
89
+ var _info$anyOf = (0, _slicedToArray2["default"])(info.anyOf, 2),
90
+ nullableType = _info$anyOf[0],
91
+ nullType = _info$anyOf[1];
92
+
93
+ if ((nullType === null || nullType === void 0 ? void 0 : nullType.type) !== 'null') {
94
+ throw new Error('case not handled by transpiler. contact maintainers.');
95
+ }
96
+
97
+ type = getTypeFromRef(nullableType === null || nullableType === void 0 ? void 0 : nullableType.$ref);
98
+ optional = true;
99
+ }
100
+
101
+ if (typeof info.type === 'string') {
102
+ if (info.type === 'array') {
103
+ if (info.items.$ref) {
104
+ type = getArrayTypeFromRef(info.items.$ref);
105
+ } else {
106
+ type = getArrayTypeFromType(info.items.type);
107
+ }
108
+ } else {
109
+ type = getType(info.type);
110
+ }
111
+ }
112
+
113
+ if (Array.isArray(info.type)) {
114
+ // assuming 2nd is null, but let's check to ensure
115
+ if (info.type.length !== 2) {
116
+ throw new Error('case not handled by transpiler. contact maintainers.');
117
+ }
118
+
119
+ var _info$type = (0, _slicedToArray2["default"])(info.type, 2),
120
+ _nullableType = _info$type[0],
121
+ _nullType = _info$type[1];
122
+
123
+ if (_nullType !== 'null') {
124
+ throw new Error('case not handled by transpiler. contact maintainers.');
125
+ }
126
+
127
+ type = getType(_nullableType);
128
+ optional = true;
129
+ }
130
+
131
+ if (!type) {
132
+ throw new Error('cannot find type for ' + JSON.stringify(info));
133
+ }
134
+
135
+ return {
136
+ type: type,
137
+ optional: optional
138
+ };
139
+ };
140
+
141
+ var getProperty = function getProperty(schema, prop) {
142
+ var _getPropertyType = getPropertyType(schema, prop),
143
+ type = _getPropertyType.type,
144
+ optional = _getPropertyType.optional;
145
+
146
+ return (0, _utils.typedIdentifier)((0, _case.camel)(prop), t.tsTypeAnnotation(type), optional);
147
+ };
148
+
149
+ var createWasmQueryMethod = function createWasmQueryMethod(jsonschema) {
150
+ var _jsonschema$propertie;
151
+
152
+ var underscoreName = Object.keys(jsonschema.properties)[0];
153
+ var methodName = (0, _case.camel)(underscoreName);
154
+ var responseType = (0, _case.pascal)("".concat(methodName, "Response"));
155
+ var properties = (_jsonschema$propertie = jsonschema.properties[underscoreName].properties) !== null && _jsonschema$propertie !== void 0 ? _jsonschema$propertie : {}; // console.log({ jsonschema, methodName, underscoreName, properties });
156
+
157
+ var params = Object.keys(properties).map(function (prop) {
158
+ return getProperty(jsonschema.properties[underscoreName], prop);
159
+ });
160
+ var args = Object.keys(properties).map(function (prop) {
161
+ return t.objectProperty(t.identifier(prop), t.identifier((0, _case.camel)(prop)), false, true);
162
+ });
163
+ var actionArg = t.objectProperty(t.identifier(underscoreName), t.objectExpression(args));
164
+ return t.classProperty(t.identifier(methodName), (0, _utils.arrowFunctionExpression)(params, t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('queryContractSmart')), [t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.objectExpression([actionArg])]))]), t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tSTypeReference(t.identifier(responseType))]))), true));
165
+ };
166
+
167
+ exports.createWasmQueryMethod = createWasmQueryMethod;
168
+
169
+ var createQueryClass = function createQueryClass(className, implementsClassName, queryMsg) {
170
+ var propertyNames = queryMsg.oneOf.map(function (method) {
171
+ var _Object$keys;
172
+
173
+ return (_Object$keys = Object.keys(method.properties)) === null || _Object$keys === void 0 ? void 0 : _Object$keys[0];
174
+ }).filter(Boolean);
175
+ var bindings = propertyNames.map(_case.camel).map(_utils.bindMethod);
176
+ var methods = queryMsg.oneOf.map(function (schema) {
177
+ return createWasmQueryMethod(schema);
178
+ });
179
+ return t.exportNamedDeclaration((0, _utils.classDeclaration)(className, [// client
180
+ (0, _utils.classProperty)('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('CosmWasmClient')))), // contractAddress
181
+ (0, _utils.classProperty)('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword())), // constructor
182
+ t.classMethod('constructor', t.identifier('constructor'), [(0, _utils.typedIdentifier)('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('CosmWasmClient')))), (0, _utils.typedIdentifier)('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement([// client/contract set
183
+ t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('client'))), t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.identifier('contractAddress')))].concat((0, _toConsumableArray2["default"])(bindings))))].concat((0, _toConsumableArray2["default"])(methods)), [t.tSExpressionWithTypeArguments(t.identifier(implementsClassName))]));
184
+ };
185
+
186
+ exports.createQueryClass = createQueryClass;
187
+
188
+ var createWasmExecMethod = function createWasmExecMethod(jsonschema) {
189
+ var _jsonschema$propertie2;
190
+
191
+ var underscoreName = Object.keys(jsonschema.properties)[0];
192
+ var methodName = (0, _case.camel)(underscoreName);
193
+ var properties = (_jsonschema$propertie2 = jsonschema.properties[underscoreName].properties) !== null && _jsonschema$propertie2 !== void 0 ? _jsonschema$propertie2 : {};
194
+ var params = Object.keys(properties).map(function (prop) {
195
+ return getProperty(jsonschema.properties[underscoreName], prop);
196
+ });
197
+ var args = Object.keys(properties).map(function (prop) {
198
+ return t.objectProperty(t.identifier(prop), t.identifier((0, _case.camel)(prop)), false, prop === (0, _case.camel)(prop));
199
+ });
200
+ return t.classProperty(t.identifier(methodName), (0, _utils.arrowFunctionExpression)((0, _toConsumableArray2["default"])(params), t.blockStatement([t.returnStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('execute')), [t.memberExpression(t.thisExpression(), t.identifier('sender')), t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.objectExpression([t.objectProperty(t.identifier(underscoreName), t.objectExpression((0, _toConsumableArray2["default"])(args)))]), t.stringLiteral('auto')])))]), // return type
201
+ t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tSTypeReference(t.identifier('ExecuteResult'))]))), true));
202
+ };
203
+
204
+ exports.createWasmExecMethod = createWasmExecMethod;
205
+
206
+ var createExecuteClass = function createExecuteClass(className, implementsClassName, extendsClassName, execMsg) {
207
+ var propertyNames = execMsg.oneOf.map(function (method) {
208
+ var _Object$keys2;
209
+
210
+ return (_Object$keys2 = Object.keys(method.properties)) === null || _Object$keys2 === void 0 ? void 0 : _Object$keys2[0];
211
+ }).filter(Boolean);
212
+ var bindings = propertyNames.map(_case.camel).map(_utils.bindMethod);
213
+ var methods = execMsg.oneOf.map(function (schema) {
214
+ return createWasmExecMethod(schema);
215
+ });
216
+ return t.exportNamedDeclaration((0, _utils.classDeclaration)(className, [// client
217
+ (0, _utils.classProperty)('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('SigningCosmWasmClient')))), // sender
218
+ (0, _utils.classProperty)('sender', t.tsTypeAnnotation(t.tsStringKeyword())), // contractAddress
219
+ (0, _utils.classProperty)('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword())), // constructor
220
+ t.classMethod('constructor', t.identifier('constructor'), [(0, _utils.typedIdentifier)('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('SigningCosmWasmClient')))), (0, _utils.typedIdentifier)('sender', t.tsTypeAnnotation(t.tsStringKeyword())), (0, _utils.typedIdentifier)('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement([// super()
221
+ t.expressionStatement(t.callExpression(t["super"](), [t.identifier('client'), t.identifier('contractAddress')])), // client/contract set
222
+ t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('client'))), t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.identifier('contractAddress')))].concat((0, _toConsumableArray2["default"])(bindings))))].concat((0, _toConsumableArray2["default"])(methods)), [t.tSExpressionWithTypeArguments(t.identifier(implementsClassName))], t.identifier(extendsClassName)));
223
+ };
224
+
225
+ exports.createExecuteClass = createExecuteClass;
226
+
227
+ var createExecuteInterface = function createExecuteInterface(className, extendsClassName, execMsg) {
228
+ var methods = execMsg.oneOf.map(function (jsonschema) {
229
+ var _jsonschema$propertie3;
230
+
231
+ var underscoreName = Object.keys(jsonschema.properties)[0];
232
+ var methodName = (0, _case.camel)(underscoreName);
233
+ var properties = (_jsonschema$propertie3 = jsonschema.properties[underscoreName].properties) !== null && _jsonschema$propertie3 !== void 0 ? _jsonschema$propertie3 : {};
234
+ var params = Object.keys(properties).map(function (prop) {
235
+ return getProperty(jsonschema.properties[underscoreName], prop);
236
+ });
237
+ return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(t.tsFunctionType(null, (0, _toConsumableArray2["default"])(params), (0, _utils.promiseTypeAnnotation)('ExecuteResult'))));
238
+ });
239
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(className), null, [t.tSExpressionWithTypeArguments(t.identifier(extendsClassName))], t.tSInterfaceBody([// contract address
240
+ t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), // contract address
241
+ t.tSPropertySignature(t.identifier('sender'), t.tsTypeAnnotation(t.tsStringKeyword()))].concat((0, _toConsumableArray2["default"])(methods)))));
242
+ };
243
+
244
+ exports.createExecuteInterface = createExecuteInterface;
245
+
246
+ var createQueryInterface = function createQueryInterface(className, queryMsg) {
247
+ var methods = queryMsg.oneOf.map(function (jsonschema) {
248
+ var _jsonschema$propertie4;
249
+
250
+ var underscoreName = Object.keys(jsonschema.properties)[0];
251
+ var methodName = (0, _case.camel)(underscoreName);
252
+ var responseType = (0, _case.pascal)("".concat(methodName, "Response"));
253
+ var properties = (_jsonschema$propertie4 = jsonschema.properties[underscoreName].properties) !== null && _jsonschema$propertie4 !== void 0 ? _jsonschema$propertie4 : {};
254
+ var params = Object.keys(properties).map(function (prop) {
255
+ return getProperty(jsonschema.properties[underscoreName], prop);
256
+ });
257
+ return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(t.tsFunctionType(null, (0, _toConsumableArray2["default"])(params), (0, _utils.promiseTypeAnnotation)(responseType))));
258
+ });
259
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(className), null, [], t.tSInterfaceBody([t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword()))].concat((0, _toConsumableArray2["default"])(methods)))));
260
+ };
261
+
262
+ exports.createQueryInterface = createQueryInterface;
263
+
264
+ var propertySignature = function propertySignature(name, typeAnnotation) {
265
+ var optional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
266
+ var prop = t.tsPropertySignature(t.identifier(name), typeAnnotation); // prop.leadingComments = [{
267
+ // type: 'Comment',
268
+ // value: ' Data on the token itself'
269
+ // }];
270
+ // prop.leadingComments = [{
271
+ // type: 'CommentBlock',
272
+ // value: '* Data on the token itself'
273
+ // }];
274
+
275
+ return prop;
276
+ };
277
+
278
+ exports.propertySignature = propertySignature;
279
+
280
+ var createTypeOrInterface = function createTypeOrInterface(Type, jsonschema) {
281
+ var _jsonschema$propertie5;
282
+
283
+ if (jsonschema.type !== 'object') {
284
+ return t.exportNamedDeclaration(t.tsTypeAliasDeclaration(t.identifier(Type), null, getType(jsonschema.type)));
285
+ }
286
+
287
+ var props = Object.keys((_jsonschema$propertie5 = jsonschema.properties) !== null && _jsonschema$propertie5 !== void 0 ? _jsonschema$propertie5 : {}).map(function (prop) {
288
+ var _getPropertyType2 = getPropertyType(jsonschema, prop),
289
+ type = _getPropertyType2.type,
290
+ optional = _getPropertyType2.optional;
291
+
292
+ return propertySignature((0, _case.camel)(prop), t.tsTypeAnnotation(type), optional);
293
+ });
294
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(Type), null, [], t.tsInterfaceBody((0, _toConsumableArray2["default"])(props))));
295
+ };
296
+
297
+ exports.createTypeOrInterface = createTypeOrInterface;
298
+
299
+ var createTypeInterface = function createTypeInterface(jsonschema) {
300
+ var Type = jsonschema.title;
301
+ return createTypeOrInterface(Type, jsonschema);
302
+ };
303
+
304
+ exports.createTypeInterface = createTypeInterface;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ var _generator = _interopRequireDefault(require("@babel/generator"));
6
+
7
+ var _query_msg = _interopRequireDefault(require("./__fixtures__/schema/query_msg.json"));
8
+
9
+ var _execute_msg_for__empty = _interopRequireDefault(require("./__fixtures__/schema/execute_msg_for__empty.json"));
10
+
11
+ var _approval_response = _interopRequireDefault(require("./__fixtures__/schema/approval_response.json"));
12
+
13
+ var _all_nft_info_response = _interopRequireDefault(require("./__fixtures__/schema/all_nft_info_response.json"));
14
+
15
+ var _approvals_response = _interopRequireDefault(require("./__fixtures__/schema/approvals_response.json"));
16
+
17
+ var _collection_info_response = _interopRequireDefault(require("./__fixtures__/schema/collection_info_response.json"));
18
+
19
+ var _contract_info_response = _interopRequireDefault(require("./__fixtures__/schema/contract_info_response.json"));
20
+
21
+ var _instantiate_msg = _interopRequireDefault(require("./__fixtures__/schema/instantiate_msg.json"));
22
+
23
+ var _nft_info_response = _interopRequireDefault(require("./__fixtures__/schema/nft_info_response.json"));
24
+
25
+ var _num_tokens_response = _interopRequireDefault(require("./__fixtures__/schema/num_tokens_response.json"));
26
+
27
+ var _operators_response = _interopRequireDefault(require("./__fixtures__/schema/operators_response.json"));
28
+
29
+ var _owner_of_response = _interopRequireDefault(require("./__fixtures__/schema/owner_of_response.json"));
30
+
31
+ var _tokens_response = _interopRequireDefault(require("./__fixtures__/schema/tokens_response.json"));
32
+
33
+ var _wasm = require("./wasm");
34
+
35
+ var expectCode = function expectCode(ast) {
36
+ expect((0, _generator["default"])(ast).code).toMatchSnapshot();
37
+ };
38
+
39
+ var printCode = function printCode(ast) {
40
+ console.log((0, _generator["default"])(ast).code);
41
+ };
42
+
43
+ it('approval_response', function () {
44
+ expectCode((0, _wasm.createTypeInterface)(_approval_response["default"]));
45
+ });
46
+ it('all_nft_info_response', function () {
47
+ expectCode((0, _wasm.createTypeInterface)(_all_nft_info_response["default"]));
48
+ });
49
+ it('approvals_response', function () {
50
+ expectCode((0, _wasm.createTypeInterface)(_approvals_response["default"]));
51
+ });
52
+ it('collection_info_response', function () {
53
+ expectCode((0, _wasm.createTypeInterface)(_collection_info_response["default"]));
54
+ });
55
+ it('contract_info_response', function () {
56
+ expectCode((0, _wasm.createTypeInterface)(_contract_info_response["default"]));
57
+ });
58
+ it('instantiate_msg', function () {
59
+ expectCode((0, _wasm.createTypeInterface)(_instantiate_msg["default"]));
60
+ });
61
+ it('nft_info_response', function () {
62
+ expectCode((0, _wasm.createTypeInterface)(_nft_info_response["default"]));
63
+ });
64
+ it('num_tokens_response', function () {
65
+ expectCode((0, _wasm.createTypeInterface)(_num_tokens_response["default"]));
66
+ });
67
+ it('operators_response', function () {
68
+ expectCode((0, _wasm.createTypeInterface)(_operators_response["default"]));
69
+ });
70
+ it('owner_of_response', function () {
71
+ expectCode((0, _wasm.createTypeInterface)(_owner_of_response["default"]));
72
+ });
73
+ it('tokens_response', function () {
74
+ expectCode((0, _wasm.createTypeInterface)(_tokens_response["default"]));
75
+ });
76
+ it('query classes', function () {
77
+ expectCode((0, _wasm.createQueryClass)('SG721QueryClient', 'SG721ReadOnlyInstance', _query_msg["default"]));
78
+ });
79
+ it('execute classes', function () {
80
+ expectCode((0, _wasm.createExecuteClass)('SG721Client', 'SG721Instance', 'SG721QueryClient', _execute_msg_for__empty["default"]));
81
+ });
82
+ it('execute interfaces', function () {
83
+ expectCode((0, _wasm.createExecuteInterface)('SG721Instance', 'SG721ReadOnlyInstance', _execute_msg_for__empty["default"]));
84
+ });
85
+ it('query interfaces', function () {
86
+ expectCode((0, _wasm.createQueryInterface)('SG721ReadOnlyInstance', _query_msg["default"]));
87
+ });
@@ -0,0 +1,3 @@
1
+ export * from './types';
2
+ export * from './utils';
3
+ export * from './wasm';
@@ -0,0 +1,3 @@
1
+ ;
2
+ ;
3
+ export {};
@@ -0,0 +1,116 @@
1
+ import * as t from '@babel/types';
2
+ import { snake } from "case";
3
+ export const bindMethod = name => {
4
+ return t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier(name)), t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier(name)), t.identifier('bind')), [t.thisExpression()])));
5
+ };
6
+ export const typedIdentifier = (name, typeAnnotation, optional = false) => {
7
+ const type = t.identifier(name);
8
+ type.typeAnnotation = typeAnnotation;
9
+ type.optional = optional;
10
+ return type;
11
+ };
12
+ export const promiseTypeAnnotation = name => {
13
+ return t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(name))])));
14
+ };
15
+ export const classDeclaration = (name, body, implementsExressions = [], superClass = null) => {
16
+ const declaration = t.classDeclaration(t.identifier(name), superClass, t.classBody(body));
17
+
18
+ if (implementsExressions.length) {
19
+ declaration.implements = implementsExressions;
20
+ }
21
+
22
+ return declaration;
23
+ };
24
+ export const classProperty = (name, typeAnnotation = null, isReadonly = false, isStatic = false) => {
25
+ const prop = t.classProperty(t.identifier(name));
26
+ if (isReadonly) prop.readonly = true;
27
+ if (isStatic) prop.static = true;
28
+ if (typeAnnotation) prop.typeAnnotation = typeAnnotation;
29
+ return prop;
30
+ };
31
+ export const arrowFunctionExpression = (params, body, returnType, isAsync = false) => {
32
+ const func = t.arrowFunctionExpression(params, body, isAsync);
33
+ if (returnType) func.returnType = returnType;
34
+ return func;
35
+ };
36
+ export const recursiveNamespace = (names, moduleBlockBody) => {
37
+ if (!names || !names.length) return moduleBlockBody;
38
+ const name = names.pop();
39
+ const body = [t.exportNamedDeclaration(t.tsModuleDeclaration(t.identifier(name), t.tsModuleBlock(recursiveNamespace(names, moduleBlockBody))))];
40
+ return body;
41
+ };
42
+ export const arrayTypeNDimensions = (body, n) => {
43
+ if (!n) return t.tsArrayType(body);
44
+ return t.tsArrayType(arrayTypeNDimensions(body, n - 1));
45
+ };
46
+ export const FieldTypeAsts = {
47
+ string: () => {
48
+ return t.tsStringKeyword();
49
+ },
50
+ array: type => {
51
+ return t.tsArrayType(FieldTypeAsts[type]());
52
+ },
53
+ Duration: () => {
54
+ return t.tsTypeReference(t.identifier('Duration'));
55
+ },
56
+ Height: () => {
57
+ return t.tsTypeReference(t.identifier('Height'));
58
+ },
59
+ Coin: () => {
60
+ return t.tsTypeReference(t.identifier('Coin'));
61
+ },
62
+ Long: () => {
63
+ return t.tsTypeReference(t.identifier('Long'));
64
+ }
65
+ };
66
+ export const shorthandProperty = prop => {
67
+ return t.objectProperty(t.identifier(prop), t.identifier(prop), false, true);
68
+ };
69
+ export const importStmt = (names, path) => {
70
+ return t.importDeclaration(names.map(name => t.importSpecifier(t.identifier(name), t.identifier(name))), t.stringLiteral(path));
71
+ };
72
+ export const importAminoMsg = () => {
73
+ return importStmt(['AminoMsg'], '@cosmjs/amino');
74
+ };
75
+ export const getFieldDimensionality = field => {
76
+ let typeName = field.type;
77
+ const isArray = typeName.endsWith('[]');
78
+ let dimensions = 0;
79
+
80
+ if (isArray) {
81
+ dimensions = typeName.match(/\[\]/g).length - 1;
82
+ typeName = typeName.replace(/\[\]/g, '');
83
+ }
84
+
85
+ return {
86
+ typeName,
87
+ dimensions,
88
+ isArray
89
+ };
90
+ };
91
+ export const memberExpressionOrIdentifier = names => {
92
+ if (names.length === 1) {
93
+ return t.identifier(names[0]);
94
+ }
95
+
96
+ if (names.length === 2) {
97
+ const [b, a] = names;
98
+ return t.memberExpression(t.identifier(a), t.identifier(b));
99
+ }
100
+
101
+ const [name, ...rest] = names;
102
+ return t.memberExpression(memberExpressionOrIdentifier(rest), t.identifier(name));
103
+ };
104
+ export const memberExpressionOrIdentifierSnake = names => {
105
+ if (names.length === 1) {
106
+ return t.identifier(snake(names[0]));
107
+ }
108
+
109
+ if (names.length === 2) {
110
+ const [b, a] = names;
111
+ return t.memberExpression(t.identifier(snake(a)), t.identifier(snake(b)));
112
+ }
113
+
114
+ const [name, ...rest] = names;
115
+ return t.memberExpression(memberExpressionOrIdentifierSnake(rest), t.identifier(snake(name)));
116
+ };
@@ -0,0 +1,47 @@
1
+ import { importStmt } from './utils';
2
+ import generate from '@babel/generator';
3
+ import * as t from '@babel/types';
4
+ import { bindMethod, typedIdentifier, promiseTypeAnnotation, classDeclaration, classProperty, arrowFunctionExpression } from './utils';
5
+
6
+ const expectCode = ast => {
7
+ expect(generate(ast).code).toMatchSnapshot();
8
+ };
9
+
10
+ const printCode = ast => {
11
+ console.log(generate(ast).code);
12
+ };
13
+
14
+ it('top import', async () => {
15
+ expectCode(importStmt(['CosmWasmClient', 'ExecuteResult', 'SigningCosmWasmClient'], '@cosmjs/cosmwasm-stargate'));
16
+ });
17
+ it('interfaces', async () => {
18
+ expectCode(t.program([t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier('SG721ReadOnlyInstance'), null, [], t.tSInterfaceBody([t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), // methods
19
+ t.tSPropertySignature(t.identifier('tokens'), t.tsTypeAnnotation(t.tsFunctionType(null, [typedIdentifier('owner', t.tsTypeAnnotation(t.tsStringKeyword())), typedIdentifier('startAfter', t.tsTypeAnnotation(t.tsStringKeyword()), true), typedIdentifier('limit', t.tsTypeAnnotation(t.tsStringKeyword()), true)], promiseTypeAnnotation('TokensResponse'))))]))), // extends
20
+ t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier('SG721Instance'), null, [t.tSExpressionWithTypeArguments(t.identifier('SG721ReadOnlyInstance'))], t.tSInterfaceBody([// contract address
21
+ t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), // METHOD
22
+ t.tSPropertySignature(t.identifier('mint'), t.tsTypeAnnotation(t.tsFunctionType(null, [typedIdentifier('sender', t.tsTypeAnnotation(t.tsStringKeyword())), typedIdentifier('anotherProp', t.tsTypeAnnotation(t.tsStringKeyword())), typedIdentifier('prop3', t.tsTypeAnnotation(t.tsStringKeyword()))], promiseTypeAnnotation('ExecuteResult'))))])))]));
23
+ });
24
+ it('readonly classes', async () => {
25
+ expectCode(t.program([t.exportNamedDeclaration(classDeclaration('SG721QueryClient', [// client
26
+ classProperty('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('CosmWasmClient')))), // contractAddress
27
+ classProperty('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword())), // constructor
28
+ t.classMethod('constructor', t.identifier('constructor'), [typedIdentifier('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('CosmWasmClient')))), typedIdentifier('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement([// client/contract set
29
+ t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('client'))), t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.identifier('contractAddress'))), // bindings
30
+ bindMethod('approval'), bindMethod('otherProp'), bindMethod('hello'), bindMethod('mintme')])), // methods:
31
+ t.classProperty(t.identifier('approval'), arrowFunctionExpression([// props
32
+ typedIdentifier('owner', t.tsTypeAnnotation(t.tsStringKeyword())), //
33
+ typedIdentifier('spender', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('queryContractSmart')), [t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.objectExpression([// props
34
+ t.objectProperty(t.identifier('owner'), t.identifier('owner'), false, true), t.objectProperty(t.identifier('spender'), t.identifier('spender'), false, true)])]))]), t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tSTypeReference(t.identifier('ApprovalResponse'))]))), true))], [t.tSExpressionWithTypeArguments(t.identifier('SG721ReadOnlyInstance'))]))]));
35
+ });
36
+ it('mutation classes', async () => {
37
+ expectCode(t.program([t.exportNamedDeclaration(classDeclaration('SG721Client', [// client
38
+ classProperty('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('SigningCosmWasmClient')))), // contractAddress
39
+ classProperty('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword())), // constructor
40
+ t.classMethod('constructor', t.identifier('constructor'), [typedIdentifier('client', t.tsTypeAnnotation(t.tsTypeReference(t.identifier('SigningCosmWasmClient')))), typedIdentifier('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement([// super()
41
+ t.expressionStatement(t.callExpression(t.super(), [t.identifier('client'), t.identifier('contractAddress')])), // client/contract set
42
+ t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('client'))), t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.identifier('contractAddress'))), // bindings
43
+ bindMethod('approval'), bindMethod('otherProp'), bindMethod('hello'), bindMethod('mintme')])), // methods:
44
+ t.classProperty(t.identifier('mint'), arrowFunctionExpression([// props
45
+ typedIdentifier('sender', t.tsTypeAnnotation(t.tsStringKeyword())), typedIdentifier('tokenId', t.tsTypeAnnotation(t.tsStringKeyword())), typedIdentifier('owner', t.tsTypeAnnotation(t.tsStringKeyword())), typedIdentifier('token_uri', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement([t.returnStatement(t.awaitExpression(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('client')), t.identifier('execute')), [t.identifier('sender'), t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.objectExpression([t.objectProperty(t.identifier('mint'), t.objectExpression([t.objectProperty(t.identifier('token_id'), t.identifier('tokenId')), t.objectProperty(t.identifier('owner'), t.identifier('owner')), t.objectProperty(t.identifier('token_uri'), t.identifier('token_uri')), t.objectProperty(t.identifier('expression'), t.objectExpression([]))]))]), t.stringLiteral('auto')])))]), // return type
46
+ t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tSTypeReference(t.identifier('ExecuteResult'))]))), true))], [t.tSExpressionWithTypeArguments(t.identifier('SG721ReadOnlyInstance'))], t.identifier('SG721QueryClient')))]));
47
+ });