Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions adminforth/commands/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,22 @@ const command = args[0];
import bundle from "./bundle.js";
import createApp from "./createApp/main.js";
import generateModels from "./generateModels.js";

import createPlugin from "./createPlugin/main.js";
switch (command) {
case "create-app":
createApp(args);
break;
case "create-plugin":
createPlugin(args);
break;
case "generate-models":
generateModels();
break;
case "bundle":
bundle();
break;
default:
console.log("Unknown command. Available commands: create-app, generate-models, bundle");
}
console.log(
"Unknown command. Available commands: create-app, create-plugin, generate-models, bundle"
);
}
26 changes: 26 additions & 0 deletions adminforth/commands/createPlugin/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import chalk from "chalk";

import {
parseArgumentsIntoOptions,
prepareWorkflow,
promptForMissingOptions,
} from "./utils.js";

export default async function createPlugin(args) {
// Step 1: Parse CLI arguments with `arg`
let options = parseArgumentsIntoOptions(args);

// Step 2: Ask for missing arguments via `inquirer`
options = await promptForMissingOptions(options);

// Step 3: Prepare a Listr-based workflow
const tasks = prepareWorkflow(options);

// Step 4: Run tasks
try {
await tasks.run();
} catch (err) {
console.error(chalk.red(`\n❌ ${err.message}\n`));
process.exit(1);
}
}
3 changes: 3 additions & 0 deletions adminforth/commands/createPlugin/templates/.gitignore.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
custom/node_modules
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"baseUrl": ".", // This should point to your project root
"paths": {
"@/*": [
// "node_modules/adminforth/dist/spa/src/*"
"../../../spa/src/*"
],
"*": [
// "node_modules/adminforth/dist/spa/node_modules/*"
"../../../spa/node_modules/*"
],
"@@/*": [
// "node_modules/adminforth/dist/spa/src/*"
"."
]
}
}
}
41 changes: 41 additions & 0 deletions adminforth/commands/createPlugin/templates/index.ts.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { AdminForthPlugin } from "adminforth";
import type { IAdminForth, IHttpServer, AdminForthResourcePages, AdminForthResourceColumn, AdminForthDataTypes, AdminForthResource } from "adminforth";
import type { PluginOptions } from './types.js';


export default class ChatGptPlugin extends AdminForthPlugin {
options: PluginOptions;

constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
}

async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);

// simply modify resourceConfig or adminforth.config. You can get access to plugin options via this.options;
}

validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
// optional method where you can safely check field types after database discovery was performed
}

instanceUniqueRepresentation(pluginOptions: any) : string {
// optional method to return unique string representation of plugin instance.
// Needed if plugin can have multiple instances on one resource
return `single`;
}

