An open source design system that's fully customizable and agent ready
TypeScript
perf(cli): a run of astryx loads only the command it names (#9822)
Christopher Chedeau1800b47b3e51
diff --git a/.changeset/cli-load-only-the-named-command.md b/.changeset/cli-load-only-the-named-command.mdnew file mode 100644index 0000000000..43d9662e96--- /dev/null+++ b/.changeset/cli-load-only-the-named-command.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[perf] A run of `astryx` loads only the command it names, so it starts with less work: `astryx --version` uses about 0.31 s less CPU, and `astryx docs --json`, `astryx component --list` and `astryx theme build` about 0.25–0.3 s less. Help, the manifest and an unknown command still load every command. Output and exit codes are unchanged.++@vjeuxdiff --git a/packages/cli/clients/cli/command-load-failure.test.mjs b/packages/cli/clients/cli/command-load-failure.test.mjsindex 54e170526c..372f29b3a5 100644--- a/packages/cli/clients/cli/command-load-failure.test.mjs+++ b/packages/cli/clients/cli/command-load-failure.test.mjs@@ -80,4 +80,11 @@ describe('a command that fails to load', () => {expect(status).toBe(0);expect(JSON.parse(stdout).type).toMatch(/^docs\./);});++ it('is listed in help, which loads every command, beside the others', () => {+ const {status, stdout} = run(['--help']);+ expect(status).toBe(0);+ expect(stdout).toMatch(/blog\s+\(failed to load: simulated load failure\)/);+ expect(stdout).toMatch(/\bdocs\b/);+ });});diff --git a/packages/cli/clients/cli/command-result-coverage.test.mjs b/packages/cli/clients/cli/command-result-coverage.test.mjsindex 4dc3f085ff..232e7cb46b 100644--- a/packages/cli/clients/cli/command-result-coverage.test.mjs+++ b/packages/cli/clients/cli/command-result-coverage.test.mjs@@ -25,7 +25,7 @@*/import {describe, it, expect} from 'vitest';-import {program} from './index.mjs';+import {program} from './program.mjs';import {reportsResult, reportsResultVia} from './lib/define-command.mjs';/**diff --git a/packages/cli/clients/cli/commands-for-args.test.mjs b/packages/cli/clients/cli/commands-for-args.test.mjsnew file mode 100644index 0000000000..63afcb034d--- /dev/null+++ b/packages/cli/clients/cli/commands-for-args.test.mjs@@ -0,0 +1,141 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A run of the bin loads only the command its arguments name+ * (commandsForArgs in index.mjs). It prints what the full program prints,+ * with the same exit status. That holds for help on every command and+ * subcommand, in text and JSON, for the manifest and for the root's own+ * answers.+ */++import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {COMMAND_NAMES, commandsForArgs, createProgram} from './index.mjs';+import {runCli} from '../../test-utils/run-cli.mjs';++/** @type {import('commander').Command} */+let full;+/** @type {string} */+let dir;++beforeAll(async () => {+ full = await createProgram();+ // Outside any project, so no project changes what help prints.+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-commands-for-args-'));+});++afterAll(() => {+ fs.rmSync(dir, {recursive: true, force: true});+});++/** @param {string[]} argv */+const loads = argv => {+ const names = commandsForArgs(full, argv);+ return names == null ? null : [...names];+};++describe('commandsForArgs', () => {+ it('names the first operand after the root options', () => {+ expect(loads(['docs'])).toEqual(['docs']);+ expect(loads(['docs', 'tokens', '--dense'])).toEqual(['docs']);+ expect(loads(['--json', 'docs'])).toEqual(['docs']);+ expect(loads(['--detail', 'brief', 'docs'])).toEqual(['docs']);+ expect(loads(['--detail=brief', 'docs'])).toEqual(['docs']);+ expect(loads(['--lang', 'zh', 'component', 'Button'])).toEqual([+ 'component',+ ]);+ expect(loads(['theme', 'build', 'theme.mjs'])).toEqual(['theme']);+ });++ // A registry name that differs from the name its module registers would+ // make `astryx <name>` answer differently from the full program.+ it('has one registry entry for each command of the full program, by name', async () => {+ const names = full.commands.map(command => command.name());+ expect([...COMMAND_NAMES].sort()).toEqual([...names].sort());+ for (const name of COMMAND_NAMES) {+ if (name === 'manifest') {+ expect(loads([name])).toBeNull();+ continue;+ }+ expect(loads([name]), name).toEqual([name]);+ const routed = await createProgram({argv: [name]});+ expect(+ routed.commands.map(command => command.name()),+ name,+ ).toEqual([name]);+ }+ });++ it('loads no command for a run that only prints the version', () => {+ expect(loads(['--version'])).toEqual([]);+ expect(loads(['-V', '--json'])).toEqual([]);+ });++ it('loads every command when the run prints or reads the whole list', () => {+ for (const argv of [+ [],+ ['--json'],+ ['--help'],+ ['-h'],+ ['--help', 'docs'],+ ['help', 'docs'],+ ['manifest', '--json'],+ ['no-such-command'],+ ['--no-such-flag', 'docs'],+ // Commander reads a value given to a flag that takes none as unknown.+ ['--json=1', 'docs'],+ ['--', 'docs'],+ ['-'],+ ['--detail'],+ ]) {+ expect(loads(argv), argv.join(' ')).toBeNull();+ }+ });+});++describe('a run that loads only its command prints what the full program prints', () => {+ /** @param {string[]} argv */+ const expectSameAnswer = async argv => {+ const asBin = await runCli(argv, {cwd: dir, asBin: true});+ const everything = await runCli(argv, {cwd: dir});+ expect(asBin, argv.join(' ')).toEqual(everything);+ };++ it('for help on every command and subcommand, in text and JSON', async () => {+ /** @type {string[][]} */+ const paths = [];+ /** @param {import('commander').Command} cmd @param {string[]} parent */+ const walk = (cmd, parent) => {+ for (const sub of cmd.commands) {+ paths.push([...parent, sub.name()]);+ walk(sub, [...parent, sub.name()]);+ }+ };+ walk(full, []);+ expect(paths.length).toBeGreaterThan(full.commands.length);+ for (const commandPath of paths) {+ await expectSameAnswer([...commandPath, '--help']);+ await expectSameAnswer([...commandPath, '--help', '--json']);+ }+ });++ it('for the root, the manifest and the version', async () => {+ for (const argv of [+ ['--help'],+ ['--help', 'docs'],+ ['-h', 'theme'],+ ['--json'],+ ['manifest', '--json'],+ ['help', 'docs'],+ ['--version'],+ ['no-such-command'],+ ['--detail', 'brief', 'docs', '--help'],+ ['--lang', 'zh', 'component', '--help'],+ ['docs', '--no-such-flag'],+ ]) {+ await expectSameAnswer(argv);+ }+ });+});diff --git a/packages/cli/clients/cli/commands/build.playbook.test.mjs b/packages/cli/clients/cli/commands/build.playbook.test.mjsindex a3abe77427..90ab84bb68 100644--- a/packages/cli/clients/cli/commands/build.playbook.test.mjs+++ b/packages/cli/clients/cli/commands/build.playbook.test.mjs@@ -10,7 +10,7 @@ import {describe, it, expect} from 'vitest';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {runCli} from '../../../test-utils/run-cli.mjs';-import {program} from '../index.mjs';+import {program} from '../program.mjs';// Run against the monorepo root so @astryxdesign/core is discoverable.const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');diff --git a/packages/cli/clients/cli/commands/outside-project.test.mjs b/packages/cli/clients/cli/commands/outside-project.test.mjsindex 5cd5459f8d..5c50898028 100644--- a/packages/cli/clients/cli/commands/outside-project.test.mjs+++ b/packages/cli/clients/cli/commands/outside-project.test.mjs@@ -23,7 +23,8 @@ import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath, pathToFileURL} from 'node:url';import {afterAll, afterEach, beforeAll, describe, expect, it, vi} from 'vitest';-import {program, JSON_SUPPORTED} from '../index.mjs';+import {JSON_SUPPORTED} from '../index.mjs';+import {program} from '../program.mjs';import {buildManifest} from '../lib/manifest.mjs';import {runCli} from '../../../test-utils/run-cli.mjs';import {diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex b6f9f5e642..da195222e0 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -3,13 +3,13 @@/*** @file Astryx CLI — Commander program setup*- * Registers all commands via lazy loading. If one command fails to load- * (bad import, syntax error), the other commands still work.+ * Commands load lazily: a bin run loads only the one its arguments name.+ * One that fails to load (bad import, syntax error) leaves the rest working.** The program is built by {@link createProgram} — a factory so tests can drive* a FRESH program in-process (via parseAsync) instead of spawning `node- * bin/astryx.mjs` per assertion. `bin/astryx.mjs` and legacy importers use the- * eager {@link program} singleton, which is just `await createProgram()`.+ * bin/astryx.mjs` per assertion. Code that reads every command at once uses+ * the full program in program.mjs.*/import {Command, Option} from 'commander';@@ -329,6 +329,52 @@ const commands = [{name: 'postinstall', path: './commands/postinstall.mjs', register: 'registerPostinstall'},];+/** The name each registry entry registers, in registration order. */+export const COMMAND_NAMES = Object.freeze(commands.map(cmd => cmd.name));++/** Commands whose run reads every other command: the manifest lists them. */+const READS_EVERY_COMMAND = new Set(['manifest']);++/**+ * The commands a run of the bin loads. Commander dispatches a run to its+ * first operand after the root's own options, so this reads the arguments the+ * same way. It returns that one command, no command for a run that only+ * prints the version, or null for every command. These runs load every+ * command: help, the manifest, `help <command>`, an unknown word, and a flag+ * the root does not declare. They print or read the whole list.+ *+ * @param {import('commander').Command} program the root, with its options+ * @param {string[]} argv the arguments after `astryx`+ * @returns {Set<string> | null}+ */+export function commandsForArgs(program, argv) {+ let printsVersion = false;+ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i];+ // Commander reads a lone `-` as an operand, as it reads any word.+ if (arg.length < 2 || arg[0] !== '-') {+ return commands.some(cmd => cmd.name === arg) && !READS_EVERY_COMMAND.has(arg)+ ? new Set([arg])+ : null;+ }+ const equals = arg.startsWith('--') ? arg.indexOf('=') : -1;+ const flag = equals === -1 ? arg : arg.slice(0, equals);+ const option = program.options.find(o => o.long === flag || o.short === flag);+ // Help flags, `--`, combined short flags and unknown flags read the whole+ // list, or make Commander stop dispatching by name.+ if (option == null) return null;+ const takesValue = option.required || option.optional;+ if (equals !== -1 && !takesValue) return null;+ if (equals === -1 && option.required) i += 1;+ const next = argv[i + 1];+ if (equals === -1 && option.optional && next != null && !(next.length > 1 && next[0] === '-')) {+ i += 1;+ }+ if (option.long === '--version') printsVersion = true;+ }+ return printsVersion ? new Set() : null;+}+const SETUP_NUDGE_EXEMPT = new Set(['init', 'agent-docs']);/**@@ -363,9 +409,12 @@ const INTEGRATION_MANIFEST_FILES = [* lazy-imported. Each call returns an independent Command so tests can* parseAsync repeatedly without commander state leaking between runs.*+ * @param {{argv?: string[]}} [options] `argv`, the arguments after `astryx`:+ * load only the commands a run of them needs (commandsForArgs). Without+ * it, every command loads.* @returns {Promise<import('commander').Command>}*/-export async function createProgram() {+export async function createProgram({argv} = {}) {const program = new Command();// Deterministic, single-line help. Commander wraps each option/command@@ -708,7 +757,9 @@ export async function createProgram() {}});+ const loads = argv == null ? null : commandsForArgs(program, argv);for (const cmd of commands) {+ if (loads != null && !loads.has(cmd.name)) continue;try {const mod = await import(cmd.path);mod[cmd.register](program, {jsonSupported: JSON_SUPPORTED, version: pkg.version});@@ -740,9 +791,3 @@ export async function createProgram() {return program;}--/**- * Eager singleton program for `bin/astryx.mjs` and legacy importers. Tests- * should call {@link createProgram} to get an isolated instance.- */-export const program = await createProgram();diff --git a/packages/cli/clients/cli/lib/exit-codes.test.mjs b/packages/cli/clients/cli/lib/exit-codes.test.mjsindex 39563e83b8..9107088016 100644--- a/packages/cli/clients/cli/lib/exit-codes.test.mjs+++ b/packages/cli/clients/cli/lib/exit-codes.test.mjs@@ -9,7 +9,8 @@ import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath, pathToFileURL} from 'node:url';import {describe, it, expect} from 'vitest';-import {program, JSON_SUPPORTED} from '../index.mjs';+import {JSON_SUPPORTED} from '../index.mjs';+import {program} from '../program.mjs';import {buildManifest} from './manifest.mjs';import {runCli} from '../../../test-utils/run-cli.mjs';diff --git a/packages/cli/clients/cli/lib/manifest.test.mjs b/packages/cli/clients/cli/lib/manifest.test.mjsindex 0f576164c9..ac724096eb 100644--- a/packages/cli/clients/cli/lib/manifest.test.mjs+++ b/packages/cli/clients/cli/lib/manifest.test.mjs@@ -19,7 +19,8 @@ import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath, pathToFileURL} from 'node:url';import {afterAll, beforeAll, describe, it, expect} from 'vitest';-import {program, JSON_SUPPORTED} from '../index.mjs';+import {JSON_SUPPORTED} from '../index.mjs';+import {program} from '../program.mjs';import {buildManifest} from './manifest.mjs';import {runCli} from '../../../test-utils/run-cli.mjs';diff --git a/packages/cli/clients/cli/program.mjs b/packages/cli/clients/cli/program.mjsnew file mode 100644index 0000000000..9bd172c089--- /dev/null+++ b/packages/cli/clients/cli/program.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The full Astryx CLI program, with every command loaded.+ *+ * @input createProgram (index.mjs).+ * @output `program`, built once when this module loads.+ * @position For code that reads every command at once, such as tests of the+ * manifest and the docs drift check. A run of the bin builds its own+ * program from its arguments (run.mjs), so it does not load this module.+ */++import {createProgram} from './index.mjs';++export const program = await createProgram();diff --git a/packages/cli/clients/cli/run.mjs b/packages/cli/clients/cli/run.mjsindex 550ee27317..0de29b2535 100644--- a/packages/cli/clients/cli/run.mjs+++ b/packages/cli/clients/cli/run.mjs@@ -33,11 +33,14 @@ export async function runCli({cliRoot, argv, declinedProjectCli}) {if (answered) return answered;const {- program,+ createProgram,loadProjectDebugHandler,loadProjectForHelp,handleVersionJsonPreflight,} = await import('./index.mjs');+ // Only the commands these arguments need load, before anything below runs,+ // as the full program did.+ const program = await createProgram({argv: process.argv.slice(2)});const {isJsonMode, toErrorEnvelope} =await import('../../foundation/response/json.mjs');const {handleCommanderError} = await import('./lib/json-shim.mjs');diff --git a/packages/cli/test-utils/run-cli.mjs b/packages/cli/test-utils/run-cli.mjsindex d632ca331b..42b7fd86c9 100644--- a/packages/cli/test-utils/run-cli.mjs+++ b/packages/cli/test-utils/run-cli.mjs@@ -39,13 +39,16 @@ class ExitSignal extends Error {* Run the Astryx CLI in-process and capture its observable surface.** @param {string[]} args argv after `astryx` (e.g. `['component', '--list']`)- * @param {string | {cwd?: string}} [cwdOrOpts] cwd (positional) or `{cwd}`+ * @param {string | {cwd?: string, asBin?: boolean}} [cwdOrOpts] cwd+ * (positional), or `{cwd}`. `asBin` builds the program as a run of the bin+ * does: with only the commands these arguments need.* @returns {Promise<{status: number, code: number, stdout: string, stderr: string}>}*/export async function runCli(args, cwdOrOpts) {const cwd =typeof cwdOrOpts === 'string' ? cwdOrOpts : cwdOrOpts && cwdOrOpts.cwd;- const program = await createProgram();+ const asBin = typeof cwdOrOpts === 'object' && cwdOrOpts?.asBin === true;+ const program = await createProgram(asBin ? {argv: args} : undefined);// Commander's own exits (parse errors, --help, --version, unknown option)// throw a CommanderError instead of calling process.exit.program.exitOverride();diff --git a/packages/cli/test/cli-strict-guard.test.mjs b/packages/cli/test/cli-strict-guard.test.mjsindex 4b2529e87c..1d1dbd2c1c 100644--- a/packages/cli/test/cli-strict-guard.test.mjs+++ b/packages/cli/test/cli-strict-guard.test.mjs@@ -19,7 +19,8 @@*/import {describe, expect, it} from 'vitest';-import {JSON_SUPPORTED, program} from '../clients/cli/index.mjs';+import {JSON_SUPPORTED} from '../clients/cli/index.mjs';+import {program} from '../clients/cli/program.mjs';import {buildManifest} from '../clients/cli/lib/manifest.mjs';/** The commands the CLI surface spec allows to fail on a warning. */diff --git a/packages/cli/test/docs-graph.test.mjs b/packages/cli/test/docs-graph.test.mjsindex 03fedffa64..590634ea40 100644--- a/packages/cli/test/docs-graph.test.mjs+++ b/packages/cli/test/docs-graph.test.mjs@@ -34,7 +34,8 @@ import {import {routeSegment} from '../foundation/discovery/docs-section-key.mjs';import {EXPERIMENTAL_AUTHORING_ROUTE} from '../foundation/discovery/authoring-self-docs.mjs';import {generateCompressedIndex} from '../foundation/agent-docs/agent-docs.mjs';-import {program, JSON_SUPPORTED} from '../clients/cli/index.mjs';+import {JSON_SUPPORTED} from '../clients/cli/index.mjs';+import {program} from '../clients/cli/program.mjs';import {buildManifest} from '../clients/cli/lib/manifest.mjs';import {runCli} from '../test-utils/run-cli.mjs';diff --git a/packages/cli/test/drift/docs-drift.mjs b/packages/cli/test/drift/docs-drift.mjsindex afd4e47e0c..d3086a7ce3 100644--- a/packages/cli/test/drift/docs-drift.mjs+++ b/packages/cli/test/drift/docs-drift.mjs@@ -113,7 +113,7 @@ export async function runDrift() {manifest.commands.forEach(walkCmd);// Hidden commands (a package-script hook) have a CommandDoc but no manifest// entry, by design.- const {program} = await import('../../clients/cli/index.mjs');+ const {program} = await import('../../clients/cli/program.mjs');const hiddenNames = new Set(program.commands.filter(c => /** @type {any} */ (c)._hidden)diff --git a/packages/cli/test/readme-prose.test.mjs b/packages/cli/test/readme-prose.test.mjsindex 069ed9d1b6..02ebd03c6d 100644--- a/packages/cli/test/readme-prose.test.mjs+++ b/packages/cli/test/readme-prose.test.mjs@@ -10,7 +10,8 @@ import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {afterAll, beforeAll, describe, it, expect} from 'vitest';-import {program, JSON_SUPPORTED} from '../clients/cli/index.mjs';+import {JSON_SUPPORTED} from '../clients/cli/index.mjs';+import {program} from '../clients/cli/program.mjs';import {buildManifest} from '../clients/cli/lib/manifest.mjs';import {runCli} from '../test-utils/run-cli.mjs';