@openfairygui/cli 0.6.3 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfairygui/cli",
3
- "version": "0.6.3",
3
+ "version": "0.7.1",
4
4
  "description": "FairyGUI Headless Authoring SDK — command-line interface.",
5
5
  "author": "OpenFairyGUI Contributors",
6
6
  "license": "MIT",
@@ -23,8 +23,7 @@
23
23
  },
24
24
  "files": [
25
25
  "dist/",
26
- "bin/",
27
- "src/"
26
+ "bin/"
28
27
  ],
29
28
  "keywords": [
30
29
  "fairygui",
@@ -35,17 +34,15 @@
35
34
  "publish",
36
35
  "restore"
37
36
  ],
38
- "devDependencies": {
39
- "@openfairygui/functions": "0.6.3",
40
- "@openfairygui/core": "0.6.3"
41
- },
42
37
  "dependencies": {
43
38
  "commander": "^14.0.2",
44
39
  "jiti": "^2.7.0",
45
- "@openfairygui/backend": "0.6.3"
40
+ "@openfairygui/backend": "0.7.1",
41
+ "@openfairygui/functions": "0.7.1",
42
+ "@openfairygui/core": "0.7.1"
46
43
  },
47
44
  "optionalDependencies": {
48
- "sharp": ">=0.33.0"
45
+ "sharp": "^0.35.5"
49
46
  },
