An open source design system that's fully customizable and agent ready
TypeScript
perf(cli): list each folder once per read, and reuse it while unchanged (#10274)
Christopher Chedeau23081b9977f5
diff --git a/.changeset/cli-listings-kept-per-process.md b/.changeset/cli-listings-kept-per-process.mdnew file mode 100644index 0000000000..463da1271e--- /dev/null+++ b/.changeset/cli-listings-kept-per-process.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[perf] A search, build or component read lists each folder once. A process that runs several reads, such as a docs site's search or an agent harness, reuses a folder's listing once the folder has stayed unchanged for two seconds. A later read lists the folder again after an entry is added, removed or renamed.++@vjeuxdiff --git a/packages/cli/api/search/_gather-components.mjs b/packages/cli/api/search/_gather-components.mjsindex 6424cb3961..d49fdc6d93 100644--- a/packages/cli/api/search/_gather-components.mjs+++ b/packages/cli/api/search/_gather-components.mjs@@ -8,6 +8,7 @@import fs from 'node:fs';import path from 'node:path';import {discoverExternalPackages} from '../../foundation/fs/paths.mjs';+import {listDir} from '../../foundation/fs/listing-cache.mjs';import {discoverComponents,discoverValidIntegrationComponents,@@ -103,7 +104,7 @@ async function gatherCoreComponents(coreDir) {// A family doc with no component of its own name (Chat) names members too.const srcDir = path.join(coreDir, 'src');const listed = new Set(names);- for (const dir of fs.existsSync(srcDir) ? fs.readdirSync(srcDir) : []) {+ for (const dir of fs.existsSync(srcDir) ? listDir(srcDir) : []) {const doc = path.join(srcDir, dir, `${dir}.doc.mjs`);if (listed.has(dir) || !fs.existsSync(doc)) continue;for (const [n, place] of familyPlaces(await loadModuleDoc(doc)))diff --git a/packages/cli/foundation/discovery/authoring-self-docs.mjs b/packages/cli/foundation/discovery/authoring-self-docs.mjsindex 203919e43f..cc06332469 100644--- a/packages/cli/foundation/discovery/authoring-self-docs.mjs+++ b/packages/cli/foundation/discovery/authoring-self-docs.mjs@@ -15,9 +15,9 @@* the self-doc tests fail.*/-import * as fs from 'node:fs';import * as path from 'node:path';import {CLI_ROOT} from '../fs/paths.mjs';+import {listDirEntries} from '../fs/listing-cache.mjs';import {readDocView} from '../doc-compiler/read.mjs';import {DOC_OUTPUT_BUDGET_BYTES,@@ -75,7 +75,7 @@ export function discoverAuthoringSelfDocSources(root = AUTHORING_ROOT) {const found = [];/** @param {string} dir */const walk = dir => {- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ for (const entry of listDirEntries(dir)) {if (entry.name === 'node_modules' || entry.name.startsWith('__'))continue;const full = path.join(dir, entry.name);diff --git a/packages/cli/foundation/discovery/cli-self-docs.mjs b/packages/cli/foundation/discovery/cli-self-docs.mjsindex 523d6f8454..ccf26ba795 100644--- a/packages/cli/foundation/discovery/cli-self-docs.mjs+++ b/packages/cli/foundation/discovery/cli-self-docs.mjs@@ -18,6 +18,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {CLI_ROOT} from '../fs/paths.mjs';+import {listDirEntries} from '../fs/listing-cache.mjs';import {readDocView} from '../doc-compiler/read.mjs';import {AUTHORING_SELF_DOCS, selfDocSection} from './authoring-self-docs.mjs';import {@@ -66,7 +67,7 @@ export function discoverCliSelfDocSources(root = CLI_ROOT) {/** @param {string} dir */const walk = dir => {if (!fs.existsSync(dir)) return;- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ for (const entry of listDirEntries(dir)) {if (entry.name === 'node_modules' ||entry.name.startsWith('__') ||diff --git a/packages/cli/foundation/discovery/docs-discovery.mjs b/packages/cli/foundation/discovery/docs-discovery.mjsindex 10ee1f90e5..e6667f5d56 100644--- a/packages/cli/foundation/discovery/docs-discovery.mjs+++ b/packages/cli/foundation/discovery/docs-discovery.mjs@@ -32,6 +32,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {CLI_ROOT} from '../fs/paths.mjs';+import {listDir, listDirEntries} from '../fs/listing-cache.mjs';import {importDocModule} from '../doc-compiler/import.mjs';import {CLI_PROVIDER_ID} from '../identity/providers.mjs';import {parseReadableDoc} from '../doc-compiler/parse-readable.mjs';@@ -135,7 +136,7 @@ export function discoverBuiltinTopics() {/** @type {Record<string, string>} */const topics = Object.create(null);if (!fs.existsSync(BUILTIN_DOCS_DIR)) return topics;- for (const file of fs.readdirSync(BUILTIN_DOCS_DIR)) {+ for (const file of listDir(BUILTIN_DOCS_DIR)) {const match = file.match(BUILTIN_TOPIC_FILE_RE);if (match) topics[match[1]] = path.join(BUILTIN_DOCS_DIR, file);}@@ -152,7 +153,7 @@ export function builtinGuideFiles() {const files = Object.values(discoverBuiltinTopics());const tree = path.join(BUILTIN_DOCS_DIR, 'tree');if (fs.existsSync(tree)) {- for (const file of fs.readdirSync(tree).sort()) {+ for (const file of listDir(tree).sort()) {if (BUILTIN_TOPIC_FILE_RE.test(file)) files.push(path.join(tree, file));}}@@ -524,7 +525,7 @@ export async function discoverIntegrationDocs(integration) {const files = [];/** @param {string} dirPath */function scanDir(dirPath) {- for (const entry of fs.readdirSync(dirPath, {withFileTypes: true})) {+ for (const entry of listDirEntries(dirPath)) {if (entry.name === 'node_modules' || entry.name === '__tests__') continue;const full = path.join(dirPath, entry.name);if (entry.isDirectory()) {@@ -737,7 +738,8 @@ export function mergeTopicReport(base, overlay) {// It also keeps the place an earlier `after` gave the one it replaces,// so sections placed after that key later still follow it.if (replaced[PLACED_AFTER] != null) {- const placed = replacing === section ? withoutPosition({...section}) : replacing;+ const placed =+ replacing === section ? withoutPosition({...section}) : replacing;for (const symbol of Object.getOwnPropertySymbols(section)) {if (!(symbol in placed)) {Object.defineProperty(diff --git a/packages/cli/foundation/discovery/icon-definition-discovery.mjs b/packages/cli/foundation/discovery/icon-definition-discovery.mjsindex e6d3eb26e4..7381d93138 100644--- a/packages/cli/foundation/discovery/icon-definition-discovery.mjs+++ b/packages/cli/foundation/discovery/icon-definition-discovery.mjs@@ -15,10 +15,10 @@* surface reads*/-import * as fs from 'node:fs';import * as path from 'node:path';import {parseIconDefinition} from '../../authoring/doctypes/icon-definition/parse.mjs';import {CLI_ROOT} from '../fs/paths.mjs';+import {listDirEntries} from '../fs/listing-cache.mjs';import {readStaticDescriptorValue} from './theme-discovery.mjs';/** @typedef {import('../../authoring/doctypes/icon-definition/type').IconDefinitionDoc} IconDefinitionDoc */@@ -53,10 +53,10 @@ export function readDefinitionsDir(dir, owner) {const definitions = [];/** @type {Array<{file: string, message: string}>} */const errors = [];- /** @type {fs.Dirent[]} */+ /** @type {import('node:fs').Dirent[]} */let entries;try {- entries = fs.readdirSync(dir, {withFileTypes: true});+ entries = listDirEntries(dir);} catch {return {definitions, errors};}diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex 05a55dd691..9a536f5204 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -28,6 +28,7 @@ import {createRequire} from 'node:module';import {readDocView} from '../doc-compiler/read.mjs';import {importDocModule} from '../doc-compiler/import.mjs';import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';+import {listDirEntries} from '../fs/listing-cache.mjs';import {CORE_PROVIDER_ID} from '../identity/providers.mjs';import {Project} from '../config/project.mjs';import {@@ -1115,8 +1116,7 @@ export function listTemplates() {const all = [];if (fs.existsSync(PAGES_DIR)) {all.push(- ...fs- .readdirSync(PAGES_DIR, {withFileTypes: true})+ ...listDirEntries(PAGES_DIR).filter(e => e.isDirectory()).map(e => e.name),);@@ -1133,7 +1133,7 @@ function findDocFiles(dir, pattern) {/** @type {string[]} */const results = [];if (!fs.existsSync(dir)) return results;- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ for (const entry of listDirEntries(dir)) {const full = path.join(dir, entry.name);if (entry.isDirectory()) {results.push(...findDocFiles(full, pattern));@@ -1160,9 +1160,7 @@ export function findPageDocFile(dirPath) {async function discoverPages() {if (!fs.existsSync(PAGES_DIR)) return [];- const dirs = fs- .readdirSync(PAGES_DIR, {withFileTypes: true})- .filter(e => e.isDirectory());+ const dirs = listDirEntries(PAGES_DIR).filter(e => e.isDirectory());/** @type {DiscoveredTemplate[]} */const templates = [];@@ -1602,7 +1600,7 @@ function findIntegrationDocFiles(root) {if (!fs.existsSync(root)) return results;/** @param {string} dir */const walk = dir => {- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ for (const entry of listDirEntries(dir)) {const full = path.join(dir, entry.name);if (entry.isDirectory()) {walk(full);diff --git a/packages/cli/foundation/discovery/theme-discovery.mjs b/packages/cli/foundation/discovery/theme-discovery.mjsindex e12118d763..fd69646844 100644--- a/packages/cli/foundation/discovery/theme-discovery.mjs+++ b/packages/cli/foundation/discovery/theme-discovery.mjs@@ -22,6 +22,7 @@ import * as path from 'node:path';import {lowerDoc} from '../doc-compiler/compile.mjs';import {packageSource} from '../doc-compiler/source.mjs';import {CLI_ROOT} from '../fs/paths.mjs';+import {listDirEntries} from '../fs/listing-cache.mjs';import {formatCliCommand} from '../env/package-manager.mjs';import {LOCAL_THEME_ROOT} from '../config/theme-state.mjs';import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';@@ -1187,7 +1188,7 @@ function listThemeFolder(folder) {const symlinks = [];/** @param {string} directory */function walk(directory) {- for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {+ for (const entry of listDirEntries(directory)) {if (isIgnoredThemeEntry(entry.name)) continue;const full = path.join(directory, entry.name);const relative = path.relative(folder, full).split(path.sep).join('/');@@ -1291,8 +1292,7 @@ export function discoverUnmigratedThemeCopies() {const root = path.resolve(projectDir, owner);if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];- return fs- .readdirSync(root, {withFileTypes: true})+ return listDirEntries(root).filter(entry => entry.isDirectory() && !isIgnoredThemeEntry(entry.name)).map(entry => unmigratedThemeCopy(path.join(root, entry.name))).filter(copy => copy !== null)@@ -1369,9 +1369,9 @@ export function discoverThemeDirectory(/** @type {DiscoveredTheme[]} */const themes = [];const slugs = new Set();- const rootEntries = fs- .readdirSync(themeRoot, {withFileTypes: true})- .filter(entry => !isIgnoredThemeEntry(entry.name));+ const rootEntries = listDirEntries(themeRoot).filter(+ entry => !isIgnoredThemeEntry(entry.name),+ );const rootDescriptor = rootEntries.find(entry => entry.isFile() && entry.name.endsWith(THEME_DOC_SUFFIX),);@@ -1614,8 +1614,7 @@ export function unreadThemeFolders(themeRoot, {packageDir, packageName} = {}) {if (!fs.existsSync(themeRoot) || !fs.statSync(themeRoot).isDirectory()) {return [];}- const folders = fs- .readdirSync(themeRoot, {withFileTypes: true})+ const folders = listDirEntries(themeRoot).filter(entry => entry.isDirectory() && !isIgnoredThemeEntry(entry.name)).map(entry => path.join(themeRoot, entry.name)).sort();@@ -1630,8 +1629,7 @@ export function unreadThemeFolders(themeRoot, {packageDir, packageName} = {}) {if (unread.length === 0) return [];const modules = [- ...fs- .readdirSync(themeRoot, {withFileTypes: true})+ ...listDirEntries(themeRoot).filter(entry =>entry.isFile() &&diff --git a/packages/cli/foundation/doc-compiler/tree.mjs b/packages/cli/foundation/doc-compiler/tree.mjsindex d00d2d0d6f..404585d33b 100644--- a/packages/cli/foundation/doc-compiler/tree.mjs+++ b/packages/cli/foundation/doc-compiler/tree.mjs@@ -20,6 +20,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {CLI_ROOT} from '../fs/paths.mjs';+import {listDir} from '../fs/listing-cache.mjs';import {loadCliSelfDocs} from '../discovery/cli-self-docs.mjs';import {astryxIconDefinitions} from '../discovery/icon-definition-discovery.mjs';import {routeSegment} from '../discovery/docs-section-key.mjs';@@ -812,8 +813,7 @@ function adoptionsFor(doc, declared, routeOf) {*/export function treeDocFiles(dir = TREE_DOCS_DIR) {if (!fs.existsSync(dir)) return [];- return fs- .readdirSync(dir)+ return listDir(dir).filter(file => /^[\w-]+\.doc\.mjs$/u.test(file)).sort(byText).map(file => path.join(dir, file));diff --git a/packages/cli/foundation/fs/listing-cache.coarse-times.test.mjs b/packages/cli/foundation/fs/listing-cache.coarse-times.test.mjsnew file mode 100644index 0000000000..651507928e--- /dev/null+++ b/packages/cli/foundation/fs/listing-cache.coarse-times.test.mjs@@ -0,0 +1,103 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Covers the listing cache on a file system that stores times+ * coarsely. There, a change within one tick of the last leaves the folder's+ * stamp as it was. A later operation still lists the folder as it is.+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {performance} from 'node:perf_hooks';+import {listDir, withListingCache} from './listing-cache.mjs';+import {recordReads, unchangedSince} from './read-record.mjs';++/**+ * The stamp each folder reports, by path, in place of its real one, and work+ * to do once right after the next stamp is taken.+ */+const {stamps, afterStamp} = vi.hoisted(() => ({+ stamps: /** @type {Map<string, string>} */ (new Map()),+ afterStamp: /** @type {{run: (() => void) | null}} */ ({run: null}),+}));++vi.mock('./read-record.mjs', async importOriginal => {+ const actual = /** @type {typeof import('./read-record.mjs')} */ (+ await importOriginal()+ );+ return {+ ...actual,+ /** @param {string} file */+ fileStamp: file => {+ const stamp = stamps.get(file) ?? actual.fileStamp(file);+ const run = afterStamp.run;+ afterStamp.run = null;+ run?.();+ return stamp;+ },+ };+});++/** @type {string} */+let dir;+let passed = 0;++beforeEach(() => {+ passed = 0;+ const now = performance.now.bind(performance);+ vi.spyOn(performance, 'now').mockImplementation(() => now() + passed);+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-listing-coarse-'));+ fs.writeFileSync(path.join(dir, 'a.txt'), '');+ fs.writeFileSync(path.join(dir, 'b.txt'), '');+});++afterEach(() => {+ vi.restoreAllMocks();+ stamps.clear();+ afterStamp.run = null;+ fs.rmSync(dir, {recursive: true, force: true});+});++describe('listing cache with coarse folder times', () => {+ it('lists a change made in the same tick as the last one', () => {+ // Every change in this tick leaves the folder's stamp as it is.+ stamps.set(path.resolve(dir), 'tick 0');+ const names = () => withListingCache(() => listDir(dir).sort());+ expect(names()).toEqual(['a.txt', 'b.txt']);+ fs.writeFileSync(path.join(dir, 'c.txt'), '');+ passed += 1000;+ expect(names()).toEqual(['a.txt', 'b.txt', 'c.txt']);+ fs.rmSync(path.join(dir, 'a.txt'));+ passed += 1500;+ // The stamp has held for 2.5 s: this read is kept, with the remove in it.+ expect(names()).toEqual(['b.txt', 'c.txt']);+ expect(names()).toEqual(['b.txt', 'c.txt']);+ // A change after that falls in a later tick, so the stamp changes.+ fs.writeFileSync(path.join(dir, 'd.txt'), '');+ stamps.set(path.resolve(dir), 'tick 1');+ expect(names()).toEqual(['b.txt', 'c.txt', 'd.txt']);+ });+ it('lets a reuse check see a change made right after the stamp of a kept listing', () => {+ stamps.set(path.resolve(dir), 'tick 0');+ withListingCache(() => listDir(dir));+ passed += 2500;+ withListingCache(() => listDir(dir));+ // The next read reuses the kept listing; the folder changes right after+ // its stamp is taken.+ afterStamp.run = () => {+ fs.writeFileSync(path.join(dir, 'c.txt'), '');+ // The real times may tick coarsely: set them after any they had.+ const later = new Date(Date.now() + 5_000);+ fs.utimesSync(dir, later, later);+ };+ /** @type {Map<string, string>} */+ const seen = new Map();+ const names = recordReads(seen, () =>+ withListingCache(() => listDir(dir).sort()),+ );+ expect(names).toEqual(['a.txt', 'b.txt']);+ expect(unchangedSince(seen)).toBe(false);+ });+});diff --git a/packages/cli/foundation/fs/listing-cache.mjs b/packages/cli/foundation/fs/listing-cache.mjsindex be7845cd36..0fe22d66e2 100644--- a/packages/cli/foundation/fs/listing-cache.mjs+++ b/packages/cli/foundation/fs/listing-cache.mjs@@ -2,23 +2,27 @@/*** @file One directory listing per path for the duration of one read-only- * operation.+ * operation, kept for later operations while the folder is unchanged.** @input A read-only operation (`withListingCache(fn)`), and directory paths* its discovery helpers list or probe.* @output The same answers `fs.readdirSync` / `fs.existsSync` give, read from* disk once per path while the operation runs, and `oncePerListing`, a- * value computed once per operation.- * @position Used by the name resolvers in foundation/discovery and by- * `existsCaseExact`. A search or build resolves ~160 components and their- * hooks, and each resolution walks the same source tree again; inside one- * operation the tree does not change, so each directory is read once.- * Outside `withListingCache` every helper reads the disk directly, exactly- * as before, so long-lived callers never see a stale listing.+ * value computed once per operation. A later operation in the same process+ * reuses a listing while its folder's stamp is unchanged.+ * @position Used by the name resolvers and doc walkers in+ * foundation/discovery and by `existsCaseExact`. A search or build resolves+ * ~160 components and their hooks, and each resolution walks the same+ * source tree again. Inside one operation the tree does not change, so each+ * directory is read once. Outside `withListingCache` every helper reads the+ * disk directly, exactly as before.*/import {AsyncLocalStorage} from 'node:async_hooks';import * as fs from 'node:fs';+import * as path from 'node:path';+import {performance} from 'node:perf_hooks';+import {fileStamp, recordContentRead} from './read-record.mjs';/*** @typedef {{@@ -33,6 +37,24 @@ import * as fs from 'node:fs';/** @type {AsyncLocalStorage<ListingCache>} */const scope = new AsyncLocalStorage();+/**+ * Listings kept for later operations in this process, by folder. Each holds+ * the folder's stamp (`fileStamp`: size, times and inode) and when this+ * process first saw it. Once the stamp has held for {@link SETTLE_MS}, it+ * holds the entries too. Adding, removing or renaming an entry changes the+ * stamp.+ * @type {Map<string, {stamp: string, since: number, entries: fs.Dirent[] | null}>}+ */+const kept = new Map();++/**+ * How long a folder's stamp must hold, by this process's clock, before its+ * listing is kept. A file system can store times as coarsely as 2 s. So a+ * change within one tick of the last can leave the stamp as it was. After the+ * stamp has held this long, a new change falls in a later tick.+ */+const SETTLE_MS = 2000;+/*** Run `fn` with a listing cache. A nested call shares the outer cache. Only* wrap operations that do not change the files they list.@@ -79,7 +101,9 @@ export function listingCacheActive() {/*** `fs.readdirSync(dir)`, read once per operation. Returns a fresh array, so a- * caller that sorts it cannot reorder another caller's listing.+ * caller that sorts it cannot reorder another caller's listing. The names come+ * from the same read as {@link listDirEntries}, so a folder listed both ways+ * is read once.* @param {string} dir* @returns {string[]}*/@@ -88,7 +112,7 @@ export function listDir(dir) {if (!cache) return fs.readdirSync(dir);let names = cache.names.get(dir);if (!names) {- names = fs.readdirSync(dir);+ names = listDirEntries(dir).map(entry => entry.name);cache.names.set(dir, names);}return names.slice();@@ -104,12 +128,40 @@ export function listDirEntries(dir) {if (!cache) return fs.readdirSync(dir, {withFileTypes: true});let entries = cache.entries.get(dir);if (!entries) {- entries = fs.readdirSync(dir, {withFileTypes: true});+ entries = keptOrRead(dir);cache.entries.set(dir, entries);}return entries.slice();}+/**+ * `dir`'s entries for an operation. They are the kept listing while the+ * folder's stamp is the one it was kept with. Otherwise they are a new read,+ * kept once the stamp has held for {@link SETTLE_MS}.+ * @param {string} dir+ * @returns {fs.Dirent[]}+ */+function keptOrRead(dir) {+ const folder = path.resolve(dir);+ // A reuse check (read-record.mjs) records the folder's state before the+ // stamp below is taken. So a change between the two shows as a change.+ recordContentRead(folder);+ const before = performance.now();+ const stamp = fileStamp(folder);+ const held = kept.get(folder);+ if (held?.entries && held.stamp === stamp) return held.entries;+ const entries = fs.readdirSync(dir, {withFileTypes: true});+ if (held?.stamp !== stamp) {+ // Taken after the stamp, so the stamp's times are no later than this.+ kept.set(folder, {stamp, since: performance.now(), entries: null});+ } else if (before - held.since >= SETTLE_MS) {+ // Read after the stamp held for the settle time: a later change gets a+ // new stamp.+ kept.set(folder, {stamp, since: held.since, entries});+ }+ return entries;+}+/*** The entry named exactly `name` in `dir`'s listing, or null when the folder* holds no such name or cannot be read. Inside an operation, a name thediff --git a/packages/cli/foundation/fs/listing-cache.test.mjs b/packages/cli/foundation/fs/listing-cache.test.mjsindex 3ff1d6ec48..f0698a6781 100644--- a/packages/cli/foundation/fs/listing-cache.test.mjs+++ b/packages/cli/foundation/fs/listing-cache.test.mjs@@ -1,9 +1,13 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import * as fs from 'node:fs';+import {createRequire, syncBuiltinESMExports} from 'node:module';import * as os from 'node:os';import * as path from 'node:path';+import {performance} from 'node:perf_hooks';+import {discoverHooks} from '../discovery/hook-discovery.mjs';+import {fileStamp, recordReads, unchangedSince} from './read-record.mjs';import {findEntry,listDir,@@ -17,13 +21,69 @@ import {existsCaseExact} from './paths.mjs';let dir;+/** node:fs's module object, whose functions every import of it shares. */+const nodeFs = createRequire(import.meta.url)('node:fs');++/**+ * Runs `fn` and counts the reads of `folder`'s listing it makes.+ * @param {string} folder+ * @param {() => void} fn+ * @returns {number}+ */+function countListings(folder, fn) {+ const original = nodeFs.readdirSync;+ let count = 0;+ nodeFs.readdirSync = function (target, ...rest) {+ if (path.resolve(String(target)) === path.resolve(folder)) count += 1;+ return original.call(this, target, ...rest);+ };+ syncBuiltinESMExports();+ try {+ fn();+ } finally {+ nodeFs.readdirSync = original;+ syncBuiltinESMExports();+ }+ return count;+}++/** How far `pass` has moved the clock the listing cache reads, in ms. */+let passed = 0;++/**+ * Moves the clock the listing cache reads (`performance.now`) on by `ms`.+ * @param {number} ms+ */+function pass(ms) {+ passed += ms;+}++/** How many times `touchLater` has run, so each run sets new times. */+let touches = 0;++/**+ * Sets `folder`'s times after any it had. A change made just after an+ * earlier one can keep the folder's times where they tick coarsely. The+ * moved clock does not move them.+ * @param {string} folder+ */+function touchLater(folder) {+ touches += 1;+ const later = new Date(Date.now() + 5_000 + touches * 1_000);+ fs.utimesSync(folder, later, later);+}+beforeEach(() => {+ passed = 0;+ const now = performance.now.bind(performance);+ vi.spyOn(performance, 'now').mockImplementation(() => now() + passed);dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-listing-cache-'));fs.writeFileSync(path.join(dir, 'b.txt'), '');fs.writeFileSync(path.join(dir, 'a.txt'), '');});afterEach(() => {+ vi.restoreAllMocks();fs.rmSync(dir, {recursive: true, force: true});});@@ -43,11 +103,12 @@ describe('listing cache', () => {await new Promise(resolve => setTimeout(resolve, 0));expect(listDir(dir).sort()).toEqual(['a.txt', 'b.txt']);expect(pathExists(path.join(dir, 'c.txt'))).toBe(false);+ // The names and the entries come from the same read.expect(listDirEntries(dir).map(entry => entry.name).sort(),- ).toEqual(['a.txt', 'b.txt', 'c.txt']);+ ).toEqual(['a.txt', 'b.txt']);});// The operation's snapshot does not outlive it.expect(listDir(dir).sort()).toEqual(['a.txt', 'b.txt', 'c.txt']);@@ -170,4 +231,92 @@ describe('listing cache', () => {).toBe(true);});});+ it("keeps a folder's listing once its stamp has held for the settle time, until the folder changes", () => {+ const names = () => withListingCache(() => listDir(dir).sort());+ const first = countListings(dir, () =>+ expect(names()).toEqual(['a.txt', 'b.txt']),+ );+ expect(first).toBe(1);+ // The stamp has held for 1 s: the next operation reads the folder again.+ pass(1000);+ expect(countListings(dir, names)).toBe(1);+ // It has held for 2.5 s: this read is kept, and the next one uses it.+ pass(1500);+ expect(countListings(dir, names)).toBe(1);+ const kept = countListings(dir, () =>+ expect(names()).toEqual(['a.txt', 'b.txt']),+ );+ expect(kept).toBe(0);+ fs.writeFileSync(path.join(dir, 'c.txt'), '');+ touchLater(dir);+ const changed = countListings(dir, () =>+ expect(names()).toEqual(['a.txt', 'b.txt', 'c.txt']),+ );+ expect(changed).toBe(1);+ // The new stamp starts its own settle time.+ expect(countListings(dir, names)).toBe(1);+ });++ it('shows each later operation the docs added, removed and renamed in a folder, within the settle time and after it', () => {+ const core = path.join(dir, 'core');+ const hooks = path.join(core, 'src', 'hooks');+ const box = path.join(core, 'src', 'Box');+ fs.mkdirSync(hooks, {recursive: true});+ fs.mkdirSync(box);+ fs.writeFileSync(path.join(hooks, 'useAlpha.doc.mjs'), '');+ fs.writeFileSync(path.join(hooks, 'useBeta.doc.mjs'), '');+ fs.writeFileSync(path.join(box, 'useBox.doc.mjs'), '');+ /** @param {string} name */+ const hookDoc = name => path.join(hooks, `${name}.doc.mjs`);+ const found = () =>+ withListingCache(() => Object.values(discoverHooks(core)).flat().sort());+ expect(found()).toEqual(['useAlpha', 'useBeta', 'useBox']);+ // Within the settle time: an add and a remove, then a rename.+ fs.writeFileSync(hookDoc('useGamma'), '');+ fs.rmSync(hookDoc('useAlpha'));+ expect(found()).toEqual(['useBeta', 'useBox', 'useGamma']);+ fs.renameSync(hookDoc('useBeta'), hookDoc('useDelta'));+ expect(found()).toEqual(['useBox', 'useDelta', 'useGamma']);+ // After it the listings are kept: an add, and a remove in a nested folder.+ pass(2500);+ expect(found()).toEqual(['useBox', 'useDelta', 'useGamma']);+ expect(countListings(hooks, found)).toBe(0);+ fs.writeFileSync(hookDoc('useEpsilon'), '');+ fs.rmSync(path.join(box, 'useBox.doc.mjs'));+ touchLater(hooks);+ touchLater(box);+ expect(found()).toEqual(['useDelta', 'useEpsilon', 'useGamma']);+ // A doc's new content keeps the folder's listing, and the doc is read+ // again.+ pass(2500);+ found();+ fs.writeFileSync(+ hookDoc('useGamma'),+ "export default {\n category: 'data',\n};\n",+ );+ /** @type {Record<string, string[]>} */+ let groups = {};+ const listings = countListings(hooks, () => {+ groups = withListingCache(() => discoverHooks(core));+ });+ expect(listings).toBe(0);+ expect(groups.Data).toEqual(['useGamma']);+ });++ it('counts a kept listing as read, so a reuse check sees its folder change', () => {+ withListingCache(() => listDir(dir));+ pass(2500);+ withListingCache(() => listDir(dir));+ /** @type {Map<string, string>} */+ const seen = new Map();+ const count = countListings(dir, () =>+ recordReads(seen, () => withListingCache(() => listDir(dir))),+ );+ expect(count).toBe(0);+ expect(seen.get(path.resolve(dir))).toBe(fileStamp(dir));+ expect(unchangedSince(seen)).toBe(true);+ fs.writeFileSync(path.join(dir, 'c.txt'), '');+ touchLater(dir);+ expect(unchangedSince(seen)).toBe(false);+ });});diff --git a/packages/cli/foundation/fs/paths.mjs b/packages/cli/foundation/fs/paths.mjsindex bfe2735eed..47f3fdc8fe 100644--- a/packages/cli/foundation/fs/paths.mjs+++ b/packages/cli/foundation/fs/paths.mjs@@ -16,6 +16,7 @@ import {fileURLToPath} from 'node:url';import {findEntry,listDir,+ listDirEntries,listingCacheActive,pathExists,} from './listing-cache.mjs';@@ -811,7 +812,7 @@ export function discoverExternalPackages(startDir = process.cwd()) {/** @param {string} searchDir */const scanDir = searchDir => {if (!fs.existsSync(searchDir)) return;- const entries = fs.readdirSync(searchDir, {withFileTypes: true});+ const entries = listDirEntries(searchDir);for (const entry of entries) {if (!entry.isDirectory()) continue;