@astryxdesign/cli 0.7.3-canary.641d08e → 0.7.3-canary.84c7b4f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +63 -63
  2. package/api/component/component-replacement.test.mjs +1 -0
  3. package/api/component/component.mjs +1 -1
  4. package/api/hook/hook.mjs +1 -1
  5. package/api/integration/validate-integration-fixes.test.mjs +6 -5
  6. package/api/integration/validate-integration-gaps.test.mjs +9 -1
  7. package/api/integration/validate-integration.d.mts +4 -0
  8. package/api/integration/validate-integration.mjs +15 -0
  9. package/api/integration/validate-integration.type.d.mts +33 -4
  10. package/api/integration/validate-integration.type.mjs +24 -5
  11. package/api/integration/validateIntegration.doc.mjs +1 -1
  12. package/api/search/_adapter.d.mts +16 -0
  13. package/api/search/_adapter.mjs +39 -0
  14. package/api/search/_adapter.test.mjs +173 -0
  15. package/api/search/search.mjs +6 -2
  16. package/assets/docs/tree/checks.doc.mjs +1 -1
  17. package/assets/docs/use-integrations.doc.mjs +120 -0
  18. package/clients/cli/command-result-coverage.test.mjs +6 -5
  19. package/clients/cli/commands/build-theme.color-scheme.test.mjs +1 -1
  20. package/clients/cli/commands/{component/index.mjs → component.mjs} +37 -37
  21. package/clients/cli/commands/component.test.mjs +6 -6
  22. package/clients/cli/commands/doctor-integration.test.mjs +49 -1
  23. package/clients/cli/commands/doctor.mjs +10 -0
  24. package/clients/cli/commands/{hook/index.mjs → hook.mjs} +22 -22
  25. package/clients/cli/commands/import-hint-correctness.test.mjs +1 -1
  26. package/clients/cli/commands/manifest.doc.mjs +1 -1
  27. package/clients/cli/commands/manifest.mjs +67 -0
  28. package/clients/cli/commands/postinstall.doc.mjs +23 -0
  29. package/clients/cli/commands/postinstall.mjs +31 -0
  30. package/clients/cli/commands/{build-theme.mjs → theme.mjs} +1 -1
  31. package/clients/cli/index.mjs +10 -85
  32. package/clients/cli/lib/component-format.mjs +1 -1
  33. package/clients/cli/lib/define-command.mjs +12 -7
  34. package/clients/cli/lib/exit-codes.test.mjs +5 -0
  35. package/clients/cli/lib/manifest.test.mjs +12 -0
  36. package/clients/cli/lib/welcome-box.mjs +50 -0
  37. package/foundation/discovery/runner-commands.mjs +1 -0
  38. package/foundation/doc-compiler/doc-loads.test.mjs +21 -9
  39. package/foundation/fs/read-record.d.mts +18 -0
  40. package/foundation/fs/read-record.mjs +131 -0
  41. package/foundation/fs/read-record.test.mjs +77 -0
  42. package/foundation/integrations/exports-subpaths.d.mts +57 -0
  43. package/foundation/integrations/exports-subpaths.mjs +113 -0
  44. package/foundation/integrations/public-imports.d.mts +81 -0
  45. package/foundation/integrations/public-imports.mjs +976 -0
  46. package/foundation/integrations/public-imports.test.mjs +868 -0
  47. package/foundation/response/response-types.doc.mjs +1 -1
  48. package/package.json +9 -9
