|
| 1 | +import "reflect-metadata"; |
| 2 | +import {existsSync, writeFileSync} from "node:fs"; |
| 3 | +import {createRequire} from "node:module"; |
| 4 | +import {resolve} from "node:path"; |
| 5 | +import {pathToFileURL} from "node:url"; |
| 6 | +import {Module} from "@code0-tech/tucana/shared"; |
| 7 | +import {Action, registeredActions} from "./action"; |
| 8 | + |
| 9 | +const USAGE = `Usage: hercules export <entry-file> [options] |
| 10 | +
|
| 11 | +Loads the given entry file (without connecting to aquila) and prints the |
| 12 | +Action as a JSON document in the shape of the tucana protobuf Module type. |
| 13 | +
|
| 14 | +Options: |
| 15 | + -o, --out <file> Write the JSON to a file instead of stdout |
| 16 | + --compact Emit compact JSON instead of pretty-printed |
| 17 | + -h, --help Show this help message |
| 18 | +
|
| 19 | +Examples: |
| 20 | + hercules export src/index.ts |
| 21 | + hercules export dist/index.js -o module.json |
| 22 | +`; |
| 23 | + |
| 24 | +interface ExportArgs { |
| 25 | + entry: string; |
| 26 | + out?: string; |
| 27 | + compact: boolean; |
| 28 | +} |
| 29 | + |
| 30 | +function fail(message: string): never { |
| 31 | + process.stderr.write(`${message}\n`); |
| 32 | + process.exit(1); |
| 33 | +} |
| 34 | + |
| 35 | +function parseExportArgs(argv: string[]): ExportArgs { |
| 36 | + let entry: string | undefined; |
| 37 | + let out: string | undefined; |
| 38 | + let compact = false; |
| 39 | + for (let i = 0; i < argv.length; i++) { |
| 40 | + const arg = argv[i]; |
| 41 | + if (arg === "-h" || arg === "--help") { |
| 42 | + process.stdout.write(USAGE); |
| 43 | + process.exit(0); |
| 44 | + } else if (arg === "-o" || arg === "--out") { |
| 45 | + out = argv[++i]; |
| 46 | + if (out == null) fail(`Missing value for ${arg}\n\n${USAGE}`); |
| 47 | + } else if (arg === "--compact") { |
| 48 | + compact = true; |
| 49 | + } else if (arg.startsWith("-")) { |
| 50 | + fail(`Unknown option: ${arg}\n\n${USAGE}`); |
| 51 | + } else if (entry == null) { |
| 52 | + entry = arg; |
| 53 | + } else { |
| 54 | + fail(`Unexpected argument: ${arg}\n\n${USAGE}`); |
| 55 | + } |
| 56 | + } |
| 57 | + if (entry == null) fail(`Missing <entry-file> argument\n\n${USAGE}`); |
| 58 | + return {entry, out, compact}; |
| 59 | +} |
| 60 | + |
| 61 | +function isAction(value: unknown): value is Action { |
| 62 | + if (value instanceof Action) return true; |
| 63 | + // The entry file may have loaded a different copy of this module (e.g. the |
| 64 | + // CJS build), in which case instanceof fails — fall back to duck typing. |
| 65 | + const candidate = value as Action | null; |
| 66 | + return typeof candidate?.buildModule === "function" |
| 67 | + && typeof candidate.identifier === "string" |
| 68 | + && typeof candidate.registerFunction === "function"; |
| 69 | +} |
| 70 | + |
| 71 | +function findAction(entryExports: Record<string, unknown>): Action { |
| 72 | + for (const value of [entryExports.default, ...Object.values(entryExports)]) { |
| 73 | + if (isAction(value)) return value; |
| 74 | + } |
| 75 | + const registered = registeredActions(); |
| 76 | + if (registered.length > 0) return registered[registered.length - 1]; |
| 77 | + throw new Error("No Action found. Export your Action instance from the entry file or construct it during module load."); |
| 78 | +} |
| 79 | + |
| 80 | +async function loadEntry(entry: string): Promise<Record<string, unknown>> { |
| 81 | + const entryPath = resolve(process.cwd(), entry); |
| 82 | + if (!existsSync(entryPath)) fail(`Entry file not found: ${entryPath}`); |
| 83 | + if (/\.[mc]?tsx?$/.test(entryPath)) { |
| 84 | + const tsxApi = "tsx/esm/api"; |
| 85 | + let tsx; |
| 86 | + try { |
| 87 | + tsx = await import(/* @vite-ignore */ tsxApi); |
| 88 | + } catch { |
| 89 | + try { |
| 90 | + // Not resolvable from the hercules install; try the user's project. |
| 91 | + const requireFromCwd = createRequire(resolve(process.cwd(), "package.json")); |
| 92 | + tsx = await import(/* @vite-ignore */ pathToFileURL(requireFromCwd.resolve(tsxApi)).href); |
| 93 | + } catch { |
| 94 | + fail("Loading a TypeScript entry requires 'tsx'. Install it (npm i -D tsx) or point the command at your built JavaScript entry."); |
| 95 | + } |
| 96 | + } |
| 97 | + tsx.register(); |
| 98 | + } |
| 99 | + return await import(/* @vite-ignore */ pathToFileURL(entryPath).href); |
| 100 | +} |
| 101 | + |
| 102 | +async function runExport(argv: string[]) { |
| 103 | + const args = parseExportArgs(argv); |
| 104 | + // Must be set before the entry file is loaded: it makes connect() a no-op |
| 105 | + // and registers constructed Action instances for findAction. |
| 106 | + process.env.HERCULES_EXPORT = "1"; |
| 107 | + const action = findAction(await loadEntry(args.entry)); |
| 108 | + const moduleJson = Module.toJson(action.buildModule()); |
| 109 | + const json = `${JSON.stringify(moduleJson, null, args.compact ? undefined : 2)}\n`; |
| 110 | + if (args.out) { |
| 111 | + const outPath = resolve(process.cwd(), args.out); |
| 112 | + writeFileSync(outPath, json); |
| 113 | + process.stderr.write(`Module written to ${outPath}\n`); |
| 114 | + } else { |
| 115 | + process.stdout.write(json); |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +async function main() { |
| 120 | + const [command, ...rest] = process.argv.slice(2); |
| 121 | + if (command == null || command === "-h" || command === "--help") { |
| 122 | + process.stdout.write(USAGE); |
| 123 | + process.exit(command == null ? 1 : 0); |
| 124 | + } |
| 125 | + if (command !== "export") fail(`Unknown command: ${command}\n\n${USAGE}`); |
| 126 | + await runExport(rest); |
| 127 | + // The entry file may have started timers or other handles; exit explicitly. |
| 128 | + process.exit(0); |
| 129 | +} |
| 130 | + |
| 131 | +main().catch((err: unknown) => fail(err instanceof Error ? err.message : String(err))); |
0 commit comments