An open source design system that's fully customizable and agent ready
TypeScript
perf(cli): a run loads the project and integration modules on use (#9855)
Christopher Chedeau02c7228a8b90
diff --git a/.changeset/cli-run-loads-project-modules-on-use.md b/.changeset/cli-run-loads-project-modules-on-use.mdnew file mode 100644index 0000000000..ecca360e47--- /dev/null+++ b/.changeset/cli-run-loads-project-modules-on-use.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[perf] Outside a project whose config names `debug` or `integrations`, `astryx --version` no longer loads the project, integration and code-rewrite modules. In a folder with no project config, it uses about three quarters less CPU. When no integration is installed, `astryx docs` and `astryx hook --list` load the project but not the code-rewrite modules. Output and exit codes are unchanged.++@vjeuxdiff --git a/packages/cli/clients/cli/commands/debug-result-summary.test.mjs b/packages/cli/clients/cli/commands/debug-result-summary.test.mjsindex 660923e9c6..df5d6a3b90 100644--- a/packages/cli/clients/cli/commands/debug-result-summary.test.mjs+++ b/packages/cli/clients/cli/commands/debug-result-summary.test.mjs@@ -14,10 +14,11 @@* @position packages/cli/clients/cli/commands — debug result integration*/-import {afterEach, describe, expect, it} from 'vitest';+import {afterEach, beforeAll, describe, expect, it} from 'vitest';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {runCli} from '../../../test-utils/run-cli.mjs';+import {createProgram} from '../index.mjs';import {begin,finish,@@ -44,6 +45,13 @@ async function runWithDebug(args) {return {run, event: events[0]};}+// Every command module loads here, once. A command loads the project module+// only when it runs. Without this, the first case's window times that first+// load as well as the run.+beforeAll(async () => {+ await createProgram();+});+afterEach(() => resetRecorder());describe('DebugEvent result summary', () => {diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex da195222e0..ff608a5ec4 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -19,6 +19,7 @@ import * as path from 'node:path';import {formatCliCommand, getCliInvocation, quoteCommandArgument} from '../../foundation/env/package-manager.mjs';import {hasRecordedProject} from '../../foundation/env/cli-command.mjs';import {isOutsideProject} from '../../foundation/env/project-scope.mjs';+import {findConfigPath} from '../../foundation/config/config-path.mjs';import {API_VERSION, setJsonMode} from '../../foundation/response/json.mjs';import {answeredBy, runChoice} from '../../foundation/release/run-context.mjs';import {cliInstallAdvice, installFolder} from '../../foundation/release/notices.mjs';@@ -29,14 +30,18 @@ import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';import {installJsonShim} from './lib/json-shim.mjs';import {markReportsResult} from './lib/define-command.mjs';+// The light modules, not agent-docs.mjs: that one loads discovery and the+// project config, which every run would pay for at startup.import {agentDocsTargetDir,assertAgentDocsTarget,+} from '../../foundation/agent-docs/agent-docs-target.mjs';+import {CLI_ROOT} from '../../foundation/fs/paths.mjs';+import {isAstryxInitialized,isAstryxPromptInReach,-} from '../../foundation/agent-docs/agent-docs.mjs';-import {CLI_ROOT} from '../../foundation/fs/paths.mjs';-import {setupNudge} from '../../foundation/agent-docs/agent-doc-state.mjs';+ setupNudge,+} from '../../foundation/agent-docs/agent-doc-state.mjs';import * as debug from '../../foundation/debug/index.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -186,9 +191,6 @@ function fullCommandName(actionCommand, root) {*/export async function loadProjectDebugHandler() {try {- const {findConfigPath, Project} = await import(- '../../foundation/config/project.mjs'- );const configPath = findConfigPath(process.cwd());if (!configPath) return;const text = fs.readFileSync(configPath, 'utf-8');@@ -196,6 +198,9 @@ export async function loadProjectDebugHandler() {debug.noteConfigGateSkipped();return;}+ // Only now: a run in a folder with no such config never loads the project+ // module and its discovery.+ const {Project} = await import('../../foundation/config/project.mjs');await Project.load(process.cwd());} catch {// A broken config is the command's problem to report, not ours.diff --git a/packages/cli/clients/cli/startup-imports.test.mjs b/packages/cli/clients/cli/startup-imports.test.mjsnew file mode 100644index 0000000000..0b55873170--- /dev/null+++ b/packages/cli/clients/cli/startup-imports.test.mjs@@ -0,0 +1,124 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A run of the bin loads only what its command uses. A run that prints+ * the version, in a folder with no project, loads none of the large parser,+ * schema and module-loader packages. The project, integration and contribution+ * modules use them. A module hook in the child records every module that the+ * run resolves.+ */++import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {afterAll, beforeAll, describe, expect, it} from 'vitest';++const BIN = fileURLToPath(new URL('./bin/astryx.mjs', import.meta.url));++/** Packages that only project, integration and code-rewrite work uses. */+const LARGE_PACKAGES = [+ '@babel/core',+ '@babel/parser',+ 'jiti',+ 'jscodeshift',+ 'postcss',+ 'recast',+ 'zod',+];++/** @type {string} */+let dir;++beforeAll(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-startup-imports-'));+});++afterAll(() => {+ fs.rmSync(dir, {recursive: true, force: true});+});++/**+ * The name of the package a module URL is in, or null outside node_modules.+ * @param {string} url+ * @returns {string | null}+ */+function packageOf(url) {+ const marker = '/node_modules/';+ const at = url.lastIndexOf(marker);+ if (at === -1) return null;+ const parts = url.slice(at + marker.length).split('/');+ return parts[0].startsWith('@') ? `${parts[0]}/${parts[1]}` : parts[0];+}++/**+ * Run the bin with `args` in an empty folder, with its own home folder, and+ * return the packages of the modules it resolved.+ * @param {string[]} args+ * @returns {{status: number | null, packages: Set<string>}}+ */+function packagesLoadedBy(args) {+ const log = path.join(dir, 'resolved.txt');+ fs.rmSync(log, {force: true});+ const hook = path.join(dir, 'record-resolved.mjs');+ fs.writeFileSync(+ hook,+ [+ "import {appendFileSync} from 'node:fs';",+ "import {registerHooks} from 'node:module';",+ 'registerHooks({',+ ' resolve(specifier, context, nextResolve) {',+ ' const result = nextResolve(specifier, context);',+ ` appendFileSync(${JSON.stringify(log)}, result.url + '\\n');`,+ ' return result;',+ ' },',+ '});',+ '',+ ].join('\n'),+ );+ const app = path.join(dir, 'app');+ const home = path.join(dir, 'home');+ fs.mkdirSync(app, {recursive: true});+ fs.mkdirSync(home, {recursive: true});+ const env = {...process.env};+ for (const key of Object.keys(env)) {+ if (key.startsWith('VITEST') || key === 'NODE_OPTIONS') delete env[key];+ }+ Object.assign(env, {+ HOME: home,+ USERPROFILE: home,+ XDG_CACHE_HOME: path.join(dir, 'cache'),+ XDG_CONFIG_HOME: path.join(home, '.config'),+ XDG_DATA_HOME: path.join(home, '.local', 'share'),+ XDG_STATE_HOME: path.join(dir, 'state'),+ CI: '1',+ NO_UPDATE_NOTIFIER: '1',+ NO_COLOR: '1',+ });+ const result = spawnSync(+ process.execPath,+ ['--import', pathToFileURL(hook).href, BIN, ...args],+ {cwd: app, env, encoding: 'utf8'},+ );+ const packages = new Set();+ for (const url of fs.readFileSync(log, 'utf8').split('\n')) {+ const name = packageOf(url);+ if (name != null) packages.add(name);+ }+ return {status: result.status, packages};+}++describe('a run of the bin that prints the version', () => {+ it('records the packages it loads, such as the command parser', () => {+ const {status, packages} = packagesLoadedBy(['--version']);+ expect(status).toBe(0);+ expect(packages.has('commander')).toBe(true);+ });++ it('loads no parser, schema or module-loader package in a folder with no project', () => {+ const {status, packages} = packagesLoadedBy(['--version']);+ expect(status).toBe(0);+ expect(LARGE_PACKAGES.filter(name => packages.has(name))).toEqual([]);+ });+});diff --git a/packages/cli/foundation/agent-docs/agent-docs-target.mjs b/packages/cli/foundation/agent-docs/agent-docs-target.mjsnew file mode 100644index 0000000000..b394084ccc--- /dev/null+++ b/packages/cli/foundation/agent-docs/agent-docs-target.mjs@@ -0,0 +1,201 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file agent-docs-target.mjs+ * @input The folder a run starts in, the home folder, and the package.json+ * files and repository markers above the folder+ * @output AgentDocsHomeError, assertAgentDocsTarget, resolveAgentDocsRoot and+ * agentDocsTargetDir, with the realDir and REPOSITORY_MARKERS helpers+ * @position The folder agent docs go to. It imports node builtins only, so the+ * per-command setup nudge (clients/cli/index.mjs) loads it without+ * agent-docs.mjs's discovery and config. agent-docs.mjs re-exports it.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++/**+ * Thrown when agent docs would be written into the home folder, or into a+ * settings folder in it such as `~/.gemini` outside a project. Agents read the+ * files there (for example `~/.claude/CLAUDE.md` or `~/.gemini/GEMINI.md`) in+ * every project, so a project's version-pinned block never goes there. Removal+ * stays allowed.+ */+export class AgentDocsHomeError extends Error {+ /** @param {string} dir */+ constructor(dir) {+ super(+ `Agent docs are not written into the home folder, or into a settings folder in it outside a project (${dir}): agents read the files there in every project. Run init inside a project folder.`,+ );+ this.name = 'AgentDocsHomeError';+ /** The refused folder. */+ this.dir = dir;+ }+}++/**+ * `p` resolved, through symlinks when it exists.+ * @param {string} p+ * @returns {string}+ */+export function realDir(p) {+ try {+ return fs.realpathSync(path.resolve(p));+ } catch {+ return path.resolve(p);+ }+}++/**+ * `dir` relative to the home folder, compared without symlinks (and without+ * case on Windows). null when there is no home folder.+ * @param {string} dir+ * @returns {string | null}+ */+function relativeToHome(dir) {+ let home;+ try {+ home = os.homedir();+ } catch {+ return null;+ }+ if (!home) return null;+ /** @param {string} p */+ const fold = p => (process.platform === 'win32' ? p.toLowerCase() : p);+ return path.relative(fold(realDir(home)), fold(realDir(dir)));+}++/**+ * Whether `dir` is the home folder.+ * @param {string} dir+ * @returns {boolean}+ */+function isHomeFolder(dir) {+ return relativeToHome(dir) === '';+}++/**+ * Whether agent docs stay out of `dir`: the home folder, or a folder in a+ * settings folder of it (a folder of the home folder whose name starts with a+ * dot, such as `~/.gemini` or `~/.claude`) that belongs to no project there.+ * Agents read the files at the top of a settings folder in every project, so+ * the settings folder itself is never a project, even with a package.json. A+ * folder below it with a package.json at or above it is a project, such as an+ * agent worktree in `~/.codex/worktrees/<id>/<repo>`.+ * @param {string} dir+ * @returns {boolean}+ */+function isHomeOrSettingsFolder(dir) {+ const rel = relativeToHome(dir);+ if (rel == null) return false;+ if (rel === '') return true;+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {+ return false;+ }+ const parts = rel.split(path.sep);+ if (!parts[0].startsWith('.')) return false;+ // Look for a package.json from `dir` up to, not including, the settings folder.+ let current = realDir(dir);+ for (let depth = parts.length; depth > 1; depth--) {+ if (fs.existsSync(path.join(current, 'package.json'))) return false;+ current = path.dirname(current);+ }+ return true;+}++/**+ * Throw {@link AgentDocsHomeError} when `targetDir` is the home folder, or a+ * settings folder in it outside a project.+ * @param {string} targetDir+ */+export function assertAgentDocsTarget(targetDir) {+ if (isHomeOrSettingsFolder(targetDir))+ throw new AgentDocsHomeError(realDir(targetDir));+}++/** Folders that mark a repository root; the project search stops there. */+export const REPOSITORY_MARKERS = ['.git', '.hg', '.sl'];++/** Dependency fields where a project declares the Astryx packages it uses. */+const DEPENDENCY_FIELDS = [+ 'dependencies',+ 'devDependencies',+ 'peerDependencies',+ 'optionalDependencies',+];++/**+ * The package.json in `dir`: its parsed content, `null` when it exists but+ * does not parse, or `undefined` when there is none.+ * @param {string} dir+ * @returns {Record<string, unknown> | null | undefined}+ */+function readPackageJson(dir) {+ const file = path.join(dir, 'package.json');+ if (!fs.existsSync(file)) return undefined;+ try {+ const parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));+ return parsed && typeof parsed === 'object' ? parsed : null;+ } catch {+ return null;+ }+}++/**+ * Whether a parsed package.json declares an `@astryxdesign` package.+ * @param {Record<string, unknown> | null} manifest+ * @returns {boolean}+ */+function declaresAstryx(manifest) {+ return DEPENDENCY_FIELDS.some(field => {+ const deps = manifest?.[field];+ return (+ deps != null &&+ typeof deps === 'object' &&+ Object.keys(deps).some(name => name.startsWith('@astryxdesign/'))+ );+ });+}++/**+ * The folder a run started in `cwd` writes agent docs to: the nearest folder at+ * or above it whose package.json declares an `@astryxdesign` package, else the+ * nearest folder with any package.json. The search stops at a repository root+ * and never reaches the home folder, so a stray `~/package.json` cannot pull+ * the docs there.+ * @param {string} cwd+ * @returns {string | null} null when no folder it searches has a package.json;+ * init then writes where it runs, as before.+ */+export function resolveAgentDocsRoot(cwd) {+ let dir = path.resolve(cwd);+ /** @type {string | null} */+ let nearest = null;+ for (let i = 0; i < 50 && !isHomeFolder(dir); i++) {+ const manifest = readPackageJson(dir);+ if (manifest !== undefined) {+ if (declaresAstryx(manifest)) return dir;+ nearest ??= dir;+ }+ if (+ REPOSITORY_MARKERS.some(marker => fs.existsSync(path.join(dir, marker)))+ )+ break;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ return nearest;+}++/**+ * The folder `init` run in `cwd` writes the agent docs to: the project root+ * {@link resolveAgentDocsRoot} finds, else `cwd` itself. The one definition+ * that init, its removal, and the per-command setup nudge all use.+ * @param {string} cwd+ * @returns {string}+ */+export function agentDocsTargetDir(cwd) {+ return resolveAgentDocsRoot(cwd) ?? cwd;+}diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex 9633caca3b..fda1140d1d 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -31,7 +31,6 @@import {spawnSync} from 'node:child_process';import * as fs from 'node:fs';-import * as os from 'node:os';import * as path from 'node:path';import {findCoreDir, findInstalledPackage, CLI_ROOT} from '../fs/paths.mjs';import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';@@ -67,6 +66,12 @@ import {WORKFLOW_STEPS,WORKFLOW_TITLE,} from './agent-doc-state.mjs';+import {+ agentDocsTargetDir,+ assertAgentDocsTarget,+ realDir,+ REPOSITORY_MARKERS,+} from './agent-docs-target.mjs';// The agent-doc locations, markers, and the setup-state predicates// (discoverAgentDocs, isAstryxInitialized, isAstryxPromptInReach) are the ONE@@ -77,6 +82,16 @@ import {// keep their `from './agent-docs.mjs'` paths.export {discoverAgentDocs, isAstryxInitialized, isAstryxPromptInReach};+// The folder the docs go to lives in ./agent-docs-target.mjs, with node+// builtins only. So the per-command setup nudge loads it without this+// module's discovery and config. Re-exported here for existing importers.+export {+ AgentDocsHomeError,+ agentDocsTargetDir,+ assertAgentDocsTarget,+ resolveAgentDocsRoot,+} from './agent-docs-target.mjs';+const MAX_PROJECT_AGENT_DOC_LINES = 32;const MANAGED_MARKER_TEXT = /(?:ASTRYX|XDS):(START|END)/u;@@ -321,186 +336,6 @@ function geminiImportsAgentsMd(targetDir) {);}-/**- * Thrown when agent docs would be written into the home folder, or into a- * settings folder in it such as `~/.gemini` outside a project. Agents read the- * files there (for example `~/.claude/CLAUDE.md` or `~/.gemini/GEMINI.md`) in- * every project, so a project's version-pinned block never goes there. Removal- * stays allowed.- */-export class AgentDocsHomeError extends Error {- /** @param {string} dir */- constructor(dir) {- super(- `Agent docs are not written into the home folder, or into a settings folder in it outside a project (${dir}): agents read the files there in every project. Run init inside a project folder.`,- );- this.name = 'AgentDocsHomeError';- /** The refused folder. */- this.dir = dir;- }-}--/**- * `p` resolved, through symlinks when it exists.- * @param {string} p- * @returns {string}- */-function realDir(p) {- try {- return fs.realpathSync(path.resolve(p));- } catch {- return path.resolve(p);- }-}--/**- * `dir` relative to the home folder, compared without symlinks (and without- * case on Windows). null when there is no home folder.- * @param {string} dir- * @returns {string | null}- */-function relativeToHome(dir) {- let home;- try {- home = os.homedir();- } catch {- return null;- }- if (!home) return null;- /** @param {string} p */- const fold = p => (process.platform === 'win32' ? p.toLowerCase() : p);- return path.relative(fold(realDir(home)), fold(realDir(dir)));-}--/**- * Whether `dir` is the home folder.- * @param {string} dir- * @returns {boolean}- */-function isHomeFolder(dir) {- return relativeToHome(dir) === '';-}--/**- * Whether agent docs stay out of `dir`: the home folder, or a folder in a- * settings folder of it (a folder of the home folder whose name starts with a- * dot, such as `~/.gemini` or `~/.claude`) that belongs to no project there.- * Agents read the files at the top of a settings folder in every project, so- * the settings folder itself is never a project, even with a package.json. A- * folder below it with a package.json at or above it is a project, such as an- * agent worktree in `~/.codex/worktrees/<id>/<repo>`.- * @param {string} dir- * @returns {boolean}- */-function isHomeOrSettingsFolder(dir) {- const rel = relativeToHome(dir);- if (rel == null) return false;- if (rel === '') return true;- if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {- return false;- }- const parts = rel.split(path.sep);- if (!parts[0].startsWith('.')) return false;- // Look for a package.json from `dir` up to, not including, the settings folder.- let current = realDir(dir);- for (let depth = parts.length; depth > 1; depth--) {- if (fs.existsSync(path.join(current, 'package.json'))) return false;- current = path.dirname(current);- }- return true;-}--/**- * Throw {@link AgentDocsHomeError} when `targetDir` is the home folder, or a- * settings folder in it outside a project.- * @param {string} targetDir- */-export function assertAgentDocsTarget(targetDir) {- if (isHomeOrSettingsFolder(targetDir)) throw new AgentDocsHomeError(realDir(targetDir));-}--/** Folders that mark a repository root; the project search stops there. */-const REPOSITORY_MARKERS = ['.git', '.hg', '.sl'];--/** Dependency fields where a project declares the Astryx packages it uses. */-const DEPENDENCY_FIELDS = [- 'dependencies',- 'devDependencies',- 'peerDependencies',- 'optionalDependencies',-];--/**- * The package.json in `dir`: its parsed content, `null` when it exists but- * does not parse, or `undefined` when there is none.- * @param {string} dir- * @returns {Record<string, unknown> | null | undefined}- */-function readPackageJson(dir) {- const file = path.join(dir, 'package.json');- if (!fs.existsSync(file)) return undefined;- try {- const parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));- return parsed && typeof parsed === 'object' ? parsed : null;- } catch {- return null;- }-}--/**- * Whether a parsed package.json declares an `@astryxdesign` package.- * @param {Record<string, unknown> | null} manifest- * @returns {boolean}- */-function declaresAstryx(manifest) {- return DEPENDENCY_FIELDS.some(field => {- const deps = manifest?.[field];- return (- deps != null &&- typeof deps === 'object' &&- Object.keys(deps).some(name => name.startsWith('@astryxdesign/'))- );- });-}--/**- * The folder a run started in `cwd` writes agent docs to: the nearest folder at- * or above it whose package.json declares an `@astryxdesign` package, else the- * nearest folder with any package.json. The search stops at a repository root- * and never reaches the home folder, so a stray `~/package.json` cannot pull- * the docs there.- * @param {string} cwd- * @returns {string | null} null when no folder it searches has a package.json;- * init then writes where it runs, as before.- */-export function resolveAgentDocsRoot(cwd) {- let dir = path.resolve(cwd);- /** @type {string | null} */- let nearest = null;- for (let i = 0; i < 50 && !isHomeFolder(dir); i++) {- const manifest = readPackageJson(dir);- if (manifest !== undefined) {- if (declaresAstryx(manifest)) return dir;- nearest ??= dir;- }- if (REPOSITORY_MARKERS.some(marker => fs.existsSync(path.join(dir, marker)))) break;- const parent = path.dirname(dir);- if (parent === dir) break;- dir = parent;- }- return nearest;-}--/**- * The folder `init` run in `cwd` writes the agent docs to: the project root- * {@link resolveAgentDocsRoot} finds, else `cwd` itself. The one definition- * that init, its removal, and the per-command setup nudge all use.- * @param {string} cwd- * @returns {string}- */-export function agentDocsTargetDir(cwd) {- return resolveAgentDocsRoot(cwd) ?? cwd;-}/*** Agent tool presets — maps tool names to their file search paths.diff --git a/packages/cli/foundation/config/config-path.mjs b/packages/cli/foundation/config/config-path.mjsnew file mode 100644index 0000000000..41853f2b62--- /dev/null+++ b/packages/cli/foundation/config/config-path.mjs@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file config-path.mjs+ * @input The folder a run starts in+ * @output CONFIG_BASENAMES and findConfigPath: the project's Astryx config+ * file, or null+ * @position packages/cli/foundation/config: finds the config without loading+ * project.mjs, so a run in a folder with no config loads none of it.+ * project.mjs re-exports both.+ */++import * as path from 'node:path';+import {findPackageRoot} from '../fs/paths.mjs';+import {findPresentFiles} from '../fs/present-files.mjs';++/** Conventional config basenames, in load-precedence order. */+export const CONFIG_BASENAMES = [+ 'astryx.config.ts',+ 'astryx.config.mjs',+ 'astryx.config.js',+];++/**+ * Find astryx.config.{ts,mjs,js} as a sibling of the nearest package.json.+ * Returns the absolute path, or null if none is present. Throws if multiple+ * config files exist at that root.+ * @param {string} [startDir]+ * @returns {string|null}+ */+export function findConfigPath(startDir = process.cwd()) {+ const root = findPackageRoot(startDir) ?? startDir;+ const present = findPresentFiles(root, CONFIG_BASENAMES);+ if (present.length > 1) {+ throw new Error(+ `Multiple Astryx config files found in ${root} (${present+ .map(p => path.basename(p))+ .join(', ')}). Keep exactly one.`,+ );+ }+ return present.length === 1 ? present[0] : null;+}diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex d231024070..1dd0f3a818 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -35,7 +35,8 @@import * as fs from 'node:fs';import * as path from 'node:path';-import {findPresentFiles, loadModuleWithParser} from '../fs/module-loader.mjs';+import {loadModuleWithParser} from '../fs/module-loader.mjs';+import {findConfigPath} from './config-path.mjs';import {parseConfig} from '../../authoring/config/parse.mjs';import {loadIntegrations,@@ -105,6 +106,8 @@ import {configContentHash,} from './config-cache.mjs';+export {CONFIG_BASENAMES, findConfigPath} from './config-path.mjs';+/*** Extract a human-readable message from an unknown thrown value.* Reproduces the historical `err?.message ?? String(err)` behavior in a@@ -321,12 +324,6 @@ function readPackageJson(dir) {* @typedef {import('../integrations/issue').AstryxIntegrationIssue & {package: string}} ProjectIntegrationIssue*/-/** Conventional config basenames, in load-precedence order. */-export const CONFIG_BASENAMES = [- 'astryx.config.ts',- 'astryx.config.mjs',- 'astryx.config.js',-];/** Default issue tracker used when neither config nor integration routes one. */export const DEFAULT_ISSUES_URL =@@ -367,25 +364,6 @@ function inheritsIntegrationDebug(projectDir) {}}-/**- * Find astryx.config.{ts,mjs,js} as a sibling of the nearest package.json.- * Returns the absolute path, or null if none is present. Throws if multiple- * config files exist at that root.- * @param {string} [startDir]- * @returns {string|null}- */-export function findConfigPath(startDir = process.cwd()) {- const root = findPackageRoot(startDir) ?? startDir;- const present = findPresentFiles(root, CONFIG_BASENAMES);- if (present.length > 1) {- throw new Error(- `Multiple Astryx config files found in ${root} (${present- .map(p => path.basename(p))- .join(', ')}). Keep exactly one.`,- );- }- return present.length === 1 ? present[0] : null;-}/*** The provider ledger each loaded Project resolved, kept off the class so itdiff --git a/packages/cli/foundation/discovery/icon-set-paths.mjs b/packages/cli/foundation/discovery/icon-set-paths.mjsnew file mode 100644index 0000000000..825dd76ff0--- /dev/null+++ b/packages/cli/foundation/discovery/icon-set-paths.mjs@@ -0,0 +1,23 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file icon-set-paths.mjs+ * @input A generated icon module's path+ * @output generatedTypesPath: the declaration file beside it+ * @position packages/cli/foundation/discovery: a path helper with no imports,+ * so the contribution inventory reads it without icon-set-writer.mjs and+ * that module's parser and manifest writer. icon-set-writer.mjs re-exports it.+ */++/**+ * The declaration file beside a generated module (`x.generated.js` →+ * `x.generated.d.ts`, `.mjs` → `.d.mts`); null for a TypeScript module.+ * @param {string} generated+ * @returns {string | null}+ */+export function generatedTypesPath(generated) {+ if (/\.m?tsx?$/u.test(generated)) return null;+ if (generated.endsWith('.mjs')) return generated.replace(/\.mjs$/u, '.d.mts');+ if (generated.endsWith('.cjs')) return generated.replace(/\.cjs$/u, '.d.cts');+ return generated.replace(/\.jsx?$/u, '.d.ts');+}diff --git a/packages/cli/foundation/discovery/icon-set-writer.mjs b/packages/cli/foundation/discovery/icon-set-writer.mjsindex b3270d70b9..a9fba62b70 100644--- a/packages/cli/foundation/discovery/icon-set-writer.mjs+++ b/packages/cli/foundation/discovery/icon-set-writer.mjs@@ -33,6 +33,9 @@ import {findLocalIntegrationManifestOrNull} from '../integrations/manifest-writeimport {loadManifestObject} from '../integrations/integrations.mjs';import {levenshteinDistance} from '../text/string-utils.mjs';import {astryxDefinitionsByName} from './icon-definition-discovery.mjs';+import {generatedTypesPath} from './icon-set-paths.mjs';++export {generatedTypesPath};import {discoverIconSetDirectory,NOTICE_FILE_RE,@@ -988,18 +991,6 @@ export function generatedModulePath(set, packageDir) {const THEME_ELEMENT_PROPS ="{'aria-hidden': true, 'width': '1em', 'height': '1em'}";-/**- * The declaration file beside a generated module (`x.generated.js` →- * `x.generated.d.ts`, `.mjs` → `.d.mts`); null for a TypeScript module.- * @param {string} generated- * @returns {string | null}- */-export function generatedTypesPath(generated) {- if (/\.m?tsx?$/u.test(generated)) return null;- if (generated.endsWith('.mjs')) return generated.replace(/\.mjs$/u, '.d.mts');- if (generated.endsWith('.cjs')) return generated.replace(/\.cjs$/u, '.d.cts');- return generated.replace(/\.jsx?$/u, '.d.ts');-}/*** The declaration file's text for a generated module's statements: eachdiff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex b420d04f5f..786616b0cf 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -384,6 +384,10 @@ const RUNNERS = {runs: "Yarn's pnpapi, under Plug'n'Play, to find an installed package",sites: ['require(pnpapi)'],},+ 'foundation/integrations/contribution-fixes.mjs': {+ runs: 'jscodeshift (CommonJS) on first use, so loading the project never loads it',+ sites: ['require(jscodeshift)'],+ },'foundation/integrations/integrations.mjs': {runs: "each installed integration's manifest",sites: ['importUserModule'],diff --git a/packages/cli/foundation/fs/module-loader.mjs b/packages/cli/foundation/fs/module-loader.mjsindex 1943edaafe..c337211439 100644--- a/packages/cli/foundation/fs/module-loader.mjs+++ b/packages/cli/foundation/fs/module-loader.mjs@@ -25,6 +25,9 @@ import {createRequire} from 'node:module';import {pathToFileURL} from 'node:url';import * as fs from 'node:fs';import {createJiti} from 'jiti';+import {findPresentFiles} from './present-files.mjs';++export {findPresentFiles};/** @type {ReturnType<typeof createJiti> | undefined} */let jitiInstance;@@ -275,18 +278,6 @@ async function importModule(file, fresh) {return await import(url.href);}-/**- * Return the conventional files (by basename, in the given precedence order)- * that exist directly in `dir`, as absolute paths. Never throws.- * @param {string} dir- * @param {string[]} basenames precedence-ordered- * @returns {string[]} absolute paths of present files, in basenames order- */-export function findPresentFiles(dir, basenames) {- return basenames- .filter(name => fs.existsSync(path.join(dir, name)))- .map(name => path.join(dir, name));-}/*** Import a user-authored module, take its default export, and validate itdiff --git a/packages/cli/foundation/fs/present-files.mjs b/packages/cli/foundation/fs/present-files.mjsnew file mode 100644index 0000000000..4d923b12c4--- /dev/null+++ b/packages/cli/foundation/fs/present-files.mjs@@ -0,0 +1,25 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file present-files.mjs+ * @input A folder and the file names to look for in it+ * @output findPresentFiles: the paths of those that exist, in order+ * @position packages/cli/foundation/fs: node builtins only, so a run reads it+ * without module-loader.mjs and its jiti. module-loader.mjs re-exports it.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++/**+ * Return the conventional files (by basename, in the given precedence order)+ * that exist directly in `dir`, as absolute paths. Never throws.+ * @param {string} dir+ * @param {string[]} basenames precedence-ordered+ * @returns {string[]} absolute paths of present files, in basenames order+ */+export function findPresentFiles(dir, basenames) {+ return basenames+ .filter(name => fs.existsSync(path.join(dir, name)))+ .map(name => path.join(dir, name));+}diff --git a/packages/cli/foundation/integrations/autolink.mjs b/packages/cli/foundation/integrations/autolink.mjsindex c7261e5acc..a34a7eae8d 100644--- a/packages/cli/foundation/integrations/autolink.mjs+++ b/packages/cli/foundation/integrations/autolink.mjs@@ -39,9 +39,14 @@import * as fs from 'node:fs';import * as path from 'node:path';-import {findNodeModulesPackage} from '../fs/paths.mjs';import {findManifestPaths, loadIntegrations} from './integrations.mjs';import {resolveProviders} from './provider-resolution.mjs';+import {+ isBarePackageName,+ resolveInstalledPackageDir,+} from './installed-package.mjs';++export {resolveInstalledPackageDir};/*** package.json fields whose keys name a dependency this project installs.@@ -58,26 +63,6 @@ export const DEPENDENCY_FIELDS = Object.freeze(['optionalDependencies',]);-/**- * Whether a dependency key is a bare package name safe to resolve.- *- * Mirrors the guard in {@link import('./integrations.mjs').resolvePackageDir}:- * a name is a directory under node_modules, so a path segment (`.`, `..`) or an- * absolute spec must never reach the resolver, which goes on to dynamically- * import what it finds.- *- * @param {string} name- * @returns {boolean}- */-function isBarePackageName(name) {- return (- typeof name === 'string' &&- name.length > 0 &&- !path.isAbsolute(name) &&- !name.startsWith('@/') &&- !name.split('/').some(segment => segment === '.' || segment === '..')- );-}/*** The dependency names this project declares, in field then declaration order,@@ -118,27 +103,6 @@ export function readDeclaredDependencies(projectDir) {return declared;}-/**- * Resolve an installed package's directory the way Node's resolver finds it:- * the nearest `node_modules/<name>` walking up from `fromDir`.- *- * Walking up matters because hoisting is normal — yarn and npm workspaces lift- * a workspace member's dependency to the repo root, so the app's own- * node_modules can be empty of a package it genuinely declares. Integrations- * named in astryx.config resolve through the same walk.- *- * Presence is decided by the package's own package.json, not the directory, so- * a stale empty directory is not mistaken for an install.- *- * @param {string} name bare package name- * @param {string} fromDir directory to start walking up from- * @returns {{packageDir: string, hostDir: string}|null} the resolved package- * directory and the directory whose node_modules holds it- */-export function resolveInstalledPackageDir(name, fromDir) {- if (!isBarePackageName(name)) return null;- return findNodeModulesPackage(fromDir, name);-}/*** Resolve a path through symlinks for identity comparison. pnpm links everydiff --git a/packages/cli/foundation/integrations/contribution-fixes.mjs b/packages/cli/foundation/integrations/contribution-fixes.mjsindex afbe11705c..297b7269bf 100644--- a/packages/cli/foundation/integrations/contribution-fixes.mjs+++ b/packages/cli/foundation/integrations/contribution-fixes.mjs@@ -20,7 +20,7 @@import * as fs from 'node:fs';import * as path from 'node:path';-import jscodeshift from 'jscodeshift';+import {createRequire} from 'node:module';import {isValidSemver} from '../env/semver.mjs';import {isThemeFolder as readsAsTheme,@@ -88,7 +88,29 @@ const ROOT_HOLDS = /** @type {Record<MetadataRoot, string>} */ ({themes: 'themes',});-const j = jscodeshift.withParser('tsx');+const require = createRequire(import.meta.url);+/** @type {typeof import('jscodeshift').default | undefined} */+let jscodeshiftModule;+/** @type {ReturnType<typeof import('jscodeshift').default['withParser']> | undefined} */+let tsxParser;++/**+ * jscodeshift, loaded at its first use: it is a large module, and a run that+ * checks no contribution file never needs it.+ * @returns {typeof import('jscodeshift').default}+ */+function jscodeshift() {+ jscodeshiftModule ??= require('jscodeshift');+ return /** @type {typeof import('jscodeshift').default} */ (+ jscodeshiftModule+ );+}++/** jscodeshift with the TypeScript parser, made once. */+function tsx() {+ tsxParser ??= jscodeshift().withParser('tsx');+ return tsxParser;+}/** @param {any} node @returns {any} */function unwrapStaticExpression(node) {@@ -136,6 +158,7 @@ function staticPropertyNamed(property, name) {* @returns {ContributionStamp | null} null when it is not contribution metadata*/export function readContributionStamp(file, templateOnly) {+ const j = tsx();let ast;try {ast = j(fs.readFileSync(file, 'utf-8'));@@ -526,7 +549,7 @@ function localImports(entry) {/** @type {string[]} */const specifiers = [];try {- const js = jscodeshift.withParser(+ const js = jscodeshift().withParser(/\.(?:ts|tsx|mts)$/u.test(file) ? 'tsx' : 'babel',);const ast = js(fs.readFileSync(file, 'utf-8'));diff --git a/packages/cli/foundation/integrations/contribution-inventory.mjs b/packages/cli/foundation/integrations/contribution-inventory.mjsindex 9a3d102bd3..5227b2de0a 100644--- a/packages/cli/foundation/integrations/contribution-inventory.mjs+++ b/packages/cli/foundation/integrations/contribution-inventory.mjs@@ -25,7 +25,7 @@ import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.import {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';import {discoverIntegrationDocs} from '../discovery/docs-discovery.mjs';import {discoverIconSetDirectory} from '../discovery/icon-set-discovery.mjs';-import {generatedTypesPath} from '../discovery/icon-set-writer.mjs';+import {generatedTypesPath} from '../discovery/icon-set-paths.mjs';// ── File-walk helpers (no module imports, no execution) ──────────diff --git a/packages/cli/foundation/integrations/installed-package.mjs b/packages/cli/foundation/integrations/installed-package.mjsnew file mode 100644index 0000000000..a042ec42e9--- /dev/null+++ b/packages/cli/foundation/integrations/installed-package.mjs@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file installed-package.mjs+ * @input A dependency name and the folder to resolve it from+ * @output isBarePackageName and resolveInstalledPackageDir: where an installed+ * package is, found the way Node's resolver walks up node_modules+ * @position packages/cli/foundation/integrations: loads no integration, so the+ * run's locked versions resolve packages without autolink.mjs and its+ * manifest loader. autolink.mjs re-exports resolveInstalledPackageDir.+ */++import * as path from 'node:path';+import {findNodeModulesPackage} from '../fs/paths.mjs';++/**+ * Whether a dependency key is a bare package name safe to resolve.+ *+ * Mirrors the guard in {@link import('./integrations.mjs').resolvePackageDir}:+ * a name is a directory under node_modules, so a path segment (`.`, `..`) or an+ * absolute spec must never reach the resolver, which goes on to dynamically+ * import what it finds.+ *+ * @param {string} name+ * @returns {boolean}+ */+export function isBarePackageName(name) {+ return (+ typeof name === 'string' &&+ name.length > 0 &&+ !path.isAbsolute(name) &&+ !name.startsWith('@/') &&+ !name.split('/').some(segment => segment === '.' || segment === '..')+ );+}++/**+ * Resolve an installed package's directory the way Node's resolver finds it:+ * the nearest `node_modules/<name>` walking up from `fromDir`.+ *+ * Walking up matters because hoisting is normal — yarn and npm workspaces lift+ * a workspace member's dependency to the repo root, so the app's own+ * node_modules can be empty of a package it genuinely declares. Integrations+ * named in astryx.config resolve through the same walk.+ *+ * Presence is decided by the package's own package.json, not the directory, so+ * a stale empty directory is not mistaken for an install.+ *+ * @param {string} name bare package name+ * @param {string} fromDir directory to start walking up from+ * @returns {{packageDir: string, hostDir: string}|null} the resolved package+ * directory and the directory whose node_modules holds it+ */+export function resolveInstalledPackageDir(name, fromDir) {+ if (!isBarePackageName(name)) return null;+ return findNodeModulesPackage(fromDir, name);+}diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex 9908f3d942..14a7adb56e 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -32,6 +32,9 @@ import {unknownIntegrationKeys,} from '../../authoring/integration/schema.mjs';import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';+import {findManifestPaths, MANIFEST_BASENAMES} from './manifest-paths.mjs';++export {findManifestPaths, MANIFEST_BASENAMES};import {parseGapReportHandler} from '../../authoring/gap-report/parse.mjs';import {parseDiscoverSource} from '../../authoring/discover/parse.mjs';import {resolveProviders} from './provider-resolution.mjs';@@ -102,12 +105,6 @@ import {resolveProviders} from './provider-resolution.mjs';* @property {string} [__discoverError] isolated discover-source validation error.*/-/** Conventional manifest basenames, in load-precedence order. */-export const MANIFEST_BASENAMES = [- 'astryx.integration.ts',- 'astryx.integration.mjs',- 'astryx.integration.js',-];/*** Normalize a package-owned provider ID without rejecting legacy unnamed local@@ -153,16 +150,6 @@ export function markProviderConflicts(integrations) {).integrations;}-/**- * Return the conventional root manifest paths present in `dir`, in- * load-precedence order. Unlike {@link resolveManifestPath} this never throws —- * callers (for example Doctor integration validation) decide how to treat zero / multiple.- * @param {string} dir- * @returns {string[]} absolute manifest paths- */-export function findManifestPaths(dir) {- return findPresentFiles(dir, MANIFEST_BASENAMES);-}/*** Parse the optional named gap-report handler without making it part of thediff --git a/packages/cli/foundation/integrations/manifest-paths.mjs b/packages/cli/foundation/integrations/manifest-paths.mjsnew file mode 100644index 0000000000..ab53da78b5--- /dev/null+++ b/packages/cli/foundation/integrations/manifest-paths.mjs@@ -0,0 +1,31 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file manifest-paths.mjs+ * @input A package folder+ * @output MANIFEST_BASENAMES and findManifestPaths: the integration manifests+ * a package has, in load-precedence order+ * @position packages/cli/foundation/integrations: reads no manifest, so the+ * run's package set finds them without integrations.mjs, its schemas and+ * its module loader. integrations.mjs re-exports both.+ */++import {findPresentFiles} from '../fs/present-files.mjs';++/** Conventional manifest basenames, in load-precedence order. */+export const MANIFEST_BASENAMES = [+ 'astryx.integration.ts',+ 'astryx.integration.mjs',+ 'astryx.integration.js',+];++/**+ * Return the conventional root manifest paths present in `dir`, in+ * load-precedence order. Unlike {@link resolveManifestPath} this never throws —+ * callers (for example Doctor integration validation) decide how to treat zero / multiple.+ * @param {string} dir+ * @returns {string[]} absolute manifest paths+ */+export function findManifestPaths(dir) {+ return findPresentFiles(dir, MANIFEST_BASENAMES);+}diff --git a/packages/cli/foundation/runtime/locked-versions.mjs b/packages/cli/foundation/runtime/locked-versions.mjsindex b99b9eefd6..753e7d60ab 100644--- a/packages/cli/foundation/runtime/locked-versions.mjs+++ b/packages/cli/foundation/runtime/locked-versions.mjs@@ -14,7 +14,7 @@import * as path from 'node:path';import {findLockfile, lockedVersion, readJson} from '../release/project.mjs';-import {resolveInstalledPackageDir} from '../integrations/autolink.mjs';+import {resolveInstalledPackageDir} from '../integrations/installed-package.mjs';const SCOPE = '@astryxdesign/';const FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies'];diff --git a/packages/cli/foundation/runtime/package-set.mjs b/packages/cli/foundation/runtime/package-set.mjsindex 90cf1769fd..2b65b645e0 100644--- a/packages/cli/foundation/runtime/package-set.mjs+++ b/packages/cli/foundation/runtime/package-set.mjs@@ -22,7 +22,7 @@import * as fs from 'node:fs';import * as path from 'node:path';-import {findManifestPaths} from '../integrations/integrations.mjs';+import {findManifestPaths} from '../integrations/manifest-paths.mjs';import {readJson} from '../release/project.mjs';import {cliBinOf, isVersionRange} from '../release/cache.mjs';import {isValidSemver, satisfiesRange} from '../env/semver.mjs';