wasm-ast-types 0.2.2 → 0.2.5

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,298 @@
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
+ default:
32
+ if ($ref.startsWith('#/definitions/')) {
33
+ return t.tsTypeReference(t.identifier($ref.replace('#/definitions/', '')));
34
+ }
35
+
36
+ throw new Error('what is $ref: ' + $ref);
37
+ }
38
+ };
39
+
40
+ var getArrayTypeFromRef = function getArrayTypeFromRef($ref) {
41
+ return t.tsArrayType(getTypeFromRef($ref));
42
+ };
43
+
44
+ var getArrayTypeFromType = function getArrayTypeFromType(type) {
45
+ return t.tsArrayType(getType(type));
46
+ }; // MARKED AS NOT DRY
47
+
48
+
49
+ var identifier = function identifier(name, typeAnnotation) {
50
+ var optional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
51
+ var type = t.identifier(name);
52
+ type.typeAnnotation = typeAnnotation;
53
+ type.optional = optional;
54
+ return type;
55
+ };
56
+
57
+ var getType = function getType(type) {
58
+ switch (type) {
59
+ case 'string':
60
+ return t.tsStringKeyword();
61
+
62
+ case 'boolean':
63
+ return t.tSBooleanKeyword();
64
+
65
+ case 'integer':
66
+ return t.tsNumberKeyword();
67
+
68
+ default:
69
+ throw new Error('what is type: ' + type);
70
+ }
71
+ }; // MARKED AS NOT DRY
72
+
73
+
74
+ var getPropertyType = function getPropertyType(schema, prop) {
75
+ var _schema$properties, _schema$required, _schema$required2;
76
+
77
+ var props = (_schema$properties = schema.properties) !== null && _schema$properties !== void 0 ? _schema$properties : {};
78
+ var info = props[prop];
79
+ var type = null;
80
+ var optional = (_schema$required = schema.required) === null || _schema$required === void 0 ? void 0 : _schema$required.includes(prop);
81
+
82
+ if (info.allOf && info.allOf.length === 1) {
83
+ info = info.allOf[0];
84
+ }
85
+
86
+ if (typeof info.$ref === 'string') {
87
+ type = getTypeFromRef(info.$ref);
88
+ }
89
+
90
+ if (Array.isArray(info.anyOf)) {
91
+ // assuming 2nd is null, but let's check to ensure
92
+ if (info.anyOf.length !== 2) {
93
+ throw new Error('case not handled by transpiler. contact maintainers.');
94
+ }
95
+
96
+ var _info$anyOf = (0, _slicedToArray2["default"])(info.anyOf, 2),
97
+ nullableType = _info$anyOf[0],
98
+ nullType = _info$anyOf[1];
99
+
100
+ if ((nullType === null || nullType === void 0 ? void 0 : nullType.type) !== 'null') {
101
+ throw new Error('case not handled by transpiler. contact maintainers.');
102
+ }
103
+
104
+ type = getTypeFromRef(nullableType === null || nullableType === void 0 ? void 0 : nullableType.$ref);
105
+ optional = true;
106
+ }
107
+
108
+ if (typeof info.type === 'string') {
109
+ if (info.type === 'array') {
110
+ if (info.items.$ref) {
111
+ type = getArrayTypeFromRef(info.items.$ref);
112
+ } else {
113
+ type = getArrayTypeFromType(info.items.type);
114
+ }
115
+ } else {
116
+ type = getType(info.type);
117
+ }
118
+ }
119
+
120
+ if (Array.isArray(info.type)) {
121
+ // assuming 2nd is null, but let's check to ensure
122
+ if (info.type.length !== 2) {
123
+ throw new Error('case not handled by transpiler. contact maintainers.');
124
+ }
125
+
126
+ var _info$type = (0, _slicedToArray2["default"])(info.type, 2),
127
+ _nullableType = _info$type[0],
128
+ _nullType = _info$type[1];
129
+
130
+ if (_nullType !== 'null') {
131
+ throw new Error('case not handled by transpiler. contact maintainers.');
132
+ }
133
+
134
+ type = getType(_nullableType);
135
+ optional = true;
136
+ }
137
+
138
+ if (!type) {
139
+ throw new Error('cannot find type for ' + JSON.stringify(info));
140
+ }
141
+
142
+ if ((_schema$required2 = schema.required) !== null && _schema$required2 !== void 0 && _schema$required2.includes(prop)) {
143
+ optional = false;
144
+ }
145
+
146
+ return {
147
+ type: type,
148
+ optional: optional
149
+ };
150
+ };
151
+
152
+ var tsTypeOperator = function tsTypeOperator(typeAnnotation, operator) {
153
+ var obj = t.tsTypeOperator(typeAnnotation);
154
+ obj.operator = operator;
155
+ return obj;
156
+ }; // MARKED AS NOT DRY
157
+
158
+
159
+ var createWasmExecMethod = function createWasmExecMethod(jsonschema) {
160
+ var _jsonschema$propertie;
161
+
162
+ var underscoreName = Object.keys(jsonschema.properties)[0];
163
+ var methodName = (0, _case.camel)(underscoreName);
164
+ var properties = (_jsonschema$propertie = jsonschema.properties[underscoreName].properties) !== null && _jsonschema$propertie !== void 0 ? _jsonschema$propertie : {};
165
+ var obj = createTypedObjectParams(jsonschema.properties[underscoreName]);
166
+ var args = Object.keys(properties).map(function (prop) {
167
+ return t.objectProperty(t.identifier(prop), t.identifier((0, _case.camel)(prop)), false, prop === (0, _case.camel)(prop));
168
+ });
169
+ var constantParams = [// t.assignmentPattern(
170
+ // identifier(
171
+ // 'fee',
172
+ // t.tsTypeAnnotation(
173
+ // t.tsUnionType(
174
+ // [
175
+ // t.tSNumberKeyword(),
176
+ // t.tsTypeReference(
177
+ // t.identifier('StdFee')
178
+ // ),
179
+ // t.tsLiteralType(
180
+ // t.stringLiteral('auto')
181
+ // )
182
+ // ]
183
+ // )
184
+ // ),
185
+ // false
186
+ // ),
187
+ // t.stringLiteral('auto')
188
+ // ),
189
+ // identifier('memo', t.tsTypeAnnotation(
190
+ // t.tsStringKeyword()
191
+ // ), true),
192
+ identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
193
+ return t.classProperty(t.identifier(methodName), (0, _utils.arrowFunctionExpression)(obj ? [// props
194
+ 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
195
+ t.tsTypeAnnotation(t.tsTypeReference(t.identifier('MsgExecuteContractEncodeObject'))), false));
196
+ };
197
+
198
+ var createFromPartialClass = function createFromPartialClass(className, implementsClassName, execMsg) {
199
+ var propertyNames = (0, _utils.getMessageProperties)(execMsg).map(function (method) {
200
+ var _Object$keys;
201
+
202
+ return (_Object$keys = Object.keys(method.properties)) === null || _Object$keys === void 0 ? void 0 : _Object$keys[0];
203
+ }).filter(Boolean);
204
+ var bindings = propertyNames.map(_case.camel).map(_utils.bindMethod);
205
+ var methods = (0, _utils.getMessageProperties)(execMsg).map(function (schema) {
206
+ return createWasmExecMethod(schema);
207
+ });
208
+ var blockStmt = [];
209
+ [].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)));
210
+ return t.exportNamedDeclaration((0, _utils.classDeclaration)(className, [// sender
211
+ (0, _utils.classProperty)('sender', t.tsTypeAnnotation(t.tsStringKeyword())), // contractAddress
212
+ (0, _utils.classProperty)('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword())), // constructor
213
+ 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));
214
+ };
215
+
216
+ exports.createFromPartialClass = createFromPartialClass;
217
+
218
+ var createFromPartialInterface = function createFromPartialInterface(className, execMsg) {
219
+ var methods = (0, _utils.getMessageProperties)(execMsg).map(function (jsonschema) {
220
+ var underscoreName = Object.keys(jsonschema.properties)[0];
221
+ var methodName = (0, _case.camel)(underscoreName);
222
+ return createPropertyFunctionWithObjectParamsForPartial(methodName, 'MsgExecuteContractEncodeObject', jsonschema.properties[underscoreName]);
223
+ });
224
+ var extendsAst = [];
225
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(className), null, extendsAst, t.tSInterfaceBody([// contract address
226
+ t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), // contract address
227
+ t.tSPropertySignature(t.identifier('sender'), t.tsTypeAnnotation(t.tsStringKeyword()))].concat((0, _toConsumableArray2["default"])(methods)))));
228
+ }; // MARKED AS NOT DRY
229
+
230
+
231
+ exports.createFromPartialInterface = createFromPartialInterface;
232
+
233
+ var propertySignature = function propertySignature(name, typeAnnotation) {
234
+ var optional = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
235
+ // prop.leadingComments = [{
236
+ // type: 'Comment',
237
+ // value: ' Data on the token itself'
238
+ // }];
239
+ // prop.leadingComments = [{
240
+ // type: 'CommentBlock',
241
+ // value: '* Data on the token itself'
242
+ // }];
243
+ return {
244
+ type: 'TSPropertySignature',
245
+ key: t.identifier(name),
246
+ typeAnnotation: typeAnnotation,
247
+ optional: optional
248
+ };
249
+ }; // MARKED AS NOT DRY
250
+
251
+
252
+ var createTypedObjectParams = function createTypedObjectParams(jsonschema) {
253
+ var _jsonschema$propertie2;
254
+
255
+ var camelize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
256
+ var keys = Object.keys((_jsonschema$propertie2 = jsonschema.properties) !== null && _jsonschema$propertie2 !== void 0 ? _jsonschema$propertie2 : {});
257
+ if (!keys.length) return;
258
+ var typedParams = keys.map(function (prop) {
259
+ var _getPropertyType = getPropertyType(jsonschema, prop),
260
+ type = _getPropertyType.type,
261
+ optional = _getPropertyType.optional;
262
+
263
+ return propertySignature(camelize ? (0, _case.camel)(prop) : prop, t.tsTypeAnnotation(type), optional);
264
+ });
265
+ var params = keys.map(function (prop) {
266
+ 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);
267
+ });
268
+ var obj = t.objectPattern((0, _toConsumableArray2["default"])(params));
269
+ obj.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral((0, _toConsumableArray2["default"])(typedParams)));
270
+ return obj;
271
+ };
272
+
273
+ var createPropertyFunctionWithObjectParamsForPartial = function createPropertyFunctionWithObjectParamsForPartial(methodName, responseType, jsonschema) {
274
+ var obj = createTypedObjectParams(jsonschema);
275
+ var fixedParams = [// identifier('fee', t.tsTypeAnnotation(
276
+ // t.tsUnionType(
277
+ // [
278
+ // t.tsNumberKeyword(),
279
+ // t.tsTypeReference(
280
+ // t.identifier('StdFee')
281
+ // ),
282
+ // t.tsLiteralType(
283
+ // t.stringLiteral('auto')
284
+ // )
285
+ // ]
286
+ // )
287
+ // ), true),
288
+ // identifier('memo', t.tsTypeAnnotation(
289
+ // t.tsStringKeyword()
290
+ // ), true),
291
+ identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
292
+ var func = {
293
+ type: 'TSFunctionType',
294
+ typeAnnotation: t.tsTypeAnnotation(t.tsTypeReference(t.identifier(responseType))),
295
+ parameters: obj ? [obj].concat(fixedParams) : fixedParams
296
+ };
297
+ return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(func));
298
+ };
@@ -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/main/wasm.js CHANGED
@@ -28,9 +28,6 @@ var getTypeFromRef = function getTypeFromRef($ref) {
28
28
  case '#/definitions/Binary':
29
29
  return t.tsTypeReference(t.identifier('Binary'));
30
30
 
31
- case '#/definitions/Expiration':
32
- return t.tsTypeReference(t.identifier('Expiration'));
33
-
34
31
  default:
35
32
  if ($ref.startsWith('#/definitions/')) {
36
33
  return t.tsTypeReference(t.identifier($ref.replace('#/definitions/', '')));
@@ -206,7 +203,7 @@ var createWasmExecMethod = function createWasmExecMethod(jsonschema) {
206
203
  var args = Object.keys(properties).map(function (prop) {
207
204
  return t.objectProperty(t.identifier(prop), t.identifier((0, _case.camel)(prop)), false, prop === (0, _case.camel)(prop));
208
205
  });
209
- var constantParams = [t.assignmentPattern(identifier('fee', t.tsTypeAnnotation(t.tsUnionType([t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee'))])), false), t.stringLiteral('auto')), identifier('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
206
+ var constantParams = [t.assignmentPattern(identifier('fee', t.tsTypeAnnotation(t.tsUnionType([t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), false), t.stringLiteral('auto')), identifier('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
210
207
  return t.classProperty(t.identifier(methodName), (0, _utils.arrowFunctionExpression)(obj ? [// props
211
208
  obj].concat(constantParams) : constantParams, 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.identifier('fee'), t.identifier('memo'), t.identifier('funds')])))]), // return type
212
209
  t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tSTypeReference(t.identifier('ExecuteResult'))]))), true));
@@ -329,7 +326,6 @@ var createQueryInterface = function createQueryInterface(className, queryMsg) {
329
326
  var underscoreName = Object.keys(jsonschema.properties)[0];
330
327
  var methodName = (0, _case.camel)(underscoreName);
331
328
  var responseType = (0, _case.pascal)("".concat(methodName, "Response"));
332
- var obj = createTypedObjectParams(jsonschema.properties[underscoreName]);
333
329
  return createPropertyFunctionWithObjectParams(methodName, responseType, jsonschema.properties[underscoreName]);
334
330
  });
335
331
  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)))));
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,254 @@
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
+ default:
11
+ if ($ref.startsWith('#/definitions/')) {
12
+ return t.tsTypeReference(t.identifier($ref.replace('#/definitions/', '')));
13
+ }
14
+
15
+ throw new Error('what is $ref: ' + $ref);
16
+ }
17
+ };
18
+
19
+ const getArrayTypeFromRef = $ref => {
20
+ return t.tsArrayType(getTypeFromRef($ref));
21
+ };
22
+
23
+ const getArrayTypeFromType = type => {
24
+ return t.tsArrayType(getType(type));
25
+ }; // MARKED AS NOT DRY
26
+
27
+
28
+ const identifier = (name, typeAnnotation, optional = false) => {
29
+ const type = t.identifier(name);
30
+ type.typeAnnotation = typeAnnotation;
31
+ type.optional = optional;
32
+ return type;
33
+ };
34
+
35
+ const getType = type => {
36
+ switch (type) {
37
+ case 'string':
38
+ return t.tsStringKeyword();
39
+
40
+ case 'boolean':
41
+ return t.tSBooleanKeyword();
42
+
43
+ case 'integer':
44
+ return t.tsNumberKeyword();
45
+
46
+ default:
47
+ throw new Error('what is type: ' + type);
48
+ }
49
+ }; // MARKED AS NOT DRY
50
+
51
+
52
+ const getPropertyType = (schema, prop) => {
53
+ const props = schema.properties ?? {};
54
+ let info = props[prop];
55
+ let type = null;
56
+ let optional = schema.required?.includes(prop);
57
+
58
+ if (info.allOf && info.allOf.length === 1) {
59
+ info = info.allOf[0];
60
+ }
61
+
62
+ if (typeof info.$ref === 'string') {
63
+ type = getTypeFromRef(info.$ref);
64
+ }
65
+
66
+ if (Array.isArray(info.anyOf)) {
67
+ // assuming 2nd is null, but let's check to ensure
68
+ if (info.anyOf.length !== 2) {
69
+ throw new Error('case not handled by transpiler. contact maintainers.');
70
+ }
71
+
72
+ const [nullableType, nullType] = info.anyOf;
73
+
74
+ if (nullType?.type !== 'null') {
75
+ throw new Error('case not handled by transpiler. contact maintainers.');
76
+ }
77
+
78
+ type = getTypeFromRef(nullableType?.$ref);
79
+ optional = true;
80
+ }
81
+
82
+ if (typeof info.type === 'string') {
83
+ if (info.type === 'array') {
84
+ if (info.items.$ref) {
85
+ type = getArrayTypeFromRef(info.items.$ref);
86
+ } else {
87
+ type = getArrayTypeFromType(info.items.type);
88
+ }
89
+ } else {
90
+ type = getType(info.type);
91
+ }
92
+ }
93
+
94
+ if (Array.isArray(info.type)) {
95
+ // assuming 2nd is null, but let's check to ensure
96
+ if (info.type.length !== 2) {
97
+ throw new Error('case not handled by transpiler. contact maintainers.');
98
+ }
99
+
100
+ const [nullableType, nullType] = info.type;
101
+
102
+ if (nullType !== 'null') {
103
+ throw new Error('case not handled by transpiler. contact maintainers.');
104
+ }
105
+
106
+ type = getType(nullableType);
107
+ optional = true;
108
+ }
109
+
110
+ if (!type) {
111
+ throw new Error('cannot find type for ' + JSON.stringify(info));
112
+ }
113
+
114
+ if (schema.required?.includes(prop)) {
115
+ optional = false;
116
+ }
117
+
118
+ return {
119
+ type,
120
+ optional
121
+ };
122
+ };
123
+
124
+ const tsTypeOperator = (typeAnnotation, operator) => {
125
+ const obj = t.tsTypeOperator(typeAnnotation);
126
+ obj.operator = operator;
127
+ return obj;
128
+ }; // MARKED AS NOT DRY
129
+
130
+
131
+ const createWasmExecMethod = jsonschema => {
132
+ const underscoreName = Object.keys(jsonschema.properties)[0];
133
+ const methodName = camel(underscoreName);
134
+ const properties = jsonschema.properties[underscoreName].properties ?? {};
135
+ const obj = createTypedObjectParams(jsonschema.properties[underscoreName]);
136
+ const args = Object.keys(properties).map(prop => {
137
+ return t.objectProperty(t.identifier(prop), t.identifier(camel(prop)), false, prop === camel(prop));
138
+ });
139
+ const constantParams = [// t.assignmentPattern(
140
+ // identifier(
141
+ // 'fee',
142
+ // t.tsTypeAnnotation(
143
+ // t.tsUnionType(
144
+ // [
145
+ // t.tSNumberKeyword(),
146
+ // t.tsTypeReference(
147
+ // t.identifier('StdFee')
148
+ // ),
149
+ // t.tsLiteralType(
150
+ // t.stringLiteral('auto')
151
+ // )
152
+ // ]
153
+ // )
154
+ // ),
155
+ // false
156
+ // ),
157
+ // t.stringLiteral('auto')
158
+ // ),
159
+ // identifier('memo', t.tsTypeAnnotation(
160
+ // t.tsStringKeyword()
161
+ // ), true),
162
+ identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
163
+ return t.classProperty(t.identifier(methodName), arrowFunctionExpression(obj ? [// props
164
+ 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
165
+ t.tsTypeAnnotation(t.tsTypeReference(t.identifier('MsgExecuteContractEncodeObject'))), false));
166
+ };
167
+
168
+ export const createFromPartialClass = (className, implementsClassName, execMsg) => {
169
+ const propertyNames = getMessageProperties(execMsg).map(method => Object.keys(method.properties)?.[0]).filter(Boolean);
170
+ const bindings = propertyNames.map(camel).map(bindMethod);
171
+ const methods = getMessageProperties(execMsg).map(schema => {
172
+ return createWasmExecMethod(schema);
173
+ });
174
+ const blockStmt = [];
175
+ [].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]);
176
+ return t.exportNamedDeclaration(classDeclaration(className, [// sender
177
+ classProperty('sender', t.tsTypeAnnotation(t.tsStringKeyword())), // contractAddress
178
+ classProperty('contractAddress', t.tsTypeAnnotation(t.tsStringKeyword())), // constructor
179
+ 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));
180
+ };
181
+ export const createFromPartialInterface = (className, execMsg) => {
182
+ const methods = getMessageProperties(execMsg).map(jsonschema => {
183
+ const underscoreName = Object.keys(jsonschema.properties)[0];
184
+ const methodName = camel(underscoreName);
185
+ return createPropertyFunctionWithObjectParamsForPartial(methodName, 'MsgExecuteContractEncodeObject', jsonschema.properties[underscoreName]);
186
+ });
187
+ const extendsAst = [];
188
+ return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(className), null, extendsAst, t.tSInterfaceBody([// contract address
189
+ t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), // contract address
190
+ t.tSPropertySignature(t.identifier('sender'), t.tsTypeAnnotation(t.tsStringKeyword())), ...methods])));
191
+ }; // MARKED AS NOT DRY
192
+
193
+ const propertySignature = (name, typeAnnotation, optional = false) => {
194
+ // prop.leadingComments = [{
195
+ // type: 'Comment',
196
+ // value: ' Data on the token itself'
197
+ // }];
198
+ // prop.leadingComments = [{
199
+ // type: 'CommentBlock',
200
+ // value: '* Data on the token itself'
201
+ // }];
202
+ return {
203
+ type: 'TSPropertySignature',
204
+ key: t.identifier(name),
205
+ typeAnnotation,
206
+ optional
207
+ };
208
+ }; // MARKED AS NOT DRY
209
+
210
+
211
+ const createTypedObjectParams = (jsonschema, camelize = true) => {
212
+ const keys = Object.keys(jsonschema.properties ?? {});
213
+ if (!keys.length) return;
214
+ const typedParams = keys.map(prop => {
215
+ const {
216
+ type,
217
+ optional
218
+ } = getPropertyType(jsonschema, prop);
219
+ return propertySignature(camelize ? camel(prop) : prop, t.tsTypeAnnotation(type), optional);
220
+ });
221
+ const params = keys.map(prop => {
222
+ return t.objectProperty(camelize ? t.identifier(camel(prop)) : t.identifier(prop), camelize ? t.identifier(camel(prop)) : t.identifier(prop), false, true);
223
+ });
224
+ const obj = t.objectPattern([...params]);
225
+ obj.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral([...typedParams]));
226
+ return obj;
227
+ };
228
+
229
+ const createPropertyFunctionWithObjectParamsForPartial = (methodName, responseType, jsonschema) => {
230
+ const obj = createTypedObjectParams(jsonschema);
231
+ const fixedParams = [// identifier('fee', t.tsTypeAnnotation(
232
+ // t.tsUnionType(
233
+ // [
234
+ // t.tsNumberKeyword(),
235
+ // t.tsTypeReference(
236
+ // t.identifier('StdFee')
237
+ // ),
238
+ // t.tsLiteralType(
239
+ // t.stringLiteral('auto')
240
+ // )
241
+ // ]
242
+ // )
243
+ // ), true),
244
+ // identifier('memo', t.tsTypeAnnotation(
245
+ // t.tsStringKeyword()
246
+ // ), true),
247
+ identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
248
+ const func = {
249
+ type: 'TSFunctionType',
250
+ typeAnnotation: t.tsTypeAnnotation(t.tsTypeReference(t.identifier(responseType))),
251
+ parameters: obj ? [obj, ...fixedParams] : fixedParams
252
+ };
253
+ return t.tSPropertySignature(t.identifier(methodName), t.tsTypeAnnotation(func));
254
+ };
@@ -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/module/wasm.js CHANGED
@@ -7,9 +7,6 @@ const getTypeFromRef = $ref => {
7
7
  case '#/definitions/Binary':
8
8
  return t.tsTypeReference(t.identifier('Binary'));
9
9
 
10
- case '#/definitions/Expiration':
11
- return t.tsTypeReference(t.identifier('Expiration'));
12
-
13
10
  default:
14
11
  if ($ref.startsWith('#/definitions/')) {
15
12
  return t.tsTypeReference(t.identifier($ref.replace('#/definitions/', '')));
@@ -160,7 +157,7 @@ export const createWasmExecMethod = jsonschema => {
160
157
  const args = Object.keys(properties).map(prop => {
161
158
  return t.objectProperty(t.identifier(prop), t.identifier(camel(prop)), false, prop === camel(prop));
162
159
  });
163
- const constantParams = [t.assignmentPattern(identifier('fee', t.tsTypeAnnotation(t.tsUnionType([t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee'))])), false), t.stringLiteral('auto')), identifier('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
160
+ const constantParams = [t.assignmentPattern(identifier('fee', t.tsTypeAnnotation(t.tsUnionType([t.tSNumberKeyword(), t.tsTypeReference(t.identifier('StdFee')), t.tsLiteralType(t.stringLiteral('auto'))])), false), t.stringLiteral('auto')), identifier('memo', t.tsTypeAnnotation(t.tsStringKeyword()), true), identifier('funds', t.tsTypeAnnotation(tsTypeOperator(t.tsArrayType(t.tsTypeReference(t.identifier('Coin'))), 'readonly')), true)];
164
161
  return t.classProperty(t.identifier(methodName), arrowFunctionExpression(obj ? [// props
165
162
  obj, ...constantParams] : constantParams, 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([...args]))]), t.identifier('fee'), t.identifier('memo'), t.identifier('funds')])))]), // return type
166
163
  t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Promise'), t.tsTypeParameterInstantiation([t.tSTypeReference(t.identifier('ExecuteResult'))]))), true));
@@ -195,47 +192,7 @@ export const createExecuteInterface = (className, extendsClassName, execMsg) =>
195
192
  const extendsAst = extendsClassName ? [t.tSExpressionWithTypeArguments(t.identifier(extendsClassName))] : [];
196
193
  return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(className), null, extendsAst, t.tSInterfaceBody([// contract address
197
194
  t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), // contract address
198
- t.tSPropertySignature(t.identifier('sender'), t.tsTypeAnnotation(t.tsStringKeyword())), ...methods // // fee
199
- // t.tSPropertySignature(
200
- // t.identifier('fee'),
201
- // t.tsTypeAnnotation(
202
- // t.tsUnionType(
203
- // [
204
- // t.tsNumberKeyword(),
205
- // t.tsTypeReference(
206
- // t.identifier('StdFee')
207
- // ),
208
- // t.tsLiteralType(
209
- // t.stringLiteral('auto')
210
- // )
211
- // ]
212
- // )
213
- // )
214
- // ),
215
- // // memo
216
- // propertySignature(
217
- // 'memo',
218
- // t.tsTypeAnnotation(
219
- // t.tsStringKeyword()
220
- // ),
221
- // true
222
- // ),
223
- // // funds
224
- // propertySignature(
225
- // 'funds',
226
- // t.tsTypeAnnotation(
227
- // tsTypeOperator(
228
- // t.tsArrayType(
229
- // t.tsTypeReference(
230
- // t.identifier('Coin')
231
- // )
232
- // ),
233
- // 'readonly'
234
- // )
235
- // ),
236
- // true
237
- // )
238
- ])));
195
+ t.tSPropertySignature(t.identifier('sender'), t.tsTypeAnnotation(t.tsStringKeyword())), ...methods])));
239
196
  };
240
197
  export const propertySignature = (name, typeAnnotation, optional = false) => {
241
198
  // prop.leadingComments = [{
@@ -294,7 +251,6 @@ export const createQueryInterface = (className, queryMsg) => {
294
251
  const underscoreName = Object.keys(jsonschema.properties)[0];
295
252
  const methodName = camel(underscoreName);
296
253
  const responseType = pascal(`${methodName}Response`);
297
- const obj = createTypedObjectParams(jsonschema.properties[underscoreName]);
298
254
  return createPropertyFunctionWithObjectParams(methodName, responseType, jsonschema.properties[underscoreName]);
299
255
  });
300
256
  return t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(className), null, [], t.tSInterfaceBody([t.tSPropertySignature(t.identifier('contractAddress'), t.tsTypeAnnotation(t.tsStringKeyword())), ...methods])));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wasm-ast-types",
3
- "version": "0.2.2",
3
+ "version": "0.2.5",
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": "c2a825ebda3fd8c1e2080ac9092148403460cc45"
88
+ "gitHead": "4e067214d530188822eca31ddbeb6eb9ec3ba462"
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;