Skip to content

Commit 97c46ff

Browse files
committed
move findAdminInstance to dedicated module
1 parent 81ae76b commit 97c46ff

File tree

4 files changed

+136
-54
lines changed

4 files changed

+136
-54
lines changed

adminforth/commands/bundle.js

Lines changed: 12 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,22 @@
1-
import fs from "fs";
2-
import { callTsProxy } from "./callTsProxy.js";
3-
import chalk from "chalk";
1+
import { callTsProxy, findAdminInstance } from "./callTsProxy.js";
2+
43

54
async function bundle() {
65
console.log("Bundling admin SPA...");
7-
const currentDirectory = process.cwd();
8-
9-
let files = fs.readdirSync(currentDirectory);
10-
let instanceFound = false;
11-
// try index.ts first
12-
if (files.includes("index.ts")) {
13-
files = files.filter((file) => file !== "index.ts");
14-
files.unshift("index.ts");
15-
}
6+
const instance = await findAdminInstance();
167

17-
for (const file of files) {
18-
if (file.endsWith(".ts")) {
19-
const fileNoTs = file.replace(/\.ts$/, "");
20-
process.env.HEAVY_DEBUG && console.log(`🪲 Trying bundleing ${file}...`);
21-
try {
22-
await callTsProxy(`
23-
import { admin } from './${fileNoTs}.js';
248

25-
export async function exec() {
26-
return await admin.bundleNow({ hotReload: false });
27-
}
28-
`);
29-
instanceFound = true;
30-
break;
9+
try {
10+
await callTsProxy(`
11+
import { admin } from './${instance.file}.js';
3112
32-
} catch (e) {
33-
process.env.HEAVY_DEBUG && console.log(`🪲 File ${file} failed`, e);
13+
export async function exec() {
14+
return await admin.bundleNow({ hotReload: false });
3415
}
35-
}
36-
}
37-
if (!instanceFound) {
38-
console.error(
39-
chalk.red(
40-
`Error: No valid instance found to bundle.\n` +
41-
`Make sure you have a file in the current directory with a .ts extension, and it exports an ` +
42-
chalk.cyan.bold('admin') +
43-
` instance like:\n\n` +
44-
chalk.yellow('export const admin = new AdminForth({...})') +
45-
`\n\nFor example, adminforth CLI creates an index.ts file which exports the admin instance.`
46-
)
47-
);
48-
return;
16+
`);
17+
18+
} catch (e) {
19+
console.log(`Running file ${file} failed`, e);
4920
}
5021
}
5122

adminforth/commands/callTsProxy.js

Lines changed: 66 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// callTsProxy.js
22
import { spawn } from "child_process";
33
import path from "path";
4+
import fs from "fs";
5+
import chalk from "chalk";
46

57
const currentFilePath = import.meta.url;
68
const currentFileFolder = path.dirname(currentFilePath).replace("file:", "");
@@ -31,18 +33,17 @@ export function callTsProxy(tsCode) {
3133
parsed.capturedLogs.forEach((log) => {
3234
console.log(...log);
3335
});
36+
37+
if (parsed.error) {
38+
reject(new Error(`${parsed.error}\n${parsed.stack}`));
39+
}
3440
resolve(parsed.result);
3541
} catch (e) {
3642
reject(new Error("Invalid JSON from tsproxy: " + stdout));
3743
}
3844
} else {
39-
try {
40-
const parsedError = JSON.parse(stderr);
41-
process.env.HEAVY_DEBUG && console.error("🪲 Error from tsproxy. Captured logs:", parsedError.capturedLogs);
42-
reject(new Error(parsedError.error));
43-
} catch (e) {
44-
reject(new Error(stderr));
45-
}
45+
console.error(`tsproxy exited with non-0, this should never happen, stdout: ${stdout}, stderr: ${stderr}`);
46+
reject(new Error(stderr));
4647
}
4748
});
4849

@@ -52,6 +53,64 @@ export function callTsProxy(tsCode) {
5253
});
5354
}
5455

