UNPKG

@kubiklabs/wasmkit

Version:

Wasmkit is a development environment to compile, deploy, test, run cosmwasm contracts on different networks.

321 lines (320 loc) 13.8 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.installDependencies = exports.createConfirmationPrompt = exports.createPlayground = exports.createDir = exports.processFilesInFolder = exports.convertTypescriptFileToJson = exports.createContractListJson = exports.printSuggestedCommands = void 0; // import * as yaml from "js-yaml"; // import { error } from "console"; // import { RecordExpression } from "@babel/types"; const chalk_1 = __importDefault(require("chalk")); const fs = __importStar(require("fs")); const path_1 = __importDefault(require("path")); const ts = __importStar(require("typescript")); const checkpoints_1 = require("../../lib/checkpoints"); const errors_1 = require("../core/errors"); const errors_list_1 = require("../core/errors-list"); const initialize_playground_1 = require("./initialize-playground"); function printSuggestedCommands(packageManager, shouldShowInstallationInstructions) { const currDir = process.cwd(); const destinationPath = path_1.default.join(currDir, 'playground'); console.log(`Success! Created project at ${chalk_1.default.greenBright(destinationPath)}.`); console.log(`Begin by typing:`); console.log(chalk_1.default.yellow(` cd playground`)); if (shouldShowInstallationInstructions) { console.log(chalk_1.default.yellow(` ${packageManager} install`)); } console.log(chalk_1.default.yellow(` ${packageManager} start`)); } exports.printSuggestedCommands = printSuggestedCommands; function createContractListJson(contractDir, destinationDir, env) { const files = fs.readdirSync(contractDir); // Get an array of all files in the directory const dest = path_1.default.join(destinationDir, "contractList.json"); const jsonData = {}; for (const file of files) { const fileName = path_1.default.parse(file).name; const filePath = path_1.default.join(contractDir, file); const yamlData = (0, checkpoints_1.loadCheckpoint)(filePath); const temp = Object.keys(yamlData); temp.forEach((keys) => { const info = yamlData[keys]; const checkpointInf = { chainId: env.config.networks[keys].chainId, codeId: info.deployInfo?.codeId, contractAddress: info.instantiateInfo?.[0].contractAddress, contractTag: (info.instantiateInfo?.[0].instantiateTag !== 'default_instantiate') ? info.instantiateInfo?.[0].instantiateTag : undefined }; const data = { [keys]: checkpointInf }; if (jsonData[fileName]) { // Merge existing data with new data jsonData[fileName] = { ...jsonData[fileName], ...data }; } else { // Add new data jsonData[fileName] = data; } }); // let existingData: Record<string, unknown> = {}; NOTE: need not merge, simply overwrite // if (fs.existsSync(dest)) { // const existingContent = fs.readFileSync(dest, "utf8"); // existingData = JSON.parse(existingContent); // } // const mergedData = { ...existingData, ...jsonData }; } // write json schema of all contracts fs.writeFileSync(dest, JSON.stringify(jsonData, null, 2)); } exports.createContractListJson = createContractListJson; function convertTypescriptFileToJson(inputFilePath, outputFilePath, name) { const sourceFile = ts.createSourceFile(inputFilePath, fs.readFileSync(inputFilePath).toString(), ts.ScriptTarget.Latest); const structures = []; function parseNode(node) { if (ts.isClassDeclaration(node)) { const properties = node.members .filter(ts.isPropertyDeclaration) .map((member) => ({ name: member.name.getText(sourceFile), type: member.type?.getText(sourceFile) ?? "unknown", modifiers: member.modifiers?.map((modifier) => modifier.getText(sourceFile)) })); structures.push({ kind: "class", name: node.name?.getText(sourceFile) ?? "unknown", properties }); } else if (ts.isInterfaceDeclaration(node)) { const properties = node.members .filter(ts.isPropertySignature) .map((Member) => ({ name: Member.name.getText(sourceFile), type: Member.type?.getText(sourceFile) ?? "unknown", modifiers: Member.modifiers?.map((modifier) => modifier.getText(sourceFile)) })); structures.push({ kind: "interface", name: node.name?.getText(sourceFile) ?? "unknown", properties }); } else if (ts.isTypeAliasDeclaration(node)) { structures.push({ kind: "typeAlias", name: node.name?.getText(sourceFile) ?? "unknown", properties: [ { name: "type", type: node.type?.getText(sourceFile) ?? "unknown" } ] }); } ts.forEachChild(node, parseNode); } parseNode(sourceFile); const schemaData = structures; const jsonData = { [name]: { schemaData } }; let existingData = {}; // NOTE: need not merge, simply overwrite if (fs.existsSync(outputFilePath)) { const existingContent = fs.readFileSync(outputFilePath, "utf8"); existingData = JSON.parse(existingContent); } const mergedData = { ...existingData, ...jsonData }; fs.writeFileSync(outputFilePath, JSON.stringify(mergedData, null, 2)); } exports.convertTypescriptFileToJson = convertTypescriptFileToJson; function processFilesInFolder(folderPath, destPath) { const files = fs.readdirSync(folderPath); files.forEach((file) => { const contractName = path_1.default.parse(file).name; const fileName = "contractSchema.json"; const schemaDest = path_1.default.join(destPath, fileName); const filePath = path_1.default.join(folderPath, file); convertTypescriptFileToJson(filePath, schemaDest, contractName); }); } exports.processFilesInFolder = processFilesInFolder; function createDir(dir) { fs.mkdir(dir, { recursive: true }, (err) => { if (err) { // TODO: expand this error msg to be more descriptive console.error("error", err); } }); } exports.createDir = createDir; function copyStaticFiles(srcPath, destinationPath, env) { if (env.config.playground?.theme) { const data = env.config.playground.theme; for (const key in data) { if (data[key].length !== 0) { handleStaticFile(path_1.default.join(srcPath, data[key]), path_1.default.join(destinationPath), key); } } } if (env.config.playground?.logoDark) { handleStaticFile(path_1.default.join(srcPath, env.config.playground.logoDark), path_1.default.join(destinationPath), "logoDark"); } if (env.config.playground?.logoLight) { handleStaticFile(path_1.default.join(srcPath, env.config.playground.logoLight), path_1.default.join(destinationPath), "logoLight"); } if (env.config.playground?.favicon) { handleStaticFile(path_1.default.join(srcPath, env.config.playground.favicon), path_1.default.join(destinationPath), "favicon"); } } function handleStaticFile(srcPath, destinationPath, name) { const fileExtension = path_1.default.extname(srcPath); const Img = fs.readFileSync(srcPath); const Dest = path_1.default.join(destinationPath, `${name}${fileExtension}`); fs.writeFileSync(Dest, Img); } function handleSocials(destinationPath, env) { const jsonData = {}; if (env.config.playground?.title) { jsonData.title = env.config.playground.title; } if (env.config.playground?.tagline) { jsonData.tagline = env.config.playground.tagline; } if (env.config.playground?.socials) { const data = env.config.playground.socials; for (const key in data) { if (data[key].length !== 0) { jsonData[key] = data[key]; } } } fs.writeFileSync(path_1.default.join(destinationPath, "social.json"), JSON.stringify(jsonData, null, 2)); } async function createPlayground(projectPath, templateName, destination, env) { const currDir = process.cwd(); const artifacts = path_1.default.join(currDir, "artifacts"); const contractsSchema = path_1.default.join(artifacts, "typescript_schema"); const checkpointsDir = path_1.default.join(artifacts, "checkpoints"); // check existence of artifact directory if (!fs.existsSync(artifacts)) { throw new errors_1.WasmkitError(errors_list_1.ERRORS.GENERAL.ARTIFACTS_NOT_FOUND, {}); } else if (!fs.existsSync(checkpointsDir)) { // check existence of checkpoint directory throw new errors_1.WasmkitError(errors_list_1.ERRORS.GENERAL.CHECKPOINTS_NOT_FOUND, {}); } else if (!fs.existsSync(contractsSchema)) { throw new errors_1.WasmkitError(errors_list_1.ERRORS.GENERAL.SCHEMA_NOT_FOUND); } const destinationPath = path_1.default.join(currDir, "playground"); await (0, initialize_playground_1.initialize)({ force: false, projectPath: projectPath, templateName: templateName, destination: destinationPath }); const playground = path_1.default.join(currDir, "playground"); const playgroundDest = path_1.default.join(playground, "src"); const ContractDir = path_1.default.join(playgroundDest, "contracts"); createDir(ContractDir); const schemaDest = path_1.default.join(ContractDir, "schema"); const instantiateDir = path_1.default.join(ContractDir, "instantiateInfo"); createDir(instantiateDir); const socialDir = path_1.default.join(ContractDir, "socials"); createDir(socialDir); createContractListJson(checkpointsDir, instantiateDir, env); createDir(schemaDest); processFilesInFolder(contractsSchema, schemaDest); if (env.config.playground) { const staticFilesDest = path_1.default.join(playgroundDest, "assets", "img"); const staticFilesSrc = path_1.default.join(currDir); copyStaticFiles(staticFilesSrc, staticFilesDest, env); handleSocials(socialDir, env); } // console.log(chalk.cyan(`★ Welcome to Wasmkit Playground v1.0 ★`)); // console.log("\n★", chalk.cyan("Project created"), "★\n"); } exports.createPlayground = createPlayground; function createConfirmationPrompt(name, message // eslint-disable-next-line ) { // eslint-disable-line @typescript-eslint/no-explicit-any return { type: "confirm", name, message, initial: "y", default: "(Y/n)", isTrue(input) { if (typeof input === "string") { return input.toLowerCase() === "y"; } return input; }, isFalse(input) { if (typeof input === "string") { return input.toLowerCase() === "n"; } return input; }, format() { const value = this.value === true ? "y" : "n"; if (this.state.submitted === true) { return this.styles.submitted(value); } return value; } }; } exports.createConfirmationPrompt = createConfirmationPrompt; async function installDependencies(packageManager, args, location) { const { exec } = await Promise.resolve().then(() => __importStar(require("child_process"))); const command = packageManager + " " + args; return await new Promise((resolve, reject) => { const childProcess = exec(command, { cwd: location }); childProcess.stdout?.on("data", (data) => { console.log(data.toString()); }); childProcess.stderr?.on("data", (data) => { console.error(data.toString()); }); childProcess.on("close", (code) => { if (code === 0) { resolve(true); } else { reject(new Error(`Command failed with code: ${code}`)); } }); childProcess.on("error", (error) => { console.error("Error executing command:", error); reject(error); }); }); } exports.installDependencies = installDependencies;