@@ -0,0 +1,23 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file CommandDoc for `astryx postinstall`. A hidden, CLI-only hook with no
5
+ * wrapped API function (so no `fn`): it prints the welcome box.
6
+ * @position packages/cli/clients/cli/commands — command documentation
7
+ */
8
+
9
+ /** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
10
+ export const doc = {
11
+ type: 'command',
12
+ name: 'postinstall',
13
+ displayName: 'astryx postinstall',
14
+ namespace: 'cli/commands',
15
+ summary: 'Print the welcome message shown after install',
16
+ description:
17
+ 'Prints a short welcome box that names the first commands to run. It is hidden ' +
18
+ 'from help and the manifest, looks nothing up, and does not support --json.',
19
+ examples: [{label: 'Print the welcome box', cli: 'astryx postinstall'}],
20
+ outsideProject: 'same',
21
+ exitCodes: [{code: 0, when: 'success'}],
22
+ related: ['init'],
23
+ };
@@ -0,0 +1,31 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file postinstall command — the hidden `astryx postinstall` hook.
5
+ *
6
+ * Prints the welcome box (lib/welcome-box.mjs). Hidden from help and the
7
+ * manifest; it looks nothing up and does not support --json.
8
+ *
9
+ * The command surface comes from the colocated CommandDoc via `defineCommand`.
10
+ */
11
+
12
+ import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
13
+ import {emit, code} from '../formatters/index.mjs';
14
+ import {defineCommand} from '../lib/define-command.mjs';
15
+ import {welcomeBox} from '../lib/welcome-box.mjs';
16
+ import {NO_RESULT_SET} from '../../../foundation/debug/index.mjs';
17
+ import {doc as postinstallCommand} from './postinstall.doc.mjs';
18
+
19
+ /**
20
+ * @param {import('commander').Command} program
21
+ */
22
+ export function registerPostinstall(program) {
23
+ defineCommand(program, postinstallCommand, {
24
+ hidden: true,
25
+ action: () => {
26
+ emit(code(welcomeBox(getCliInvocation())));
27
+ // Prints the welcome box. Nothing is looked up.
28
+ return NO_RESULT_SET;
29
+ },
30
+ });
31
+ }
@@ -96,7 +96,7 @@ import {doc as themePaletteGenerateFn} from '../../../api/theme/themePaletteGene
96
96
 
97
97
  /**
98
98
  * Path to this CLI's real entry (clients/cli/bin/astryx.mjs), resolved from
99
- * this module's location (clients/cli/commands/build-theme.mjs → ../bin/
99
+ * this module's location (clients/cli/commands/theme.mjs → ../bin/
100
100
  * astryx.mjs). Used to re-invoke `theme build` as a child process in watch mode.
101
101
  */
