@taqueria/lib-ligo 0.40.10

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/index.mjs ADDED
@@ -0,0 +1,700 @@
1
+ // index.ts
2
+ import { Option, Plugin, PositionalArg, Task, Template } from "@taqueria/node-sdk";
3
+
4
+ // createContract.ts
5
+ import { sendAsyncErr } from "@taqueria/node-sdk";
6
+ import { writeFile } from "fs/promises";
7
+
8
+ // ligo_templates.ts
9
+ var mligo_template = `
10
+ type storage = int
11
+ type return = operation list * storage
12
+
13
+ (* Three entrypoints *)
14
+ [@entry] let increment (delta : int) (store : storage) : return =
15
+ [], store + delta
16
+ [@entry] let decrement (delta : int) (store : storage) : return =
17
+ [], store - delta
18
+ [@entry] let reset (() : unit) (_ : storage) : return =
19
+ [], 0
20
+ `;
21
+ var jsligo_template = `
22
+ type storage = int;
23
+ type ret = [list<operation>, storage];
24
+
25
+ // Three entrypoints
26
+
27
+ // @entry
28
+ const increment = (delta : int, store : storage) : ret =>
29
+ [list([]), store + delta];
30
+
31
+ // @entry
32
+ const decrement = (delta : int, store : storage) : ret =>
33
+ [list([]), store - delta];
34
+
35
+ // @entry
36
+ const reset = (_ : unit, _ : storage) : ret =>
37
+ [list([]), 0];
38
+ `;
39
+
40
+ // createContract.ts
41
+ var getLigoTemplate = async (contractName, syntax) => {
42
+ const matchResult = contractName.match(/\.[^.]+$/);
43
+ const ext = matchResult ? matchResult[0].substring(1) : null;
44
+ if (syntax === "mligo")
45
+ return mligo_template;
46
+ if (syntax === "jsligo")
47
+ return jsligo_template;
48
+ if (syntax === void 0) {
49
+ if (ext === "mligo")
50
+ return mligo_template;
51
+ if (ext === "jsligo")
52
+ return jsligo_template;
53
+ return sendAsyncErr(
54
+ `Unable to infer LIGO syntax from "${contractName}". Please specify a LIGO syntax via the --syntax option`
55
+ );
56
+ } else {
57
+ return sendAsyncErr(`"${syntax}" is not a valid syntax. Please specify a valid LIGO syntax`);
58
+ }
59
+ };
60
+ var createContract = (args) => {
61
+ const unsafeOpts = args;
62
+ const contractName = unsafeOpts.sourceFileName;
63
+ const syntax = unsafeOpts.syntax;
64
+ const contractsDir = `${args.config.projectDir}/${args.config.contractsDir}`;
65
+ return getLigoTemplate(contractName, syntax).then((ligo_template) => writeFile(`${contractsDir}/${contractName}`, ligo_template));
66
+ };
67
+ var createContract_default = createContract;
68
+
69
+ // main.ts
70
+ import { sendAsyncErr as sendAsyncErr5, sendAsyncRes } from "@taqueria/node-sdk";
71
+
72
+ // common.ts
73
+ import { getDockerImage, sendErr } from "@taqueria/node-sdk";
74
+ import { join } from "path";
75
+ var getInputFilenameAbsPath = (parsedArgs, sourceFile) => join(parsedArgs.config.projectDir, parsedArgs.config.contractsDir ?? "contracts", sourceFile);
76
+ var getInputFilenameRelPath = (parsedArgs, sourceFile) => join(parsedArgs.config.contractsDir ?? "contracts", sourceFile);
77
+ var formatLigoError = (err) => {
78
+ let result = err.message.replace(/Command failed.+?\n/, "");
79
+ if (result.includes("An internal error ocurred. Please, contact the developers.") && result.includes("Module Contract not found with last Contract.")) {
80
+ result = `By convention, Taqueria expects you to import your contract with Contract as the module name.
81
+ For instance, if you have a contract in a file called "increment.mligo", in your parameter/storage list file you must include #import "Increment.mligo" "Contract" for compilation to be successful.`;
82
+ }
83
+ err.message = result.replace(
84
+ "An internal error ocurred. Please, contact the developers.",
85
+ "The LIGO compiler experienced an internal error. Please contact the LIGO developers."
86
+ );
87
+ return err;
88
+ };
89
+ var emitExternalError = (errs, sourceFile) => {
90
+ sendErr(`
91
+ === Error messages for ${sourceFile} ===`);
92
+ const errors = Array.isArray(errs) ? errs : [errs];
93
+ errors.map((err) => {
94
+ err instanceof Error ? sendErr(err.message) : sendErr(err);
95
+ });
96
+ sendErr(`===`);
97
+ };
98
+ var configure = (dockerImage, dockerImageEnvVar) => ({
99
+ LIGO_DEFAULT_IMAGE: dockerImage,
100
+ LIGO_IMAGE_ENV_VAR: dockerImageEnvVar,
101
+ getLigoDockerImage: () => getDockerImage(dockerImage, dockerImageEnvVar)
102
+ });
103
+
104
+ // compile.ts
105
+ import {
106
+ execCmd,
107
+ getArch,
108
+ getArtifactsDir,
109
+ sendErr as sendErr2,
110
+ sendJsonRes,
111
+ sendWarn
112
+ } from "@taqueria/node-sdk";
113
+ import { createReadStream } from "fs";
114
+ import { access, writeFile as writeFile2 } from "fs/promises";
115
+ import { basename, join as join2 } from "path";
116
+ import * as readline from "readline";
117
+ var COMPILE_ERR_MSG = "Not compiled";
118
+ var isStorageKind = (exprKind) => exprKind === "storage" || exprKind === "default_storage";
119
+ var isSupportedLigoSyntax = (sourceFile) => /\.(mligo|jsligo)$/.test(sourceFile);
120
+ var isUnsupportedLigoSyntax = (sourceFile) => /\.(ligo|religo)$/.test(sourceFile);
121
+ var isLIGOFile = (sourceFile) => isSupportedLigoSyntax(sourceFile) || isUnsupportedLigoSyntax(sourceFile);
122
+ var isStorageListFile = (sourceFile) => /.+\.(storageList|storages)\.(ligo|religo|mligo|jsligo)$/.test(sourceFile);
123
+ var isParameterListFile = (sourceFile) => /.+\.(parameterList|parameters)\.(ligo|religo|mligo|jsligo)$/.test(sourceFile);
124
+ var extractExt = (path) => {
125
+ const matchResult = path.match(/\.(ligo|religo|mligo|jsligo)$/);
126
+ return matchResult ? matchResult[0] : "";
127
+ };
128
+ var removeExt = (path) => {
129
+ const extRegex = new RegExp(extractExt(path));
130
+ return path.replace(extRegex, "");
131
+ };
132
+ var isOutputFormatJSON = (parsedArgs) => parsedArgs.json;
133
+ var getOutputContractFilename = (parsedArgs, module) => {
134
+ const ext = isOutputFormatJSON(parsedArgs) ? ".json" : ".tz";
135
+ return join2(getArtifactsDir(parsedArgs), `${module.moduleName}${ext}`);
136
+ };
137
+ var getOutputExprFilename = (parsedArgs, module, exprKind, exprName) => {
138
+ const contractName = module.moduleName;
139
+ const ext = isOutputFormatJSON(parsedArgs) ? ".json" : ".tz";
140
+ const outputFile = exprKind === "default_storage" ? `${contractName}.default_storage${ext}` : `${contractName}.${exprKind}.${exprName}${ext}`;
141
+ return join2(getArtifactsDir(parsedArgs), `${outputFile}`);
142
+ };
143
+ var getExprNames = (parsedArgs, sourceFile) => {
144
+ return new Promise((resolve, reject) => {
145
+ const inputFilePath = getInputFilenameAbsPath(parsedArgs, sourceFile);
146
+ const readInterface = readline.createInterface({
147
+ input: createReadStream(inputFilePath),
148
+ output: process.stdout
149
+ });
150
+ const variableNames = [];
151
+ readInterface.on("line", function(line) {
152
+ if (!line.trim().startsWith("//")) {
153
+ const matches = line.match(/(?<=\s*(let|const)\s+)[a-zA-Z0-9_]+/g);
154
+ if (matches) {
155
+ variableNames.push(...matches);
156
+ }
157
+ }
158
+ });
159
+ readInterface.on("close", function() {
160
+ resolve(variableNames);
161
+ });
162
+ });
163
+ };
164
+ var getInitialMessage = (pair, module) => {
165
+ const messages = {
166
+ "mligo-file-main": `// When this file was created, the smart contract was defined with a main function that was not within a named module. As such, the examples below are written with that assumption in mind.`,
167
+ "mligo-file-entry": `// When this file was created, the smart contract was defined with an entrypoint using \`@entry\` that was not within a named module. As such, the examples below are written with that assumption in mind.`,
168
+ "mligo-module-main": `// When this file was created, the smart contract was defined with a main function that was within a named module. As such, the examples below are written with that assumption in mind.`,
169
+ "mligo-module-entry": `// When this file was created, the smart contract was defined with an entrypoint using \`@entry\` that was within a named module. As such, the examples below are written with that assumption in mind.`,
170
+ "jsligo-file-main": `// When this file was created, the smart contract was defined with a main function that was not within a namespace. As such, the examples below are written with that assumption in mind.
171
+ // NOTE: The "storage" type should be exported from the contract file (${module.sourceFile})`,
172
+ "jsligo-file-entry": `// When this file was created, the smart contract was defined with an entrypoint using \`@entry\` that was not within a namespace. As such, the examples below are written with that assumption in mind.`,
173
+ "jsligo-module-main": `// When this file was created, the smart contract was defined with a main function that was within a namespace. As such, the examples below are written with that assumption in mind.
174
+ // NOTE: The "storage" type should be exported from the contract file (${module.sourceFile})`,
175
+ "jsligo-module-entry": `// When this file was created, the smart contract was defined with an entrypoint using \`@entry\` that was within a namespace. As such, the examples below are written with that assumption in mind.`
176
+ // ... any other combinations
177
+ };
178
+ return messages[pair] || "// This file was created by Taqueria.";
179
+ };
180
+ var getCommonMsg = (langType, listType) => {
181
+ const varKeyword = langType === "mligo" ? "let" : "const";
182
+ const commonMsgForStorage = `// IMPORTANT: We suggest always explicitly typing your storage values:
183
+ // E.g.: \`${varKeyword} storage: int = 10\` or \`${varKeyword} storage: Contract.storage = 10\``;
184
+ const commonMsgForParameter = `// IMPORTANT: We suggest always explicitly typing your parameter values:
185
+ // E.g.: \`${varKeyword} parameter: int = 10\` or \`${varKeyword} parameter: Contract.parameter = 10\``;
186
+ return listType === "storage" ? commonMsgForStorage : commonMsgForParameter;
187
+ };
188
+ var getContent = (moduleInfo, listType) => {
189
+ const linkToContract = `#import "${moduleInfo.sourceFile}" "Contract"`;
190
+ const pair = `${moduleInfo.syntax}-${moduleInfo.type}`;
191
+ const initialMsg = getInitialMessage(pair, moduleInfo);
192
+ const commonMsg = getCommonMsg(moduleInfo.syntax, listType);
193
+ return `${linkToContract}
194
+
195
+ ${initialMsg}
196
+
197
+ ${commonMsg}`;
198
+ };
199
+ var initContentForStorage = (moduleInfo) => getContent(moduleInfo, "storage");
200
+ var initContentForParameter = (moduleInfo) => getContent(moduleInfo, "parameter");
201
+ var inject = (commonObj) => {
202
+ const { getLigoDockerImage } = commonObj;
203
+ const getListDeclarationsCmd = async (parsedArgs, sourceFile) => {
204
+ const projectDir = process.env.PROJECT_DIR ?? parsedArgs.projectDir;
205
+ if (!projectDir)
206
+ throw new Error(`No project directory provided`);
207
+ const baseCmd = `DOCKER_DEFAULT_PLATFORM=linux/amd64 docker run --rm -v "${projectDir}":/project -w /project -u $(id -u):$(id -g) ${getLigoDockerImage()} info list-declarations`;
208
+ const inputFile = getInputFilenameRelPath(parsedArgs, sourceFile);
209
+ const flags = "--display-format json";
210
+ const cmd = `${baseCmd} ${inputFile} ${flags}`;
211
+ return cmd;
212
+ };
213
+ const listContractModules = async (parsedArgs, sourceFile) => {
214
+ try {
215
+ await getArch();
216
+ const cmd = await getListDeclarationsCmd(parsedArgs, sourceFile);
217
+ const { stderr, stdout } = await execCmd(cmd);
218
+ if (stderr.length > 0)
219
+ return Promise.reject(stderr);
220
+ return JSON.parse(stdout).declarations.reduce(
221
+ (acc, decl) => {
222
+ const srcFile = removeExt(basename(sourceFile));
223
+ const syntax = extractExt(sourceFile).replace(".", "");
224
+ if (decl === "main") {
225
+ return [...acc, { moduleName: srcFile, sourceName: sourceFile, sourceFile, type: "file-main", syntax }];
226
+ } else if (decl === "$main") {
227
+ return [...acc, { moduleName: srcFile, sourceName: sourceFile, sourceFile, type: "file-entry", syntax }];
228
+ } else if (decl.endsWith(".main")) {
229
+ const moduleName = decl.replace(/\.main$/, "");
230
+ return [...acc, {
231
+ moduleName,
232
+ sourceName: `${sourceFile}/${moduleName}`,
233
+ sourceFile,
234
+ type: "module-main",
235
+ syntax
236
+ }];
237
+ } else if (decl.endsWith(".$main")) {
238
+ const moduleName = decl.replace(/\.\$main$/, "");
239
+ return [...acc, {
240
+ moduleName,
241
+ sourceName: `${sourceFile}/${moduleName}`,
242
+ sourceFile,
243
+ type: "module-entry",
244
+ syntax
245
+ }];
246
+ }
247
+ return acc;
248
+ },
249
+ []
250
+ );
251
+ } catch (err) {
252
+ emitExternalError(err, sourceFile);
253
+ return [];
254
+ }
255
+ };
256
+ const getCompileContractCmd = async (parsedArgs, sourceFile, module) => {
257
+ const projectDir = process.env.PROJECT_DIR ?? parsedArgs.projectDir;
258
+ if (!projectDir)
259
+ throw new Error(`No project directory provided`);
260
+ const baseCmd = `DOCKER_DEFAULT_PLATFORM=linux/amd64 docker run --rm -v "${projectDir}":/project -w /project -u $(id -u):$(id -g) ${getLigoDockerImage()} compile contract`;
261
+ const inputFile = getInputFilenameRelPath(parsedArgs, sourceFile);
262
+ const outputFile = `-o ${getOutputContractFilename(parsedArgs, module)}`;
263
+ const flags = isOutputFormatJSON(parsedArgs) ? " --michelson-format json " : "";
264
+ const moduleFlag = module.type.startsWith("file-") ? "" : `-m ${module.moduleName}`;
265
+ const cmd = `${baseCmd} ${inputFile} ${outputFile} ${flags}${moduleFlag}`;
266
+ return cmd;
267
+ };
268
+ const compileContract = async (parsedArgs, sourceFile, module) => {
269
+ try {
270
+ await getArch();
271
+ const cmd = await getCompileContractCmd(parsedArgs, sourceFile, module);
272
+ const { stderr } = await execCmd(cmd);
273
+ if (stderr.length > 0)
274
+ sendWarn(stderr);
275
+ return {
276
+ source: module.sourceName,
277
+ artifact: getOutputContractFilename(parsedArgs, module)
278
+ };
279
+ } catch (err) {
280
+ emitExternalError(err, sourceFile);
281
+ return {
282
+ source: module.sourceName,
283
+ artifact: COMPILE_ERR_MSG
284
+ };
285
+ }
286
+ };
287
+ const getCompileExprCmd = (parsedArgs, sourceFile, module, exprKind, exprName) => {
288
+ const projectDir = process.env.PROJECT_DIR ?? parsedArgs.projectDir;
289
+ if (!projectDir)
290
+ throw new Error(`No project directory provided`);
291
+ const compilerType = isStorageKind(exprKind) ? "storage" : "parameter";
292
+ const baseCmd = `DOCKER_DEFAULT_PLATFORM=linux/amd64 docker run --rm -v "${projectDir}":/project -w /project -u $(id -u):$(id -g) ${getLigoDockerImage()} compile ${compilerType}`;
293
+ const inputFile = getInputFilenameRelPath(parsedArgs, sourceFile);
294
+ const outputFile = `-o ${getOutputExprFilename(parsedArgs, module, exprKind, exprName)}`;
295
+ const flags = isOutputFormatJSON(parsedArgs) ? " --michelson-format json " : "";
296
+ const moduleFlag = (() => {
297
+ switch (module.type) {
298
+ case "file-main":
299
+ case "file-entry":
300
+ return "-m Contract";
301
+ default:
302
+ return `-m Contract.${module.moduleName}`;
303
+ }
304
+ })();
305
+ const cmd = `${baseCmd} ${inputFile} ${exprName} ${outputFile} ${flags} ${moduleFlag}`;
306
+ return cmd;
307
+ };
308
+ const compileExpr = (parsedArgs, sourceFile, module, exprKind) => (exprName) => {
309
+ return getArch().then(() => getCompileExprCmd(parsedArgs, sourceFile, module, exprKind, exprName)).then(execCmd).then(({ stderr }) => {
310
+ if (stderr.length > 0)
311
+ sendWarn(stderr);
312
+ const artifactName = getOutputExprFilename(parsedArgs, module, exprKind, exprName);
313
+ return {
314
+ source: module.sourceName,
315
+ artifact: artifactName
316
+ };
317
+ }).catch((err) => {
318
+ return {
319
+ source: module.sourceName,
320
+ artifact: `${exprName} in ${sourceFile} not compiled`,
321
+ err
322
+ };
323
+ });
324
+ };
325
+ const compileExprs = async (parsedArgs, sourceFile, module, exprKind) => {
326
+ let exprs = [];
327
+ try {
328
+ exprs = await getExprNames(parsedArgs, sourceFile);
329
+ } catch (err) {
330
+ emitExternalError(err, sourceFile);
331
+ return [{
332
+ source: module.sourceName,
333
+ artifact: `No ${isStorageKind(exprKind) ? "storage" : "parameter"} expressions compiled`
334
+ }];
335
+ }
336
+ const results = await Promise.all(exprs.map(async (exprName, index) => {
337
+ const compileResult = await compileExpr(
338
+ parsedArgs,
339
+ sourceFile,
340
+ module,
341
+ exprKind === "storage" && index === 0 ? "default_storage" : exprKind
342
+ )(exprName);
343
+ return compileResult;
344
+ }));
345
+ const errors = results.reduce(
346
+ (acc, result) => {
347
+ if (result.err) {
348
+ if (!(result.err instanceof Error))
349
+ return [...acc, result.err];
350
+ const ligoErrs = acc.filter((err) => err instanceof Error).map((err) => err.message);
351
+ const formattedError = formatLigoError(result.err);
352
+ return ligoErrs.includes(formattedError.message) ? acc : [...acc, formattedError];
353
+ }
354
+ return acc;
355
+ },
356
+ []
357
+ );
358
+ const retval = results.map(({ source, artifact }) => ({ source, artifact }));
359
+ if (errors.length)
360
+ emitExternalError(errors, sourceFile);
361
+ return retval;
362
+ };
363
+ const compileContractWithStorageAndParameter = async (parsedArgs, sourceFile, module) => {
364
+ const contractCompileResult = await compileContract(parsedArgs, sourceFile, module);
365
+ if (contractCompileResult.artifact === COMPILE_ERR_MSG)
366
+ return [contractCompileResult];
367
+ debugger;
368
+ const storageListFile = `${module.moduleName}.storageList${extractExt(sourceFile)}`;
369
+ const storageListFilename = getInputFilenameAbsPath(parsedArgs, storageListFile);
370
+ const storageCompileResult = await access(storageListFilename).then(() => compileExprs(parsedArgs, storageListFile, module, "storage")).catch(() => {
371
+ sendWarn(
372
+ `Note: storage file associated with "${module.moduleName}" can't be found, so "${storageListFile}" has been created for you. Use this file to define all initial storage values for this contract
373
+ `
374
+ );
375
+ return writeFile2(storageListFilename, initContentForStorage(module), "utf8");
376
+ });
377
+ const parameterListFile = `${module.moduleName}.parameterList${extractExt(sourceFile)}`;
378
+ const parameterListFilename = getInputFilenameAbsPath(parsedArgs, parameterListFile);
379
+ const parameterCompileResult = await access(parameterListFilename).then(() => compileExprs(parsedArgs, parameterListFile, module, "parameter")).catch(() => {
380
+ sendWarn(
381
+ `Note: parameter file associated with "${module.moduleName}" can't be found, so "${parameterListFile}" has been created for you. Use this file to define all parameter values for this contract
382
+ `
383
+ );
384
+ return writeFile2(parameterListFilename, initContentForParameter(module), "utf8");
385
+ });
386
+ const storageArtifacts = storageCompileResult ? storageCompileResult.map((res) => res.artifact).join("\n") : "";
387
+ const parameterArtifacts = parameterCompileResult ? parameterCompileResult.map((res) => res.artifact).join("\n") : "";
388
+ const combinedArtifact = [
389
+ contractCompileResult.artifact,
390
+ storageArtifacts,
391
+ parameterArtifacts
392
+ ].filter(Boolean).join("\n");
393
+ const combinedRow = {
394
+ source: module.sourceName,
395
+ artifact: combinedArtifact
396
+ };
397
+ return [combinedRow];
398
+ };
399
+ return {
400
+ getLigoDockerImage,
401
+ getListDeclarationsCmd,
402
+ listContractModules,
403
+ getCompileContractCmd,
404
+ compileContract,
405
+ getCompileExprCmd,
406
+ compileExpr,
407
+ compileExprs,
408
+ compileContractWithStorageAndParameter
409
+ };
410
+ };
411
+ var compile = async (commonObj, parsedArgs) => {
412
+ const { listContractModules, compileContractWithStorageAndParameter } = inject(commonObj);
413
+ const sourceFile = parsedArgs.sourceFile;
414
+ if (!isLIGOFile(sourceFile)) {
415
+ sendErr2(`${sourceFile} is not a LIGO file`);
416
+ return;
417
+ }
418
+ if (isStorageListFile(sourceFile) || isParameterListFile(sourceFile)) {
419
+ sendErr2(`Storage and parameter list files are not meant to be compiled directly`);
420
+ return;
421
+ }
422
+ if (isUnsupportedLigoSyntax(sourceFile)) {
423
+ sendErr2(`Unsupported LIGO syntax detected in ${sourceFile}. Note, we only support .jsligo and .mligo files.`);
424
+ return;
425
+ }
426
+ try {
427
+ const modules = await listContractModules(parsedArgs, sourceFile);
428
+ if (modules.length === 0) {
429
+ return sendJsonRes([
430
+ {
431
+ source: sourceFile,
432
+ artifact: `No contract modules found in "${sourceFile}"`
433
+ }
434
+ ]);
435
+ }
436
+ let allCompileResults = [];
437
+ for (const module of modules) {
438
+ if (parsedArgs.module && parsedArgs.module !== module.moduleName)
439
+ continue;
440
+ const compileResults = await compileContractWithStorageAndParameter(parsedArgs, sourceFile, module);
441
+ allCompileResults = allCompileResults.concat(compileResults);
442
+ }
443
+ sendJsonRes(allCompileResults, { footer: `
444
+ Compiled ${allCompileResults.length} contract(s) in "${sourceFile}"` });
445
+ } catch (err) {
446
+ sendErr2(`Error processing "${sourceFile}": ${err}`);
447
+ }
448
+ };
449
+ var compile_default = compile;
450
+
451
+ // compile-all.ts
452
+ import { sendErr as sendErr3, sendJsonRes as sendJsonRes2 } from "@taqueria/node-sdk";
453
+ import glob from "fast-glob";
454
+ import { join as join3 } from "path";
455
+ var compileAll = async (commonObj, parsedArgs) => {
456
+ const { listContractModules, compileContractWithStorageAndParameter } = inject(commonObj);
457
+ let compilePromises = [];
458
+ const contractFilenames = await glob(
459
+ ["**/*.ligo", "**/*.religo", "**/*.mligo", "**/*.jsligo"],
460
+ {
461
+ cwd: join3(parsedArgs.config.projectDir, parsedArgs.config.contractsDir ?? "contracts"),
462
+ absolute: false
463
+ }
464
+ );
465
+ for (const filename of contractFilenames) {
466
+ if (isStorageListFile(filename) || isParameterListFile(filename))
467
+ continue;
468
+ const moduleNames = await listContractModules(parsedArgs, filename);
469
+ for (const moduleName of moduleNames) {
470
+ compilePromises.push(compileContractWithStorageAndParameter(parsedArgs, filename, moduleName));
471
+ }
472
+ }
473
+ return Promise.all(compilePromises).then((tables) => tables.flat()).then(sendJsonRes2).catch((err) => sendErr3(err, false));
474
+ };
475
+ var compile_all_default = compileAll;
476
+
477
+ // ligo.ts
478
+ import { execCmd as execCmd2, getArch as getArch2, sendAsyncErr as sendAsyncErr3, sendRes as sendRes2, spawnCmd } from "@taqueria/node-sdk";
479
+ import { readJsonFile, writeJsonFile } from "@taqueria/node-sdk";
480
+ import { join as join4 } from "path";
481
+ var getArbitraryLigoCmd = (commonObj, parsedArgs, uid, gid, userArgs) => {
482
+ const projectDir = process.env.PROJECT_DIR ?? parsedArgs.projectDir;
483
+ if (!projectDir)
484
+ throw `No project directory provided`;
485
+ const userMap = uid && gid ? `${uid}:${gid}` : uid;
486
+ const userMapArgs = uid ? ["-u", userMap] : [];
487
+ const binary = "docker";
488
+ const baseArgs = [
489
+ "run",
490
+ "--rm",
491
+ "-v",
492
+ `${projectDir}:/project`,
493
+ "-w",
494
+ "/project",
495
+ ...userMapArgs,
496
+ commonObj.getLigoDockerImage()
497
+ ];
498
+ const processedUserArgs = userArgs.split(" ").map((arg) => arg.startsWith("\\-") ? arg.substring(1) : arg).filter(
499
+ (arg) => arg
500
+ );
501
+ const args = [...baseArgs, ...processedUserArgs, "--skip-analytics"];
502
+ const envVars = { "DOCKER_DEFAULT_PLATFORM": "linux/amd64" };
503
+ return [
504
+ [binary, ...args].join(" "),
505
+ envVars
506
+ ];
507
+ };
508
+ var ensureEsyExists = async (parsedArgs) => {
509
+ const esyJsonPath = join4(parsedArgs.projectDir, "esy.json");
510
+ try {
511
+ return await readJsonFile(esyJsonPath);
512
+ } catch {
513
+ return await writeJsonFile(esyJsonPath)({});
514
+ }
515
+ };
516
+ var runArbitraryLigoCmd = (commonObj, parsedArgs, cmd) => ensureEsyExists(parsedArgs).then(getArch2).then(async () => {
517
+ const uid = await execCmd2("id -u");
518
+ const gid = await execCmd2("id -g");
519
+ return [uid.stdout.trim(), gid.stdout.trim()];
520
+ }).then(([uid, gid]) => getArbitraryLigoCmd(commonObj, parsedArgs, uid, gid, cmd)).then(([cmd2, envVars]) => spawnCmd(cmd2, envVars)).then(
521
+ (code) => code !== null && code === 0 ? `Command "${cmd}" ran successfully by LIGO` : `Command "${cmd}" failed. Please check your command`
522
+ ).catch((err) => sendAsyncErr3(`An internal error has occurred: ${err.message}`));
523
+ var ligo = (commonObj, parsedArgs) => {
524
+ const args = parsedArgs.command;
525
+ return runArbitraryLigoCmd(commonObj, parsedArgs, args).then(sendRes2).catch((err) => sendAsyncErr3(err, false));
526
+ };
527
+ var ligo_default = ligo;
528
+
529
+ // test.ts
530
+ import { execCmd as execCmd3, getArch as getArch3, sendAsyncErr as sendAsyncErr4, sendJsonRes as sendJsonRes3, sendWarn as sendWarn2 } from "@taqueria/node-sdk";
531
+ var inject2 = (commonObj) => {
532
+ const { getLigoDockerImage } = commonObj;
533
+ const getTestContractCmd = (parsedArgs, sourceFile) => {
534
+ const projectDir = process.env.PROJECT_DIR ?? parsedArgs.projectDir;
535
+ if (!projectDir)
536
+ throw `No project directory provided`;
537
+ const baseCmd = `DOCKER_DEFAULT_PLATFORM=linux/amd64 docker run --rm -v "${projectDir}":/project -w /project -u $(id -u):$(id -g) ${getLigoDockerImage()} run test`;
538
+ const inputFile = getInputFilenameRelPath(parsedArgs, sourceFile);
539
+ const cmd = `${baseCmd} ${inputFile}`;
540
+ return cmd;
541
+ };
542
+ const testContract = (parsedArgs, sourceFile) => getArch3().then(() => getTestContractCmd(parsedArgs, sourceFile)).then(execCmd3).then(({ stdout, stderr }) => {
543
+ if (stderr.length > 0)
544
+ sendWarn2(stderr);
545
+ const result = "\u{1F389} All tests passed \u{1F389}";
546
+ return {
547
+ contract: sourceFile,
548
+ testResults: stdout.length > 0 ? `${stdout}
549
+ ${result}` : result
550
+ };
551
+ }).catch((err) => {
552
+ emitExternalError(err, sourceFile);
553
+ return {
554
+ contract: sourceFile,
555
+ testResults: "Some tests failed :("
556
+ };
557
+ });
558
+ return {
559
+ testContract,
560
+ getTestContractCmd
561
+ };
562
+ };
563
+ var test = (commonObj, parsedArgs) => {
564
+ const { testContract } = inject2(commonObj);
565
+ const sourceFile = parsedArgs.sourceFile;
566
+ if (!sourceFile)
567
+ return sendAsyncErr4(`No source file provided`);
568
+ return testContract(parsedArgs, sourceFile).then((result) => [result]).then(sendJsonRes3).catch(
569
+ (err) => sendAsyncErr4(err, false)
570
+ );
571
+ };
572
+ var test_default = test;
573
+
574
+ // main.ts
575
+ var main = (dockerImage, dockerImageEnvVar) => (parsedArgs) => {
576
+ const commonObj = configure(dockerImage, dockerImageEnvVar);
577
+ const unsafeOpts = parsedArgs;
578
+ switch (unsafeOpts.task) {
579
+ case "ligo":
580
+ return ligo_default(commonObj, unsafeOpts);
581
+ case "compile":
582
+ return compile_default(commonObj, unsafeOpts);
583
+ case "compile-all":
584
+ return compile_all_default(commonObj, unsafeOpts);
585
+ case "test":
586
+ return test_default(commonObj, parsedArgs);
587
+ case "get-image":
588
+ return sendAsyncRes(commonObj.getLigoDockerImage());
589
+ default:
590
+ return sendAsyncErr5(`${unsafeOpts.task} is not an understood task by the LIGO plugin`);
591
+ }
592
+ };
593
+ var main_default = main;
594
+
595
+ // index.ts
596
+ var configurePlugin = (settings) => {
597
+ const schema = {
598
+ name: settings.name,
599
+ schema: "1.0",
600
+ version: "0.1",
601
+ alias: settings.alias,
602
+ tasks: [
603
+ Task.create({
604
+ task: "ligo",
605
+ command: "ligo",
606
+ description: "This task allows you to run arbitrary LIGO native commands. Note that they might not benefit from the abstractions provided by Taqueria",
607
+ options: [
608
+ Option.create({
609
+ shortFlag: "c",
610
+ flag: "command",
611
+ type: "string",
612
+ description: "The command to be passed to the underlying LIGO binary, wrapped in quotes",
613
+ required: true
614
+ })
615
+ ],
616
+ handler: "proxy",
617
+ encoding: "none"
618
+ }),
619
+ Task.create({
620
+ task: "compile",
621
+ command: "compile <sourceFile>",
622
+ aliases: ["c", "compile-ligo"],
623
+ description: "Compile a smart contract written in a LIGO syntax to Michelson code, along with its associated storage/parameter list files if they are found",
624
+ options: [
625
+ Option.create({
626
+ flag: "json",
627
+ boolean: true,
628
+ description: "Emit JSON-encoded Michelson"
629
+ }),
630
+ Option.create({
631
+ flag: "module",
632
+ shortFlag: "m",
633
+ type: "string",
634
+ description: "The LIGO module to be compiled"
635
+ })
636
+ ],
637
+ handler: "proxy",
638
+ encoding: "json"
639
+ }),
640
+ Task.create({
641
+ task: "compile-all",
642
+ command: "compile-all",
643
+ description: "Compile all main smart contracts written in a LIGO syntax to Michelson code, along with their associated storage/parameter list files if they are found",
644
+ options: [
645
+ Option.create({
646
+ flag: "json",
647
+ boolean: true,
648
+ description: "Emit JSON-encoded Michelson"
649
+ })
650
+ ],
651
+ handler: "proxy",
652
+ encoding: "json"
653
+ }),
654
+ Task.create({
655
+ task: "test",
656
+ command: "test <sourceFile>",
657
+ description: "Test a smart contract written in LIGO",
658
+ handler: "proxy",
659
+ encoding: "json"
660
+ }),
661
+ Task.create({
662
+ task: "get-image",
663
+ command: "get-image",
664
+ description: "Gets the name of the image to be used",
665
+ handler: "proxy",
666
+ hidden: true
667
+ })
668
+ ],
669
+ templates: [
670
+ Template.create({
671
+ template: "contract",
672
+ command: "contract <sourceFileName>",
673
+ description: "Create a LIGO contract with boilerplate code",
674
+ positionals: [
675
+ PositionalArg.create({
676
+ placeholder: "sourceFileName",
677
+ type: "string",
678
+ description: "The name of the LIGO contract to generate"
679
+ })
680
+ ],
681
+ options: [
682
+ Option.create({
683
+ shortFlag: "s",
684
+ flag: "syntax",
685
+ type: "string",
686
+ description: "The syntax used in the contract"
687
+ })
688
+ ],
689
+ handler: createContract_default
690
+ })
691
+ ],
692
+ proxy: main_default(settings.dockerImage, settings.dockerImageEnvVar),
693
+ postInstall: `node ${__dirname}/postinstall.js`
694
+ };
695
+ return Plugin.create(() => settings.configurator ? settings.configurator(schema) : schema, settings.unparsedArgs);
696
+ };
697
+ export {
698
+ configurePlugin
699
+ };
700
+ //# sourceMappingURL=index.mjs.map