@godspeedsystems/godspeed
Version:
Godspeed CLI
358 lines • 15.4 kB
JavaScript
;
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.isAGodspeedProject = void 0;
process.env.SUPPRESS_NO_CONFIG_WARNING = "true";
const dotenv = __importStar(require("dotenv"));
const chalk_1 = __importDefault(require("chalk"));
const commander_1 = require("commander");
const index_1 = __importDefault(require("./commands/create/index"));
// import update from "./commands/update/index";
const path_1 = __importDefault(require("path"));
// import { spawn, spawnSync } from "child_process";
const cross_spawn_1 = __importDefault(require("cross-spawn"));
const os = require("os");
const devops_plugin_1 = __importDefault(require("./commands/devops-plugin"));
const plugin_1 = __importDefault(require("./commands/plugin"));
const prisma_1 = __importDefault(require("./commands/prisma"));
const otel_1 = __importDefault(require("./commands/otel"));
const index_2 = require("./utils/index");
const fsExtras = require("fs-extra");
const process_1 = require("process");
const fs_1 = __importStar(require("fs"));
const node_os_1 = require("node:os");
const promises_1 = require("fs/promises");
// load .env
dotenv.config({ path: path_1.default.resolve(__dirname, "../.env") });
// added a new ENV variable in docker-compose.yml
// const isInsideDevContainer = (): boolean => {
// return !!process.env.INSIDE_CONTAINER;
// };
const detectOSType = () => {
switch (process.platform) {
case "win32":
return "Windows";
case "linux":
return "Linux";
case "darwin":
return "Mac";
default:
return "UNKNOWN";
}
};
const isAGodspeedProject = () => {
// verify .godspeed file, only then, it is a godspeed project
try {
(0, fs_1.readFileSync)(path_1.default.join((0, process_1.cwd)(), ".godspeed"));
}
catch (error) {
console.log(`${chalk_1.default.yellow((0, process_1.cwd)())} ${chalk_1.default.red("is not a Godspeed Framework project.")}`);
console.log("\n", chalk_1.default.yellow("godspeed"), chalk_1.default.yellow("commands works inside godspeed project directory."));
return false;
}
let packageJSON;
try {
// @ts-ignore
packageJSON = JSON.parse((0, fs_1.readFileSync)(path_1.default.join((0, process_1.cwd)(), "package.json"), { encoding: "utf-8" }));
}
catch (error) {
console.log(`This (${chalk_1.default.yellow((0, process_1.cwd)())})`, "is not a Godspeed project.");
console.log("\n", chalk_1.default.yellow("godspeed"), chalk_1.default.yellow("commands only work inside godspeed project directory."));
return false;
}
return true;
};
exports.isAGodspeedProject = isAGodspeedProject;
const updateServicesJson = async (add = true) => {
const servicesFile = path_1.default.join(os.homedir(), ".godspeed", "services.json");
try {
if (!fs_1.default.existsSync(servicesFile))
return;
const servicesData = JSON.parse(fs_1.default.readFileSync(servicesFile, "utf-8"));
const currentProject = {
serviceId: path_1.default.basename(process.cwd()),
name: path_1.default.basename(process.cwd()),
path: process.cwd(),
status: "active",
last_updated: new Date().toISOString(),
initialized: true,
};
if (add) {
const exists = servicesData.services.some((service) => service.path === process.cwd());
if (!exists)
servicesData.services.push(currentProject);
}
else {
servicesData.services = servicesData.services.filter((service) => service.path !== process.cwd());
}
await fs_1.default.promises.writeFile(servicesFile, JSON.stringify(servicesData, null, 2), "utf-8");
console.log(chalk_1.default.green("Project data updated successfully."));
}
catch (error) {
if (error.code === "EACCES") {
const action = add ? "link" : "unlink";
console.error("\x1b[31mPermission denied: Cannot write to services.json\x1b[0m");
console.error(`\x1b[33mTry running: \x1b[1msudo godspeed ${action}\x1b[0m`);
}
else {
console.error("\x1b[31mAn error occurred:\x1b[0m", error);
}
}
};
(async function main() {
// console.log(chalk.bold(chalk.green("\n~~~~~~ Godspeed CLI ~~~~~~\n")));
console.log("\n");
console.log(chalk_1.default.white(" ,_, ") +
chalk_1.default.red.bold("╔════════════════════════════════════╗"));
console.log(chalk_1.default.bold(" (o") +
chalk_1.default.red.bold(",") +
chalk_1.default.yellow.bold("o") +
chalk_1.default.bold(") ") +
chalk_1.default.red.bold("║") +
chalk_1.default.yellow.bold(" Welcome to Godspeed ") +
chalk_1.default.red.bold("║"));
console.log(chalk_1.default.blue(" ({___}) ") +
chalk_1.default.red.bold("║") +
chalk_1.default.yellow.bold(" World's First Meta Framework ") +
chalk_1.default.red.bold("║"));
console.log(chalk_1.default.bold(' " " ') +
chalk_1.default.red.bold("╚════════════════════════════════════╝"));
console.log("\n");
//checking installed version
// const currentVersion = execSync('npm list -g @godspeedsystems/godspeed --json').toString();
// const parsedVersion = JSON.parse(currentVersion);
// const installedVersion = parsedVersion.dependencies["@godspeedsystems/godspeed"].version
// //checking latest from npm version
// const metadata = await pacote.manifest("@godspeedsystems/godspeed");
// const latestversion = metadata.version;
// if (latestversion !== installedVersion) {
// console.log(chalk.yellow.bold(`\nWarning: A new version of the godspeed is available (${latestversion}). Update using:`));
// console.log(chalk.cyan.bold(' npm i -g @godspeedsystems/godspeed\n'));
// }
const program = new commander_1.Command();
// @ts-ignore
let { version, homepage } = require(path_1.default.join(__dirname, "../package.json"));
// remove @godspeedsystems from the name
program
.name("Godspeed CLI")
.description("CLI tool for godspeed framework.")
.version(version);
program.showHelpAfterError();
program.showSuggestionAfterError(true);
program.allowUnknownOption();
program.allowExcessArguments();
program.configureOutput({
writeOut: (str) => {
console.log(`${str}\n`);
console.log(`For detailed documentation visit ${homepage}`);
console.log(`\n`);
},
outputError: (str, write) => {
write(chalk_1.default.red(str));
},
});
program
.command("create")
.description("create a new godspeed project.")
.argument("<projectName>", "name of the project.")
.option("--from-template <projectTemplateName>", "create a project from a template.")
.option("--from-example <exampleName>", "create a project from examples.")
.action((projectName, options) => {
(0, index_1.default)(projectName, options, version);
});
// program
// .command("update")
// .description(
// "Update existing godspeed project. (execute from project root folder)"
// )
// .action(async (options) => {
// if (await isAGodspeedProject()) {
// update(options, version);
// }
// });
program
.command("dev")
.description("run godspeed development server.")
.action(async () => {
if (await (0, exports.isAGodspeedProject)()) {
(0, cross_spawn_1.default)("npm", ["run", "dev"], {
stdio: "inherit",
});
}
});
program
.command("clean")
.description(`clean the previous build.`)
.action(async (options) => {
if ((0, exports.isAGodspeedProject)()) {
(0, cross_spawn_1.default)("npm", ["run", "clean"], {
stdio: "inherit",
});
}
});
program
.command("link")
.description("Link a local Godspeed project to the global environment for development in godspeed-daemon.")
.action(async () => {
if (await (0, exports.isAGodspeedProject)()) {
updateServicesJson(true);
}
});
program
.command("unlink")
.description("Unlink a local Godspeed project from the global environment.")
.action(async () => {
if (await (0, exports.isAGodspeedProject)()) {
updateServicesJson(false);
}
});
program
.command("gen-crud-api")
.description("scans your prisma datasources and generate CRUD APIs events and workflows")
.action(async () => {
if ((0, exports.isAGodspeedProject)()) {
(0, cross_spawn_1.default)("npm", ["run", "gen-crud-api"], { stdio: "inherit" });
}
});
program
.command("gen-graphql-schema")
.description("scans your graphql events and generate graphql schema")
.action(async () => {
if ((0, exports.isAGodspeedProject)()) {
await (0, index_2.genGraphqlSchema)();
}
});
program
.command("build")
.description("build the godspeed project. create a production build.")
.action(async (options) => {
if (await (0, exports.isAGodspeedProject)()) {
(0, cross_spawn_1.default)("npm", ["run", "build"], {
stdio: "inherit",
env: {
// NODE_ENV: "production",
...process.env,
},
});
}
});
program
.command("preview")
.description("preview the production build.")
.action(async (options) => {
if (await (0, exports.isAGodspeedProject)()) {
(0, cross_spawn_1.default)("npm", ["run", "preview"], {
stdio: "inherit",
env: {
// NODE_ENV: "production",
...process.env,
},
});
}
});
// fetch the list of installed devops-plugins
const pluginPath = path_1.default.resolve((0, node_os_1.homedir)(), `.godspeed/devops-plugins/node_modules/@godspeedsystems/`);
const devopsPluginSubCommand = program.command('devops-plugin')
.description(`manages godspeed devops-plugins.`);
devopsPluginSubCommand
.addCommand(devops_plugin_1.default.install);
devopsPluginSubCommand
.addCommand(devops_plugin_1.default.list);
devopsPluginSubCommand
.addCommand(devops_plugin_1.default.remove);
devopsPluginSubCommand
.addCommand(devops_plugin_1.default.update);
const devopsPluginHelp = `
To see help for any installed devops plugin, you can run:
<plugin-name> help
`;
devopsPluginSubCommand.on('--help', () => {
console.log(devopsPluginHelp);
});
//check if devops-plugin is installed.
if (fs_1.default.existsSync(pluginPath)) {
const installedPlugins = await (0, promises_1.readdir)(pluginPath);
for (const installedPluginName of installedPlugins) {
devopsPluginSubCommand
.command(`${installedPluginName}`)
.description("installed godspeed devops plugin")
.allowUnknownOption(true)
.action(async () => {
const installedPluginPath = path_1.default.resolve(pluginPath, installedPluginName, "dist/index.js");
// check if installedPluginPath exists.
if (!fs_1.default.existsSync(installedPluginPath)) {
console.error(`${installedPluginName} is not installed properly. Please make sure ${installedPluginPath} exists.`);
return;
}
const args = process.argv.slice(4);
// Spawn the plugin with all arguments and options
(0, cross_spawn_1.default)('node', [installedPluginPath, ...args], {
stdio: 'inherit',
});
});
}
}
program
.command("serve")
.description("build and preview the production build in watch mode.")
.action(async (options) => {
if (await (0, exports.isAGodspeedProject)()) {
(0, cross_spawn_1.default)("npm", ["run", "serve"], {
stdio: "inherit",
env: {
// NODE_ENV: "production",
...process.env,
},
});
}
});
program
.command("plugin")
.addCommand(plugin_1.default.add)
.addCommand(plugin_1.default.remove)
.addCommand(plugin_1.default.update)
.description(`manage(add, remove, update) eventsource and datasource plugins for godspeed.`);
// bypass all conmmands to prisma CLI, except godspeed prepare
if (process.argv[2] === "prisma") {
if (process.argv[3] !== "prepare") {
(0, cross_spawn_1.default)("npx", ["prisma"].concat(process.argv.slice(3)));
}
}
program
.command("prisma")
.description("proxy to prisma commands with some add-on commands to handle prisma datasources.")
.addCommand(prisma_1.default.prepare);
program
.command("otel")
.addCommand(otel_1.default.enable)
.addCommand(otel_1.default.disable)
.description("enable/disable Observability in Godspeed.");
program.parse();
})();
//# sourceMappingURL=index.js.map