An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): read a debug handler from loaded integrations (#5998)
Joey99282ebf0a2c
diff --git a/.changeset/integration-debug-handlers.md b/.changeset/integration-debug-handlers.mdnew file mode 100644index 0000000000..e5cd4f588c--- /dev/null+++ b/.changeset/integration-debug-handlers.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] An integration can now supply a `debug` handler, so installing it turns on its debug logs with no change to the app. Export `debug` from `astryx.integration.*`; the app's own `debug` still runs, both get every event, and a handler that throws cannot affect the command. Opt out with `{"astryx": {"inheritDebug": false}}`.++@josephfarinadiff --git a/packages/cli/assets/docs/cli-integrations.doc.mjs b/packages/cli/assets/docs/cli-integrations.doc.mjsindex 4f7dd34ffe..efaa1d5500 100644--- a/packages/cli/assets/docs/cli-integrations.doc.mjs+++ b/packages/cli/assets/docs/cli-integrations.doc.mjs@@ -166,6 +166,29 @@ export const docs = {},],},+ {+ title: 'Recording Runs',+ category: 'guide',+ content: [+ {+ type: 'prose',+ text: 'An integration can receive every command run in the apps that install it, so you can see how your package is actually used without asking each app to add anything. Export a function named `debug` from the integration file. It is a NAMED export, deliberately not a manifest field: a CLI version that predates this feature reads only the default export, so adding one does not disturb any consumer.',+ },+ {+ type: 'code',+ lang: 'typescript',+ code: "// astryx.integration.ts\nimport type {DebugEvent} from '@astryxdesign/cli/authoring';\n\nexport function debug(event: DebugEvent): void {\n // synchronous only — the process is exiting\n reportSomewhere(event);\n}\n\nexport default {\n components: './components',\n};",+ },+ {+ type: 'prose',+ text: 'The event is the same `DebugEvent` a consumer receives from `debug` in their own `astryx.config`, and both run: an app that sets its own handler still reaches yours, and yours never displaces theirs. The app handler is called first, then each integration in the order the config lists them. Every handler is called in isolation with its own copy of the event — one that throws, prints, or calls `process.exit` cannot change the command\'s output or exit code, and cannot stop the others.',+ },+ {+ type: 'prose',+ text: 'The handler is synchronous, for the same reason a consumer\'s is: it runs on process exit, where Node abandons pending async work. Buffer or write synchronously; do not await. An app that wants no inherited handler sets `{"astryx": {"inheritDebug": false}}` in its `package.json`, which suppresses every integration\'s handler while leaving its own untouched.',+ },+ ],+ },{title: 'How It Works',category: 'guide',diff --git a/packages/cli/authoring/config/config.doc.mjs b/packages/cli/authoring/config/config.doc.mjsindex fc8a308ebf..b8b2ef5422 100644--- a/packages/cli/authoring/config/config.doc.mjs+++ b/packages/cli/authoring/config/config.doc.mjs@@ -48,7 +48,7 @@ export const doc = {name: 'debug',type: '(event: DebugEvent) => void',description:- 'Record every command run. The handler is synchronous; promises are not awaited and output goes to stderr. Declare `debug` directly in this file so early commands can discover it.',+ 'Record every command run. The handler is synchronous; promises are not awaited and output goes to stderr. Declare `debug` directly in this file so early commands can discover it. An integration can supply one too, as a `debug` named export from its manifest — both run; set `{"astryx": {"inheritDebug": false}}` in package.json to take only your own.',example:"event => appendFileSync('runs.ndjson', JSON.stringify(event) + '\\n')",},diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.tsindex 79fc7cec85..ddfaf5bd65 100644--- a/packages/cli/authoring/integration/type.ts+++ b/packages/cli/authoring/integration/type.ts@@ -6,6 +6,13 @@* package.json). Identity (name/version) comes from package.json, not the* manifest. Authors write a plain object against {@link AstryxIntegration};* the CLI validates it via `parseIntegration` at the load boundary.+ *+ * The manifest module may also carry a `debug` NAMED export — a+ * `DebugEventHandler` that receives every command run in the apps that install+ * the integration. It is not a field here on purpose: a CLI released before a+ * given field existed rejects it, and a rejected manifest contributes nothing+ * at all, while a named export is simply not read. See the `cli-integrations`+ * doc topic.*/export interface AstryxIntegration {/** Relative path to the components/docs root (resolved to absolute). */diff --git a/packages/cli/clients/cli/e2e-smoke.test.mjs b/packages/cli/clients/cli/e2e-smoke.test.mjsindex 2ade4cec46..66e491f5ab 100644--- a/packages/cli/clients/cli/e2e-smoke.test.mjs+++ b/packages/cli/clients/cli/e2e-smoke.test.mjs@@ -105,7 +105,11 @@ describe('e2e smoke: the bin does not run a project config it was not asked to',// its integrations. Most commands never did either. Running a project's own// code on `astryx --version`, for a project that never opted in, is a cost// this feature does not get to impose, so the bin reads the config as text- // and only loads it when `debug` appears. Only a real process can show this.+ // and only loads it when it mentions something that can produce a handler:+ // `debug` (the project's own) or `integrations` (which may export one).+ // A project that lists integrations has asked for those packages' code to+ // run; a project that lists neither has asked for none of this. Only a real+ // process can show the difference.const projects = [];function project(configBody) {@@ -125,29 +129,34 @@ describe('e2e smoke: the bin does not run a project config it was not asked to',return {dir, evaluated: () => fs.existsSync(marker)};}- afterAll(() => {- for (const dir of projects) fs.rmSync(dir, {recursive: true, force: true});- });-- it('leaves a config without the key unevaluated', () => {- const p = project('export default { integrations: [] };\n');- const res = spawnSync(process.execPath, [CLI_BIN, '--version'], {+ /** @param {{dir: string}} p */+ function runVersion(p) {+ return spawnSync(process.execPath, [CLI_BIN, '--version'], {cwd: p.dir,encoding: 'utf8',timeout: 30_000,});- expect(res.status).toBe(0);+ }++ afterAll(() => {+ for (const dir of projects) fs.rmSync(dir, {recursive: true, force: true});+ });++ it('leaves a config that mentions neither key unevaluated', () => {+ const p = project('export default { experimental: {} };\n');+ expect(runVersion(p).status).toBe(0);expect(p.evaluated()).toBe(false);});- it('still loads a config that opts in', () => {+ it('still loads a config that opts in with debug', () => {const p = project('export default { debug: () => {} };\n');- const res = spawnSync(process.execPath, [CLI_BIN, '--version'], {- cwd: p.dir,- encoding: 'utf8',- timeout: 30_000,- });- expect(res.status).toBe(0);+ expect(runVersion(p).status).toBe(0);+ expect(p.evaluated()).toBe(true);+ });++ it('loads a config that declares integrations, which may contribute one', () => {+ const p = project("export default { integrations: ['@acme/widgets'] };\n");+ expect(runVersion(p).status).toBe(0);expect(p.evaluated()).toBe(true);});});diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex 6c2ac79130..9b18eee452 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -106,7 +106,7 @@ function fullCommandName(actionCommand, root) {}/**- * Load the project's `debug` function, if it has one.+ * Load the handlers that will receive this run, before Commander parses.** Called from the bin BEFORE Commander parses, not from a hook. Most commands* never touch `astryx.config` on their own, and parse errors and `--help`@@ -117,14 +117,30 @@ function fullCommandName(actionCommand, root) {* module and loads every integration it names, and before this feature most* commands did neither: running a project's own code on `astryx --version`,* for a project that never asked for any of this, is not a cost the feature- * gets to impose. So the file is read as text first and only loaded if the- * word appears in it. A project with no config pays one `existsSync` walk; a- * project with a config and no `debug` pays one small `readFile`.+ * gets to impose. So the file is read as text first and only loaded if it+ * mentions something that could produce a handler. A project with no config+ * pays one `existsSync` walk; a project with a config that mentions neither+ * pays one small `readFile`.+ *+ * TWO words open the gate, because there are two places a handler can come+ * from. `debug` is the project's own. `integrations` is the other: an+ * integration contributes a handler as a `debug` named export from its+ * manifest, so a config that lists integrations may have one even though the+ * word `debug` appears nowhere in it — which is the shape of essentially every+ * app that installs an integration. Without the second word this feature would+ * reach only the commands that happen to load a Project for their own reasons+ * (`component`, `search`, `docs`, `template`, `doctor`, …) and would miss+ * `--version`, `--help`, `theme *`, `blog`, and every parse error.+ *+ * Measured cost of that second word, on an integration whose manifest is+ * TypeScript (the expensive case — jiti): ~50ms added to `astryx --version`,+ * and nothing at all to a command that was going to load the project anyway.+ * It is paid only by projects that declare integrations.** The text test is deliberately loose — any occurrence, comments included —* because a false positive costs one config load the CLI used to do anyway,* while a false negative silently records nothing. The one shape it cannot- * see is a config that never spells the word, e.g. spreading in an object+ * see is a config that never spells either word, e.g. spreading in an object* from another module; that is documented on the `debug` config key.** @returns {Promise<void>}@@ -136,7 +152,8 @@ export async function loadProjectDebugHandler() {);const configPath = findConfigPath(process.cwd());if (!configPath) return;- if (!fs.readFileSync(configPath, 'utf-8').includes('debug')) {+ const text = fs.readFileSync(configPath, 'utf-8');+ if (!text.includes('debug') && !text.includes('integrations')) {debug.noteConfigGateSkipped();return;}diff --git a/packages/cli/foundation/config/integration-debug.test.mjs b/packages/cli/foundation/config/integration-debug.test.mjsnew file mode 100644index 0000000000..6a58c95a8f--- /dev/null+++ b/packages/cli/foundation/config/integration-debug.test.mjs@@ -0,0 +1,193 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Loading a project registers the handlers that will receive the run.+ *+ * The unit tests beside the recorder cover the fan-out. These cover the wiring+ * that gets there from real files on disk: an integration's `debug` named+ * export reaching the recorder through `Project.load`, an app's own `debug`+ * surviving alongside it, and the one way an app can refuse an inherited+ * handler.+ *+ * @position packages/cli/foundation/config — behaviour coverage+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {Project} from './project.mjs';+import {begin, finish, setCommand, resetRecorder} from '../debug/recorder.mjs';++/** Where handlers loaded from disk report themselves. */+const SINK = '__astryxIntegrationDebugTestSink';++let tmpDir = '';++/** @returns {string[]} the handlers that fired, in order. */+function fired() {+ return /** @type {any} */ (globalThis)[SINK] ?? [];+}++/**+ * A manifest module that reports itself when its handler is called.+ * @param {string} name+ * @param {{throws?: boolean, handler?: boolean}} [options]+ */+function integration(name, {throws = false, handler = true} = {}) {+ const dir = path.join(tmpDir, 'node_modules', name);+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name, version: '1.0.0'}),+ );+ const body = throws+ ? `export const debug = () => { throw new Error('${name} exploded'); };\n`+ : handler+ ? `export const debug = () => { (globalThis.${SINK} ??= []).push('${name}'); };\n`+ : '';+ fs.writeFileSync(+ path.join(dir, 'astryx.integration.mjs'),+ `${body}export default {};\n`,+ );+}++/** @param {string[]} integrations @param {boolean} [ownHandler] */+function config(integrations, ownHandler = false) {+ const own = ownHandler+ ? ` debug: () => { (globalThis.${SINK} ??= []).push('app'); },\n`+ : '';+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.config.mjs'),+ `export default {\n integrations: ${JSON.stringify(integrations)},\n${own}};\n`,+ );+}++/** @param {Record<string, unknown>} [astryx] */+function packageJson(astryx) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer', ...(astryx ? {astryx} : {})}),+ );+}++/** Drive one complete invocation through the recorder. */+async function runOneCommand() {+ begin({argv: ['docs']});+ setCommand('docs');+ await Project.load(tmpDir);+ return finish({exitCode: 0});+}++beforeEach(() => {+ resetRecorder();+ /** @type {any} */ (globalThis)[SINK] = [];+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-int-debug-'));+ packageJson();+});++afterEach(() => {+ resetRecorder();+ delete (/** @type {any} */ (globalThis)[SINK]);+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('installing an integration is enough', () => {+ it('records the run with no `debug` anywhere in the app config', async () => {+ integration('reporting-integration');+ config(['reporting-integration']);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.config.mjs'), 'utf-8'),+ ).not.toMatch(/debug/);++ expect(await runOneCommand()).toBe(true);+ expect(fired()).toEqual(['reporting-integration']);+ });++ it('records nothing when the integration exports no handler', async () => {+ integration('plain-integration', {handler: false});+ config(['plain-integration']);++ expect(await runOneCommand()).toBe(false);+ expect(fired()).toEqual([]);+ });++ it('gives every integration its own events', async () => {+ integration('first-integration');+ integration('second-integration');+ config(['first-integration', 'second-integration']);++ await runOneCommand();++ expect(fired()).toEqual(['first-integration', 'second-integration']);+ });+});++describe('the app config does not displace them, and they do not displace it', () => {+ it('calls the app handler and the integration handler, app first', async () => {+ integration('reporting-integration');+ config(['reporting-integration'], true);++ await runOneCommand();++ expect(fired()).toEqual(['app', 'reporting-integration']);+ });++ it('keeps the others when one integration handler throws', async () => {+ integration('exploding-integration', {throws: true});+ integration('working-integration');+ config(['exploding-integration', 'working-integration'], true);++ expect(await runOneCommand()).toBe(true);+ expect(fired()).toEqual(['app', 'working-integration']);+ });+});++describe('an app can refuse an inherited handler', () => {+ it('drops integration handlers under astryx.inheritDebug false', async () => {+ packageJson({inheritDebug: false});+ integration('reporting-integration');+ config(['reporting-integration'], true);++ await runOneCommand();++ expect(fired()).toEqual(['app']);+ });++ it('keeps them under an explicit true', async () => {+ packageJson({inheritDebug: true});+ integration('reporting-integration');+ config(['reporting-integration']);++ await runOneCommand();++ expect(fired()).toEqual(['reporting-integration']);+ });++ it('keeps them when package.json says nothing about astryx', async () => {+ integration('reporting-integration');+ config(['reporting-integration']);++ await runOneCommand();++ expect(fired()).toEqual(['reporting-integration']);+ });+});++describe('loading the project twice delivers once', () => {+ // The CLI does load twice for most commands: once before Commander parses,+ // so `--help` and parse errors are recorded, and again when the command+ // reads the project for its own reasons.+ it('does not double-deliver across two Project.loads', async () => {+ integration('reporting-integration');+ config(['reporting-integration'], true);++ begin({argv: ['docs']});+ setCommand('docs');+ await Project.load(tmpDir);+ await Project.load(tmpDir);+ finish({exitCode: 0});++ expect(fired()).toEqual(['app', 'reporting-integration']);+ });+});diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 8830b3fe78..362e2acdd7 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -38,6 +38,7 @@ import {loadIntegrations} from '../integrations/integrations.mjs';import {setProject as setDebugProject,setEventHandler as setDebugEventHandler,+ setIntegrationEventHandlers as setDebugIntegrationEventHandlers,} from '../debug/index.mjs';import {CORE_PACKAGE,@@ -115,6 +116,39 @@ function findPackageRoot(startDir) {return null;}+/**+ * Whether this project accepts `debug` handlers contributed by the+ * integrations it loads.+ *+ * On by default: installing an integration is how a project asks for that+ * package's behaviour, and a handler it contributes is behaviour. A project+ * that wants none of it says so in its package.json —+ *+ * {"astryx": {"inheritDebug": false}}+ *+ * package.json rather than astryx.config because the answer has to survive an+ * older CLI reading the same project: an unknown config key is a hard config+ * error, while `astryx` in package.json is inert to every version that does not+ * look for it. Only `false` opts out; anything else, including a missing file,+ * leaves inheritance on.+ *+ * This governs INHERITED handlers only. A project's own `debug` always runs.+ *+ * @param {string|null} configPath+ * @returns {boolean}+ */+function inheritsIntegrationDebug(configPath) {+ if (!configPath) return true;+ try {+ const pkgPath = path.join(path.dirname(configPath), 'package.json');+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));+ return pkg?.astryx?.inheritDebug !== false;+ } catch {+ // No package.json, or unreadable/malformed — not an opt-out.+ return true;+ }+}+/*** 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@@ -233,6 +267,18 @@ export class Project {// recorder collects provisionally until now precisely because the config// could not be read any earlier; it only needs the handler by exit.setDebugEventHandler(config.debug);+ // Integrations may contribute a handler too, as a `debug` NAMED export+ // from their manifest module. Both destinations receive the event: an+ // app that sets `debug` to watch its own runs must not thereby drop out+ // of an integration's debug logs, and an integration must not silence the+ // app. Passed as one ordered list rather than appended one at a time,+ // because Project.load can run more than once in a process and appending+ // would deliver twice.+ setDebugIntegrationEventHandlers(+ inheritsIntegrationDebug(configPath)+ ? loadedIntegrations.map(integration => integration.__debug)+ : [],+ );setDebugProject({hasConfig: Boolean(configPath),integrationCount: integrations.length,diff --git a/packages/cli/foundation/debug/index.mjs b/packages/cli/foundation/debug/index.mjsindex 65b5913283..cb5fc4f304 100644--- a/packages/cli/foundation/debug/index.mjs+++ b/packages/cli/foundation/debug/index.mjs@@ -35,6 +35,7 @@ export {setProject,recordResultSummary,setEventHandler,+ setIntegrationEventHandlers,noteConfigGateSkipped,setOutcome,recordEnvelope,diff --git a/packages/cli/foundation/debug/integration-handlers.test.mjs b/packages/cli/foundation/debug/integration-handlers.test.mjsnew file mode 100644index 0000000000..59e471db6d--- /dev/null+++ b/packages/cli/foundation/debug/integration-handlers.test.mjs@@ -0,0 +1,267 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Handlers contributed by integrations, alongside the project's own.+ *+ * An integration exports `debug` from its manifest module and every app that+ * installs it starts recording, with no change to the app. The app's own+ * `debug` is unaffected: both are destinations, neither replaces the other.+ * These cover the fan-out and the isolation that fanning out demands.+ *+ * @position packages/cli/foundation/debug — behaviour coverage+ */++import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {+ begin,+ finish,+ setCommand,+ setEventHandler,+ setIntegrationEventHandlers,+ resetRecorder,+} from './recorder.mjs';++/** Run one complete invocation. @returns {boolean} whether anything was delivered. */+function run(command = 'docs') {+ begin({argv: [command]});+ setCommand(command);+ return finish({exitCode: 0});+}++beforeEach(() => {+ resetRecorder();+});++afterEach(() => {+ resetRecorder();+});++describe('an integration can supply the handler', () => {+ it('records a run when only an integration supplied one', () => {+ const fromIntegration = vi.fn();+ setIntegrationEventHandlers([fromIntegration]);++ expect(run()).toBe(true);+ expect(fromIntegration).toHaveBeenCalledTimes(1);+ expect(fromIntegration.mock.calls[0][0].command).toBe('docs');+ });++ it('delivers to every integration, not just the first', () => {+ const one = vi.fn();+ const two = vi.fn();+ const three = vi.fn();+ setIntegrationEventHandlers([one, two, three]);++ run();++ expect(one).toHaveBeenCalledTimes(1);+ expect(two).toHaveBeenCalledTimes(1);+ expect(three).toHaveBeenCalledTimes(1);+ });++ it('records nothing when neither the project nor an integration supplied one', () => {+ setIntegrationEventHandlers([]);+ expect(run()).toBe(false);+ });++ it('ignores entries that are not functions', () => {+ const real = vi.fn();+ setIntegrationEventHandlers(+ /** @type {any} */ ([null, undefined, 'nope', 42, real]),+ );++ expect(run()).toBe(true);+ expect(real).toHaveBeenCalledTimes(1);+ });+});++describe('the project and its integrations both win', () => {+ // The case that motivated the feature. Under fallback semantics an app that+ // set `debug` for its own debugging would silently drop out of every+ // integration's debug logs — invisibly, because nothing reports a handler+ // that was never called.+ it('calls the project handler AND the integration handlers', () => {+ const fromConfig = vi.fn();+ const fromIntegration = vi.fn();+ setEventHandler(fromConfig);+ setIntegrationEventHandlers([fromIntegration]);++ run();++ expect(fromConfig).toHaveBeenCalledTimes(1);+ expect(fromIntegration).toHaveBeenCalledTimes(1);+ });++ it('delivers the project handler first, then integrations in load order', () => {+ /** @type {string[]} */+ const order = [];+ setEventHandler(() => order.push('config'));+ setIntegrationEventHandlers([+ () => order.push('first'),+ () => order.push('second'),+ ]);++ run();++ expect(order).toEqual(['config', 'first', 'second']);+ });++ it('gives each handler its own copy, so one cannot edit what the next is told', () => {+ /** @type {string[]} */+ const seen = [];+ setEventHandler(event => {+ event.command = 'MUTATED';+ seen.push(event.command);+ });+ setIntegrationEventHandlers([event => seen.push(event.command)]);++ run();++ expect(seen).toEqual(['MUTATED', 'docs']);+ });++ it('calls a handler once when the project and an integration share it', () => {+ const shared = vi.fn();+ setEventHandler(shared);+ setIntegrationEventHandlers([shared]);++ run();++ expect(shared).toHaveBeenCalledTimes(1);+ });++ it('calls a handler once when two integrations resolve to it', () => {+ const shared = vi.fn();+ setIntegrationEventHandlers([shared, shared]);++ run();++ expect(shared).toHaveBeenCalledTimes(1);+ });+});++describe('registering twice does not deliver twice', () => {+ // `Project.load` is a plain factory, and a single command can run it more+ // than once — the pre-parse handler load, then the command's own. The setter+ // replaces the set for exactly this reason.+ it('replaces the previous set rather than appending to it', () => {+ const handler = vi.fn();+ setIntegrationEventHandlers([handler]);+ setIntegrationEventHandlers([handler]);++ run();++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('drops handlers that the second registration left out', () => {+ const gone = vi.fn();+ const kept = vi.fn();+ setIntegrationEventHandlers([gone]);+ setIntegrationEventHandlers([kept]);++ run();++ expect(gone).not.toHaveBeenCalled();+ expect(kept).toHaveBeenCalledTimes(1);+ });++ it('is cleared by resetRecorder so nothing leaks between runs', () => {+ const handler = vi.fn();+ setIntegrationEventHandlers([handler]);+ resetRecorder();++ run();++ expect(handler).not.toHaveBeenCalled();+ });+});++describe('one bad handler cannot take the others down', () => {+ it('runs the handlers after one that throws', () => {+ const after = vi.fn();+ setIntegrationEventHandlers([+ () => {+ throw new Error('integration handler exploded');+ },+ after,+ ]);++ expect(() => run()).not.toThrow();+ expect(after).toHaveBeenCalledTimes(1);+ });++ it('keeps the project handler when an integration throws first', () => {+ const fromConfig = vi.fn();+ setEventHandler(fromConfig);+ setIntegrationEventHandlers([+ () => {+ throw new Error('boom');+ },+ ]);++ run();++ expect(fromConfig).toHaveBeenCalledTimes(1);+ });++ it('leaves the exit code the command chose', () => {+ const before = process.exitCode;+ setIntegrationEventHandlers([+ () => {+ process.exitCode = 77;+ process.exit(3);+ },+ ]);++ begin({argv: ['docs']});+ setCommand('docs');+ finish({exitCode: 0});++ expect(process.exitCode).toBe(before);+ });++ it('still reports delivery when one handler of several failed', () => {+ setIntegrationEventHandlers([+ () => {+ throw new Error('boom');+ },+ () => {},+ ]);++ expect(run()).toBe(true);+ });+});++describe('a Ctrl-C is recorded for an integration handler too', () => {+ // `process.on('exit')` does not run for a signalled death, so the recorder+ // installs signal listeners — but only once it has somewhere to deliver. An+ // integration handler is somewhere.+ const debugDir = path.dirname(fileURLToPath(import.meta.url));++ it('arms the signal handlers when the only handler came from an integration', () => {+ const source = `+ const d = await import(${JSON.stringify(path.join(debugDir, 'index.mjs'))});+ d.begin({argv: ['theme', 'build', '--watch'], cliVersion: '0.0.0'});+ d.setCommand('theme build');+ d.setIntegrationEventHandlers([+ e => process.stderr.write('EVENT ' + JSON.stringify(e) + '\\n'),+ ]);+ process.kill(process.pid, 'SIGINT');+ setTimeout(() => process.exit(7), 2000);+ `;+ const res = spawnSync(+ process.execPath,+ ['--input-type=module', '-e', source],+ {encoding: 'utf8', timeout: 30_000},+ );+ const line = (res.stderr || '')+ .split('\n')+ .find(l => l.startsWith('EVENT '));+ expect(line).toBeTruthy();+ expect(JSON.parse(line.slice(6)).signal).toBe('SIGINT');+ });+});diff --git a/packages/cli/foundation/debug/on-event.test.mjs b/packages/cli/foundation/debug/on-event.test.mjsindex fd268b5119..46d0a58893 100644--- a/packages/cli/foundation/debug/on-event.test.mjs+++ b/packages/cli/foundation/debug/on-event.test.mjs@@ -25,6 +25,7 @@ import {setGlobalOptions,setOutcome,setEventHandler,+ setIntegrationEventHandlers,noteConfigGateSkipped,recordEnvelope,recordHelp,@@ -386,7 +387,16 @@ describe('the config gate, when it guesses wrong', () => {noteConfigGateSkipped();setEventHandler(() => {});});- expect(said).toMatch(/astryx\.config sets `debug`/);+ expect(said).toMatch(/a debug handler was registered/);+ });++ it('says so when the handler that turns up came from an integration', () => {+ const said = withStderr(() => {+ begin({argv: []});+ noteConfigGateSkipped();+ setIntegrationEventHandlers([() => {}]);+ });+ expect(said).toMatch(/a debug handler was registered/);});it('stays quiet when the gate was right', () => {@@ -424,7 +434,7 @@ describe('the config gate, when it guesses wrong', () => {setEventHandler(() => {});setEventHandler(() => {});});- expect(said.match(/astryx\.config sets/g)).toHaveLength(1);+ expect(said.match(/a debug handler was registered/g)).toHaveLength(1);});it('stays quiet under --json, where stderr is still not the place', () => {diff --git a/packages/cli/foundation/debug/recorder.mjs b/packages/cli/foundation/debug/recorder.mjsindex 0abb7322bd..a8a242e331 100644--- a/packages/cli/foundation/debug/recorder.mjs+++ b/packages/cli/foundation/debug/recorder.mjs@@ -66,8 +66,21 @@ export const MAX_CAPTURED_OUTPUT = 32 * 1024;/** @type {import('./event.mjs').InFlightEvent | null} */let _event = null;-/** @type {import('../../authoring/debug/type').DebugEventHandler | null} */-let _handler = null;+/**+ * The project's own handler, from `debug` in `astryx.config`.+ * @type {import('../../authoring/debug/type').DebugEventHandler | null}+ */+let _projectHandler = null;+/**+ * Handlers contributed by loaded integrations, in integration load order.+ *+ * A separate list from the project's own because the two arrive from different+ * places and neither replaces the other: an app that sets `debug` for its own+ * debugging must not thereby remove itself from an integration's debug logs, and+ * an integration must not silence the app. Both are delivered to.+ * @type {import('../../authoring/debug/type').DebugEventHandler[]}+ */+let _integrationHandlers = [];let _finished = false;let _listenerInstalled = false;let _signalsArmed = false;@@ -178,17 +191,70 @@ export function currentEvent() {* {@link begin} — the recorder collects provisionally and only needs a* destination by the time the event is sealed at exit.*+ * This does NOT displace handlers contributed by integrations, and they do not+ * displace this one. See {@link setIntegrationEventHandlers}.+ ** @param {import('../../authoring/debug/type').DebugEventHandler | null | undefined} handler*/export function setEventHandler(handler) {guard(() => {- _handler = typeof handler === 'function' ? handler : null;- if (!_event || !_handler) return;- armSignalHandlers();- if (_configGateSkipped) reportConfigGateMiss();+ _projectHandler = typeof handler === 'function' ? handler : null;+ afterHandlersChanged();});}+/**+ * Register the handlers contributed by loaded integrations, replacing any+ * previously registered set.+ *+ * REPLACE, not append. `Project.load` is a plain factory — nothing memoizes it+ * process-wide — so a single command can load the same project more than once+ * (the pre-parse handler load, then the command's own). Appending would deliver+ * the same event to the same integration twice.+ *+ * Non-functions are dropped, and the list is deduplicated by function identity+ * so the same handler reached through two specs is still called once.+ *+ * @param {ReadonlyArray<import('../../authoring/debug/type').DebugEventHandler | null | undefined>} [handlers]+ */+export function setIntegrationEventHandlers(handlers = []) {+ guard(() => {+ const next = [];+ const seen = new Set();+ for (const handler of handlers ?? []) {+ if (typeof handler !== 'function' || seen.has(handler)) continue;+ seen.add(handler);+ next.push(handler);+ }+ _integrationHandlers = next;+ afterHandlersChanged();+ });+}++/**+ * Every handler this event will be delivered to, in delivery order: the+ * project's own first, then integrations in load order. Deduplicated by+ * identity, so a project that re-exports its integration's handler as its own+ * `debug` still gets one call.+ *+ * @returns {import('../../authoring/debug/type').DebugEventHandler[]}+ */+function effectiveHandlers() {+ /** @type {import('../../authoring/debug/type').DebugEventHandler[]} */+ const all = _projectHandler ? [_projectHandler] : [];+ for (const handler of _integrationHandlers) {+ if (!all.includes(handler)) all.push(handler);+ }+ return all;+}++/** Arm signals and report a missed config gate once a destination exists. */+function afterHandlersChanged() {+ if (!_event || effectiveHandlers().length === 0) return;+ armSignalHandlers();+ if (_configGateSkipped) reportConfigGateMiss();+}+export function noteConfigGateSkipped() {_configGateSkipped = true;}@@ -200,9 +266,10 @@ function reportConfigGateMiss() {const write = _originalWrites?.err ?? process.stderr.write;write.call(process.stderr,- 'astryx: your astryx.config sets `debug`, but the file does not contain ' +- 'the word, so commands that do not otherwise read the config are not ' +- 'recorded. Name the key literally in the config file.\n',+ 'astryx: a debug handler was registered, but your astryx.config file ' ++ 'contains neither the word `debug` nor `integrations`, so commands ' ++ 'that do not otherwise read the config are not recorded. Name the key ' ++ 'literally in the config file.\n',);} catch {/* best effort */@@ -249,7 +316,7 @@ export function begin({argv = process.argv.slice(2), cliVersion} = {}) {// setEventHandler arms the signals. Arm here too, so a caller that already// had one does not silently lose every signal-terminated run to lifecycle// ordering.- if (_handler) armSignalHandlers();+ if (effectiveHandlers().length > 0) armSignalHandlers();started = true;});return started;@@ -527,9 +594,11 @@ export function finish({exitCode} = {}) {// Stop teeing before doing anything else, so nothing the handler prints// ends up in the record it was handed.releaseOutput();- // No destination — the project did not set `debug`. Nothing to do, and- // nothing was paid for: the environment probe below never runs.- if (!_handler) return;+ // No destination — neither the project nor any loaded integration supplied+ // a handler. Nothing to do, and nothing was paid for: the environment probe+ // below never runs.+ const handlers = effectiveHandlers();+ if (handlers.length === 0) return;_event.env = captureEnv({cliVersion: _cliVersion});_event.output.stdout = collected(_stdout);@@ -604,9 +673,15 @@ export function finish({exitCode} = {}) {: null,};- // A COPY. Handing over the live object would let third-party code mutate- // the record mid-flight; its errors are swallowed for the same reason.- delivered = callHandler(_handler, structuredClone(sealed));+ // A COPY PER HANDLER. Handing over the live object would let third-party+ // code mutate the record mid-flight, and handing the same copy to two+ // handlers would let the first one edit what the second is told. Each call+ // is isolated in turn — one handler throwing, printing, or calling+ // process.exit changes nothing for the others or for the command.+ for (const handler of handlers) {+ const ran = callHandler(handler, structuredClone(sealed));+ delivered = delivered || ran;+ }});return delivered;}@@ -680,7 +755,8 @@ export function resetRecorder() {_stderr.chunks.length = 0;_stderr.bytes = 0;_event = null;- _handler = null;+ _projectHandler = null;+ _integrationHandlers = [];_finished = false;_configGateSkipped = false;_startedAt = 0;diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex dfc6ab62ff..3f4c8dc111 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -39,6 +39,9 @@ import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';* such an integration contributes nothing and is surfaced via Project.issues()* @property {string[]} [__unknownKeys] manifest keys this CLI does not know —* surfaced as a warning; the rest of the manifest still contributes+ * @property {import('../../authoring/debug/type').DebugEventHandler} [__debug]+ * the manifest module's `debug` NAMED export, when it exported a function.+ * Not a manifest key — see {@link loadManifest}.*//** Conventional manifest basenames, in load-precedence order. */@@ -69,9 +72,17 @@ export function findManifestPaths(dir) {* strips the unknown keys: after `parseIntegration` there is nothing left to* report. Exposed for validate-integration.*+ * `debug` comes back separately because it is a NAMED export, not a manifest+ * key. A key would have to survive the manifest schema of every CLI version+ * already installed against this integration, and older ones reject an unknown+ * key outright — losing that integration's components, templates and codemods+ * with it (#5119). A named export is simply not read by a CLI that does not+ * know about it, so an integration can start contributing one without a+ * coordinated upgrade.+ ** @param {string} file absolute manifest path* @param {string} [label] used in error messages- * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[]}>}+ * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler}>}*/export async function loadManifest(file, label = 'integration manifest') {const mod = await importUserModule(file);@@ -79,6 +90,12 @@ export async function loadManifest(file, label = 'integration manifest') {return {manifest: parseIntegration(raw, label),unknownKeys: unknownIntegrationKeys(raw),+ debug:+ typeof mod?.debug === 'function'+ ? /** @type {import('../../authoring/debug/type').DebugEventHandler} */ (+ mod.debug+ )+ : undefined,};}@@ -178,11 +195,14 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {let manifest;/** @type {string[]} */let unknownKeys;+ /** @type {import('../../authoring/debug/type').DebugEventHandler | undefined} */+ let debugHandler;try {- ({manifest, unknownKeys} = await loadManifest(- manifestFile,- `Integration ${spec}`,- ));+ ({+ manifest,+ unknownKeys,+ debug: debugHandler,+ } = await loadManifest(manifestFile, `Integration ${spec}`));} catch (err) {// A manifest that throws on import or fails schema validation must NOT take// down every command (component/docs/theme don't need this integration).@@ -219,6 +239,7 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {docs: resolveRoot(manifest.docs),issuesUrl: manifest.issuesUrl,__unknownKeys: unknownKeys,+ __debug: debugHandler,__spec: spec,__packageDir: packageDir,__manifestFile: manifestFile,diff --git a/packages/cli/foundation/integrations/integrations.test.mjs b/packages/cli/foundation/integrations/integrations.test.mjsindex 7a1722f7d7..dab0c8df78 100644--- a/packages/cli/foundation/integrations/integrations.test.mjs+++ b/packages/cli/foundation/integrations/integrations.test.mjs@@ -173,3 +173,49 @@ describe('a broken integration manifest degrades gracefully (skip + warn)', () =expect(issues.some(i => /boom manifest/.test(i.message))).toBe(true);});});++describe('the `debug` named export', () => {+ // A NAMED export, not a manifest key. A key would have to be understood by+ // every CLI version already installed against the integration, and an older+ // one rejects an unknown key by discarding the whole manifest — components,+ // templates and codemods with it (#5119). A named export is simply not read+ // by a CLI that does not know about it.+ it('is carried out of the manifest module as __debug', async () => {+ writeManifestPackage(tmpDir, {+ body: `export const debug = () => {};\nexport default {issuesUrl: 'https://example.com/i'};\n`,+ });++ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});++ expect(typeof loaded.__debug).toBe('function');+ expect(loaded.issuesUrl).toBe('https://example.com/i');+ });++ it('leaves __debug undefined when the module does not export one', async () => {+ writeManifestPackage(tmpDir, {body: `export default {};\n`});++ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});++ expect(loaded.__debug).toBeUndefined();+ });++ it('leaves __debug undefined when the export is not a function', async () => {+ writeManifestPackage(tmpDir, {+ body: `export const debug = 'not a function';\nexport default {};\n`,+ });++ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});++ expect(loaded.__debug).toBeUndefined();+ });++ it('does not become a manifest key, so it is not reported as an unknown one', async () => {+ writeManifestPackage(tmpDir, {+ body: `export const debug = () => {};\nexport default {};\n`,+ });++ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});++ expect(loaded.__unknownKeys).toEqual([]);+ });+});