56+
export async function findAdminInstance() {
57+
process.env.HEAVY_DEBUG && console.log("🌐 Finding admin instance...");
58+
const currentDirectory = process.cwd();
59+
60+
let files = fs.readdirSync(currentDirectory);
61+
let instanceFound = {
62+
file: null,
63+
version: null,
64+
};
65+
// try index.ts first
66+
if (files.includes("index.ts")) {
67+
files = files.filter((file) => file !== "index.ts");
68+
files.unshift("index.ts");
69+
}
70+
71+
for (const file of files) {
72+
if (file.endsWith(".ts")) {
73+
const fileNoTs = file.replace(/\.ts$/, "");
74+
process.env.HEAVY_DEBUG && console.log(`🪲 Trying bundleing ${file}...`);
75+
try {
76+
res = await callTsProxy(`
77+
import { admin } from './${fileNoTs}.js';
78+
79+
export async function exec() {
80+
return admin.formatAdminForth();
81+
}
82+
`);
83+
instanceFound.file = fileNoTs;
84+
instanceFound.version = res;
85+
break;
86+
87+
} catch (e) {
88+
// do our best to guess that this file has a good chance to be admin instance
89+
// and show the error so user can fix it
90+
const fileContent = fs.readFileSync(file, "utf-8");
91+
if (fileContent.includes("export const admin")) {
92+
console.error(chalk.red(`Error running ${file}:`, e));
93+
process.exit(1);
94+
}
95+
process.env.HEAVY_DEBUG && console.log(`🪲 File ${file} failed`, e);
96+
}
97+
}
98+
}
99+
if (!instanceFound.file) {
100+
console.error(
101+
chalk.red(
102+
`Error: No valid instance found to bundle.\n` +
103+
`Make sure you have a file in the current directory with a .ts extension, and it exports an ` +
104+
chalk.cyan.bold('admin') +
105+
` instance like:\n\n` +
106+
chalk.yellow('export const admin = new AdminForth({...})') +
107+
`\n\nFor example, adminforth CLI creates an index.ts file which exports the admin instance.`
108+
)
109+
);
110+
process.exit(1);
111+
}
112+
return instanceFound;
113+
}
55114

56115
// Example usage:
57116
// callTsProxy(`

adminforth/commands/cli.js

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,39 @@ import createApp from "./createApp/main.js";
88
import generateModels from "./generateModels.js";
99
import createPlugin from "./createPlugin/main.js";
1010
import createComponent from "./createCustomComponent/main.js";
11+
import chalk from "chalk";
12+
import path from "path";
13+
import fs from "fs";
14+
15+
function showHelp() {
16+
console.log(
17+
chalk.white("Available commands:\n") +
18+
chalk.green(' create-app') + chalk.white(' Create a new AdminForth app\n') +
19+
chalk.green(' create-plugin') + chalk.white(' Create a plugin for your AdminForth app\n') +
20+
chalk.green(' generate-models') + chalk.white(' Generate TypeScript models from your databases\n') +
21+
chalk.green(' bundle') + chalk.white(' Bundles your AdminForth app SPA for production\n') +
22+
chalk.green(' component') + chalk.white(' Scaffold a custom Vue component\n')
23+
);
24+
}
25+
26+
function currentFileDir(importMetaUrl) {
27+
const filePath = importMetaUrl.replace("file://", "");
28+
const fileDir = path.dirname(filePath);
29+
return fileDir;
30+
}
31+
32+
function showVersion() {
33+
const ADMIN_FORTH_ABSOLUTE_PATH = path.join(currentFileDir(import.meta.url), '..');
34+
35+
const package_json = JSON.parse(fs.readFileSync(path.join(ADMIN_FORTH_ABSOLUTE_PATH, 'package.json'), 'utf8'));
36+
37+
const ADMINFORTH_VERSION = package_json.version;
38+
39+
console.log(
40+
chalk.white('AdminForth CLI version: ') +
41+
chalk.cyan.bold(ADMINFORTH_VERSION)
42+
);
43+
}
1144

1245
switch (command) {
1346
case "create-app":
@@ -22,11 +55,23 @@ switch (command) {
2255
case "bundle":
2356
bundle();
2457
break;
25-
case "custom-component":
58+
case "component":
2659
createComponent(args);
2760
break;
28-
default:
61+
case "help":
62+
case "--help":
63+
case "-h":
64+
showHelp();
65+
break;
66+
case "--version":
67+
case "version":
68+
case "-v":
69+
showVersion();
70+
break;
71+
default: {
2972
console.log(
30-
"Unknown command. Available commands: create-app, create-plugin, generate-models, bundle, custom-component"
73+
"Unknown command."
3174
);
75+
showHelp();
76+
}
3277
}

adminforth/commands/proxy.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,19 @@ import path from 'path';
4141

4242
// Restore original console.log
4343
console.log = origLog;
44-
console.log(JSON.stringify({ result, capturedLogs }));
44+
console.log(JSON.stringify({
45+
result,
46+
capturedLogs,
47+
error: null
48+
}));
4549
} catch (error: any) {
4650
// Restore original console.log
4751
console.log = origLog;
48-
console.error(JSON.stringify({ error: error.message, capturedLogs }));
49-
process.exit(1);
52+
console.log(JSON.stringify({
53+
error: error.message,
54+
stack: error.stack,
55+
capturedLogs
56+
}));
5057
} finally {
5158
await unlink(tmpFile).catch(() => {});
5259
}

0 commit comments

Comments
 (0)