102
102
  function resolveCliBin() {
@@ -26,12 +26,11 @@ import {projectRootOf} from '../../foundation/release/choose.mjs';
26
26
  import {readReleaseFacts} from '../../foundation/release/project.mjs';
27
27
  import {buildManifest} from './lib/manifest.mjs';
28
28
  import {cliError} from './lib/cli-error.mjs';
29
- import {emit, section, text, records} from './formatters/index.mjs';
29
+ import {section, text, records} from './formatters/index.mjs';
30
30
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
31
31
  import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
32
32
  import {installJsonShim} from './lib/json-shim.mjs';
33
- import {addDocHelp, markReportsResult} from './lib/define-command.mjs';
34
- import {doc as manifestDoc} from './commands/manifest.doc.mjs';
33
+ import {markReportsResult} from './lib/define-command.mjs';
35
34
  import {
36
35
  agentDocsTargetDir,
37
36
  assertAgentDocsTarget,
@@ -297,7 +296,7 @@ function captureInvocation(actionCommand, root) {
297
296
  */
298
297
  const commands = [
299
298
  {name: 'init', path: './commands/init.mjs', register: 'registerInit'},
300
- {name: 'component', path: './commands/component/index.mjs', register: 'registerComponent'},
299
+ {name: 'component', path: './commands/component.mjs', register: 'registerComponent'},
301
300
  {name: 'docs', path: './commands/docs.mjs', register: 'registerDocs'},
302
301
  {name: 'blog', path: './commands/blog.mjs', register: 'registerBlog'},
303
302
  {name: 'swizzle', path: './commands/swizzle.mjs', register: 'registerSwizzle'},
@@ -305,13 +304,17 @@ const commands = [
305
304
  // agent-docs folded into init — functions still importable from agent-docs.mjs
306
305
  {name: 'template', path: './commands/template.mjs', register: 'registerTemplate'},
307
306
  {name: 'upgrade', path: './commands/upgrade.mjs', register: 'registerUpgrade'},
308
- {name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},
307
+ {name: 'theme', path: './commands/theme.mjs', register: 'registerTheme'},
309
308
  {name: 'integration', path: './commands/integration.mjs', register: 'registerIntegration'},
310
- {name: 'hook', path: './commands/hook/index.mjs', register: 'registerHook'},
309
+ {name: 'hook', path: './commands/hook.mjs', register: 'registerHook'},
311
310
  {name: 'discover', path: './commands/discover.mjs', register: 'registerDiscover'},
312
311
  {name: 'search', path: './commands/search.mjs', register: 'registerSearch'},
313
312
  {name: 'build', path: './commands/build.mjs', register: 'registerBuild'},
314
313
  {name: 'doctor', path: './commands/doctor.mjs', register: 'registerDoctor'},
314
+ // Registered after every other command: the manifest lists the commands in
315
+ // registration order.
316
+ {name: 'manifest', path: './commands/manifest.mjs', register: 'registerManifest'},
317
+ {name: 'postinstall', path: './commands/postinstall.mjs', register: 'registerPostinstall'},
315
318
  ];
316
319
 
317
320
  const SETUP_NUDGE_EXEMPT = new Set(['init', 'agent-docs']);
@@ -677,7 +680,7 @@ export async function createProgram() {
677
680
  for (const cmd of commands) {
678
681
  try {
679
682
  const mod = await import(cmd.path);
680
- mod[cmd.register](program);
683
+ mod[cmd.register](program, {jsonSupported: JSON_SUPPORTED, version: pkg.version});
681
684
  } catch (e) {
682
685
  // Command fails to load but CLI still works
683
686
  const reason = /** @type {any} */ (e).message;
@@ -697,84 +700,6 @@ export async function createProgram() {
697
700
  }
698
701
  }
699
702
 
700
- // Capability manifest — a single, self-describing view of the whole CLI so
701
- // agents can discover every command, argument, flag, and response type without
702
- // scraping `--help`. `astryx manifest --json` is the dedicated surface; the bare
703
- // `xds --json` embeds the same payload under data.manifest for convenience.
704
- // Intentionally CLI-special — no `api/manifest`. It introspects the live
705
- // Commander `program`, so extracting it to `api/` would create the `api → cli`
706
- // cycle from #4302. `buildManifest(program)` lives in lib/; see its header.
707
- const manifestCommand = program
708
- .command('manifest')
709
- .description('Print the full CLI capability manifest (use with --json)')
710
- .action(() => {
711
- const manifest = buildManifest(program, {
712
- jsonSupported: JSON_SUPPORTED,
713
- version: pkg.version,
714
- });
715
- // The manifest IS a result set: one entry per command the CLI ships.
716
- debug.recordCommandResult(
717
- debug.resultSet({
718
- count: manifest.commands.length,
719
- resultKind: 'command',
720
- }),
721
- );
722
- if (program.opts().json) {
723
- process.__xdsJsonHandled = true;
724
- console.log(JSON.stringify({apiVersion: API_VERSION, type: 'manifest', data: manifest, meta: {answeredBy: answeredBy()}}, null, 2));
725
- return;
726
- }
727
- // Human-readable summary as greppable records (agents should use --json).
728
- // One record per command: name, whether it supports --json, and the
729
- // description. Field names are the manifest entry's own keys.
730
- emit(
731
- section(`${manifest.name} v${manifest.version} (${manifest.commands.length} commands)`),
732
- records(
733
- manifest.commands.map(c => ({
734
- name: c.name,
735
- json: c.json ? 'yes' : '',
736
- description: c.description || '',
737
- })),
738
- {fields: ['name', 'json', 'description']},
739
- ),
740
- text(`Run \`${getCliInvocation()} manifest --json\` for the full structured manifest.`),
741
- );
742
- });
743
- addDocHelp(manifestCommand, manifestDoc);
744
- markReportsResult(manifestCommand);
745
-
746
- // Hidden command used by package.json postinstall scripts
747
- const postinstallCommand = program
748
- .command('postinstall', {hidden: true})
749
- .action(() => {
750
- // Prints the welcome box. Nothing is looked up.
751
- debug.recordCommandResult(debug.NO_RESULT_SET);
752
- const r = getCliInvocation();
753
- const pad = (/** @type {string} */ s, /** @type {number} */ len) => s + ' '.repeat(Math.max(0, len - s.length));
754
- const W = 49; // inner width of the box
755
- const line = (/** @type {string} */ s) => ` │ ${pad(s, W)}│`;
756
- console.log(`
757
- ╭${'─'.repeat(W + 2)}╮
758
- ${line('')}
759
- ${line(' Design system installed!')}
760
- ${line('')}
761
- ${line(' Get started:')}
762
- ${line(` ${r} init Setup + AI agent docs`)}
763
- ${line(` ${r} --help See all commands`)}
764
- ${line('')}
765
- ${line(' Or run directly:')}
766
- ${line(` ${r} init Setup + AI agent docs`)}
767
- ${line(` ${r} component Browse component docs`)}
768
- ${line(` ${r} hook Browse hook docs`)}
769
- ${line(` ${r} docs Design system reference`)}
770
- ${line(` ${r} swizzle Customize a component`)}
771
- ${line(` ${r} template Add a page template`)}
772
- ${line('')}
773
- ╰${'─'.repeat(W + 2)}╯
774
- `);
775
- });
776
- markReportsResult(postinstallCommand);
777
-
778
703
  // Install the JSON shim AFTER all commands are registered so we can
779
704
  // patch outputHelp on every command (root + subcommands). The shim
780
705
  // extends the --json contract to cover Commander's parse-time short
@@ -21,7 +21,7 @@ import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
21
21
  * (→ `.astryx-table-cell`), and `astryx-button` → key `button`.
22
22
  *
23
23
  * Keep the `astryx-` literal in sync with packages/core/src/naming.ts
24
- * (NAMESPACE / classPrefix), the same way build-theme.mjs mirrors it.
24
+ * (NAMESPACE / classPrefix), the same way commands/theme.mjs mirrors it.
25
25
  * <!-- SYNC: packages/core/src/naming.ts (namespace prefix source of truth) -->
26
26
  * @param {import('@astryxdesign/cli/authoring').ComponentThemingTarget} target
27
27
  * @returns {string}
@@ -63,10 +63,10 @@ export function reportsResultVia(cmd) {
63
63
  /**
64
64
  * Mark a hand-registered command as reporting its result.
65
65
  *
66
- * For the handful of commands that cannot come from a CommandDoc — the root
67
- * program, `manifest` (it introspects the live program, so it cannot be
68
- * declared by one), `postinstall`, and the stub left behind when a command
69
- * module fails to load. They call {@link recordCommandResult} themselves; this
66
+ * For what does not come from a CommandDoc: the root program, and the stub
67
+ * left behind when a command module fails to load. Every command, `manifest`
68
+ * and the hidden `postinstall` hook included, registers through
69
+ * {@link defineCommand}. These call {@link recordCommandResult} themselves; this
70
70
  * says so, and the coverage test pins the set of commands allowed to, so the
71
71
  * mark cannot become a quiet way around the contract.
72
72
  *
@@ -105,10 +105,12 @@ export function commandDocsOf(cmd) {
105
105
  * fn?: import('@astryxdesign/cli/authoring').FunctionDoc,
106
106
  * action?: (...args: any[]) => import('../../../foundation/debug/command-result.mjs').CommandResult
107
107
  * | Promise<import('../../../foundation/debug/command-result.mjs').CommandResult>,
108
- * }} [impl]
108
+ * hidden?: boolean,
109
+ * }} [impl] `hidden` keeps the command out of help and the manifest (a
110
+ * package-script hook, not a command for people or agents).
109
111
  * @returns {import('commander').Command} the created command.
110
112
  */
111
- export function defineCommand(parent, doc, {fn, action} = {}) {
113
+ export function defineCommand(parent, doc, {fn, action, hidden} = {}) {
112
114
  // The command token is the last path segment ("theme build" -> "build"),
113
115
  // since subcommands are added to their group command, not the program.
114
116
  const token = doc.name.split(' ').pop() ?? doc.name;
@@ -119,7 +121,10 @@ export function defineCommand(parent, doc, {fn, action} = {}) {
119
121
  })
120
122
  .join(' ');
121
123
 
122
- const cmd = parent.command(argSpec ? `${token} ${argSpec}` : token);
124
+ const cmd = parent.command(
125
+ argSpec ? `${token} ${argSpec}` : token,
126
+ hidden ? {hidden: true} : {},
127
+ );
123
128
  Object.defineProperty(cmd, COMMAND_DOCS, {value: {doc, fn}, configurable: true});
124
129
  if (doc.summary) cmd.description(doc.summary);
125
130
  if (doc.deprecated) {
@@ -24,6 +24,10 @@ for (const file of fs.readdirSync(COMMANDS).sort()) {
24
24
  }
25
25
 
26
26
  const manifest = buildManifest(program, {jsonSupported: JSON_SUPPORTED, version: '0.0.0-test'});
27
+ /** Hidden commands (a package-script hook): documented, never in the manifest. */
28
+ const HIDDEN = new Set(
29
+ program.commands.filter((c) => /** @type {any} */ (c)._hidden).map((c) => c.name()),
30
+ );
27
31
  /** @type {Map<string, any>} */
28
32
  const entries = new Map();
29
33
  const walk = (/** @type {any} */ c) => {
@@ -98,6 +102,7 @@ describe('command exit codes', () => {
98
102
 
99
103
  it('the manifest carries every command exit code', () => {
100
104
  for (const doc of commandDocs) {
105
+ if (HIDDEN.has(doc.name)) continue;
101
106
  expect(entries.get(doc.name)?.exitCodes, doc.name).toEqual(
102
107
  doc.exitCodes.map(({code, when}) => ({code, when})),
103
108
  );
@@ -55,6 +55,10 @@ const CLI_LAYER_TYPES = {
55
55
  };
56
56
 
57
57
  const manifest = buildManifest(program, {jsonSupported: JSON_SUPPORTED, version: '0.0.0-test'});
58
+ /** Hidden commands (a package-script hook): documented, never in the manifest. */
59
+ const HIDDEN = new Set(
60
+ program.commands.filter((c) => /** @type {any} */ (c)._hidden).map((c) => c.name()),
61
+ );
58
62
 
59
63
  /** Flatten the manifest command tree into fully-qualified names. */
60
64
  function flatten(cmds, out = []) {
@@ -116,12 +120,19 @@ describe('manifest: drift guards', () => {
116
120
 
117
121
  it('takes every command example from its CommandDoc', () => {
118
122
  for (const [name, doc] of commandDocs) {
123
+ if (HIDDEN.has(name)) continue;
119
124
  const entry = allEntries.find((c) => c.name === name);
120
125
  expect(entry, `CommandDoc "${name}" has no manifest entry`).toBeDefined();
121
126
  expect(entry.examples ?? [], name).toEqual((doc.examples ?? []).map((e) => e.cli));
122
127
  }
123
128
  });
124
129
 
130
+ it('documents the hidden postinstall hook and keeps it out of the manifest', () => {
131
+ expect([...HIDDEN]).toEqual(['postinstall']);
132
+ expect(commandDocs.has('postinstall')).toBe(true);
133
+ expect(allNames.has('postinstall')).toBe(false);
134
+ });
135
+
125
136
  it('lists every response type the wrapped API function returns', () => {
126
137
  for (const [name, doc] of commandDocs) {
127
138
  if (!doc.fn) continue;
@@ -152,6 +163,7 @@ describe('manifest: drift guards', () => {
152
163
 
153
164
  it('takes response types from the wrapped FunctionDoc, plus CLI-layer envelopes', () => {
154
165
  for (const [name, doc] of commandDocs) {
166
+ if (HIDDEN.has(name)) continue;
155
167
  const entry = allEntries.find((c) => c.name === name);
156
168
  const returns = doc.fn ? functionDocs.get(doc.fn).returns.map((r) => r.type) : [];
157
169
  const expected = [...returns, ...(CLI_LAYER_TYPES[name] ?? [])];
@@ -0,0 +1,50 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The welcome box `astryx postinstall` prints after the package installs.
5
+ *
6
+ * A fixed banner, not tabular output, so it is drawn here rather than with the
7
+ * formatter kit; the command prints it verbatim through `emit(code(...))`.
8
+ * @input The CLI invocation for this project (e.g. `pnpm exec astryx`).
9
+ * @output {@link welcomeBox}
10
+ * @position clients/cli/lib — presentation helper for commands/postinstall.mjs
11
+ */
12
+
13
+ /** Inner width of the box. */
14
+ const W = 49;
15
+
16
+ /**
17
+ * @param {string} s
18
+ * @param {number} len
19
+ */
20
+ const pad = (s, len) => s + ' '.repeat(Math.max(0, len - s.length));
21
+
22
+ /** @param {string} s */
23
+ const line = s => ` │ ${pad(s, W)}│`;
24
+
25
+ /**
26
+ * The welcome box, with a blank line before and after it.
27
+ * @param {string} r the CLI invocation, e.g. `pnpm exec astryx`
28
+ * @returns {string}
29
+ */
30
+ export function welcomeBox(r) {
31
+ return `
32
+ ╭${'─'.repeat(W + 2)}╮
33
+ ${line('')}
34
+ ${line(' Design system installed!')}
35
+ ${line('')}
36
+ ${line(' Get started:')}
37
+ ${line(` ${r} init Setup + AI agent docs`)}
38
+ ${line(` ${r} --help See all commands`)}
39
+ ${line('')}
40
+ ${line(' Or run directly:')}
41
+ ${line(` ${r} init Setup + AI agent docs`)}
42
+ ${line(` ${r} component Browse component docs`)}
43
+ ${line(` ${r} hook Browse hook docs`)}
44
+ ${line(` ${r} docs Design system reference`)}
45
+ ${line(` ${r} swizzle Customize a component`)}
46
+ ${line(` ${r} template Add a page template`)}
47
+ ${line('')}
48
+ ╰${'─'.repeat(W + 2)}╯
49
+ `;
50
+ }
@@ -67,6 +67,7 @@ export const CLI_COMMANDS = Object.freeze([
67
67
  'init',
68
68
  'integration',
69
69
  'manifest',
70
+ 'postinstall',
70
71
  'search',
71
72
  'swizzle',
72
73
  'template',
@@ -102,7 +102,15 @@ const RUNNERS = {
102
102
  runs: SELF_DOCS,
103
103
  sites: ['import ../../../api/blog/blog.doc.mjs', 'import ./blog.doc.mjs'],
104
104
  },
105
- 'clients/cli/commands/build-theme.mjs': {
105
+ 'clients/cli/commands/manifest.mjs': {
106
+ runs: SELF_DOCS,
107
+ sites: ['import ./manifest.doc.mjs'],
108
+ },
109
+ 'clients/cli/commands/postinstall.mjs': {
110
+ runs: SELF_DOCS,
111
+ sites: ['import ./postinstall.doc.mjs'],
112
+ },
113
+ 'clients/cli/commands/theme.mjs': {
106
114
  runs: `${SELF_DOCS}; and \`astryx theme build\`, a child process per theme`,
107
115
  sites: [
108
116
  'child_process.spawn',
@@ -135,11 +143,11 @@ const RUNNERS = {
135
143
  'import ./build.doc.mjs',
136
144
  ],
137
145
  },
138
- 'clients/cli/commands/component/index.mjs': {
146
+ 'clients/cli/commands/component.mjs': {
139
147
  runs: SELF_DOCS,
140
148
  sites: [
141
- 'import ../../../../api/component/component.doc.mjs',
142
- 'import ../component.doc.mjs',
149
+ 'import ../../../api/component/component.doc.mjs',
150
+ 'import ./component.doc.mjs',
143
151
  ],
144
152
  },
145
153
  'clients/cli/commands/discover.mjs': {
@@ -180,11 +188,11 @@ const RUNNERS = {
180
188
  'import ./gap-report.doc.mjs',
181
189
  ],
182
190
  },
183
- 'clients/cli/commands/hook/index.mjs': {
191
+ 'clients/cli/commands/hook.mjs': {
184
192
  runs: SELF_DOCS,
185
193
  sites: [
186
- 'import ../../../../api/hook/hook.doc.mjs',
187
- 'import ../hook.doc.mjs',
194
+ 'import ../../../api/hook/hook.doc.mjs',
195
+ 'import ./hook.doc.mjs',
188
196
  ],
189
197
  },
190
198
  'clients/cli/commands/init.mjs': {
@@ -233,8 +241,8 @@ const RUNNERS = {
233
241
  ],
234
242
  },
235
243
  'clients/cli/index.mjs': {
236
- runs: 'the command modules, to register each command, and the manifest command doc',
237
- sites: ['import ./commands/manifest.doc.mjs', 'import(<computed>)'],
244
+ runs: 'the command modules, to register each command',
245
+ sites: ['import(<computed>)'],
238
246
  },
239
247
  'clients/cli/lib/manifest.mjs': {
240
248
  runs: 'the manifest command doc, for the exit codes the manifest reports',
@@ -323,6 +331,10 @@ const RUNNERS = {
323
331
  'require.cache',
324
332
  ],
325
333
  },
334
+ 'foundation/fs/read-record.mjs': {
335
+ runs: "nothing; it wraps node:fs's read calls to record the paths an operation reads, and republishes them to ESM imports",
336
+ sites: ['module.syncBuiltinESMExports'],
337
+ },
326
338
  'foundation/fs/paths.mjs': {
327
339
  runs: "Yarn's pnpapi, under Plug'n'Play, to find an installed package",
328
340
  sites: ['require(pnpapi)'],
@@ -0,0 +1,18 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * Whether every recorded path is still in the state it had when it was read.
6
+ * @param {Map<string, string>} recorded - From recordReads.
7
+ * @returns {boolean}
8
+ */
9
+ export function unchangedSince(recorded: Map<string, string>): boolean;
10
+ /**
11
+ * Run `fn`, adding to `seen` each path it reads, with that path's state when
12
+ * it was first read (see the file header).
13
+ * @template T
14
+ * @param {Map<string, string>} seen
15
+ * @param {() => T} fn
16
+ * @returns {T}
17
+ */
18
+ export function recordReads<T>(seen: Map<string, string>, fn: () => T): T;
@@ -0,0 +1,131 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Which files and folders an operation read, so a long-running caller
5
+ * can tell whether its inputs changed since.
6
+ *
7
+ * @input An operation run inside `recordReads(seen, fn)`.
8
+ * @output `seen` gets every file whose content the operation read through fs
9
+ * and every folder it listed or probed, each with its state when first
10
+ * read; `unchangedSince(seen)` says whether all are still in that state.
11
+ * @position Used by search's adapter to reuse a gathered catalog only while
12
+ * it is exact. Outside `recordReads` nothing is recorded and every fs call
13
+ * behaves as before.
14
+ */
15
+
16
+ import {AsyncLocalStorage} from 'node:async_hooks';
17
+ import {createRequire, syncBuiltinESMExports} from 'node:module';
18
+ import * as path from 'node:path';
19
+ import {fileURLToPath} from 'node:url';
20
+
21
+ /**
22
+ * The paths the running operation touched: every file it read and every
23
+ * folder it listed or probed.
24
+ * @type {AsyncLocalStorage<Map<string, string>>}
25
+ */
26
+ const reads = new AsyncLocalStorage();
27
+
28
+ /** node:fs's module object, whose functions every import of it shares. */
29
+ const fs = createRequire(import.meta.url)('node:fs');
30
+
31
+ /** The fs reads whose path argument is recorded. */
32
+ const RECORDED = [
33
+ 'readFileSync',
34
+ 'readdirSync',
35
+ 'statSync',
36
+ 'lstatSync',
37
+ 'existsSync',
38
+ 'realpathSync',
39
+ 'accessSync',
40
+ 'openSync',
41
+ ];
42
+
43
+ /** The reads that see a file's content, so the file itself is checked. */
44
+ const CONTENT_READS = new Set(['readFileSync', 'openSync']);
45
+
46
+ let recording = false;
47
+
48
+ /** fs.statSync as loaded, before installRecorder wraps it. */
49
+ const statSyncRaw = fs.statSync;
50
+
51
+ /**
52
+ * Wrap fs's read calls once so that, inside `reads.run`, each path they are
53
+ * given is added to that run's set. Outside a run they behave exactly as
54
+ * before.
55
+ */
56
+ function installRecorder() {
57
+ if (recording) return;
58
+ recording = true;
59
+ for (const name of RECORDED) {
60
+ const original = fs[name];
61
+ if (typeof original !== 'function') continue;
62
+ /**
63
+ * @this {unknown}
64
+ * @param {...any} args
65
+ */
66
+ const wrapped = function (...args) {
67
+ const seen = reads.getStore();
68
+ const target = args[0];
69
+ if (seen && (typeof target === 'string' || target instanceof URL)) {
70
+ const file =
71
+ typeof target === 'string'
72
+ ? path.resolve(target)
73
+ : fileURLToPath(target);
74
+ // A file read is checked itself; a probe or listing is checked by its
75
+ // folder, whose time changes when an entry is added, removed or
76
+ // renamed.
77
+ const checked =
78
+ CONTENT_READS.has(name) || name === 'readdirSync'
79
+ ? file
80
+ : path.dirname(file);
81
+ // Its state is taken when it is first read, before the read, so a
82
+ // change made while the operation runs shows as a change afterwards.
83
+ if (!seen.has(checked)) seen.set(checked, stateOf(checked));
84
+ }
85
+ return original.apply(this, args);
86
+ };
87
+ Object.assign(wrapped, original);
88
+ fs[name] = wrapped;
89
+ }
90
+ // ESM imports of node:fs see the wrapped functions too.
91
+ syncBuiltinESMExports();
92
+ }
93
+
94
+ /**
95
+ * One path's state: its change time and size, or that it is absent.
96
+ * @param {string} file
97
+ * @returns {string}
98
+ */
99
+ function stateOf(file) {
100
+ try {
101
+ const stat = statSyncRaw(file);
102
+ return `${stat.mtimeMs}\0${stat.size}`;
103
+ } catch {
104
+ return '-';
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Whether every recorded path is still in the state it had when it was read.
110
+ * @param {Map<string, string>} recorded - From recordReads.
111
+ * @returns {boolean}
112
+ */
113
+ export function unchangedSince(recorded) {
114
+ for (const [file, state] of recorded) {
115
+ if (stateOf(file) !== state) return false;
116
+ }
117
+ return true;
118
+ }
119
+
120
+ /**
121
+ * Run `fn`, adding to `seen` each path it reads, with that path's state when
122
+ * it was first read (see the file header).
123
+ * @template T
124
+ * @param {Map<string, string>} seen
125
+ * @param {() => T} fn
126
+ * @returns {T}
127
+ */
128
+ export function recordReads(seen, fn) {
129
+ installRecorder();
130
+ return reads.run(seen, fn);
131
+ }
@@ -0,0 +1,77 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Tests for read-record: which paths an operation read, and whether
5
+ * any changed since, including a change made while the operation ran.
6
+ */
7
+
8
+ import {describe, it, expect} from 'vitest';
9
+ import * as fs from 'node:fs';
10
+ import * as os from 'node:os';
11
+ import * as path from 'node:path';
12
+ import {recordReads, unchangedSince} from './read-record.mjs';
13
+
14
+ function scratch() {
15
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-read-record-'));
16
+ const file = path.join(dir, 'doc.txt');
17
+ fs.writeFileSync(file, 'one');
18
+ return {dir, file};
19
+ }
20
+
21
+ describe('recordReads', () => {
22
+ it('records a read file and a listed folder, and sees them unchanged', () => {
23
+ const {dir, file} = scratch();
24
+ /** @type {Map<string, string>} */
25
+ const seen = new Map();
26
+ recordReads(seen, () => {
27
+ fs.readFileSync(file, 'utf8');
28
+ fs.readdirSync(dir);
29
+ });
30
+ expect([...seen.keys()]).toEqual(expect.arrayContaining([file, dir]));
31
+ expect(unchangedSince(seen)).toBe(true);
32
+ });
33
+
34
+ it('sees an edit made after the operation', () => {
35
+ const {file} = scratch();
36
+ /** @type {Map<string, string>} */
37
+ const seen = new Map();
38
+ recordReads(seen, () => fs.readFileSync(file, 'utf8'));
39
+ const later = new Date(Date.now() + 5_000);
40
+ fs.writeFileSync(file, 'two, longer');
41
+ fs.utimesSync(file, later, later);
42
+ expect(unchangedSince(seen)).toBe(false);
43
+ });
44
+
45
+ it('sees an edit made while the operation ran, after the file was read', () => {
46
+ const {file} = scratch();
47
+ /** @type {Map<string, string>} */
48
+ const seen = new Map();
49
+ recordReads(seen, () => {
50
+ fs.readFileSync(file, 'utf8');
51
+ const later = new Date(Date.now() + 5_000);
52
+ fs.writeFileSync(file, 'edited mid-run');
53
+ fs.utimesSync(file, later, later);
54
+ });
55
+ expect(unchangedSince(seen)).toBe(false);
56
+ });
57
+
58
+ it('sees a file added to a folder it probed', () => {
59
+ const {dir} = scratch();
60
+ /** @type {Map<string, string>} */
61
+ const seen = new Map();
62
+ recordReads(seen, () => fs.existsSync(path.join(dir, 'missing.txt')));
63
+ const later = new Date(Date.now() + 5_000);
64
+ fs.writeFileSync(path.join(dir, 'missing.txt'), 'now here');
65
+ fs.utimesSync(dir, later, later);
66
+ expect(unchangedSince(seen)).toBe(false);
67
+ });
68
+
69
+ it('records nothing outside an operation', () => {
70
+ const {file} = scratch();
71
+ /** @type {Map<string, string>} */
72
+ const seen = new Map();
73
+ recordReads(seen, () => {});
74
+ fs.readFileSync(file, 'utf8');
75
+ expect(seen.size).toBe(0);
76
+ });
77
+ });