50
47
  "scripts": {
51
48
  "build": "tsdown src/cli.ts --format esm --platform node --no-dts --external sharp --external jiti"
package/src/cli.ts DELETED
@@ -1,56 +0,0 @@
1
- import { Command, CommanderError } from 'commander';
2
- import path from 'node:path';
3
- import { pathToFileURL } from 'node:url';
4
- import { configureJson, parsedCommand, printJsonError, wantsJson } from './utils/json-output.js';
5
- import { registerBackendCapabilitiesCommand } from './commands/backend-capabilities.js';
6
- import { registerInspectCommand } from './commands/inspect.js';
7
- import { registerPublishCommand } from './commands/publish.js';
8
- import { registerRestoreCommand } from './commands/restore.js';
9
- import { registerValidateCommand } from './commands/validate.js';
10
- import { registerDocsCommand } from './commands/docs.js';
11
- import { registerDoctorCommand } from './commands/doctor.js';
12
- import { readPackageVersion } from './utils/package-version.js';
13
-
14
- const PACKAGE_VERSION = readPackageVersion();
15
-
16
- export function createProgram(): Command {
17
- const program = new Command('ofgui');
18
- configureJson(program);
19
-
20
- program.description('FairyGUI Headless Authoring CLI').version(PACKAGE_VERSION).showHelpAfterError();
21
-
22
- registerInspectCommand(program);
23
- registerPublishCommand(program);
24
- registerRestoreCommand(program);
25
- registerValidateCommand(program);
26
- registerBackendCapabilitiesCommand(program);
27
- registerDocsCommand(program);
28
- registerDoctorCommand(program);
29
-
30
- program.addHelpText(
31
- 'after',
32
- [
33
- '',
34
- 'Alias:',
35
- ' openfairygui',
36
- '',
37
- 'Input can be a .fairy file or a project root directory (auto-discovers .fairy file).',
38
- 'Publish settings are read from the project; --project-type applies target-specific output rules.',
39
- ].join('\n'),
40
- );
41
-
42
- return program;
43
- }
44
-
45
- if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
46
- const program = createProgram();
47
- program.parseAsync(process.argv).catch((err) => {
48
- if (err instanceof CommanderError && err.exitCode === 0) return;
49
- const command = parsedCommand(program);
50
- const message = err instanceof Error ? err.message : String(err);
51
- if (wantsJson(process.argv)) printJsonError(command, { code: err instanceof CommanderError ? 'invalid_arguments'
52
- : command === 'publish' || command === 'restore' ? `${command}_failed` : 'command_failed', message });
53
- else console.error(message);
54
- process.exitCode = err instanceof CommanderError ? 2 : 1;
55
- });
56
- }
@@ -1,39 +0,0 @@
1
- import { createNodeBackendRuntime } from '@openfairygui/backend/node';
2
- import type { Command } from 'commander';
3
- import path from 'node:path';
4
- import { printJson } from '../utils/json-output.js';
5
-
6
- export function registerBackendCapabilitiesCommand(program: Command): void {
7
- program
8
- .command('backend-capabilities')
9
- .description('Open a backend session, print runtime capabilities, then close it')
10
- .argument('<project-dir>', 'Project root directory')
11
- .option('--json', 'Print the machine-readable runtime capabilities after closing the session')
12
- .action(async (projectDir: string, options: { json?: boolean }) => {
13
- const runtime = createNodeBackendRuntime();
14
- const opened = await runtime.openSession({ projectPath: path.resolve(projectDir) });
15
- if (!opened.ok) {
16
- const failure = opened as Extract<typeof opened, { ok: false }>;
17
- throw new Error(`backend-capabilities: ${failure.error.message}`);
18
- }
19
-
20
- let capabilities: ReturnType<typeof runtime.getCapabilities>;
21
- let closed: Awaited<ReturnType<typeof runtime.closeSession>>;
22
- try {
23
- capabilities = runtime.getCapabilities();
24
- if (!capabilities.ok) throw new Error('backend-capabilities: failed to read capabilities');
25
- if (!options.json) {
26
- console.log(`Session: ${opened.data.sessionId}`);
27
- console.log(`Project: ${opened.data.canonicalProjectPath}`);
28
- console.log(`Revision: ${opened.data.revision}`);
29
- console.log(`Runtime owner: ${capabilities.data.runtimeOwner}`);
30
- console.log(`Transaction owner: ${capabilities.data.transactionKernelOwner}`);
31
- console.log(`App seam owner: ${capabilities.data.appSeamOwner}`);
32
- }
33
- } finally {
34
- closed = await runtime.closeSession({ sessionId: opened.data.sessionId });
35
- }
36
- if (!closed.ok) throw new Error(`backend-capabilities: ${closed.error.message}`);
37
- if (options.json) printJson('backend-capabilities', capabilities.data);
38
- });
39
- }
@@ -1,36 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { findInstalledDocumentation, getInstalledDocumentationIndex, getInstalledDocumentationVersion, readInstalledDocumentation } from '@openfairygui/backend/docs';
3
- import { readPackageVersion } from '../utils/package-version.js';
4
- import { printJson, printJsonError } from '../utils/json-output.js';
5
- import type { CliCommand, CliCommandResults } from '../contracts.js';
6
-
7
- export function registerDocsCommand(program: Command): void {
8
- const docs = program.command('docs').description('Read version-bound installed documentation offline (no download or repository required)');
9
- function print<C extends Extract<CliCommand, `docs ${string}`>>(command: C, options: { json?: boolean }, read: () => CliCommandResults[C]): void {
10
- const version = getInstalledDocumentationVersion();
11
- try {
12
- if (version.packageVersion !== readPackageVersion()) throw new Error('CLI and installed documentation versions differ; ask the host to reconcile the installation.');
13
- const result = read();
14
- if (options.json) printJson(command, result);
15
- else {
16
- console.log(`${version.packageName}@${version.packageVersion} | contract ${version.BACKEND_CONTRACT_VERSION} | schema ${version.BACKEND_CAPABILITY_SCHEMA_VERSION}`);
17
- console.log('text' in result ? result.text : result.documents.map((entry) => `${entry.id}\t${entry.title}`).join('\n'));
18
- }
19
- } catch (error) {
20
- const message = error instanceof Error ? error.message : String(error);
21
- if (options.json) printJsonError(command, { code: 'documentation_unavailable', message });
22
- else console.error(message);
23
- process.exitCode = 1;
24
- }
25
- }
26
- docs.command('ls').description('List installed document IDs, URIs and version').option('--json', 'Print JSON')
27
- .action((options) => print('docs ls', options, getInstalledDocumentationIndex));
28
- docs.command('find <query>').description('Search only the installed corpus').option('--json', 'Print JSON')
29
- .action((query: string, options) => print('docs find', options, () => findInstalledDocumentation(query)));
30
- docs.command('cat <id>').description('Read an exact ID from docs ls, not a filesystem path').option('--json', 'Print JSON')
31
- .action((id: string, options) => print('docs cat', options, () => readInstalledDocumentation(id)));
32
- docs.command('diagnostic <code>').description('Read a diagnostic recovery guide; never execute repairs').option('--json', 'Print JSON')
33
- .action((code: string, options) => print('docs diagnostic', options, () => readInstalledDocumentation(`diagnostics/${code}`)));
34
- docs.command('schema <kind>').description('Read a self-contained operation schema or cli/<command> output schema').option('--json', 'Print JSON')
35
- .action((kind: string, options) => print('docs schema', options, () => readInstalledDocumentation(kind.startsWith('cli/') ? kind : `operations/${kind}`)));
36
- }
@@ -1,112 +0,0 @@
1
- import { InvalidArgumentError, type Command } from 'commander';
2
- import fs from 'node:fs/promises';
3
- import { constants } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import path from 'node:path';
6
- import { createNodeBackendRuntime } from '@openfairygui/backend/node';
7
- import { getInstalledDocumentationVersion } from '@openfairygui/backend/docs';
8
- import { validateProjectNode } from '@openfairygui/functions/node';
9
- import { readPackageVersion } from '../utils/package-version.js';
10
- import { resolveFairyPath } from '../utils/project-input.js';
11
- import type { DoctorReport } from '../contracts.js';
12
- import { printJson } from '../utils/json-output.js';
13
-
14
- async function inspectNativeImages(): Promise<DoctorReport['checks'][number]> {
15
- try {
16
- const sharp = (await import('sharp')).default;
17
- for (const format of ['png', 'jpeg'] as const) {
18
- const encoded = await sharp({ create: { width: 1, height: 1, channels: 3, background: '#204060' } }).toFormat(format).toBuffer();
19
- const { data, info } = await sharp(encoded).raw().toBuffer({ resolveWithObject: true });
20
- if (info.width !== 1 || info.height !== 1 || info.channels !== 3 || data.length !== 3) throw new Error(`${format} pixel decoding returned unexpected dimensions.`);
21
- }
22
- return { id: 'native-images', status: 'ok', version: sharp.versions.sharp, message: 'In-memory PNG/JPEG encoding and pixel decoding passed.' };
23
- } catch (error) {
24
- return { id: 'native-images', status: 'incomplete', message: `Native image capability unavailable or failed; ask the host to check Sharp before publishing/restoring. ${error instanceof Error ? error.message : String(error)}` };
25
- }
26
- }
27
-
28
- async function inspectDirectory(id: 'temp-directory' | 'output-directory', requested: string): Promise<DoctorReport['checks'][number]> {
29
- const check: Extract<DoctorReport['checks'][number], { path: string }> = {
30
- id, status: 'error', path: path.resolve(requested), inspectedPath: path.resolve(requested), exists: null, message: '',
31
- };
32
- try {
33
- for (;;) {
34
- try {
35
- await fs.lstat(check.inspectedPath);
36
- } catch (error) {
37
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
38
- if (check.inspectedPath === check.path) check.exists = false;
39
- const parent = path.dirname(check.inspectedPath);
40
- if (id === 'temp-directory' || parent === check.inspectedPath) throw error;
41
- check.inspectedPath = parent;
42
- continue;
43
- }
44
- if (check.inspectedPath === check.path) check.exists = true;
45
- // Resolve only after lstat succeeds: a dangling symlink is an error, not a missing directory to create.
46
- check.inspectedPath = await fs.realpath(check.inspectedPath);
47
- if (!(await fs.stat(check.inspectedPath)).isDirectory()) throw new Error('The inspected path is not a directory.');
48
- await fs.access(check.inspectedPath, constants.R_OK | constants.W_OK | constants.X_OK);
49
- check.status = 'ok';
50
- check.message = check.exists ? 'Directory access flags passed; no files written.' : 'Target absent; only the nearest existing ancestor passed access flags. Nothing created.';
51
- break;
52
- }
53
- } catch (error) { check.message = error instanceof Error ? error.message : String(error); }
54
- return check;
55
- }
56
-
57
- export function registerDoctorCommand(program: Command): void {
58
- program.command('doctor').description('Diagnose versions, native images and directory access; optionally validate a project; never write or repair')
59
- .argument('[project-dir]', 'Optional project directory or .fairy file for Node validation')
60
- .option('--output-dir <directory>', 'Check output directory access (or its existing ancestor), without creating it', (value: string) => {
61
- if (!value) throw new InvalidArgumentError('Output directory must not be empty.');
62
- return value;
63
- })
64
- .option('--json', 'Print the complete machine-readable product diagnosis')
65
- .action(async (projectDir: string | undefined, options: { json?: boolean; outputDir?: string }) => {
66
- const version = getInstalledDocumentationVersion();
67
- const errors: DoctorReport['errors'] = [];
68
- const cliVersion = readPackageVersion();
69
- if (cliVersion !== version.packageVersion) errors.push({ code: 'installed_version_mismatch', message: 'CLI and documentation versions differ; ask the host to reconcile the installation.' });
70
- const minimumMajor = /^>=(\d+)$/u.exec(version.nodeEngine)?.[1];
71
- if (!minimumMajor || Number(process.versions.node.split('.')[0]) < Number(minimumMajor)) errors.push({ code: 'unsupported_node_version', message: `Installed package requires Node ${version.nodeEngine}.` });
72
- const capabilities = createNodeBackendRuntime().getCapabilities();
73
- const checks = await Promise.all([
74
- inspectNativeImages(), inspectDirectory('temp-directory', tmpdir()),
75
- ...(options.outputDir === undefined ? [] : [inspectDirectory('output-directory', options.outputDir)]),
76
- ]);
77
- let project: Awaited<ReturnType<typeof validateProjectNode>> | null = null;
78
- let projectPath: string | null = null;
79
- if (projectDir) {
80
- try {
81
- projectPath = await resolveFairyPath(projectDir);
82
- project = await validateProjectNode(projectPath);
83
- } catch (error) { errors.push({ code: 'project_check_failed', message: error instanceof Error ? error.message : String(error) }); }
84
- }
85
- const status = errors.length || !capabilities.ok || project?.status === 'invalid' || checks.some((check) => check.status === 'error') ? 'error'
86
- : project?.status === 'incomplete' || checks.some((check) => check.status === 'incomplete') ? 'incomplete' : 'ready';
87
- const report: DoctorReport = {
88
- scope: 'installed-product', ...version, cliVersion, nodeVersion: process.versions.node,
89
- status, errors, checks, capabilities, projectPath, project,
90
- limits: [
91
- 'No installation, configuration changes, probe writes, session opening or repair.',
92
- 'Without a project, project source bytes are not tested; native images use only an in-memory PNG/JPEG sample.',
93
- 'Directory access flags do not prove effective ACL permissions, available space, later writes, rename/rollback or continued access. Missing output directories are not created.',
94
- 'Capabilities are declarations, not proof of publish/restore or runtime rendering. Project plugins and configured output destinations are not executed or checked; only an explicit --output-dir is inspected.',
95
- ],
96
- };
97
- if (options.json) printJson('doctor', report, status === 'ready' ? undefined : {
98
- code: status === 'error' ? 'doctor_failed' : 'doctor_incomplete', message: `Product diagnosis is ${status}; inspect result.checks, result.errors and result.project.`,
99
- });
100
- else {
101
- console.log(`${status.toUpperCase()}: OpenFairyGUI ${cliVersion} (documentation ${version.packageVersion}, Node ${report.nodeVersion})`);
102
- for (const error of errors) console.log(`${error.code}: ${error.message}`);
103
- for (const check of checks) console.log(`${check.status} ${check.id}${'path' in check ? ` ${check.path} (inspected ${check.inspectedPath})` : ''}: ${check.message}`);
104
- if (project) {
105
- console.log(`Project ${project.status}: ${projectPath}`);
106
- for (const diagnostic of project.diagnostics) console.log(`${diagnostic.severity} ${diagnostic.code} ${diagnostic.path}: ${diagnostic.message}`);
107
- }
108
- console.log(report.limits.join('\n'));
109
- }
110
- process.exitCode = status === 'ready' ? 0 : status === 'error' ? 1 : 3;
111
- });
112
- }
@@ -1,49 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { inspect, type InspectReport } from '@openfairygui/functions';
3
- import { NodeIO } from '@openfairygui/core/node';
4
- import { resolveFairyPath } from '../utils/project-input.js';
5
- import { printJson } from '../utils/json-output.js';
6
-
7
- export function registerInspectCommand(program: Command): void {
8
- program
9
- .command('inspect')
10
- .description('Show project contents report')
11
- .argument('<project-dir>', 'Project root directory or .fairy file')
12
- .option('--json', 'Print the machine-readable inspection report')
13
- .action(async (projectDir: string, options: { json?: boolean }) => {
14
- const fairyPath = await resolveFairyPath(projectDir);
15
-
16
- const io = new NodeIO();
17
- const doc = await io.readProject(fairyPath);
18
- const report = inspect(doc);
19
-
20
- if (options.json) printJson('inspect', report);
21
- else {
22
- console.log(`Project: ${fairyPath}\n`);
23
- printReport(report);
24
- }
25
- });
26
- }
27
-
28
- function printReport(report: InspectReport): void {
29
- console.log(`ID: ${report.projectId}`);
30
- console.log(`Type: ${report.projectType}, Version: ${report.version}`);
31
- console.log(`\nPackages: ${report.totals.packages}`);
32
- console.log(` Images: ${report.totals.images}`);
33
- console.log(` Sounds: ${report.totals.sounds}`);
34
- console.log(` Fonts: ${report.totals.fonts}`);
35
- console.log(` MovieClips: ${report.totals.movieClips}`);
36
- console.log(` Components: ${report.totals.components}`);
37
- console.log(` DisplayObjs: ${report.totals.displayObjects}`);
38
- console.log(` Gears: ${report.totals.gears}`);
39
- console.log(` Controllers: ${report.totals.controllers}`);
40
- console.log(` Transitions: ${report.totals.transitions}`);
41
-
42
- console.log('\nPackage details:');
43
- for (const pkg of report.packages) {
44
- const res = pkg.resources;
45
- console.log(
46
- ` ${pkg.name} (${pkg.id}): ${res.images.count} img, ${res.sounds.count} snd, ${res.fonts.count} font, ${res.components.count} comp`,
47
- );
48
- }
49
- }
@@ -1,72 +0,0 @@
1
- import path from 'node:path';
2
- import { NodeIO } from '@openfairygui/core/node';
3
- import { resolvePublishOptions } from '@openfairygui/functions';
4
- import { publishNode } from '@openfairygui/functions/node';
5
- import type { Command } from 'commander';
6
- import { resolveFairyPath } from '../utils/project-input.js';
7
- import { parseProjectType } from '../utils/project-type.js';
8
- import { printJson } from '../utils/json-output.js';
9
-
10
- type PublishCommandOptions = {
11
- output?: string;
12
- compressed?: boolean;
13
- packages?: string;
14
- branch?: string;
15
- projectType?: string;
16
- json?: boolean;
17
- };
18
-
19
- export function registerPublishCommand(program: Command): void {
20
- program
21
- .command('publish')
22
- .description('Publish project to binary outputs and configured generated code')
23
- .argument('<project-dir>', 'Project root directory or .fairy file')
24
- .option('--json', 'Print one JSON result or error (exit 0: success, 1: workflow failure, 2: invalid arguments)')
25
- .option('-o, --output <dir>', 'Override project or package publish output directory')
26
- .option('-c, --compressed', 'Compress binary data (overrides project setting)')
27
- .option('-p, --packages <a,b,c>', 'Only publish specific packages (comma-separated)')
28
- .option('-b, --branch <name>', 'Active branch used by "主干合并活跃分支"; omit for main branch')
29
- .option(
30
- '-t, --project-type <name|id>',
31
- 'Override project type (for example: unity, layabox, cocoscreator, 0, 4, 3)',
32
- )
33
- .action(async (projectDir: string, options: PublishCommandOptions) => {
34
- const fairyPath = await resolveFairyPath(projectDir);
35
- const projectRootDir = path.dirname(fairyPath);
36
- const outputDir = options.output ? path.resolve(options.output) : undefined;
37
-
38
- console.log(`Reading project: ${fairyPath}`);
39
- const io = new NodeIO();
40
- const doc = await io.readProject(fairyPath);
41
- const projectType = parseProjectType(options.projectType);
42
- if (projectType !== undefined) {
43
- doc.getRoot().setProjectType(projectType);
44
- }
45
-
46
- const pkgFilter = options.packages?.split(',').map((value) => value.trim());
47
- const resolved = resolvePublishOptions(doc, {
48
- compressed: options.compressed,
49
- packages: pkgFilter,
50
- targetProjectType: projectType,
51
- });
52
-
53
- console.log(`Settings: ext=${resolved.fileExtension}, compressed=${resolved.compressed}`);
54
- if (options.branch) {
55
- console.log(`Active branch: ${options.branch}`);
56
- }
57
-
58
- const result = await publishNode({
59
- document: doc,
60
- output: outputDir,
61
- compressed: resolved.compressed,
62
- fileExtension: resolved.fileExtension,
63
- packages: resolved.packages,
64
- assetsPath: path.join(projectRootDir, 'assets'),
65
- atlas: resolved.atlas,
66
- branch: options.branch,
67
- });
68
- if (options.json) { printJson('publish', result); return; }
69
-
70
- console.log(`\nDone!${outputDir ? ` Output override: ${outputDir}` : ''}`);
71
- });
72
- }
@@ -1,56 +0,0 @@
1
- import path from 'node:path';
2
- import { restoreNode } from '@openfairygui/functions/node';
3
- import type { Command } from 'commander';
4
- import { parseProjectType } from '../utils/project-type.js';
5
- import { printJson } from '../utils/json-output.js';
6
-
7
- type RestoreCommandOptions = {
8
- output: string;
9
- packages?: string;
10
- force?: boolean;
11
- projectType?: string;
12
- json?: boolean;
13
- };
14
-
15
- export function registerRestoreCommand(program: Command): void {
16
- program
17
- .command('restore')
18
- .description('Recover a project directory from trusted local published artifacts')
19
- .argument('<release-dir>', 'Published release directory')
20
- .option('--json', 'Print one JSON result or error (exit 0: success, 1: workflow failure, 2: invalid arguments)')
21
- .requiredOption('-o, --output <dir>', 'Output project directory')
22
- .option('-p, --packages <a,b,c>', 'Only restore specific packages (comma-separated)')
23
- .option('-f, --force', 'Replace a non-empty output directory only after a complete staged restore')
24
- .option('-t, --project-type <name|id>', 'Override restored project type; default is unity')
25
- .action(async (releaseDir: string, options: RestoreCommandOptions) => {
26
- const inputDir = path.resolve(releaseDir);
27
- const outputDir = path.resolve(options.output);
28
- const pkgFilter = options.packages
29
- ? options.packages
30
- .split(',')
31
- .map((value) => value.trim())
32
- .filter(Boolean)
33
- : undefined;
34
- const projectType = parseProjectType(options.projectType);
35
-
36
- console.log(`Restoring published FairyGUI project: ${inputDir}`);
37
- const result = await restoreNode({
38
- inputDir,
39
- output: outputDir,
40
- packages: pkgFilter,
41
- force: options.force,
42
- projectType,
43
- });
44
-
45
- const packages = result.document.getRoot().listPackages();
46
- if (options.json) {
47
- printJson('restore', { projectPath: result.projectPath, packages: packages.map((pkg) => ({ id: pkg.getId(), name: pkg.getName() })), warnings: result.warnings });
48
- return;
49
- }
50
- console.log(`\nDone! Output: ${result.projectPath}`);
51
- console.log(`Packages: ${packages.map((pkg) => pkg.getName()).join(', ')}`);
52
- for (const warning of result.warnings) {
53
- console.warn(`Warning: ${warning}`);
54
- }
55
- });
56
- }
@@ -1,29 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { validateProjectNode } from '@openfairygui/functions/node';
3
- import { resolveFairyPath } from '../utils/project-input.js';
4
- import { printJson } from '../utils/json-output.js';
5
-
6
- export function registerValidateCommand(program: Command): void {
7
- program
8
- .command('validate')
9
- .description('Validate project structure, references, and source files')
10
- .argument('<project-dir>', 'Project root directory or .fairy file')
11
- .option('--json', 'Print the machine-readable validation report')
12
- .action(async (projectDir: string, options: { json?: boolean }) => {
13
- const fairyPath = await resolveFairyPath(projectDir);
14
- const report = await validateProjectNode(fairyPath);
15
- if (options.json) {
16
- printJson('validate', report, report.status === 'valid' ? undefined : {
17
- code: report.status === 'invalid' ? 'validation_failed' : 'validation_incomplete',
18
- message: `Project validation is ${report.status}; inspect result.diagnostics.`,
19
- });
20
- } else {
21
- console.log(`${report.status.toUpperCase()}: ${fairyPath}`);
22
- for (const diagnostic of report.diagnostics) {
23
- const source = diagnostic.sourcePath ? ` (${diagnostic.sourcePath})` : '';
24
- console.log(`${diagnostic.severity.toUpperCase()} ${diagnostic.code} ${diagnostic.path}${source}: ${diagnostic.message}`);
25
- }
26
- }
27
- process.exitCode = report.status === 'valid' ? 0 : report.status === 'invalid' ? 1 : 3;
28
- });
29
- }
package/src/contracts.ts DELETED
@@ -1,50 +0,0 @@
1
- import type { ProjectValidationReport } from '@openfairygui/core';
2
- import type { InspectReport } from '@openfairygui/functions';
3
- import type { PublishNodeResult } from '@openfairygui/functions/node';
4
- import type { BackendRuntime } from '@openfairygui/backend';
5
- import type { getInstalledDocumentationIndex, getInstalledDocumentationVersion, readInstalledDocumentation } from '@openfairygui/backend/docs';
6
-
7
- export interface DoctorReport extends ReturnType<typeof getInstalledDocumentationVersion> {
8
- scope: 'installed-product';
9
- cliVersion: string;
10
- nodeVersion: string;
11
- status: 'ready' | 'error' | 'incomplete';
12
- errors: { code: 'installed_version_mismatch' | 'unsupported_node_version' | 'project_check_failed'; message: string }[];
13
- checks: (
14
- | { id: 'native-images'; status: 'ok' | 'incomplete'; message: string; version?: string }
15
- | { id: 'temp-directory' | 'output-directory'; status: 'ok' | 'error'; path: string; inspectedPath: string; exists: boolean | null; message: string }
16
- )[];
17
- capabilities: ReturnType<BackendRuntime['getCapabilities']>;
18
- projectPath: string | null;
19
- project: ProjectValidationReport | null;
20
- limits: string[];
21
- }
22
-
23
- /** CLI owns transport shapes; workflow reports remain owned by their packages. */
24
- export interface CliCommandResults {
25
- ofgui: never;
26
- docs: never;
27
- inspect: InspectReport;
28
- validate: ProjectValidationReport;
29
- publish: PublishNodeResult;
30
- restore: { projectPath: string; packages: { id: string; name: string }[]; warnings: string[] };
31
- doctor: DoctorReport;
32
- 'backend-capabilities': Extract<ReturnType<BackendRuntime['getCapabilities']>, { ok: true }>['data'];
33
- 'docs ls': ReturnType<typeof getInstalledDocumentationIndex>;
34
- 'docs find': ReturnType<typeof getInstalledDocumentationIndex>;
35
- 'docs cat': ReturnType<typeof readInstalledDocumentation>;
36
- 'docs diagnostic': ReturnType<typeof readInstalledDocumentation>;
37
- 'docs schema': ReturnType<typeof readInstalledDocumentation>;
38
- }
39
-
40
- export type CliCommand = keyof CliCommandResults;
41
- export interface CliError {
42
- code: 'invalid_arguments' | 'command_failed' | 'publish_failed' | 'restore_failed' | 'documentation_unavailable'
43
- | 'validation_failed' | 'validation_incomplete' | 'doctor_failed' | 'doctor_incomplete';
44
- message: string;
45
- }
46
- export type CliEnvelope<C extends CliCommand> =
47
- | { schemaVersion: 1; command: C; success: true; result: CliCommandResults[C] }
48
- | { schemaVersion: 1; command: C; success: false; error: CliError; result?: CliCommandResults[C] };
49
- /** The generator emits one schema per command, including parser-only failures. */
50
- export type CliOutputContracts = { [C in CliCommand]: CliEnvelope<C> };
@@ -1,40 +0,0 @@
1
- import type { Command } from 'commander';
2
- import type { CliCommand, CliCommandResults, CliEnvelope, CliError } from '../contracts.js';
3
-
4
- // Keep exactly one JSON document on stdout, even if a trusted project plugin logs.
5
- const stdout = process.stdout.write.bind(process.stdout);
6
- export function wantsJson(argv: string[]): boolean {
7
- const args = argv.slice(2, argv.indexOf('--') < 0 ? undefined : argv.indexOf('--'));
8
- return args.includes('--json') && !args.some((arg) => ['--help', '-h', '--version', '-V'].includes(arg));
9
- }
10
-
11
- export function configureJson(program: Command): void {
12
- program.option('--json', 'Print one JSON envelope (exit 0: success, 1: failure, 2: arguments, 3: incomplete)').exitOverride();
13
- if (wantsJson(process.argv)) process.stdout.write = process.stderr.write.bind(process.stderr);
14
- program.hook('preAction', (_root, command) => { command.setOptionValue('json', command.optsWithGlobals().json); });
15
- }
16
-
17
- export function parsedCommand(program: Command): CliCommand {
18
- const names: string[] = [];
19
- let current = program;
20
- for (;;) {
21
- const next = current.commands.find((command) => command.name() === current.args[0]);
22
- if (!next) break;
23
- names.push(next.name());
24
- current = next;
25
- }
26
- // test:repo checks all registered command paths against CliOutputContracts.
27
- return (names.join(' ') || 'ofgui') as CliCommand;
28
- }
29
-
30
- export function printJson<C extends CliCommand>(command: C, result: CliCommandResults[C], error?: CliError): void {
31
- const envelope: CliEnvelope<C> = error
32
- ? { schemaVersion: 1, command, success: false, error, result }
33
- : { schemaVersion: 1, command, success: true, result };
34
- stdout(`${JSON.stringify(envelope)}\n`);
35
- }
36
-
37
- export function printJsonError(command: CliCommand, error: CliError): void {
38
- const envelope: CliEnvelope<CliCommand> = { schemaVersion: 1, command, success: false, error };
39
- stdout(`${JSON.stringify(envelope)}\n`);
40
- }
@@ -1,23 +0,0 @@
1
- import { createRequire } from 'node:module';
2
-
3
- const require = createRequire(import.meta.url);
4
- declare const __OPENFAIRYGUI_PACKAGE_VERSION__: string | undefined;
5
-
6
- function getInjectedPackageVersion(): string | null {
7
- const version = typeof __OPENFAIRYGUI_PACKAGE_VERSION__ === 'string' ? __OPENFAIRYGUI_PACKAGE_VERSION__ : null;
8
- return typeof version === 'string' && version.length > 0 ? version : null;
9
- }
10
-
11
- export function readPackageVersion(): string {
12
- const injectedVersion = getInjectedPackageVersion();
13
- if (injectedVersion) return injectedVersion;
14
- try {
15
- const pkg = require('../../package.json') as { version?: unknown };
16
- if (typeof pkg.version === 'string' && pkg.version.length > 0) {
17
- return pkg.version;
18
- }
19
- } catch {
20
- // Keep the CLI usable when executed from a bundled artifact missing package.json.
21
- }
22
- return '0.0.0-dev';
23
- }
@@ -1,26 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
-
4
- /** Resolve input to a .fairy file path. Accepts a directory or a .fairy file. */
5
- export async function resolveFairyPath(input: string): Promise<string> {
6
- const resolved = path.resolve(input);
7
- const stat = await fs.stat(resolved);
8
-
9
- if (stat.isFile() && resolved.endsWith('.fairy')) {
10
- return resolved;
11
- }
12
-
13
- if (stat.isDirectory()) {
14
- const entries = await fs.readdir(resolved);
15
- const fairyFiles = entries.filter((entry) => entry.endsWith('.fairy'));
16
- if (fairyFiles.length === 1) {
17
- return path.join(resolved, fairyFiles[0]);
18
- }
19
- if (fairyFiles.length > 1) {
20
- throw new Error(`Multiple .fairy files found in ${resolved}: ${fairyFiles.join(', ')}. Please specify one.`);
21
- }
22
- throw new Error(`No .fairy file found in ${resolved}`);
23
- }
24
-
25
- throw new Error(`Input is not a .fairy file or directory: ${resolved}`);
26
- }