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