@taqueria/plugin-contract-types 0.8.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/chunk-GC2KSB5D.js +226 -0
  2. package/chunk-GC2KSB5D.js.map +1 -0
  3. package/chunk-T4SGVAIL.js +604 -0
  4. package/chunk-T4SGVAIL.js.map +1 -0
  5. package/example/test-generation/example-contract-0.jest-demo.ts +78 -0
  6. package/example/test-generation/example-contract-1.jest-demo.ts +196 -0
  7. package/example/test-generation/example-contract-10.jest-demo.ts +47 -0
  8. package/example/test-generation/example-contract-11.jest-demo.ts +48 -0
  9. package/example/test-generation/example-contract-2.jest-demo.ts +277 -0
  10. package/example/test-generation/example-contract-4.jest-demo.ts +203 -0
  11. package/example/test-generation/example-contract-5.jest-demo.ts +235 -0
  12. package/example/test-generation/example-contract-6.jest-demo.ts +277 -0
  13. package/example/test-generation/example-contract-7.jest-demo.ts +170 -0
  14. package/example/test-generation/example-contract-8.jest-demo.ts +227 -0
  15. package/example/test-generation/example-contract-9.jest-demo.ts +42 -0
  16. package/example/types-file/example-contract-10.types.ts +2 -2
  17. package/example/types-file/example-contract-11.types.ts +2 -2
  18. package/example/types-file/type-aliases.ts +4 -0
  19. package/index.cjs +920 -0
  20. package/index.cjs.map +1 -0
  21. package/index.d.ts +1 -0
  22. package/index.js +78 -882
  23. package/index.js.map +1 -1
  24. package/index.ts +1 -0
  25. package/package.json +27 -12
  26. package/src/cli-process.cjs +848 -0
  27. package/src/cli-process.cjs.map +1 -0
  28. package/src/cli-process.d.ts +9 -0
  29. package/src/cli-process.js +8 -0
  30. package/src/cli-process.js.map +1 -0
  31. package/src/generator/process.ts +37 -13
  32. package/src/generator/testing-code-generator-jest-demo.ts +75 -0
  33. package/src/generator/testing-code-generator.cjs +613 -0
  34. package/src/generator/testing-code-generator.cjs.map +1 -0
  35. package/src/generator/testing-code-generator.d.ts +79 -0
  36. package/src/generator/testing-code-generator.js +131 -0
  37. package/src/generator/testing-code-generator.js.map +1 -0
  38. package/src/generator/testing-code-generator.ts +282 -0
  39. package/src/generator/typescript-output.ts +136 -14
  40. package/src/type-aliases.ts +1 -0
  41. package/tsconfig.json +4 -1
  42. package/lib/tsconfig.tsbuildinfo +0 -1
