@astryxdesign/cli 0.7.7-canary.95438ff → 0.7.7-canary.97191cf

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.
@@ -27,6 +27,7 @@ import {
27
27
  packageReferenceProblems,
28
28
  } from '../docs/_adapter.mjs';
29
29
  import {findProjectCoreDir} from '../../foundation/fs/paths.mjs';
30
+ import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
30
31
  import {
31
32
  discoverIntegrationComponents,
32
33
  discoverOwnedComponents,
@@ -154,6 +155,16 @@ function addErrors(issues, errors, code) {
154
155
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationTemplateConflictResponse>}
155
156
  */
156
157
  export async function integrationTemplateConflicts(pkg, options = {}) {
158
+ // Read-only: one listing of each folder serves the whole check.
159
+ return withListingCache(() => templateConflicts(pkg, options));
160
+ }
161
+
162
+ /**
163
+ * @param {string | undefined} pkg
164
+ * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} options
165
+ * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationTemplateConflictResponse>}
166
+ */
167
+ async function templateConflicts(pkg, options) {
157
168
  const {cwd = process.cwd()} = options;
158
169
  const resolved = await resolveIntegration(pkg, cwd);
159
170
  const validated = resolved.found;
@@ -291,6 +302,16 @@ export async function integrationTemplateConflicts(pkg, options = {}) {
291
302
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationComponentConflictResponse>}
292
303
  */
293
304
  export async function integrationComponentConflicts(pkg, options = {}) {
305
+ // Read-only: one listing of each folder serves the whole check.
306
+ return withListingCache(() => componentConflicts(pkg, options));
307
+ }
308
+
309
+ /**
310
+ * @param {string | undefined} pkg
311
+ * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} options
312
+ * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationComponentConflictResponse>}
313
+ */
314
+ async function componentConflicts(pkg, options) {
294
315
  const {cwd = process.cwd()} = options;
295
316
  const resolved = await resolveIntegration(pkg, cwd);
296
317
  const validated = resolved.found;
@@ -387,6 +408,16 @@ export async function integrationComponentConflicts(pkg, options = {}) {
387
408
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationDocConflictResponse>}
388
409
  */
389
410
  export async function integrationDocConflicts(pkg, options = {}) {
411
+ // Read-only: one listing of each folder serves the whole check.
412
+ return withListingCache(() => docConflicts(pkg, options));
413
+ }
414
+
415
+ /**
416
+ * @param {string | undefined} pkg
417
+ * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} options
418
+ * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationDocConflictResponse>}
419
+ */
420
+ async function docConflicts(pkg, options) {
390
421
  const {cwd = process.cwd()} = options;
391
422
  const resolved = await resolveIntegration(pkg, cwd);
392
423
  const validated = resolved.found;
@@ -36,6 +36,7 @@ import {
36
36
  summarizeIssues,
37
37
  validateIntegration,
38
38
  } from '../validate-integration.mjs';
39
+ import {withListingCache} from '../../../foundation/fs/listing-cache.mjs';
39
40
 
40
41
  /** @typedef {import('../integration-check.type.mjs').IntegrationCheckName} IntegrationCheckName */
41
42
  /** @typedef {import('../integration-check.type.mjs').IntegrationCheckReport} IntegrationCheckReport */
@@ -244,9 +245,13 @@ export async function integrationCheck(options = {}) {
244
245
  /** @type {IntegrationCheckResponse[]} */
245
246
  const responses = [];
246
247
  responses.push(await validateIntegration(undefined, {cwd}));
247
- responses.push(await integrationComponentConflicts(undefined, {cwd}));
248
- responses.push(await integrationTemplateConflicts(undefined, {cwd}));
249
- responses.push(await integrationDocConflicts(undefined, {cwd}));
248
+ // The three authoring checks only read, so they share one listing of each
249
+ // folder.
250
+ await withListingCache(async () => {
251
+ responses.push(await integrationComponentConflicts(undefined, {cwd}));
252
+ responses.push(await integrationTemplateConflicts(undefined, {cwd}));
253
+ responses.push(await integrationDocConflicts(undefined, {cwd}));
254
+ });
250
255
 
251
256
  const [validation] = responses;
252
257
  return {
@@ -0,0 +1,14 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
4
+ export const doc = {
5
+ type: 'block',
6
+ exampleFor: 'useGridFocus',
7
+ name: 'useGridFocus — Color Swatch Grid',
8
+ displayName: 'useGridFocus — Color Swatch Grid',
9
+ description:
10
+ 'A color swatch picker in rows of eight with one Tab stop. useGridFocus moves focus with the arrow keys, Home and End, and Ctrl+Home and Ctrl+End. Each swatch is a button, so Enter or a click picks it.',
11
+ isReady: true,
12
+ aspectRatio: 4 / 3,
13
+ componentsUsed: ['Card', 'Text', 'Layout'],
14
+ };
@@ -0,0 +1,86 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {useState} from 'react';
6
+ import {Card} from '@astryxdesign/core/Card';
7
+ import {useGridFocus} from '@astryxdesign/core/hooks';
8
+ import {VStack} from '@astryxdesign/core/Layout';
9
+ import {Text} from '@astryxdesign/core/Text';
10
+
11
+ const COLUMNS = 8;
12
+
13
+ const SWATCHES = [
14
+ {name: 'Red', value: '#e5484d'},
15
+ {name: 'Tomato', value: '#f76b15'},
16
+ {name: 'Amber', value: '#ffc53d'},
17
+ {name: 'Lime', value: '#bdee63'},
18
+ {name: 'Green', value: '#30a46c'},
19
+ {name: 'Teal', value: '#12a594'},
20
+ {name: 'Cyan', value: '#00a2c7'},
21
+ {name: 'Blue', value: '#0090ff'},
22
+ {name: 'Indigo', value: '#3e63dd'},
23
+ {name: 'Violet', value: '#6e56cf'},
24
+ {name: 'Purple', value: '#8e4ec6'},
25
+ {name: 'Plum', value: '#ab4aba'},
26
+ {name: 'Pink', value: '#d6409f'},
27
+ {name: 'Brown', value: '#ad7f58'},
28
+ {name: 'Gray', value: '#8d8d8d'},
29
+ {name: 'Black', value: '#111111'},
30
+ ];
31
+
32
+ const ROWS = Array.from({length: SWATCHES.length / COLUMNS}, (_, row) =>
33
+ SWATCHES.slice(row * COLUMNS, (row + 1) * COLUMNS),
34
+ );
35
+
36
+ export default function UseGridFocusHookUsage() {
37
+ const [selected, setSelected] = useState(SWATCHES[0].name);
38
+ const {gridRef, handleKeyDown, handleFocus} = useGridFocus<HTMLDivElement>({
39
+ columns: COLUMNS,
40
+ cellSelector: '[role="gridcell"]',
41
+ getFocusTarget: cell => cell.querySelector('button'),
42
+ hasRovingTabIndex: true,
43
+ });
44
+
45
+ return (
46
+ <Card padding={4}>
47
+ <VStack gap={3}>
48
+ <Text type="body">Selected: {selected}</Text>
49
+ <div
50
+ ref={gridRef}
51
+ role="grid"
52
+ aria-label="Colors"
53
+ onKeyDown={handleKeyDown}
54
+ onFocus={handleFocus}
55
+ style={{display: 'flex', flexDirection: 'column', gap: 4}}>
56
+ {ROWS.map((row, index) => (
57
+ <div key={index} role="row" style={{display: 'flex', gap: 4}}>
58
+ {row.map(swatch => (
59
+ <div
60
+ key={swatch.name}
61
+ role="gridcell"
62
+ aria-selected={swatch.name === selected}>
63
+ <button
64
+ type="button"
65
+ aria-label={swatch.name}
66
+ aria-pressed={swatch.name === selected}
67
+ onClick={() => setSelected(swatch.name)}
68
+ style={{
69
+ width: 28,
70
+ height: 28,
71
+ border: 'none',
72
+ boxShadow:
73
+ 'inset 0 0 0 1px var(--color-border-emphasized)',
74
+ borderRadius: 4,
75
+ background: swatch.value,
76
+ }}
77
+ />
78
+ </div>
79
+ ))}
80
+ </div>
81
+ ))}
82
+ </div>
83
+ </VStack>
84
+ </Card>
85
+ );
86
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
4
+ export const doc = {
5
+ type: 'block',
6
+ exampleFor: 'useOverflow',
7
+ name: 'useOverflow — Editor Toolbar',
8
+ displayName: 'useOverflow — Editor Toolbar',
9
+ description:
10
+ 'Resize the card: useOverflow moves the toolbar actions that do not fit into a More menu, and shows them again when the card gets wider.',
11
+ isReady: true,
12
+ aspectRatio: 16 / 9,
13
+ componentsUsed: ['Card', 'Button', 'DropdownMenu'],
14
+ };
@@ -0,0 +1,89 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import * as stylex from '@stylexjs/stylex';
6
+ import {useOverflow} from '@astryxdesign/core/hooks';
7
+ import {Button} from '@astryxdesign/core/Button';
8
+ import {Card} from '@astryxdesign/core/Card';
9
+ import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
10
+
11
+ const actions = [
12
+ 'Bold',
13
+ 'Italic',
14
+ 'Underline',
15
+ 'Strikethrough',
16
+ 'Link',
17
+ 'Quote',
18
+ 'Code',
19
+ 'Clear formatting',
20
+ ];
21
+
22
+ const GAP = 4;
23
+
24
+ const styles = stylex.create({
25
+ box: {
26
+ resize: 'horizontal',
27
+ overflow: 'hidden',
28
+ width: 480,
29
+ minWidth: 120,
30
+ maxWidth: '100%',
31
+ },
32
+ row: {
33
+ display: 'flex',
34
+ gap: GAP,
35
+ },
36
+ // Takes no space and paints nothing, so the hook measures every item
37
+ // without a flicker. Do not use display: none, which stops measurement.
38
+ measure: {
39
+ position: 'absolute',
40
+ visibility: 'hidden',
41
+ height: 0,
42
+ overflow: 'hidden',
43
+ whiteSpace: 'nowrap',
44
+ pointerEvents: 'none',
45
+ },
46
+ });
47
+
48
+ function MoreMenu({items}: {items: string[]}) {
49
+ return (
50
+ <DropdownMenu
51
+ button={{label: 'More', variant: 'ghost', size: 'sm'}}
52
+ items={items.map(label => ({label}))}
53
+ />
54
+ );
55
+ }
56
+
57
+ export default function UseOverflowHookUsage() {
58
+ const {containerRef, measureRef, visibleCount, hasOverflow} = useOverflow(
59
+ actions.length,
60
+ {gap: GAP},
61
+ );
62
+
63
+ return (
64
+ <Card padding={2} xstyle={styles.box}>
65
+ <div
66
+ ref={measureRef}
67
+ aria-hidden="true"
68
+ inert
69
+ {...stylex.props(styles.row, styles.measure)}>
70
+ {actions.map(label => (
71
+ <Button key={label} label={label} variant="ghost" size="sm" />
72
+ ))}
73
+ <div data-overflow-indicator>
74
+ <MoreMenu items={actions} />
75
+ </div>
76
+ </div>
77
+ <div
78
+ ref={containerRef}
79
+ role="group"
80
+ aria-label="Text formatting"
81
+ {...stylex.props(styles.row)}>
82
+ {actions.slice(0, visibleCount).map(label => (
83
+ <Button key={label} label={label} variant="ghost" size="sm" />
84
+ ))}
85
+ {hasOverflow && <MoreMenu items={actions.slice(visibleCount)} />}
86
+ </div>
87
+ </Card>
88
+ );
89
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
4
+ export const doc = {
5
+ type: 'block',
6
+ exampleFor: 'useOutlineFromMarkdown',
7
+ name: 'useOutlineFromMarkdown — Docs Article',
8
+ displayName: 'useOutlineFromMarkdown — Docs Article',
9
+ description:
10
+ 'A docs-style article with an Outline next to it, built from the same Markdown string through useOutlineFromMarkdown. "Add section" appends a heading to the string, and a new entry that links to it appears in the outline.',
11
+ isReady: true,
12
+ aspectRatio: 16 / 9,
13
+ componentsUsed: ['Markdown', 'Outline', 'ScrollableArea', 'Button', 'Layout'],
14
+ };
@@ -0,0 +1,69 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {useRef, useState} from 'react';
6
+ import {Button} from '@astryxdesign/core/Button';
7
+ import {HStack, VStack} from '@astryxdesign/core/Layout';
8
+ import {Markdown} from '@astryxdesign/core/Markdown';
9
+ import {Outline, useOutlineFromMarkdown} from '@astryxdesign/core/Outline';
10
+ import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';
11
+
12
+ const ARTICLE = `## Before you start
13
+
14
+ Check that your project builds on the current release. Commit your work, so
15
+ that you can compare the result of the upgrade.
16
+
17
+ ## Run the upgrade
18
+
19
+ Update the packages, then rebuild the project. The upgrade changes no source
20
+ files.
21
+
22
+ ### Update the packages
23
+
24
+ Install the new version of every package at the same time. Mixed versions fail
25
+ the build.
26
+
27
+ ### Rebuild the project
28
+
29
+ Delete the build output first. A stale cache can hide a real error.
30
+
31
+ ## Check the result
32
+
33
+ Open the pages that you use most, and compare them with the earlier build.
34
+ `;
35
+
36
+ const NEW_SECTION = `
37
+ ## New section
38
+
39
+ The button added this heading to the Markdown string.
40
+ `;
41
+
42
+ export default function UseOutlineFromMarkdownHookUsage() {
43
+ const [markdown, setMarkdown] = useState(ARTICLE);
44
+ const items = useOutlineFromMarkdown(markdown);
45
+ const articleRef = useRef<HTMLDivElement>(null);
46
+
47
+ return (
48
+ <HStack gap={6} align="start" width="100%">
49
+ <ScrollableArea
50
+ ref={articleRef}
51
+ label="Article"
52
+ height={320}
53
+ width="100%">
54
+ <Markdown>{markdown}</Markdown>
55
+ </ScrollableArea>
56
+ <VStack gap={3} align="start" width={220}>
57
+ {/* A non-zero offset moves only the article. With 0, a click also moves
58
+ the page around the article. */}
59
+ <Outline items={items} scrollContainerRef={articleRef} offset={8} />
60
+ <Button
61
+ label="Add section"
62
+ variant="secondary"
63
+ size="sm"
64
+ onClick={() => setMarkdown(current => current + NEW_SECTION)}
65
+ />
66
+ </VStack>
67
+ </HStack>
68
+ );
69
+ }
@@ -8,7 +8,12 @@ import * as fs from 'node:fs';
8
8
  import {createRequire} from 'node:module';
9
9
  import * as path from 'node:path';
10
10
  import {DOC_EXPORTS} from '../doc-compiler/read.mjs';
11
- import {listDir, listDirEntries, pathExists} from '../fs/listing-cache.mjs';
11
+ import {
12
+ listDir,
13
+ listDirEntries,
14
+ pathExists,
15
+ withListingCache,
16
+ } from '../fs/listing-cache.mjs';
12
17
  import {existsCaseExact} from '../fs/paths.mjs';
13
18
  import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
14
19
  import {loadComponentDoc} from './component-loader.mjs';
@@ -595,20 +600,25 @@ export function findComponentSource(coreDir, name) {
595
600
  * @param {string} dirPath
596
601
  * @returns {string | null}
597
602
  */
598
- function searchDir(dirPath) {
599
- if (!pathExists(dirPath)) return null;
603
+ function searchDir(dirPath, listed = false) {
604
+ // A folder from its parent's listing exists; only a starting folder
605
+ // needs the check.
606
+ if (!listed && !pathExists(dirPath)) return null;
600
607
  const entries = listDirEntries(dirPath);
601
608
 
602
- // Check for an exact match (prefixed or bare) first
609
+ // Check for an exact match (prefixed or bare) first. The listing in hand
610
+ // holds every name in the folder, so no name is probed on disk.
603
611
  for (const candidate of candidateFiles) {
612
+ const entry = entries.find(e => e.name === candidate);
613
+ if (!entry) continue;
604
614
  const exact = path.join(dirPath, candidate);
605
- if (existsCaseExact(exact, dirPath)) return exact;
615
+ if (!entry.isSymbolicLink() || pathExists(exact)) return exact;
606
616
  }
607
617
 
608
618
  // Recurse into subdirectories
609
619
  for (const entry of entries) {
610
620
  if (entry.isDirectory()) {
611
- const found = searchDir(path.join(dirPath, entry.name));
621
+ const found = searchDir(path.join(dirPath, entry.name), true);
612
622
  if (found) return found;
613
623
  }
614
624
  }
@@ -1703,6 +1713,16 @@ export function unscopedComponentOwners(owners) {
1703
1713
  * @returns {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>}
1704
1714
  */
1705
1715
  export function discoverOwnedComponents(coreDir, loadedIntegrations = []) {
1716
+ // Read-only: one listing of each folder serves the whole discovery.
1717
+ return withListingCache(() => ownedComponents(coreDir, loadedIntegrations));
1718
+ }
1719
+
1720
+ /**
1721
+ * @param {string} coreDir
1722
+ * @param {Array<{name: string, components?: string, issuesUrl?: string}>} loadedIntegrations
1723
+ * @returns {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>}
1724
+ */
1725
+ function ownedComponents(coreDir, loadedIntegrations) {
1706
1726
  /** @type {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>} */
1707
1727
  const records = [];
1708
1728
 
@@ -45,6 +45,7 @@ import {
45
45
  TYPESCRIPT_FIX,
46
46
  unusableTypeScriptReason,
47
47
  } from './project-typescript.mjs';
48
+ import {keepSourceFiles} from './source-file-cache.mjs';
48
49
 
49
50
  /**
50
51
  * @typedef {'components' | 'hooks' | 'templates' | 'docs' | 'docs-overlay' | 'themes' | 'icon-sets'} DocRoot
@@ -1035,8 +1036,9 @@ export async function checkDocTypes(files, options) {
1035
1036
  paths: {[AUTHORING]: [AUTHORING_TYPES]},
1036
1037
  };
1037
1038
  const host = ts.createCompilerHost(options_);
1038
- const getSourceFile = host.getSourceFile.bind(host);
1039
- // Every other file is parsed once, so a later pass reuses it.
1039
+ // Every other file is parsed once, so a later pass reuses it; and once per
1040
+ // process for these options, so a later check does too.
1041
+ const getSourceFile = keepSourceFiles(ts, host, options_);
1040
1042
  /** @type {Map<string, any>} */
1041
1043
  const parsed = new Map();
1042
1044
  host.getSourceFile = (
@@ -54,6 +54,7 @@ import {
54
54
  TYPESCRIPT_FIX,
55
55
  unusableTypeScriptReason,
56
56
  } from './project-typescript.mjs';
57
+ import {keepSourceFiles} from './source-file-cache.mjs';
57
58
  import {judgeType} from './type-match.mjs';
58
59
  import {typeTextTooOld} from './type-text.mjs';
59
60
  import {
@@ -1802,6 +1803,10 @@ export function comparePropTables(tables, options) {
1802
1803
  typesNotCompared: [],
1803
1804
  };
1804
1805
  }
1806
+ // Parsed once per process for these options: every check reads the same
1807
+ // library and package declarations.
1808
+ const host = ts.createCompilerHost(project.options);
1809
+ host.getSourceFile = keepSourceFiles(ts, host, project.options);
1805
1810
  const program = ts.createProgram({
1806
1811
  rootNames: [
1807
1812
  ...new Set([
@@ -1810,6 +1815,7 @@ export function comparePropTables(tables, options) {
1810
1815
  ]),
1811
1816
  ],
1812
1817
  options: project.options,
1818
+ host,
1813
1819
  });
1814
1820
  const checker = program.getTypeChecker();
1815
1821
  const isOwnFile = ownFileTest(root);
@@ -0,0 +1,15 @@
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
+ * `host.getSourceFile`, keeping each file it parses while the file's stamp is
6
+ * the same, for every program whose options parse and bind a file as
7
+ * `options` do. A kept file still counts as read by the running operation
8
+ * (`recordContentRead`), as a parse would. On a TypeScript older than 5.3 the
9
+ * host's own `getSourceFile` is returned.
10
+ * @param {any} ts the project's own `typescript`
11
+ * @param {any} host
12
+ * @param {any} options the compiler options of the programs that use it
13
+ * @returns {(fileName: string, languageVersionOrOptions: any, onError?: any, shouldCreate?: boolean) => any}
14
+ */
15
+ export function keepSourceFiles(ts: any, host: any, options: any): (fileName: string, languageVersionOrOptions: any, onError?: any, shouldCreate?: boolean) => any;
@@ -0,0 +1,140 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file source-file-cache.mjs
5
+ * @input A TypeScript compiler host, the project's own `typescript`, and the
6
+ * compiler options its programs use
7
+ * @output `keepSourceFiles`: the host's `getSourceFile`, keeping each parsed
8
+ * file while its stamp (`fileStamp`) is the same, for every program in this
9
+ * process whose options parse and bind a file alike.
10
+ * @position The props comparison (./prop-drift.mjs) and the doc types check
11
+ * (./doc-types.mjs) build a program for every check, and each parsed the
12
+ * same declarations again: the TypeScript library's, React's, the
13
+ * authoring types. A process that checks more than once (a test run, a
14
+ * long-running caller, a check over several roots) now parses each once.
15
+ * TypeScript's language service shares parsed files between programs the
16
+ * same way; from 5.3 a program keeps what it resolved for a file itself, not
17
+ * on the file, which is what makes sharing them safe across programs.
18
+ */
19
+
20
+ import path from 'node:path';
21
+ import {fileStamp, recordContentRead} from '../fs/read-record.mjs';
22
+
23
+ /**
24
+ * The files kept, per TypeScript and per how the options parse and bind a
25
+ * file (`settingsKey`), the most recently used options last.
26
+ * @type {WeakMap<object, Map<string, Map<string, {stamp: string, sourceFile: any}>>>}
27
+ */
28
+ const kept = new WeakMap();
29
+
30
+ /** The most files kept for one key; the oldest go first. */
31
+ const MAX_FILES = 5000;
32
+
33
+ /**
34
+ * The most keys kept per TypeScript; the least recently used go first. Each
35
+ * holds its own parse of the TypeScript library's declarations, the largest
36
+ * files a program reads.
37
+ */
38
+ const MAX_KEYS = 8;
39
+
40
+ /** @type {WeakMap<object, any>} one document registry per TypeScript */
41
+ const registries = new WeakMap();
42
+
43
+ /**
44
+ * What in `options` decides how a file parses and binds: the key TypeScript's
45
+ * language service shares parsed files by (its document registry's), and
46
+ * whether a script binds in strict mode, which that key reads only from an
47
+ * explicit `alwaysStrict`. Options that only resolve or check (`paths`,
48
+ * `types`, `lib`, the strict checks) do not change it.
49
+ * @param {any} ts
50
+ * @param {any} options
51
+ * @returns {string}
52
+ */
53
+ function settingsKey(ts, options) {
54
+ let registry = registries.get(ts);
55
+ if (registry == null) {
56
+ registry = ts.createDocumentRegistry();
57
+ registries.set(ts, registry);
58
+ }
59
+ const strict =
60
+ typeof ts.getStrictOptionValue === 'function'
61
+ ? ts.getStrictOptionValue(options, 'alwaysStrict')
62
+ : (options.alwaysStrict ?? options.strict ?? false);
63
+ return `${registry.getKeyForCompilationSettings(options)}|${strict ? 1 : 0}`;
64
+ }
65
+
66
+ /**
67
+ * Whether this TypeScript keeps a program's module resolutions on the program
68
+ * (5.3 and later) rather than on the parsed files it shares.
69
+ * @param {any} ts
70
+ */
71
+ function sharesSafely(ts) {
72
+ const [major, minor] = String(ts.versionMajorMinor ?? '0.0')
73
+ .split('.')
74
+ .map(Number);
75
+ return major > 5 || (major === 5 && minor >= 3);
76
+ }
77
+
78
+ /**
79
+ * `host.getSourceFile`, keeping each file it parses while the file's stamp is
80
+ * the same, for every program whose options parse and bind a file as
81
+ * `options` do. A kept file still counts as read by the running operation
82
+ * (`recordContentRead`), as a parse would. On a TypeScript older than 5.3 the
83
+ * host's own `getSourceFile` is returned.
84
+ * @param {any} ts the project's own `typescript`
85
+ * @param {any} host
86
+ * @param {any} options the compiler options of the programs that use it
87
+ * @returns {(fileName: string, languageVersionOrOptions: any, onError?: any, shouldCreate?: boolean) => any}
88
+ */
89
+ export function keepSourceFiles(ts, host, options) {
90
+ const getSourceFile = host.getSourceFile.bind(host);
91
+ if (!sharesSafely(ts)) return getSourceFile;
92
+ let bySettings = kept.get(ts);
93
+ if (bySettings == null) {
94
+ bySettings = new Map();
95
+ kept.set(ts, bySettings);
96
+ }
97
+ const settings = settingsKey(ts, options);
98
+ const byFile = bySettings.get(settings) ?? new Map();
99
+ // Most recently used last; past MAX_KEYS, the least recently used go.
100
+ bySettings.delete(settings);
101
+ bySettings.set(settings, byFile);
102
+ if (bySettings.size > MAX_KEYS) {
103
+ bySettings.delete(/** @type {string} */ (bySettings.keys().next().value));
104
+ }
105
+ return (fileName, languageVersionOrOptions, onError, shouldCreate) => {
106
+ // How the file parses: its language version and, from TypeScript 5.0,
107
+ // its module format and JSDoc parsing (the module detection the options
108
+ // give is in `settings`).
109
+ const parse =
110
+ languageVersionOrOptions != null &&
111
+ typeof languageVersionOrOptions === 'object'
112
+ ? [
113
+ languageVersionOrOptions.languageVersion,
114
+ languageVersionOrOptions.impliedNodeFormat,
115
+ languageVersionOrOptions.jsDocParsingMode,
116
+ ]
117
+ : [languageVersionOrOptions];
118
+ const key = `${path.resolve(fileName)}\0${JSON.stringify(parse)}`;
119
+ const stamp = fileStamp(fileName);
120
+ const seen = byFile.get(key);
121
+ if (seen != null && stamp !== '-' && seen.stamp === stamp) {
122
+ recordContentRead(fileName);
123
+ return seen.sourceFile;
124
+ }
125
+ const sourceFile = getSourceFile(
126
+ fileName,
127
+ languageVersionOrOptions,
128
+ onError,
129
+ shouldCreate,
130
+ );
131
+ byFile.delete(key);
132
+ if (sourceFile != null && stamp !== '-') {
133
+ byFile.set(key, {stamp, sourceFile});
134
+ if (byFile.size > MAX_FILES) {
135
+ byFile.delete(/** @type {string} */ (byFile.keys().next().value));
136
+ }
137
+ }
138
+ return sourceFile;
139
+ };
140
+ }
@@ -9,6 +9,11 @@
9
9
  * @returns {T}
10
10
  */
11
11
  export function withListingCache<T>(fn: () => T): T;
12
+ /**
13
+ * Whether an operation's listing cache is active.
14
+ * @returns {boolean}
15
+ */
16
+ export function listingCacheActive(): boolean;
12
17
  /**
13
18
  * `fs.readdirSync(dir)`, read once per operation. Returns a fresh array, so a
14
19
  * caller that sorts it cannot reorder another caller's listing.
@@ -22,6 +27,15 @@ export function listDir(dir: string): string[];
22
27
  * @returns {fs.Dirent[]}
23
28
  */
24
29
  export function listDirEntries(dir: string): fs.Dirent[];
30
+ /**
31
+ * The entry named exactly `name` in `dir`'s listing, or null when the folder
32
+ * holds no such name or cannot be read. Inside an operation, a name the
33
+ * listing lacks costs no probe of the disk.
34
+ * @param {string} dir
35
+ * @param {string} name
36
+ * @returns {fs.Dirent | null}
37
+ */
38
+ export function findEntry(dir: string, name: string): fs.Dirent | null;
25
39
  /**
26
40
  * `fs.existsSync(target)`, probed once per operation.
27
41
  * @param {string} target
@@ -31,6 +45,7 @@ export function pathExists(target: string): boolean;
31
45
  export type ListingCache = {
32
46
  names: Map<string, string[]>;
33
47
  entries: Map<string, fs.Dirent[]>;
48
+ byName: Map<string, Map<string, fs.Dirent>>;
34
49
  exists: Map<string, boolean>;
35
50
  };
36
51
  import * as fs from 'node:fs';
@@ -23,6 +23,7 @@ import * as fs from 'node:fs';
23
23
  * @typedef {{
24
24
  * names: Map<string, string[]>,
25
25
  * entries: Map<string, fs.Dirent[]>,
26
+ * byName: Map<string, Map<string, fs.Dirent>>,
26
27
  * exists: Map<string, boolean>,
27
28
  * }} ListingCache
28
29
  */
@@ -40,11 +41,24 @@ const scope = new AsyncLocalStorage();
40
41
  export function withListingCache(fn) {
41
42
  if (scope.getStore()) return fn();
42
43
  return scope.run(
43
- {names: new Map(), entries: new Map(), exists: new Map()},
44
+ {
45
+ names: new Map(),
46
+ entries: new Map(),
47
+ byName: new Map(),
48
+ exists: new Map(),
49
+ },
44
50
  fn,
45
51
  );
46
52
  }
47
53
 
54
+ /**
55
+ * Whether an operation's listing cache is active.
56
+ * @returns {boolean}
57
+ */
58
+ export function listingCacheActive() {
59
+ return scope.getStore() != null;
60
+ }
61
+
48
62
  /**
49
63
  * `fs.readdirSync(dir)`, read once per operation. Returns a fresh array, so a
50
64
  * caller that sorts it cannot reorder another caller's listing.
@@ -78,6 +92,41 @@ export function listDirEntries(dir) {
78
92
  return entries.slice();
79
93
  }
80
94
 
95
+ /**
96
+ * The entry named exactly `name` in `dir`'s listing, or null when the folder
97
+ * holds no such name or cannot be read. Inside an operation, a name the
98
+ * listing lacks costs no probe of the disk.
99
+ * @param {string} dir
100
+ * @param {string} name
101
+ * @returns {fs.Dirent | null}
102
+ */
103
+ export function findEntry(dir, name) {
104
+ const cache = scope.getStore();
105
+ if (!cache) {
106
+ try {
107
+ return (
108
+ fs
109
+ .readdirSync(dir, {withFileTypes: true})
110
+ .find(entry => entry.name === name) ?? null
111
+ );
112
+ } catch {
113
+ return null;
114
+ }
115
+ }
116
+ let byName = cache.byName.get(dir);
117
+ if (!byName) {
118
+ let entries;
119
+ try {
120
+ entries = listDirEntries(dir);
121
+ } catch {
122
+ return null;
123
+ }
124
+ byName = new Map(entries.map(entry => [entry.name, entry]));
125
+ cache.byName.set(dir, byName);
126
+ }
127
+ return byName.get(name) ?? null;
128
+ }
129
+
81
130
  /**
82
131
  * `fs.existsSync(target)`, probed once per operation.
83
132
  * @param {string} target
@@ -13,7 +13,12 @@ import {createRequire} from 'node:module';
13
13
  import * as os from 'node:os';
14
14
  import * as path from 'node:path';
15
15
  import {fileURLToPath} from 'node:url';
16
- import {listDir, pathExists} from './listing-cache.mjs';
16
+ import {
17
+ findEntry,
18
+ listDir,
19
+ listingCacheActive,
20
+ pathExists,
21
+ } from './listing-cache.mjs';
17
22
  import {ERROR_CODES} from '../response/error-codes.mjs';
18
23
  import {carriedCore, runChoice} from '../release/run-context.mjs';
19
24
  import {findDeclaringPackage} from '../release/project.mjs';
@@ -867,6 +872,31 @@ export function listComponents(coreDir) {
867
872
  .sort();
868
873
  }
869
874
 
875
+ /**
876
+ * `path.relative(root, target)`, read straight off the string when `target`
877
+ * is a plain path under `root`. A resolver probes tens of thousands of such
878
+ * paths, and `path.relative` normalizes both on every call.
879
+ * @param {string} root
880
+ * @param {string} target
881
+ * @returns {string}
882
+ */
883
+ function relativeInside(root, target) {
884
+ const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
885
+ if (path.isAbsolute(root) && target.startsWith(prefix)) {
886
+ const rest = target.slice(prefix.length);
887
+ const plain =
888
+ rest !== '' &&
889
+ !(path.sep === '\\' && rest.includes('/')) &&
890
+ rest
891
+ .split(path.sep)
892
+ .every(
893
+ segment => segment !== '' && segment !== '.' && segment !== '..',
894
+ );
895
+ if (plain) return rest;
896
+ }
897
+ return path.relative(root, target);
898
+ }
899
+
870
900
  /**
871
901
  * Does `targetPath` exist with EXACTLY this spelling?
872
902
  *
@@ -883,13 +913,28 @@ export function listComponents(coreDir) {
883
913
  * @returns {boolean}
884
914
  */
885
915
  export function existsCaseExact(targetPath, rootDir) {
886
- if (!pathExists(targetPath)) return false;
887
-
888
- const rel = path.relative(rootDir, targetPath);
889
- if (rel === '') return true;
916
+ const rel = relativeInside(rootDir, targetPath);
917
+ if (rel === '') return pathExists(targetPath);
890
918
  if (path.isAbsolute(rel) || rel === '..' || rel.startsWith(`..${path.sep}`))
891
919
  return false;
892
920
 
921
+ if (listingCacheActive()) {
922
+ // Inside an operation the folders' listings answer, so a name that a
923
+ // listing lacks costs no probe of the disk. A symbolic link still needs
924
+ // its target.
925
+ let folder = rootDir;
926
+ let entry = null;
927
+ for (const segment of rel.split(path.sep)) {
928
+ entry = findEntry(folder, segment);
929
+ if (!entry) return false;
930
+ folder = folder.endsWith(path.sep)
931
+ ? `${folder}${segment}`
932
+ : `${folder}${path.sep}${segment}`;
933
+ }
934
+ return !entry?.isSymbolicLink() || pathExists(targetPath);
935
+ }
936
+
937
+ if (!pathExists(targetPath)) return false;
893
938
  let dir = rootDir;
894
939
  for (const segment of rel.split(path.sep)) {
895
940
  let entries;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.7.7-canary.95438ff",
3
+ "version": "0.7.7-canary.97191cf",
4
4
  "displayName": "CLI",
5
5
  "description": "Scaffold projects, browse templates, generate themes, and get agent-ready docs from the command line.",
6
6
  "author": "Meta Open Source",
@@ -124,10 +124,10 @@
124
124
  "zod": "^4.4.3"
125
125
  },
126
126
  "peerDependencies": {
127
- "@astryxdesign/charts": "0.7.7-canary.95438ff",
128
- "@astryxdesign/core": "0.7.7-canary.95438ff",
129
- "@astryxdesign/lab": "0.7.7-canary.95438ff",
130
- "@astryxdesign/theme-neutral": "0.7.7-canary.95438ff"
127
+ "@astryxdesign/charts": "0.7.7-canary.97191cf",
128
+ "@astryxdesign/core": "0.7.7-canary.97191cf",
129
+ "@astryxdesign/lab": "0.7.7-canary.97191cf",
130
+ "@astryxdesign/theme-neutral": "0.7.7-canary.97191cf"
131
131
  },
132
132
  "peerDependenciesMeta": {
133
133
  "@astryxdesign/charts": {
@@ -144,10 +144,10 @@
144
144
  }
145
145
  },
146
146
  "devDependencies": {
147
- "@astryxdesign/charts": "0.7.7-canary.95438ff",
148
- "@astryxdesign/core": "0.7.7-canary.95438ff",
149
- "@astryxdesign/lab": "0.7.7-canary.95438ff",
150
- "@astryxdesign/theme-neutral": "0.7.7-canary.95438ff",
147
+ "@astryxdesign/charts": "0.7.7-canary.97191cf",
148
+ "@astryxdesign/core": "0.7.7-canary.97191cf",
149
+ "@astryxdesign/lab": "0.7.7-canary.97191cf",
150
+ "@astryxdesign/theme-neutral": "0.7.7-canary.97191cf",
151
151
  "@heroicons/react": "^2.2.0",
152
152
  "@stylexjs/stylex": "^0.19.0",
153
153
  "@types/babel__core": "^7.20.5",