@taqueria/plugin-contract-types 0.39.18 → 0.39.20

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