wasm-ast-types 0.2.3 → 0.2.4

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/index.js CHANGED
@@ -43,6 +43,19 @@ Object.keys(_recoil).forEach(function (key) {
43
43
  });
44
44
  });
45
45
 
46
+ var _messages = require("./messages");
47
+
48
+ Object.keys(_messages).forEach(function (key) {
49
+ if (key === "default" || key === "__esModule") return;
50
+ if (key in exports && exports[key] === _messages[key]) return;
51
+ Object.defineProperty(exports, key, {
52
+ enumerable: true,
53
+ get: function get() {
54
+ return _messages[key];
55
+ }
56
+ });
57
+ });
58
+
46
59
  var _reactQuery = require("./react-query");
47
60
 
48
61
  Object.keys(_reactQuery).forEach(function (key) {
@@ -0,0 +1,301 @@
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.createFromPartialInterface = exports.createFromPartialClass = 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('Binary'));
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
+ }; // MARKED AS NOT DRY
50
+
51
+
52
+ var identifier = function identifier(name, typeAnnotation) {
53
+ var optional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
54
+ var type = t.identifier(name);
55
+ type.typeAnnotation = typeAnnotation;
56
+ type.optional = optional;
57
+ return type;
58
+ };
59
+
60
+ var getType = function getType(type) {
61
+ switch (type) {
62
+ case 'string':
63
+ return t.tsStringKeyword();
64
+
65
+ case 'boolean':
66
+ return t.tSBooleanKeyword();
67
+
68
+ case 'integer':
69
+ return t.tsNumberKeyword();
70
+
71
+ default:
72
+ throw new Error('what is type: ' + type);
73
+ }
74
+ }; // MARKED AS NOT DRY
75
+
76
+
77
+ var getPropertyType = function getPropertyType(schema, prop) {
78
+ var _schema$properties, _schema$required, _schema$required2;
79
+
80
+ var props = (_schema$properties = schema.properties) !== null && _schema$properties !== void 0 ? _schema$properties : {};
81
+ var info = props[prop];
82
+ var type = null;
83
+ var optional = (_schema$required = schema.required) === null || _schema$required === void 0 ? void 0 : _schema$required.includes(prop);
84
+
85
+ if (info.allOf && info.allOf.length === 1) {
86
+ info = info.allOf[0];
87
+ }
88
+
89
+ if (typeof info.$ref === 'string') {
90
+ type = getTypeFromRef(info.$ref);
91
+ }
92
+
93
+ if (Array.isArray(info.anyOf)) {
94
+ // assuming 2nd is null, but let's check to ensure
95
+ if (info.anyOf.length !== 2) {
96
+ throw new Error('case not handled by transpiler. contact maintainers.');
97
+ }
98
+
99
+ var _info$anyOf = (0, _slicedToArray2["default"])(info.anyOf, 2),
100
+ nullableType = _info$anyOf[0],
101
+ nullType = _info$anyOf[1];
102
+
103
+ if ((nullType === null || nullType === void 0 ? void 0 : nullType.type) !== 'null') {
104
+ throw new Error('case not handled by transpiler. contact maintainers.');
105
+ }
106
+
107
+ type = getTypeFromRef(nullableType === null || nullableType === void 0 ? void 0 : nullableType.$ref);
108
+ optional = true;
109
+ }
110
+
111
+ if (typeof info.type === 'string') {
112
+ if (info.type === 'array') {
113
+ if (info.items.$ref) {
114
+ type = getArrayTypeFromRef(info.items.$ref);
115
+ } else {
116
+ type = getArrayTypeFromType(info.items.type);
117
+ }
118
+ } else {
119
+ type = getType(info.type);
120
+ }
121
+ }
122
+
123
+ if (Array.isArray(info.type)) {
124
+ // assuming 2nd is null, but let's check to ensure
125
+ if (info.type.length !== 2) {
126
+ throw new Error('case not handled by transpiler. contact maintainers.');
127
+ }
128
+
129
+ var _info$type = (0, _slicedToArray2["default"])(info.type, 2),
130
+ _nullableType = _info$type[0],
131
+ _nullType = _info$type[1];
132
+
133
+ if (_nullType !== 'null') {
134
+ throw new Error('case not handled by transpiler. contact maintainers.');
135
+ }
136
+
137
+ type = getType(_nullableType);
138
+ optional = true;
139
+ }
140
+
141
+ if (!type) {
142
+ throw new Error('cannot find type for ' + JSON.stringify(info));
143
+ }
144
+
145
+ if ((_schema$required2 = schema.required) !== null && _schema$required2 !== void 0 && _schema$required2.includes(prop)) {
146
+ optional = false;
147
+ }
148
+
149
+ return {
150
+ type: type,
151
+ optional: optional
152
+ };
153
+ };
154
+
155
+ var tsTypeOperator = function tsTypeOperator(typeAnnotation, operator) {
156
+ var obj = t.tsTypeOperator(typeAnnotation);
157
+ obj.operator = operator;
158
+ return obj;
159
+ }; // MARKED AS NOT DRY
160
+
161
+
162
+ var createWasmExecMethod = function createWasmExecMethod(jsonschema) {
163
+ var _jsonschema$propertie;
164
+
165
+ var underscoreName = Object.keys(jsonschema.properties)[0];
166
+ var methodName = (0, _case.camel)(underscoreName);
167
+ var properties = (_jsonschema$propertie = jsonschema.properties[underscoreName].properties) !== null && _jsonschema$propertie !== void 0 ? _jsonschema$propertie : {};
168
+ var obj = createTypedObjectParams(jsonschema.properties[underscoreName]);
169
+ var args = Object.keys(properties).map(function (prop) {
170
+ return t.objectProperty(t.identifier(prop), t.identifier((0, _case.camel)(prop)), false, prop === (0, _case.camel)(prop));
171
+ });
172
+ var constantParams = [// t.assignmentPattern(
173
+ // identifier(
174
+ // 'fee',
175
+ // t.tsTypeAnnotation(
176
+ // t.tsUnionType(
177
+ // [
178
+ // t.tSNumberKeyword(),
179
+ // t.tsTypeReference(
180
+ // t.identifier('StdFee')
181
+ // ),
182
+ // t.tsLiteralType(
183
+ // t.stringLiteral('auto')
184
+ // )
185
+ // ]
186
+ // )
187
+ // ),
188
+ // false
189
+ // ),
190
+ // t.stringLiteral('auto')
191
+ // ),
192
+ // identifier('memo', t.tsTypeAnnotation(
193
+ // t.tsStringKeyword()
194
+ // ), true),
195
+ identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
196
+ return t.classProperty(t.identifier(methodName), (0, _utils.arrowFunctionExpression)(obj ? [// props
197
+ obj].concat(constantParams) : constantParams, t.blockStatement([t.returnStatement(t.objectExpression([t.objectProperty(t.identifier('typeUrl'), t.stringLiteral('/cosmwasm.wasm.v1.MsgExecuteContract')), t.objectProperty(t.identifier('value'), t.callExpression(t.memberExpression(t.identifier('MsgExecuteContract'), t.identifier('fromPartial')), [t.objectExpression([t.objectProperty(t.identifier('sender'), t.memberExpression(t.thisExpression(), t.identifier('sender'))), t.objectProperty(t.identifier('contract'), t.memberExpression(t.thisExpression(), t.identifier('contractAddress'))), t.objectProperty(t.identifier('msg'), t.callExpression(t.identifier('toUtf8'), [t.callExpression(t.memberExpression(t.identifier('JSON'), t.identifier('stringify')), [t.objectExpression([t.objectProperty(t.identifier(underscoreName), t.objectExpression(args))])])])), t.objectProperty(t.identifier('funds'), t.identifier('funds'), false, true)])]))]))]), // return type
198
+ t.tsTypeAnnotation(t.tsTypeReference(t.identifier('MsgExecuteContractEncodeObject'))), false));
199
+ };
200
+
201
+ var createFromPartialClass = function createFromPartialClass(className, implementsClassName, execMsg) {
202
+ var propertyNames = (0, _utils.getMessageProperties)(execMsg).map(function (method) {
203
+ var _Object$keys;
204
+
205
+ return (_Object$keys = Object.keys(method.properties)) === null || _Object$keys === void 0 ? void 0 : _Object$keys[0];
206
+ }).filter(Boolean);
207
+ var bindings = propertyNames.map(_case.camel).map(_utils.bindMethod);
208
+ var methods = (0, _utils.getMessageProperties)(execMsg).map(function (schema) {
209
+ return createWasmExecMethod(schema);
210
+ });
211
+ var blockStmt = [];
212
+ [].push.apply(blockStmt, [t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('sender')), t.identifier('sender'))), t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.identifier('contractAddress')))].concat((0, _toConsumableArray2["default"])(bindings)));
213
+ return t.exportNamedDeclaration((0, _utils.classDeclaration)(className, [// sender
214
+ (0, _utils.classProperty)('sender', t.tsTypeAnnotation(t.tsStringKeyword())), // contractAddress
215
+ (0, _utils.classProperty)('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword())), // constructor
216
+ t.classMethod('constructor', t.identifier('constructor'), [(0, _utils.typedIdentifier)('sender', t.tsTypeAnnotation(t.tsStringKeyword())), (0, _utils.typedIdentifier)('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement(blockStmt))].concat((0, _toConsumableArray2["default"])(methods)), [t.tSExpressionWithTypeArguments(t.identifier(implementsClassName))], null));
217
+ };
218
+
219
+ exports.createFromPartialClass = createFromPartialClass;
220
+
221
+ var createFromPartialInterface = function createFromPartialInterface(className, execMsg) {
222
+ var methods = (0, _utils.getMessageProperties)(execMsg).map(function (jsonschema) {
223
+ var underscoreName = Object.keys(jsonschema.properties)[0];
224
+ var methodName = (0, _case.camel)(underscoreName);
225
+ return createPropertyFunctionWithObjectParamsForPartial(methodName, 'MsgExecuteContractEncodeObject', jsonschema.properties[underscoreName]);
226
+ });
227
+ var extendsAst = [];
228
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(className), null, extendsAst, t.tSInterfaceBody([// contract address
229
+ t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), // contract address
230
+ t.tSPropertySignature(t.identifier('sender'), t.tsTypeAnnotation(t.tsStringKeyword()))].concat((0, _toConsumableArray2["default"])(methods)))));
231
+ }; // MARKED AS NOT DRY
232
+
233
+
234
+ exports.createFromPartialInterface = createFromPartialInterface;
235
+
236
+ var propertySignature = function propertySignature(name, typeAnnotation) {
237
+ var optional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
238
+ // prop.leadingComments = [{
239
+ // type: 'Comment',
240
+ // value: ' Data on the token itself'
241
+ // }];
242
+ // prop.leadingComments = [{
243
+ // type: 'CommentBlock',
244
+ // value: '* Data on the token itself'
245
+ // }];
246
+ return {
247
+ type: 'TSPropertySignature',
248
+ key: t.identifier(name),
249
+ typeAnnotation: typeAnnotation,
250
+ optional: optional
251
+ };
252
+ }; // MARKED AS NOT DRY
253
+
254
+
255
+ var createTypedObjectParams = function createTypedObjectParams(jsonschema) {
256
+ var _jsonschema$propertie2;
257
+
258
+ var camelize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
259
+ var keys = Object.keys((_jsonschema$propertie2 = jsonschema.properties) !== null && _jsonschema$propertie2 !== void 0 ? _jsonschema$propertie2 : {});
260
+ if (!keys.length) return;
261
+ var typedParams = keys.map(function (prop) {
262
+ var _getPropertyType = getPropertyType(jsonschema, prop),
263
+ type = _getPropertyType.type,
264
+ optional = _getPropertyType.optional;
265
+
266
+ return propertySignature(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(type), optional);
267
+ });
268
+ var params = keys.map(function (prop) {
269
+ return t.objectProperty(camelize ? t.identifier((0, _case.camel)(prop)) : t.identifier(prop), camelize ? t.identifier((0, _case.camel)(prop)) : t.identifier(prop), false, true);
270
+ });
271
+ var obj = t.objectPattern((0, _toConsumableArray2["default"])(params));
272
+ obj.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral((0, _toConsumableArray2["default"])(typedParams)));
273
+ return obj;
274
+ };
275
+
276
+ var createPropertyFunctionWithObjectParamsForPartial = function createPropertyFunctionWithObjectParamsForPartial(methodName, responseType, jsonschema) {
277
+ var obj = createTypedObjectParams(jsonschema);
278
+ var fixedParams = [// identifier('fee', t.tsTypeAnnotation(
279
+ // t.tsUnionType(
280
+ // [
281
+ // t.tsNumberKeyword(),
282
+ // t.tsTypeReference(
283
+ // t.identifier('StdFee')
284
+ // ),
285
+ // t.tsLiteralType(
286
+ // t.stringLiteral('auto')
287
+ // )
288
+ // ]
289
+ // )
290
+ // ), true),
291
+ // identifier('memo', t.tsTypeAnnotation(
292
+ // t.tsStringKeyword()
293
+ // ), true),
294
+ identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
295
+ var func = {
296
+ type: 'TSFunctionType',
297
+ typeAnnotation: t.tsTypeAnnotation(t.tsTypeReference(t.identifier(responseType))),
298
+ parameters: obj ? [obj].concat(fixedParams) : fixedParams
299
+ };
300
+ return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(func));
301
+ };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ var _generator = _interopRequireDefault(require("@babel/generator"));
6
+
7
+ var _execute_msg_for__empty = _interopRequireDefault(require("./__fixtures__/schema/execute_msg_for__empty.json"));
8
+
9
+ var _messages = require("./messages");
10
+
11
+ var expectCode = function expectCode(ast) {
12
+ expect((0, _generator["default"])(ast).code).toMatchSnapshot();
13
+ };
14
+
15
+ var printCode = function printCode(ast) {
16
+ console.log((0, _generator["default"])(ast).code);
17
+ };
18
+
19
+ it('execute classes', function () {
20
+ expectCode((0, _messages.createFromPartialClass)('SG721MessageComposer', 'SG721Message', _execute_msg_for__empty["default"]));
21
+ });
22
+ it('createFromPartialInterface', function () {
23
+ expectCode((0, _messages.createFromPartialInterface)('SG721Message', _execute_msg_for__empty["default"]));
24
+ });
package/module/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './utils';
2
2
  export * from './wasm';
3
3
  export * from './recoil';
4
+ export * from './messages';
4
5
  export * from './react-query';
@@ -0,0 +1,257 @@
1
+ import * as t from '@babel/types';
2
+ import { camel } from 'case';
3
+ import { bindMethod, typedIdentifier, classDeclaration, classProperty, arrowFunctionExpression, getMessageProperties } from './utils';
4
+
5
+ const getTypeFromRef = $ref => {
6
+ switch ($ref) {
7
+ case '#/definitions/Binary':
8
+ return t.tsTypeReference(t.identifier('Binary'));
9
+
10
+ case '#/definitions/Expiration':
11
+ return t.tsTypeReference(t.identifier('Expiration'));
12
+
13
+ default:
14
+ if ($ref.startsWith('#/definitions/')) {
15
+ return t.tsTypeReference(t.identifier($ref.replace('#/definitions/', '')));
16
+ }
17
+
18
+ throw new Error('what is $ref: ' + $ref);
19
+ }
20
+ };
21
+
22
+ const getArrayTypeFromRef = $ref => {
23
+ return t.tsArrayType(getTypeFromRef($ref));
24
+ };
25
+
26
+ const getArrayTypeFromType = type => {
27
+ return t.tsArrayType(getType(type));
28
+ }; // MARKED AS NOT DRY
29
+
30
+
31
+ const identifier = (name, typeAnnotation, optional = false) => {
32
+ const type = t.identifier(name);
33
+ type.typeAnnotation = typeAnnotation;
34
+ type.optional = optional;
35
+ return type;
36
+ };
37
+
38
+ const getType = type => {
39
+ switch (type) {
40
+ case 'string':
41
+ return t.tsStringKeyword();
42
+
43
+ case 'boolean':
44
+ return t.tSBooleanKeyword();
45
+
46
+ case 'integer':
47
+ return t.tsNumberKeyword();
48
+
49
+ default:
50
+ throw new Error('what is type: ' + type);
51
+ }
52
+ }; // MARKED AS NOT DRY
53
+
54
+
55
+ const getPropertyType = (schema, prop) => {
56
+ const props = schema.properties ?? {};
57
+ let info = props[prop];
58
+ let type = null;
59
+ let optional = schema.required?.includes(prop);
60
+
61
+ if (info.allOf && info.allOf.length === 1) {
62
+ info = info.allOf[0];
63
+ }
64
+
65
+ if (typeof info.$ref === 'string') {
66
+ type = getTypeFromRef(info.$ref);
67
+ }
68
+
69
+ if (Array.isArray(info.anyOf)) {
70
+ // assuming 2nd is null, but let's check to ensure
71
+ if (info.anyOf.length !== 2) {
72
+ throw new Error('case not handled by transpiler. contact maintainers.');
73
+ }
74
+
75
+ const [nullableType, nullType] = info.anyOf;
76
+
77
+ if (nullType?.type !== 'null') {
78
+ throw new Error('case not handled by transpiler. contact maintainers.');
79
+ }
80
+
81
+ type = getTypeFromRef(nullableType?.$ref);
82
+ optional = true;
83
+ }
84
+
85
+ if (typeof info.type === 'string') {
86
+ if (info.type === 'array') {
87
+ if (info.items.$ref) {
88
+ type = getArrayTypeFromRef(info.items.$ref);
89
+ } else {
90
+ type = getArrayTypeFromType(info.items.type);
91
+ }
92
+ } else {
93
+ type = getType(info.type);
94
+ }
95
+ }
96
+
97
+ if (Array.isArray(info.type)) {
98
+ // assuming 2nd is null, but let's check to ensure
99
+ if (info.type.length !== 2) {
100
+ throw new Error('case not handled by transpiler. contact maintainers.');
101
+ }
102
+
103
+ const [nullableType, nullType] = info.type;
104
+
105
+ if (nullType !== 'null') {
106
+ throw new Error('case not handled by transpiler. contact maintainers.');
107
+ }
108
+
109
+ type = getType(nullableType);
110
+ optional = true;
111
+ }
112
+
113
+ if (!type) {
114
+ throw new Error('cannot find type for ' + JSON.stringify(info));
115
+ }
116
+
117
+ if (schema.required?.includes(prop)) {
118
+ optional = false;
119
+ }
120
+
121
+ return {
122
+ type,
123
+ optional
124
+ };
125
+ };
126
+
127
+ const tsTypeOperator = (typeAnnotation, operator) => {
128
+ const obj = t.tsTypeOperator(typeAnnotation);
129
+ obj.operator = operator;
130
+ return obj;
131
+ }; // MARKED AS NOT DRY
132
+
133
+
134
+ const createWasmExecMethod = jsonschema => {
135
+ const underscoreName = Object.keys(jsonschema.properties)[0];
136
+ const methodName = camel(underscoreName);
137
+ const properties = jsonschema.properties[underscoreName].properties ?? {};
138
+ const obj = createTypedObjectParams(jsonschema.properties[underscoreName]);
139
+ const args = Object.keys(properties).map(prop => {
140
+ return t.objectProperty(t.identifier(prop), t.identifier(camel(prop)), false, prop === camel(prop));
141
+ });
142
+ const constantParams = [// t.assignmentPattern(
143
+ // identifier(
144
+ // 'fee',
145
+ // t.tsTypeAnnotation(
146
+ // t.tsUnionType(
147
+ // [
148
+ // t.tSNumberKeyword(),
149
+ // t.tsTypeReference(
150
+ // t.identifier('StdFee')
151
+ // ),
152
+ // t.tsLiteralType(
153
+ // t.stringLiteral('auto')
154
+ // )
155
+ // ]
156
+ // )
157
+ // ),
158
+ // false
159
+ // ),
160
+ // t.stringLiteral('auto')
161
+ // ),
162
+ // identifier('memo', t.tsTypeAnnotation(
163
+ // t.tsStringKeyword()
164
+ // ), true),
165
+ identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
166
+ return t.classProperty(t.identifier(methodName), arrowFunctionExpression(obj ? [// props
167
+ obj, ...constantParams] : constantParams, t.blockStatement([t.returnStatement(t.objectExpression([t.objectProperty(t.identifier('typeUrl'), t.stringLiteral('/cosmwasm.wasm.v1.MsgExecuteContract')), t.objectProperty(t.identifier('value'), t.callExpression(t.memberExpression(t.identifier('MsgExecuteContract'), t.identifier('fromPartial')), [t.objectExpression([t.objectProperty(t.identifier('sender'), t.memberExpression(t.thisExpression(), t.identifier('sender'))), t.objectProperty(t.identifier('contract'), t.memberExpression(t.thisExpression(), t.identifier('contractAddress'))), t.objectProperty(t.identifier('msg'), t.callExpression(t.identifier('toUtf8'), [t.callExpression(t.memberExpression(t.identifier('JSON'), t.identifier('stringify')), [t.objectExpression([t.objectProperty(t.identifier(underscoreName), t.objectExpression(args))])])])), t.objectProperty(t.identifier('funds'), t.identifier('funds'), false, true)])]))]))]), // return type
168
+ t.tsTypeAnnotation(t.tsTypeReference(t.identifier('MsgExecuteContractEncodeObject'))), false));
169
+ };
170
+
171
+ export const createFromPartialClass = (className, implementsClassName, execMsg) => {
172
+ const propertyNames = getMessageProperties(execMsg).map(method => Object.keys(method.properties)?.[0]).filter(Boolean);
173
+ const bindings = propertyNames.map(camel).map(bindMethod);
174
+ const methods = getMessageProperties(execMsg).map(schema => {
175
+ return createWasmExecMethod(schema);
176
+ });
177
+ const blockStmt = [];
178
+ [].push.apply(blockStmt, [t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('sender')), t.identifier('sender'))), t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier('contractAddress')), t.identifier('contractAddress'))), ...bindings]);
179
+ return t.exportNamedDeclaration(classDeclaration(className, [// sender
180
+ classProperty('sender', t.tsTypeAnnotation(t.tsStringKeyword())), // contractAddress
181
+ classProperty('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword())), // constructor
182
+ t.classMethod('constructor', t.identifier('constructor'), [typedIdentifier('sender', t.tsTypeAnnotation(t.tsStringKeyword())), typedIdentifier('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword()))], t.blockStatement(blockStmt)), ...methods], [t.tSExpressionWithTypeArguments(t.identifier(implementsClassName))], null));
183
+ };
184
+ export const createFromPartialInterface = (className, execMsg) => {
185
+ const methods = getMessageProperties(execMsg).map(jsonschema => {
186
+ const underscoreName = Object.keys(jsonschema.properties)[0];
187
+ const methodName = camel(underscoreName);
188
+ return createPropertyFunctionWithObjectParamsForPartial(methodName, 'MsgExecuteContractEncodeObject', jsonschema.properties[underscoreName]);
189
+ });
190
+ const extendsAst = [];
191
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(className), null, extendsAst, t.tSInterfaceBody([// contract address
192
+ t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), // contract address
193
+ t.tSPropertySignature(t.identifier('sender'), t.tsTypeAnnotation(t.tsStringKeyword())), ...methods])));
194
+ }; // MARKED AS NOT DRY
195
+
196
+ const propertySignature = (name, typeAnnotation, optional = false) => {
197
+ // prop.leadingComments = [{
198
+ // type: 'Comment',
199
+ // value: ' Data on the token itself'
200
+ // }];
201
+ // prop.leadingComments = [{
202
+ // type: 'CommentBlock',
203
+ // value: '* Data on the token itself'
204
+ // }];
205
+ return {
206
+ type: 'TSPropertySignature',
207
+ key: t.identifier(name),
208
+ typeAnnotation,
209
+ optional
210
+ };
211
+ }; // MARKED AS NOT DRY
212
+
213
+
214
+ const createTypedObjectParams = (jsonschema, camelize = true) => {
215
+ const keys = Object.keys(jsonschema.properties ?? {});
216
+ if (!keys.length) return;
217
+ const typedParams = keys.map(prop => {
218
+ const {
219
+ type,
220
+ optional
221
+ } = getPropertyType(jsonschema, prop);
222
+ return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(type), optional);
223
+ });
224
+ const params = keys.map(prop => {
225
+ return t.objectProperty(camelize ? t.identifier(camel(prop)) : t.identifier(prop), camelize ? t.identifier(camel(prop)) : t.identifier(prop), false, true);
226
+ });
227
+ const obj = t.objectPattern([...params]);
228
+ obj.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral([...typedParams]));
229
+ return obj;
230
+ };
231
+
232
+ const createPropertyFunctionWithObjectParamsForPartial = (methodName, responseType, jsonschema) => {
233
+ const obj = createTypedObjectParams(jsonschema);
234
+ const fixedParams = [// identifier('fee', t.tsTypeAnnotation(
235
+ // t.tsUnionType(
236
+ // [
237
+ // t.tsNumberKeyword(),
238
+ // t.tsTypeReference(
239
+ // t.identifier('StdFee')
240
+ // ),
241
+ // t.tsLiteralType(
242
+ // t.stringLiteral('auto')
243
+ // )
244
+ // ]
245
+ // )
246
+ // ), true),
247
+ // identifier('memo', t.tsTypeAnnotation(
248
+ // t.tsStringKeyword()
249
+ // ), true),
250
+ identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
251
+ const func = {
252
+ type: 'TSFunctionType',
253
+ typeAnnotation: t.tsTypeAnnotation(t.tsTypeReference(t.identifier(responseType))),
254
+ parameters: obj ? [obj, ...fixedParams] : fixedParams
255
+ };
256
+ return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(func));
257
+ };
@@ -0,0 +1,18 @@
1
+ import generate from '@babel/generator';
2
+ import execute_msg from './__fixtures__/schema/execute_msg_for__empty.json';
3
+ import { createFromPartialClass, createFromPartialInterface } from './messages';
4
+
5
+ const expectCode = ast => {
6
+ expect(generate(ast).code).toMatchSnapshot();
7
+ };
8
+
9
+ const printCode = ast => {
10
+ console.log(generate(ast).code);
11
+ };
12
+
13
+ it('execute classes', () => {
14
+ expectCode(createFromPartialClass('SG721MessageComposer', 'SG721Message', execute_msg));
15
+ });
16
+ it('createFromPartialInterface', () => {
17
+ expectCode(createFromPartialInterface('SG721Message', execute_msg));
18
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wasm-ast-types",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "CosmWasm TypeScript AST generation",
5
5
  "author": "Dan Lynch <pyramation@gmail.com>",
6
6
  "homepage": "https://github.com/pyramation/cosmwasm-typescript-gen/tree/master/packages/wasm-ast-types#readme",
@@ -85,5 +85,5 @@
85
85
  "ast-stringify": "0.1.0",
86
86
  "case": "1.6.3"
87
87
  },
88
- "gitHead": "e7cd5b9e8bc60161c28db9a74f3c372ddd0fc6b1"
88
+ "gitHead": "c20c918c707e86cb8ebc0ea50764f7e9769f18b9"
89
89
  }
package/types/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './utils';
2
2
  export * from './wasm';
3
3
  export * from './recoil';
4
+ export * from './messages';
4
5
  export * from './react-query';
@@ -1,35 +1,4 @@
1
1
  import * as t from '@babel/types';
2
- import { Mutation } from './types';
3
- export declare const addMsgMethod: ({ methodName, typeUrl, TypeName, methodToCall }: {
4
- methodName: any;
5
- typeUrl: any;
6
- TypeName: any;
7
- methodToCall: any;
8
- }) => t.ObjectMethod;
9
- export declare const addFromJSONMethod: ({ methodName, typeUrl, TypeName }: {
10
- methodName: any;
11
- typeUrl: any;
12
- TypeName: any;
13
- }) => t.ObjectMethod;
14
- export declare const addFromPartialMethod: ({ methodName, typeUrl, TypeName }: {
15
- methodName: any;
16
- typeUrl: any;
17
- TypeName: any;
18
- }) => t.ObjectMethod;
19
- export declare const addToJSONMethod: ({ methodName, typeUrl, TypeName }: {
20
- methodName: any;
21
- typeUrl: any;
22
- TypeName: any;
23
- }) => t.ObjectMethod;
24
- export declare const addJsonMethod: ({ methodName, typeUrl, TypeName }: {
25
- methodName: any;
26
- typeUrl: any;
27
- TypeName: any;
28
- }) => t.ObjectMethod;
29
- export declare const addEncodedMethod: ({ methodName, typeUrl, TypeName }: {
30
- methodName: any;
31
- typeUrl: any;
32
- TypeName: any;
33
- }) => t.ObjectMethod;
34
- export declare const messages: (mutations: Mutation[]) => t.ExportNamedDeclaration;
35
- export declare const encoded: (mutations: Mutation[]) => t.ExportNamedDeclaration;
2
+ import { ExecuteMsg } from './types';
3
+ export declare const createFromPartialClass: (className: string, implementsClassName: string, execMsg: ExecuteMsg) => t.ExportNamedDeclaration;
4
+ export declare const createFromPartialInterface: (className: string, execMsg: ExecuteMsg) => t.ExportNamedDeclaration;
package/types/utils.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as t from '@babel/types';
2
- import { Field, QueryMsg } from './types';
2
+ import { Field, QueryMsg, ExecuteMsg } from './types';
3
3
  import { TSTypeAnnotation, TSExpressionWithTypeArguments } from '@babel/types';
4
4
  export declare const getMessageProperties: (msg: QueryMsg | ExecuteMsg) => any;
5
5
  export declare const tsPropertySignature: (key: t.Expression, typeAnnotation: t.TSTypeAnnotation, optional: boolean) => t.TSPropertySignature;
package/types/wasm.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as t from '@babel/types';
2
2
  import { QueryMsg, ExecuteMsg } from './types';
3
+ export declare const identifier: (name: string, typeAnnotation: t.TSTypeAnnotation, optional?: boolean) => t.Identifier;
3
4
  export declare const getPropertyType: (schema: any, prop: any) => {
4
5
  type: any;
5
6
  optional: any;
@@ -17,6 +18,7 @@ export declare const propertySignature: (name: string, typeAnnotation: t.TSTypeA
17
18
  };
18
19
  export declare const createTypedObjectParams: (jsonschema: any, camelize?: boolean) => t.ObjectPattern;
19
20
  export declare const createPropertyFunctionWithObjectParams: (methodName: string, responseType: string, jsonschema: any) => t.TSPropertySignature;
21
+ export declare const createPropertyFunctionWithObjectParamsForExec: (methodName: string, responseType: string, jsonschema: any) => t.TSPropertySignature;
20
22
  export declare const createQueryInterface: (className: string, queryMsg: QueryMsg) => t.ExportNamedDeclaration;
21
23
  export declare const createTypeOrInterface: (Type: string, jsonschema: any) => t.ExportNamedDeclaration;
22
24
  export declare const createTypeInterface: (jsonschema: any) => t.ExportNamedDeclaration;