setupEndpoints(server: IHttpServer) {
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/example`,
handler: async ({ body }) => {
const { name } = body;
return { hey: `Hello ${name}` };
}
});
}

}
21 changes: 21 additions & 0 deletions adminforth/commands/createPlugin/templates/package.json.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "{{pluginName}}",
"version": "1.0.1",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"build": "tsc && rsync -av --exclude 'node_modules' custom dist/ && npm version patch"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/node": "latest",
"typescript": "^5.7.3"
},
"dependencies": {
"adminforth": "latest",
}
}
13 changes: 13 additions & 0 deletions adminforth/commands/createPlugin/templates/tsconfig.json.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include*/
"module": "node16", /* Specify what module code is generated. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": false, /* Enable all strict type-checking options. */
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
},
"exclude": ["node_modules", "dist", "custom"], /* Exclude files from compilation. */
}

3 changes: 3 additions & 0 deletions adminforth/commands/createPlugin/templates/types.ts.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface PluginOptions {

}
222 changes: 222 additions & 0 deletions adminforth/commands/createPlugin/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
import arg from 'arg';
import chalk from 'chalk';
import fs from 'fs';
import fse from 'fs-extra';
import inquirer from 'inquirer';
import path from 'path';
import { Listr } from 'listr2';
import { fileURLToPath } from 'url';
import { execa } from 'execa';
import Handlebars from 'handlebars';

export function parseArgumentsIntoOptions(rawArgs) {
const args = arg(
{
"--plugin-name": String,
// you can add more flags here if needed
},
{
argv: rawArgs.slice(1), // skip "create-plugin"
}
);

return {
pluginName: args["--plugin-name"],
};
}

export async function promptForMissingOptions(options) {
const questions = [];

if (!options.pluginName) {
questions.push({
type: "input",
name: "pluginName",
message: "Please specify the name of the plugin >",
default: "adminforth-plugin",
});
}

const answers = await inquirer.prompt(questions);
return {
...options,
pluginName: options.pluginName || answers.pluginName,
};
}

function checkNodeVersion(minRequiredVersion = 20) {
const current = process.versions.node.split(".");
const major = parseInt(current[0], 10);

if (isNaN(major) || major < minRequiredVersion) {
throw new Error(
`Node.js v${minRequiredVersion}+ is required. You have ${process.versions.node}. ` +
`Please upgrade Node.js. We recommend using nvm for managing multiple Node.js versions.`
);
}
}

function checkForExistingPackageJson() {
if (fs.existsSync(path.join(process.cwd(), "package.json"))) {
throw new Error(
`A package.json already exists in this directory.\n` +
`Please remove it or use an empty directory.`
);
}
}

function initialChecks() {
return [
{
title: "👀 Checking Node.js version...",
task: () => checkNodeVersion(20),
},
{
title: "👀 Validating current working directory...",
task: () => checkForExistingPackageJson(),
},
];
}

function renderHBSTemplate(templatePath, data) {
const template = fs.readFileSync(templatePath, "utf-8");
const compiled = Handlebars.compile(template);
return compiled(data);
}

async function scaffoldProject(ctx, options, cwd) {
const pluginName = options.pluginName;

const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);

// Prepare directories
ctx.customDir = path.join(cwd, "custom");
await fse.ensureDir(ctx.customDir);

// Write templated files
await writeTemplateFiles(dirname, cwd, {
pluginName,
});
}

async function writeTemplateFiles(dirname, cwd, options) {
const { pluginName } = options;

// Build a list of files to generate
const templateTasks = [
{
src: "tsconfig.json.hbs",
dest: "tsconfig.json",
data: {},
},
{
src: "package.json.hbs",
dest: "package.json",
data: { pluginName },
},
{
src: "index.ts.hbs",
dest: "index.ts",
data: {},
},
{
src: ".gitignore.hbs",
dest: ".gitignore",
data: {},
},
{
src: "types.ts.hbs",
dest: "types.ts",
data: {},
},
{
src: "custom/tsconfig.json.hbs",
dest: "custom/tsconfig.json",
data: {},
},
];

for (const task of templateTasks) {
// If a condition is specified and false, skip this file
if (task.condition === false) continue;

const destPath = path.join(cwd, task.dest);
fse.ensureDirSync(path.dirname(destPath));

if (task.empty) {
fs.writeFileSync(destPath, "");
} else {
const templatePath = path.join(dirname, "templates", task.src);
const compiled = renderHBSTemplate(templatePath, task.data);
fs.writeFileSync(destPath, compiled);
}
}
}

async function installDependencies(ctx, cwd) {
const customDir = ctx.customDir;

await Promise.all([
await execa("npm", ["install", "--no-package-lock"], { cwd }),
await execa("npm", ["install"], { cwd: customDir }),
]);
}

function generateFinalInstructions() {
let instruction = "⏭️ Your plugin is ready! Next steps:\n";

instruction += `
${chalk.dim("// Build your plugin")}
${chalk.cyan("$ npm run build")}\n`;

instruction += `
${chalk.dim("// To test your plugin locally")}
${chalk.cyan("$ npm link")}\n`;

instruction += `
${chalk.dim("// In your AdminForth project")}
${chalk.cyan("$ npm link " + chalk.italic("your-plugin-name"))}\n`;

instruction += "\n😉 Happy coding!";

return instruction;
}

export function prepareWorkflow(options) {
const cwd = process.cwd();
const tasks = new Listr(
[
{
title: "🔍 Initial checks...",
task: (_, task) => task.newListr(initialChecks(), { concurrent: true }),
},
{
title: "🚀 Scaffolding your plugin...",
task: async (ctx) => scaffoldProject(ctx, options, cwd),
},
{
title: "📦 Installing dependencies...",
task: async (ctx) => installDependencies(ctx, cwd),
},
{
title: "📝 Preparing final instructions...",
task: (ctx) => {
console.log(
chalk.green(`✅ Successfully created your new AdminForth plugin!\n`)
);
console.log(generateFinalInstructions());
console.log("\n\n");
},
},
],
{
rendererOptions: { collapseSubtasks: false },
concurrent: false,
exitOnError: true,
collectErrors: true,
}
);

return tasks;
}
Loading