package/index.cjs ADDED
@@ -0,0 +1,920 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // index.ts
27
+ var taqueria_plugin_contract_types_exports = {};
28
+ __export(taqueria_plugin_contract_types_exports, {
29
+ generateContractTypesProcessContractFiles: () => generateContractTypesProcessContractFiles
30
+ });
31
+ module.exports = __toCommonJS(taqueria_plugin_contract_types_exports);
32
+ var import_node_sdk = require("@taqueria/node-sdk");
33
+
34
+ // tasks.ts
35
+ var import_fast_glob = __toESM(require("fast-glob"), 1);
36
+ var import_path2 = require("path");
37
+
38
+ // src/cli-process.ts
39
+ var import_fs = __toESM(require("fs"), 1);
40
+ var import_path = __toESM(require("path"), 1);
41
+ var import_util = require("util");
42
+
43
+ // src/generator/contract-name.ts
44
+ var normalizeContractName = (text) => text.replace(/[^A-Za-z0-9]/g, "_").split("_").filter((x) => x).map((x) => x[0].toUpperCase() + x.substring(1)).join("");
45
+
46
+ // src/generator/process.ts
47
+ var M = __toESM(require("@taquito/michel-codec"), 1);
48
+
49
+ // src/generator/common.ts
50
+ var GenerateApiError = class {
51
+ constructor(message, data) {
52
+ this.message = message;
53
+ this.data = data;
54
+ this.name = `GenerateApiError`;
55
+ console.error(`\u274C GenerateApiError: ${message}`, data);
56
+ }
57
+ };
58
+ var assertExhaustive = (value, message) => {
59
+ console.error(message, { value });
60
+ };
61
+ var reduceFlatMap = (out, x) => {
62
+ out.push(...x);
63
+ return out;
64
+ };
65
+
66
+ // src/generator/contract-parser.ts
67
+ var parseContractStorage = (storage) => {
68
+ const fields = storage.args.map((x) => visitVar(x)).reduce(reduceFlatMap, []);
69
+ if (fields.length === 1 && !fields[0].name) {
70
+ return {
71
+ storage: fields[0].type
72
+ };
73
+ }
74
+ return {
75
+ storage: {
76
+ kind: `object`,
77
+ raw: storage,
78
+ fields
79
+ }
80
+ };
81
+ };
82
+ var parseContractParameter = (parameter) => {
83
+ return {
84
+ methods: parameter.args.map((x) => visitContractParameterEndpoint(x)).reduce(reduceFlatMap, [])
85
+ };
86
+ };
87
+ var visitContractParameterEndpoint = (node) => {
88
+ var _a, _b;
89
+ if (node.prim === `or`) {
90
+ return node.args.map((x) => visitContractParameterEndpoint(x)).reduce(reduceFlatMap, []);
91
+ }
92
+ if (node.prim === `list` && node.args.length === 1 && ((_a = node.args[0]) == null ? void 0 : _a.prim) === `or`) {
93
+ return node.args.map((x) => visitContractParameterEndpoint(x)).reduce(reduceFlatMap, []);
94
+ }
95
+ const nameRaw = (_b = node.annots) == null ? void 0 : _b[0];
96
+ const name = (nameRaw == null ? void 0 : nameRaw.startsWith("%")) ? nameRaw.substr(1) : null;
97
+ if (!name) {
98
+ console.warn(`Unknown method: ${node.prim}`, { node, args: node.args });
99
+ return [];
100
+ }
101
+ const nodeType = visitType(node, { ignorePairName: node.prim === "pair" });
102
+ if (nodeType.kind === "object") {
103
+ return [{ name, args: nodeType.fields }];
104
+ }
105
+ return [{
106
+ name,
107
+ args: [{ type: nodeType }]
108
+ }];
109
+ };
110
+ var visitVar = (node) => {
111
+ var _a;
112
+ const name = `annots` in node && ((_a = node.annots) == null ? void 0 : _a.length) === 1 ? node.annots[0].substr(1) : void 0;
113
+ const type = visitType(node);
114
+ return [{
115
+ name,
116
+ type
117
+ }];
118
+ };
119
+ var visitType = (node, options) => {
120
+ if (!(`prim` in node)) {
121
+ console.error(`visitType no prim`, { node });
122
+ return { kind: `unknown`, raw: node };
123
+ }
124
+ if (node.prim === `or`) {
125
+ const unionVars = node.args.map((x) => visitVar(x)).reduce(reduceFlatMap, []).map((x) => x);
126
+ const union = unionVars.map((x) => !x.name && x.type.kind === "union" ? x.type.union : [x]).reduce(reduceFlatMap, []);
127
+ if (union.some((x) => !x)) {
128
+ throw new GenerateApiError(`or: Some fields are null`, { node });
129
+ }
130
+ return {
131
+ kind: `union`,
132
+ raw: node,
133
+ union
134
+ };
135
+ }
136
+ if (node.prim === `pair`) {
137
+ const fields = node.args.map((x) => visitVar(x)).reduce(reduceFlatMap, []);
138
+ if (fields.some((x) => !x)) {
139
+ throw new GenerateApiError(`pair: Some fields are null`, { node, args: node.args, fields });
140
+ }
141
+ const fieldsFlat = fields.map(
142
+ (x) => (!x.name || (options == null ? void 0 : options.ignorePairName)) && x.type.kind === "object" ? x.type.fields : [x]
143
+ ).reduce(reduceFlatMap, []);
144
+ return {
145
+ kind: `object`,
146
+ raw: node,
147
+ fields: fieldsFlat
148
+ };
149
+ }
150
+ if (node.prim === `list` || node.prim === `set`) {
151
+ if (node.args.length !== 1) {
152
+ throw new GenerateApiError(`list does not have 1 arg`, { node, args: node.args });
153
+ }
154
+ const arrayItem = visitType(node.args[0]);
155
+ if (!arrayItem) {
156
+ throw new GenerateApiError(`arrayItem are null`, { node, args: node.args, arrayItem });
157
+ }
158
+ return {
159
+ kind: `array`,
160
+ raw: node,
161
+ array: { item: arrayItem }
162
+ };
163
+ }
164
+ if (node.prim === `map` || node.prim === `big_map`) {
165
+ if (node.args.length !== 2) {
166
+ throw new GenerateApiError(`map does not have 2 args`, { node, args: node.args });
167
+ }
168
+ const mapKey = visitType(node.args[0]);
169
+ const mapValue = visitType(node.args[1]);
170
+ if (!mapKey || !mapValue) {
171
+ throw new GenerateApiError(`map is missing key or value`, { node, args: node.args, mapKey, mapValue });
172
+ }
173
+ return {
174
+ kind: `map`,
175
+ raw: node,
176
+ map: {
177
+ key: mapKey,
178
+ value: mapValue,
179
+ isBigMap: node.prim === `big_map`
180
+ }
181
+ };
182
+ }
183
+ if (node.prim === `option`) {
184
+ return {
185
+ ...visitType(node.args[0]),
186
+ optional: true
187
+ };
188
+ }
189
+ if (node.prim === `bool`) {
190
+ return {
191
+ kind: `value`,
192
+ raw: node,
193
+ value: node.prim,
194
+ typescriptType: `boolean`
195
+ };
196
+ }
197
+ if (node.prim === `nat` || node.prim === `int` || node.prim === `mutez`) {
198
+ return {
199
+ kind: `value`,
200
+ raw: node,
201
+ value: node.prim,
202
+ typescriptType: `number`
203
+ };
204
+ }
205
+ if (node.prim === `timestamp`) {
206
+ return {
207
+ kind: `value`,
208
+ raw: node,
209
+ value: node.prim,
210
+ typescriptType: `Date`
211
+ };
212
+ }
213
+ if (node.prim === `address` || node.prim === `key` || node.prim === `key_hash` || node.prim === `chain_id` || node.prim === `string` || node.prim === `signature` || node.prim === `ticket` || node.prim === `bls12_381_fr` || node.prim === `bls12_381_g1` || node.prim === `bls12_381_g2` || node.prim === `sapling_state` || node.prim === `sapling_transaction` || node.prim === `contract`) {
214
+ return {
215
+ kind: `value`,
216
+ raw: node,
217
+ value: node.prim,
218
+ typescriptType: `string`
219
+ };
220
+ }
221
+ if (node.prim === `unit`) {
222
+ return {
223
+ kind: `unit`,
224
+ raw: node
225
+ };
226
+ }
227
+ if (node.prim === `bytes`) {
228
+ return {
229
+ kind: `value`,
230
+ raw: node,
231
+ value: node.prim,
232
+ typescriptType: `string`
233
+ };
234
+ }
235
+ if (node.prim === `lambda` || node.prim === `operation`) {
236
+ return {
237
+ kind: `value`,
238
+ raw: node,
239
+ value: node.prim,
240
+ typescriptType: `string`
241
+ };
242
+ }
243
+ if (node.prim === "chest" || node.prim === "chest_key") {
244
+ return {
245
+ kind: `value`,
246
+ raw: node,
247
+ value: node.prim,
248
+ typescriptType: `string`
249
+ };
250
+ }
251
+ if (node.prim === `never`) {
252
+ return {
253
+ kind: `never`,
254
+ raw: node
255
+ };
256
+ }
257
+ assertExhaustive(node, `Unknown type`);
258
+ throw new GenerateApiError(`Unknown type`, { node });
259
+ };
260
+
261
+ // src/generator/schema-output.ts
262
+ var toSchema = (methods, storage) => {
263
+ const getSchemaObjectType = (vars) => {
264
+ if (vars.some((x) => !x)) {
265
+ throw new GenerateApiError(`getSchemaObjectType has null vars`, { vars });
266
+ }
267
+ return vars.reduce((out, x, i) => {
268
+ out[x.name ?? i] = getSchemaType(x.type);
269
+ return out;
270
+ }, {});
271
+ };
272
+ const getSchemaType = (t) => {
273
+ return (t.kind === `value` && t.value ? t.value : null) ?? (t.kind === `array` && t.array ? [getSchemaType(t.array.item)] : null) ?? (t.kind === `map` && t.map ? [`map`, getSchemaType(t.map.key), getSchemaType(t.map.value)] : null) ?? (t.kind === `object` && t.fields ? getSchemaObjectType(t.fields) : null) ?? (t.kind === `unit` ? `unit` : null) ?? (t.kind === `never` ? `never` : null) ?? `${t.raw}`;
274
+ };
275
+ const schemaMethods = methods.reduce((out, x) => {
276
+ out[x.name] = {
277
+ params: x.args.length === 1 && !x.args[0].name ? getSchemaType(x.args[0].type) : getSchemaObjectType(x.args ?? [])
278
+ };
279
+ return out;
280
+ }, {});
281
+ const schemaStorage = getSchemaType(storage.storage);
282
+ return {
283
+ methods: schemaMethods,
284
+ storage: schemaStorage
285
+ };
286
+ };
287
+
288
+ // src/generator/typescript-output.ts
289
+ var createTypescriptCodeGenerator = (options) => {
290
+ const usedStrictTypes = [];
291
+ const addTypeAlias = (strictType) => {
292
+ if (!usedStrictTypes.some((x) => x.aliasType === strictType.aliasType)) {
293
+ usedStrictTypes.push(strictType);
294
+ }
295
+ };
296
+ const tabs = (indent) => Array(indent).fill(` `).join(``);
297
+ const toIndentedItems = (indent, delimeters, items) => {
298
+ return `
299
+ ${tabs(indent + 1)}${items.join(`${delimeters.afterItem ?? ``}
300
+ ${tabs(indent + 1)}${delimeters.beforeItem ?? ``}`)}
301
+ ${tabs(indent)}`;
302
+ };
303
+ const typeToCode = (t, indent) => {
304
+ if ((options == null ? void 0 : options.mode) === "defaultValue") {
305
+ return typeToCode_defaultValue(t, indent);
306
+ }
307
+ if (t.kind === `value`) {
308
+ const prim = `prim` in t.raw ? t.raw.prim : `unknown`;
309
+ if (t.typescriptType === `boolean` || t.typescriptType === `string` && prim === `string`) {
310
+ return `${t.typescriptType}`;
311
+ }
312
+ if (t.typescriptType === "number") {
313
+ const simpleBaseType2 = `string | BigNumber | number`;
314
+ const typeAlias2 = {
315
+ aliasType: prim,
316
+ simpleTypeDefinition: `type ${prim} = ${simpleBaseType2};`,
317
+ simpleTypeImports: [{ name: "BigNumber", isDefault: true, from: "bignumber.js" }]
318
+ };
319
+ addTypeAlias(typeAlias2);
320
+ return typeAlias2.aliasType;
321
+ }
322
+ const simpleBaseType = t.typescriptType === "Date" ? "Date | string" : t.typescriptType;
323
+ const typeAlias = { aliasType: prim, simpleTypeDefinition: `type ${prim} = ${simpleBaseType};` };
324
+ addTypeAlias(typeAlias);
325
+ return typeAlias.aliasType;
326
+ }
327
+ if (t.kind === `array`) {
328
+ return `Array<${typeToCode(t.array.item, indent)}>`;
329
+ }
330
+ if (t.kind === `map`) {
331
+ const typeAlias = t.map.isBigMap ? {
332
+ aliasType: `BigMap`,
333
+ simpleTypeDefinition: "type BigMap<K, T> = MichelsonMap<K, T>;",
334
+ simpleTypeImports: [{ name: "MichelsonMap", from: "@taquito/taquito" }]
335
+ } : {
336
+ aliasType: `MMap`,
337
+ simpleTypeDefinition: "type MMap<K, T> = MichelsonMap<K, T>;",
338
+ simpleTypeImports: [{ name: "MichelsonMap", from: "@taquito/taquito" }]
339
+ };
340
+ addTypeAlias(typeAlias);
341
+ return `${typeAlias.aliasType}<${typeToCode(t.map.key, indent)}, ${typeToCode(t.map.value, indent)}>`;
342
+ }
343
+ if (t.kind === `object`) {
344
+ return `{${toIndentedItems(indent, {}, t.fields.map((a, i) => varToCode(a, i, indent + 1) + `;`))}}`;
345
+ }
346
+ if (t.kind === `union`) {
347
+ const getUnionItem = (a, i) => {
348
+ const itemCode = `${varToCode(a, i, indent + 1)}`;
349
+ if (!itemCode.includes(`
350
+ `)) {
351
+ return `{ ${itemCode} }`;
352
+ }
353
+ return `{${toIndentedItems(indent + 1, {}, [`${varToCode(a, i, indent + 2)}`])}}`;
354
+ };
355
+ return `(${toIndentedItems(indent, { beforeItem: `| ` }, t.union.map(getUnionItem))})`;
356
+ }
357
+ if (t.kind === `unit`) {
358
+ const typeAlias = {
359
+ aliasType: `unit`,
360
+ simpleTypeDefinition: `type unit = (true | undefined);`
361
+ };
362
+ addTypeAlias(typeAlias);
363
+ return typeAlias.aliasType;
364
+ }
365
+ if (t.kind === `never`) {
366
+ return `never`;
367
+ }
368
+ if (t.kind === `unknown`) {
369
+ return `unknown`;
370
+ }
371
+ assertExhaustive(t, `Unknown type`);
372
+ throw new GenerateApiError(`Unknown type node`, { t });
373
+ };
374
+ const typeToCode_defaultValue = (t, indent) => {
375
+ if (t.kind === `value`) {
376
+ const prim = `prim` in t.raw ? t.raw.prim : `unknown`;
377
+ if (t.typescriptType === "boolean") {
378
+ return `true`;
379
+ }
380
+ if (t.typescriptType === `string` && prim === `string`) {
381
+ return `'VALUE'`;
382
+ }
383
+ if (t.typescriptType === "number") {
384
+ return `tas.${prim}('42')`;
385
+ }
386
+ if (t.typescriptType === "Date") {
387
+ return `tas.timestamp(new Date())`;
388
+ }
389
+ if (prim === "address" || prim === "contract") {
390
+ return `tas.${prim}('tz1ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456')`;
391
+ }
392
+ if (prim === "bytes") {
393
+ return `tas.${prim}(char2Bytes('DATA'))`;
394
+ }
395
+ if (t.typescriptType === "string") {
396
+ return `tas.${prim}('VALUE')`;
397
+ }
398
+ assertExhaustive(t.typescriptType, `Unknown value type`);
399
+ return prim;
400
+ }
401
+ if (t.kind === `array`) {
402
+ return `[${typeToCode(t.array.item, indent)}]`;
403
+ }
404
+ if (t.kind === `map`) {
405
+ const keyPrim = `prim` in t.map.key.raw ? t.map.key.raw.prim : `unknown`;
406
+ const isStringBasedKey = t.map.key.kind === "value" && keyPrim === "string";
407
+ if (isStringBasedKey) {
408
+ return `tas.${t.map.isBigMap ? "bigMap" : "map"}({
409
+ ${tabs(indent + 1)}${typeToCode(t.map.key, indent)}: ${typeToCode(t.map.value, indent)},
410
+ ${tabs(indent)}})`;
411
+ }
412
+ return `tas.${t.map.isBigMap ? "bigMap" : "map"}([{
413
+ ${tabs(indent + 1)}key: ${typeToCode(t.map.key, indent)},
414
+ ${tabs(indent + 1)}value: ${typeToCode(t.map.value, indent)},
415
+ ${tabs(indent)}}])`;
416
+ }
417
+ if (t.kind === `object`) {
418
+ const delimeter = (options == null ? void 0 : options.mode) === "defaultValue" ? "," : `;`;
419
+ return `{${toIndentedItems(indent, {}, t.fields.map((a, i) => varToCode(a, i, indent + 1) + delimeter))}}`;
420
+ }
421
+ if (t.kind === `union`) {
422
+ const getUnionItem = (a, i) => {
423
+ const itemCode = `${varToCode(a, i, indent + 1)}`;
424
+ if (!itemCode.includes(`
425
+ `)) {
426
+ return `{ ${itemCode} }`;
427
+ }
428
+ return `{${toIndentedItems(indent + 1, {}, [`${varToCode(a, i, indent + 2)}`])}}`;
429
+ };
430
+ return `(${toIndentedItems(indent, { beforeItem: `| ` }, t.union.map(getUnionItem))})`;
431
+ }
432
+ if (t.kind === `unit`) {
433
+ return `tas.unit()`;
434
+ }
435
+ if (t.kind === `never`) {
436
+ return `never`;
437
+ }
438
+ if (t.kind === `unknown`) {
439
+ return `unknown`;
440
+ }
441
+ assertExhaustive(t, `Unknown type`);
442
+ throw new GenerateApiError(`Unknown type node`, { t });
443
+ };
444
+ const varToCode = (t, i, indent, numberVarNamePrefix = "") => {
445
+ return `${t.name ?? `${numberVarNamePrefix}${i}`}${t.type.optional && (options == null ? void 0 : options.mode) !== "defaultValue" ? `?` : ``}: ${typeToCode(t.type, indent)}`;
446
+ };
447
+ const argsToCode = (args, indent, asObject) => {
448
+ if (args.length === 1) {
449
+ if (args[0].type.kind === `unit`)
450
+ return ``;
451
+ if ((options == null ? void 0 : options.mode) === "defaultValue") {
452
+ return typeToCode(args[0].type, indent + 1);
453
+ }
454
+ return `${args[0].name ?? `param`}: ${typeToCode(args[0].type, indent + 1)}`;
455
+ }
456
+ const result = `${toIndentedItems(
457
+ indent,
458
+ {},
459
+ args.filter((x) => x.name || x.type.kind !== `unit`).map((a, i) => {
460
+ if (!asObject && (options == null ? void 0 : options.mode) === "defaultValue") {
461
+ return typeToCode(a.type, indent + 1) + `,`;
462
+ }
463
+ return varToCode(a, i, indent + 1, asObject ? "" : "_") + `,`;
464
+ })
465
+ )}`;
466
+ if (asObject) {
467
+ if ((options == null ? void 0 : options.mode) === "defaultValue") {
468
+ return `{${result}}`;
469
+ }
470
+ return `params: {${result}}`;
471
+ }
472
+ return result;
473
+ };
474
+ return {
475
+ usedStrictTypes,
476
+ tabs,
477
+ toIndentedItems,
478
+ typeToCode,
479
+ argsToCode
480
+ };
481
+ };
482
+ var toTypescriptCode = (storage, methods, contractName, parsedContract, protocol, typeAliasData, typeUtilsData) => {
483
+ const {
484
+ usedStrictTypes,
485
+ toIndentedItems,
486
+ typeToCode,
487
+ argsToCode
488
+ } = createTypescriptCodeGenerator();
489
+ const methodsToCode = (indent) => {
490
+ const methodFields = methods.map((x) => {
491
+ const methodCode = `${x.name}: (${argsToCode(x.args, indent + 1, false)}) => Promise<void>;`;
492
+ return methodCode;
493
+ });
494
+ const methodsTypeCode = `type Methods = {${toIndentedItems(indent, {}, methodFields)}};`;
495
+ return methodsTypeCode;
496
+ };
497
+ const methodsObjectToCode = (indent) => {
498
+ const methodFields = methods.map((x) => {
499
+ const methodCode = `${x.name}: (${argsToCode(x.args, indent + 1, true)}) => Promise<void>;`;
500
+ return methodCode;
501
+ });
502
+ const methodsTypeCode = `type MethodsObject = {${toIndentedItems(indent, {}, methodFields)}};`;
503
+ return methodsTypeCode;
504
+ };
505
+ const storageToCode = (indent) => {
506
+ const storageTypeCode = `type Storage = ${typeToCode(storage.storage, indent)};`;
507
+ return storageTypeCode;
508
+ };
509
+ const methodsCode = methodsToCode(0);
510
+ const methodsObjectCode = methodsObjectToCode(0);
511
+ const storageCode = storageToCode(0);
512
+ const simpleTypeMappingImportsAll = new Map(
513
+ usedStrictTypes.map((x) => x.simpleTypeImports ?? []).reduce(reduceFlatMap, []).map(
514
+ (x) => [`${x == null ? void 0 : x.from}:${x == null ? void 0 : x.name}:${x == null ? void 0 : x.isDefault}`, x]
515
+ )
516
+ );
517
+ const simpleTypeMappingImportsFrom = [...simpleTypeMappingImportsAll.values()].reduce((out, x) => {
518
+ const entry = out[x.from] ?? (out[x.from] = { names: [] });
519
+ if (x.isDefault) {
520
+ entry.default = x.name;
521
+ } else {
522
+ entry.names.push(x.name);
523
+ }
524
+ entry.names.sort((a, b) => a.localeCompare(b));
525
+ return out;
526
+ }, {});
527
+ const simpleTypeMappingImportsText = Object.keys(simpleTypeMappingImportsFrom).map((k) => {
528
+ const entry = simpleTypeMappingImportsFrom[k];
529
+ const items = [entry.default, entry.names.length ? `{ ${entry.names.join(", ")} }` : ""].filter((x) => x);
530
+ return `import ${items.join(", ")} from '${k}';
531
+ `;
532
+ }).join("");
533
+ const simpleTypeMapping = usedStrictTypes.sort((a, b) => a.aliasType.localeCompare(b.aliasType)).map((x) => x.simpleTypeDefinition).join(`
534
+ `);
535
+ const typeUtilsDefinitions = `import { ContractAbstractionFromContractType, WalletContractAbstractionFromContractType } from '${typeUtilsData.importPath}';`;
536
+ const typeAliasesDefinitions = typeAliasData.mode === "simple" ? `${simpleTypeMappingImportsText}${simpleTypeMapping}` : typeAliasData.mode === "local" ? typeAliasData.fileContent : `import { ${usedStrictTypes.map((x) => x.aliasType).join(`, `)} } from '${typeAliasData.importPath}';`;
537
+ const contractTypeName = `${contractName}ContractType`;
538
+ const walletTypeName = `${contractName}WalletType`;
539
+ const codeName = `${contractName}Code`;
540
+ const typesFileContent = `
541
+ ${typeUtilsDefinitions}
542
+ ${typeAliasesDefinitions}
543
+
544
+ ${storageCode}
545
+
546
+ ${methodsCode}
547
+
548
+ ${methodsObjectCode}
549
+
550
+ type contractTypes = { methods: Methods, methodsObject: MethodsObject, storage: Storage, code: { __type: '${codeName}', protocol: string, code: object[] } };
551
+ export type ${contractTypeName} = ContractAbstractionFromContractType<contractTypes>;
552
+ export type ${walletTypeName} = WalletContractAbstractionFromContractType<contractTypes>;
553
+ `;
554
+ const contractCodeFileContent = `
555
+ export const ${codeName}: { __type: '${codeName}', protocol: string, code: object[] } = {
556
+ __type: '${codeName}',
557
+ protocol: '${protocol.key}',
558
+ code: JSON.parse(\`${JSON.stringify(parsedContract)}\`)
559
+ };
560
+ `;
561
+ return {
562
+ typesFileContent,
563
+ contractCodeFileContent,
564
+ storage: storageCode,
565
+ methods: methodsCode,
566
+ methodsObject: methodsObjectCode
567
+ };
568
+ };
569
+
570
+ // src/generator/process.ts
571
+ var parseContractWithMinimalProtocolLevel = (contractScript, format, contractLevelIndex) => {
572
+ const contractLevels = [
573
+ { name: "PsDELPH1", key: M.Protocol.PsDELPH1 },
574
+ { name: "PtEdo2Zk", key: M.Protocol.PtEdo2Zk },
575
+ { name: "PsFLorena", key: M.Protocol.PsFLorena }
576
+ ];
577
+ const protocol = contractLevels[contractLevelIndex];
578
+ if (!protocol) {
579
+ throw new GenerateApiError(`Could not parse contract script`, contractScript);
580
+ }
581
+ const p = new M.Parser({ protocol: protocol.key });
582
+ try {
583
+ const contract = format === "tz" ? p.parseScript(contractScript) : p.parseJSON(JSON.parse(contractScript));
584
+ if (contract) {
585
+ return {
586
+ contract,
587
+ protocol
588
+ };
589
+ }
590
+ } catch {
591
+ }
592
+ return parseContractWithMinimalProtocolLevel(contractScript, format, contractLevelIndex + 1);
593
+ };
594
+ var parseContractInterface = (contractScript, format) => {
595
+ const p = new M.Parser({ protocol: M.Protocol.PsFLorena });
596
+ const { contract, protocol } = parseContractWithMinimalProtocolLevel(contractScript, format, 0);
597
+ const contractStorage = contract.find((x) => x.prim === `storage`);
598
+ const contractParameter = contract.find((x) => x.prim === `parameter`);
599
+ const storageResult = contractStorage && parseContractStorage(contractStorage);
600
+ const storage = storageResult ?? { storage: { kind: `object`, raw: { prim: `never` }, fields: [] } };
601
+ const parameterResult = contractParameter && parseContractParameter(contractParameter);
602
+ const methods = (parameterResult == null ? void 0 : parameterResult.methods) ?? [];
603
+ return {
604
+ storage,
605
+ methods,
606
+ contract,
607
+ protocol
608
+ };
609
+ };
610
+ var generateContractTypesFromMichelsonCode = (contractScript, contractName, format, typeAliasData, typeUtilsData) => {
611
+ const {
612
+ storage,
613
+ methods,
614
+ contract,
615
+ protocol
616
+ } = parseContractInterface(
617
+ contractScript,
618
+ format
619
+ );
620
+ if (methods.length === 1)
621
+ methods[0].name = `default`;
622
+ const schemaOutput = toSchema(methods, storage);
623
+ const typescriptCode = toTypescriptCode(
624
+ storage,
625
+ methods,
626
+ contractName,
627
+ contract,
628
+ protocol,
629
+ typeAliasData,
630
+ typeUtilsData
631
+ );
632
+ return {
633
+ schemaOutput,
634
+ typescriptCodeOutput: typescriptCode,
635
+ parsedContract: contract,
636
+ minimalProtocol: protocol.key
637
+ };
638
+ };
639
+
640
+ // src/type-aliases-file-content.ts
641
+ var typeAliasesFileContent = `
642
+ import { BigNumber } from 'bignumber.js';
643
+ import { MichelsonMap } from '@taquito/taquito';
644
+
645
+ export type unit = (true | undefined) & { __type: 'unit' };
646
+
647
+ export type address = string & { __type: 'address' };
648
+ export type bytes = string & { __type: 'bytes' };
649
+ export type contract = string & { __type: 'contract' };
650
+ export type operation = string & { __type: 'operation' };
651
+ export type key = string & { __type: 'key' };
652
+ export type key_hash = string & { __type: 'key_hash' };
653
+ export type signature = string & { __type: 'signature' };
654
+ export type ticket = string & { __type: 'ticket' };
655
+
656
+ export type timestamp = string & { __type: 'timestamp' };
657
+
658
+ export type int = BigNumber & { __type: 'int' };
659
+ export type nat = BigNumber & { __type: 'nat' };
660
+
661
+ export type mutez = BigNumber & { __type: 'mutez' };
662
+ export type tez = BigNumber & { __type: 'tez' };
663
+
664
+ type MapKey = Array<any> | object | string | boolean | number;
665
+ export type MMap<K extends MapKey, V> = Omit<MichelsonMap<K, V>, 'get'> & { get: (key: K) => V };
666
+ export type BigMap<K extends MapKey, V> = Omit<MichelsonMap<K, V>, 'get'> & { get: (key: K) => Promise<V> };
667
+
668
+ export type chest = string & { __type: 'chest' };
669
+ export type chest_key = string & { __type: 'chest_key' };
670
+
671
+ const createStringTypeTas = <T extends string>() => {
672
+ return (value: string): T => value as T;
673
+ };
674
+
675
+ const createBigNumberTypeTas = <T extends BigNumber>() => {
676
+ return (value: number | BigNumber | string): T => new BigNumber(value) as T;
677
+ };
678
+
679
+ type asMapParamOf<K, V> = K extends string ? { [key: string]: V } | Array<{ key: K, value: V }>
680
+ : K extends number ? { [key: number]: V } | Array<{ key: K, value: V }>
681
+ : Array<{ key: K, value: V }>;
682
+
683
+ function asMap<K extends MapKey, V>(value: asMapParamOf<K, V>): MMap<K, V> {
684
+ const m = new MichelsonMap<K, V>();
685
+ if (Array.isArray(value)) {
686
+ const vArray = value as Array<{ key: K, value: V }>;
687
+ vArray.forEach(x => m.set(x.key, x.value));
688
+ } else {
689
+ const vObject = value as { [key: string]: V };
690
+ Object.keys(vObject).forEach(key => m.set(key as unknown as K, vObject[key]));
691
+ }
692
+ return m as MMap<K, V>;
693
+ }
694
+ const asBigMap = <K extends MapKey, V>(value: asMapParamOf<K, V>) => asMap(value) as unknown as BigMap<K, V>;
695
+
696
+ function add<T extends BigNumber>(a: T, b: T): T {
697
+ return a.plus(b) as T;
698
+ }
699
+ function subtract<T extends BigNumber>(a: T, b: T): T {
700
+ return a.minus(b) as T;
701
+ }
702
+
703
+ /** tas: Tezos 'as' casting for strict types */
704
+ export const tas = {
705
+ address: createStringTypeTas<address>(),
706
+ bytes: createStringTypeTas<bytes>(),
707
+ contract: createStringTypeTas<contract>(),
708
+ chest: createStringTypeTas<chest>(),
709
+ chest_key: createStringTypeTas<chest_key>(),
710
+ timestamp: (value: string | Date): timestamp => new Date(value).toISOString() as timestamp,
711
+
712
+ int: createBigNumberTypeTas<int>(),
713
+ nat: createBigNumberTypeTas<nat>(),
714
+ mutez: createBigNumberTypeTas<mutez>(),
715
+ tez: createBigNumberTypeTas<tez>(),
716
+
717
+ map: asMap,
718
+ bigMap: asBigMap,
719
+
720
+ // Operations
721
+ add,
722
+ subtract,
723
+
724
+ // To number
725
+ number: (value: string | BigNumber) => Number(value + ''),
726
+ };
727
+ `;
728
+
729
+ // src/type-utils-file-content.ts
730
+ var typeUtilsFileContent = `
731
+ import { ContractAbstraction, ContractMethod, ContractMethodObject, ContractProvider, Wallet } from '@taquito/taquito';
732
+
733
+ type BaseContractType = { methods: unknown, methodsObject: unknown, storage: unknown };
734
+
735
+ type ContractMethodsOf<T extends ContractProvider | Wallet, TContract extends BaseContractType> = {
736
+ [M in keyof TContract['methods']]:
737
+ TContract['methods'][M] extends (...args: infer A) => unknown
738
+ ? (...args: A) => ContractMethod<T>
739
+ : never
740
+ };
741
+ type ContractMethodsObjectsOf<T extends ContractProvider | Wallet, TContract extends BaseContractType> = {
742
+ [M in keyof TContract['methodsObject']]:
743
+ TContract['methodsObject'][M] extends (...args: infer A) => unknown
744
+ ? (...args: A) => ContractMethodObject<T>
745
+ : never
746
+ };
747
+ type ContractStorageOf<TContract extends BaseContractType> = TContract['storage'];
748
+
749
+ export type ContractAbstractionFromContractType<TContract extends BaseContractType> =
750
+ ContractAbstraction<ContractProvider,
751
+ ContractMethodsOf<ContractProvider, TContract>,
752
+ ContractMethodsObjectsOf<ContractProvider, TContract>,
753
+ {},
754
+ {},
755
+ ContractStorageOf<TContract>
756
+ >;
757
+
758
+ export type WalletContractAbstractionFromContractType<TContract extends BaseContractType> =
759
+ ContractAbstraction<Wallet,
760
+ ContractMethodsOf<Wallet, TContract>,
761
+ ContractMethodsObjectsOf<Wallet, TContract>,
762
+ {},
763
+ {},
764
+ ContractStorageOf<TContract>
765
+ >;
766
+ `;
767
+
768
+ // src/cli-process.ts
769
+ var fs = {
770
+ mkdir: (0, import_util.promisify)(import_fs.default.mkdir),
771
+ copyFile: (0, import_util.promisify)(import_fs.default.copyFile),
772
+ readdir: (0, import_util.promisify)(import_fs.default.readdir),
773
+ readFile: (0, import_util.promisify)(import_fs.default.readFile),
774
+ writeFile: (0, import_util.promisify)(import_fs.default.writeFile),
775
+ stat: (0, import_util.promisify)(import_fs.default.stat),
776
+ exists: import_fs.default.existsSync
777
+ };
778
+ var getAllFiles = async (rootPath, filter) => {
779
+ const allFiles = [];
780
+ const getAllFilesRecursive = async (dirPath) => {
781
+ let files = await fs.readdir(dirPath, { withFileTypes: true });
782
+ for (const f of files) {
783
+ const subPath = import_path.default.resolve(dirPath, f.name);
784
+ if (f.isDirectory()) {
785
+ await getAllFilesRecursive(subPath);
786
+ continue;
787
+ }
788
+ if (!filter(subPath)) {
789
+ continue;
790
+ }
791
+ allFiles.push(subPath);
792
+ }
793
+ };
794
+ await getAllFilesRecursive(rootPath);
795
+ return allFiles;
796
+ };
797
+ var generateContractTypesProcessContractFiles = async ({
798
+ inputTzContractDirectory,
799
+ inputFiles,
800
+ outputTypescriptDirectory,
801
+ format,
802
+ typeAliasMode
803
+ }) => {
804
+ console.log(
805
+ `Generating Types: ${import_path.default.resolve(inputTzContractDirectory)} => ${import_path.default.resolve(outputTypescriptDirectory)}`
806
+ );
807
+ const ext = "." + format;
808
+ const filesAll = await getAllFiles(inputTzContractDirectory, (x) => x.endsWith(ext));
809
+ const files = inputFiles ? filesAll.filter((f) => inputFiles.some((inputFile) => f.endsWith(inputFile))) : filesAll;
810
+ console.log(`Contracts Found: ${[``, ...files].join(`
811
+ - `)}`);
812
+ const typeAliasImportPath = `@taquito/contract-type-generator`;
813
+ const typeAliasData = typeAliasMode === "local" ? { mode: typeAliasMode, fileContent: typeAliasesFileContent } : typeAliasMode === "file" ? { mode: typeAliasMode, importPath: `./type-aliases` } : typeAliasMode === "library" ? { mode: typeAliasMode, importPath: typeAliasImportPath } : { mode: "simple" };
814
+ if (typeAliasMode === "file") {
815
+ await fs.mkdir(outputTypescriptDirectory, { recursive: true });
816
+ await fs.writeFile(import_path.default.join(outputTypescriptDirectory, "./type-aliases.ts"), typeAliasesFileContent);
817
+ }
818
+ const typeUtilsData = { importPath: `./type-utils` };
819
+ await fs.mkdir(outputTypescriptDirectory, { recursive: true });
820
+ await fs.writeFile(import_path.default.join(outputTypescriptDirectory, "./type-utils.ts"), typeUtilsFileContent);
821
+ for (const fullPath of files) {
822
+ const fileRelativePath = fullPath.replace(import_path.default.resolve(inputTzContractDirectory), "");
823
+ const fileName = fileRelativePath.replace(ext, "");
824
+ const inputFilePath = import_path.default.join(inputTzContractDirectory, fileRelativePath);
825
+ const typesOutputFilePath = import_path.default.join(outputTypescriptDirectory, fileRelativePath.replace(ext, `.types.ts`));
826
+ const codeContentOutputFilePath = import_path.default.join(outputTypescriptDirectory, fileRelativePath.replace(ext, `.code.ts`));
827
+ const schemaContentOutputFilePath = import_path.default.join(
828
+ outputTypescriptDirectory,
829
+ fileRelativePath.replace(ext, `.schema.json`)
830
+ );
831
+ console.log(`Processing ${fileRelativePath}...`);
832
+ try {
833
+ const contractTypeName = normalizeContractName(fileName);
834
+ const michelsonCode = await fs.readFile(inputFilePath, { encoding: `utf8` });
835
+ const {
836
+ schemaOutput,
837
+ typescriptCodeOutput: { typesFileContent, contractCodeFileContent }
838
+ } = generateContractTypesFromMichelsonCode(michelsonCode, contractTypeName, format, typeAliasData, typeUtilsData);
839
+ await fs.mkdir(import_path.default.dirname(typesOutputFilePath), { recursive: true });
840
+ await fs.writeFile(typesOutputFilePath, typesFileContent);
841
+ await fs.writeFile(codeContentOutputFilePath, contractCodeFileContent);
842
+ const debugSchema = false;
843
+ if (debugSchema) {
844
+ await fs.writeFile(schemaContentOutputFilePath, JSON.stringify(schemaOutput, null, 2));
845
+ }
846
+ } catch (err) {
847
+ console.error(`\u274C Could not process ${fileRelativePath}`, { err });
848
+ }
849
+ }
850
+ };
851
+
852
+ // tasks.ts
853
+ var getContractAbspath = (contractFilename, parsedArgs) => (0, import_path2.join)(parsedArgs.config.artifactsDir, /\.tz$/.test(contractFilename) ? contractFilename : `${contractFilename}.tz`);
854
+ var generateContractTypes = (parsedArgs) => async (contractFilename) => {
855
+ const contractAbspath = getContractAbspath(contractFilename, parsedArgs);
856
+ await generateContractTypesProcessContractFiles({
857
+ inputTzContractDirectory: parsedArgs.config.artifactsDir,
858
+ inputFiles: [contractAbspath],
859
+ outputTypescriptDirectory: parsedArgs.typescriptDir || "types",
860
+ format: "tz",
861
+ typeAliasMode: parsedArgs.typeAliasMode ?? "file"
862
+ });
863
+ return `${contractFilename}: Types generated`;
864
+ };
865
+ var generateContractTypesAll = async (parsedArgs) => {
866
+ const files = await (0, import_fast_glob.default)("**/*.tz", { cwd: parsedArgs.config.artifactsDir });
867
+ return await Promise.all(files.map(generateContractTypes(parsedArgs)));
868
+ };
869
+ var generateTypes = (parsedArgs) => {
870
+ parsedArgs.typescriptDir = parsedArgs.typescriptDir || "types";
871
+ console.log("generateTypes", {
872
+ typescriptDir: parsedArgs.typescriptDir
873
+ });
874
+ const p = parsedArgs.contract ? generateContractTypes(parsedArgs)(parsedArgs.contract) : generateContractTypesAll(parsedArgs);
875
+ return p.then((data) => {
876
+ console.log(
877
+ Array.isArray(data) ? data.join("\n") : data
878
+ );
879
+ });
880
+ };
881
+ var tasks = {
882
+ generateTypes
883
+ };
884
+
885
+ // index.ts
886
+ import_node_sdk.Plugin.create((i18n) => ({
887
+ alias: "contract-types",
888
+ schema: "1.0",
889
+ version: "0.1",
890
+ tasks: [
891
+ import_node_sdk.Task.create({
892
+ task: "generate types",
893
+ command: "generate types [typescriptDir]",
894
+ description: "Generate types for a contract to be used with taquito",
895
+ positionals: [
896
+ import_node_sdk.PositionalArg.create({
897
+ placeholder: "typescriptDir",
898
+ description: "The output directory for the generated type files",
899
+ defaultValue: "types"
900
+ })
901
+ ],
902
+ options: [
903
+ import_node_sdk.Option.create({
904
+ shortFlag: "t",
905
+ flag: "typeAliasMode",
906
+ choices: ["file", "simple"],
907
+ description: "The type aliases used in the generated types"
908
+ })
909
+ ],
910
+ aliases: ["gen types", "gentypes"],
911
+ handler: "proxy"
912
+ })
913
+ ],
914
+ proxy: tasks.generateTypes
915
+ }), process.argv);
916
+ // Annotate the CommonJS export names for ESM import in node:
917
+ 0 && (module.exports = {
918
+ generateContractTypesProcessContractFiles
919
+ });
920
+ //# sourceMappingURL=index.cjs.map