Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

Hot-reload runtime catalogs during development (#6706)

nynexman446471f8be3fecd3
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 427ff6a736..c4502bd762 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -115,9 +115,10 @@ Storybook will open at http://localhost:6006 with:
- **Mode switcher** - Toggle between Light and Dark modes
- **Component stories** - Interactive component examples
-**If you make changes to `@astryxdesign/core`:** ordinary source changes update
-without a rebuild or restart. After editing `packages/core/locales/*.json`,
-restart Storybook; rebuild Core before restarting the docsite.
+**If you make changes to `@astryxdesign/core`:** source changes update without a
+rebuild or restart. Storybook and the docsite also watch
+`packages/core/locales/*.json`, regenerate the compact runtime catalogs, and
+reload imported messages after a locale edit.
### Running the Doc Site
diff --git a/apps/docsite/package.json b/apps/docsite/package.json
index 16a1e00a52..e3f7e07477 100644
--- a/apps/docsite/package.json
+++ b/apps/docsite/package.json
@@ -5,7 +5,8 @@
"scripts": {
"build:theme": "astryx theme build src/themes/astryxTheme.ts --out src/themes/astryx.css",
"generate": "node scripts/check-workspace-build.mjs && pnpm build:theme && node scripts/generate-data.mjs && node scripts/generate-scope.mjs && node scripts/generate-playground-types.mjs && node scripts/copy-vendor.mjs",
- "dev": "pnpm generate && next dev --webpack",
+ "dev": "pnpm generate && node ../../scripts/generate-i18n-runtime.mjs --watch -- pnpm --parallel --filter @astryxdesign/core --filter @astryxdesign/docsite dev:i18n",
+ "dev:i18n": "next dev --webpack",
"build": "pnpm generate && next build --webpack && node scripts/check-template-gallery-bundle.mjs",
"start": "next start",
"typecheck": "tsc --noEmit",
diff --git a/apps/storybook/package.json b/apps/storybook/package.json
index 2900f4dc1c..ececf512e6 100644
--- a/apps/storybook/package.json
+++ b/apps/storybook/package.json
@@ -3,7 +3,7 @@
"version": "0.0.1",
"private": true,
"scripts": {
- "dev": "node ../../scripts/generate-i18n-runtime.mjs && storybook dev -p 6006",
+ "dev": "node ../../scripts/generate-i18n-runtime.mjs --watch -- storybook dev -p 6006",
"build": "node ../../scripts/generate-i18n-runtime.mjs && storybook build -o dist",
"rtl-audit": "node rtl-audit/rtl-audit.mjs --storybook-dir dist --output rtl-audit-report.json",
"typecheck": "tsc --noEmit"
diff --git a/packages/core/package.json b/packages/core/package.json
index 62a6c4ead2..541d5dfb20 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -699,6 +699,7 @@
"build:esm": "babel src --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts\" --config-file ./babel.config.json",
"build:css": "node ../../scripts/build-css.mjs",
"dev": "babel src --watch --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*\" --config-file ./babel.config.json",
+ "dev:i18n": "babel src/i18n/generated-locales --watch --out-dir dist/i18n/generated-locales --extensions .ts --out-file-extension .js --config-file ./babel.config.json",
"test": "vitest run --root ../..",
"test:watch": "vitest --root ../..",
"lint": "eslint src",
diff --git a/scripts/generate-i18n-runtime.mjs b/scripts/generate-i18n-runtime.mjs
index d405a269cd..11727db963 100644
--- a/scripts/generate-i18n-runtime.mjs
+++ b/scripts/generate-i18n-runtime.mjs
@@ -9,6 +9,7 @@
* key-to-defaultMessage map used at runtime.
*/
+import {spawn} from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
@@ -135,6 +136,12 @@ function removeStaleModules(expectedFiles) {
return removed;
}
+export function isSourceLocaleFile(file) {
+ return (
+ typeof file === 'string' && file.endsWith('.json') && file !== PSEUDO_FILE
+ );
+}
+
export async function generateRuntimeCatalogs({check = false} = {}) {
const runtimeCatalogs = createRuntimeCatalogs(readSourceCatalogs());
@@ -162,8 +169,87 @@ export async function generateRuntimeCatalogs({check = false} = {}) {
);
}
+export function createSpawnInvocation(
+ command,
+ platform = process.platform,
+ commandShell = process.env.ComSpec ?? 'cmd.exe',
+) {
+ if (platform !== 'win32') {
+ return {file: command[0], args: command.slice(1)};
+ }
+ const unsafe = command.find(arg => !/^[A-Za-z0-9_@./:\\=-]+$/.test(arg));
+ if (unsafe !== undefined) {
+ throw new Error(
+ `Windows watch commands cannot contain spaces or shell metacharacters: ${unsafe}`,
+ );
+ }
+ return {
+ file: commandShell,
+ args: ['/d', '/s', '/c', command.join(' ')],
+ };
+}
+
+async function watchRuntimeCatalogs(command) {
+ let debounce;
+ let regeneration = Promise.resolve();
+ const queueGeneration = () => {
+ const next = regeneration.then(() => generateRuntimeCatalogs());
+ regeneration = next.catch(() => {});
+ return next;
+ };
+ const watcher = fs.watch(SOURCE_LOCALES_DIR, (_event, file) => {
+ const fileName = file == null ? null : String(file);
+ if (fileName !== null && !isSourceLocaleFile(fileName)) return;
+ clearTimeout(debounce);
+ debounce = setTimeout(() => {
+ void queueGeneration().catch(error => {
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(
+ `Could not regenerate runtime locale catalogs: ${message}`,
+ );
+ });
+ }, 75);
+ });
+
+ try {
+ // Register the watcher first so an edit during initial generation queues a
+ // second pass instead of leaving the child process on stale catalogs.
+ await queueGeneration();
+
+ const spawnOptions = {env: process.env, stdio: 'inherit'};
+ const invocation = createSpawnInvocation(command);
+ const child = spawn(invocation.file, invocation.args, spawnOptions);
+ const forwardInterrupt = () => child.kill('SIGINT');
+ const forwardTermination = () => child.kill('SIGTERM');
+ process.on('SIGINT', forwardInterrupt);
+ process.on('SIGTERM', forwardTermination);
+
+ try {
+ return await new Promise((resolve, reject) => {
+ child.once('error', reject);
+ child.once('exit', (code, signal) => resolve(signal ? 1 : (code ?? 1)));
+ });
+ } finally {
+ process.removeListener('SIGINT', forwardInterrupt);
+ process.removeListener('SIGTERM', forwardTermination);
+ }
+ } finally {
+ clearTimeout(debounce);
+ watcher.close();
+ }
+}
+
async function main() {
const args = process.argv.slice(2);
+ if (args.includes('--watch')) {
+ const separator = args.indexOf('--');
+ const command = separator === -1 ? [] : args.slice(separator + 1);
+ if (command.length === 0) {
+ throw new Error('`--watch` requires a command after `--`');
+ }
+ process.exitCode = await watchRuntimeCatalogs(command);
+ return;
+ }
await generateRuntimeCatalogs({check: args.includes('--check')});
}
diff --git a/scripts/generate-i18n-runtime.test.mjs b/scripts/generate-i18n-runtime.test.mjs
index 727096658f..97756420f9 100644
--- a/scripts/generate-i18n-runtime.test.mjs
+++ b/scripts/generate-i18n-runtime.test.mjs
@@ -1,6 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {spawnSync} from 'node:child_process';
+import {spawn, spawnSync} from 'node:child_process';
+import {once} from 'node:events';
import {mkdtempSync, rmSync, symlinkSync} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
@@ -9,11 +10,39 @@ import {describe, expect, it} from 'vitest';
import {
createRuntimeCatalog,
createRuntimeCatalogs,
+ createSpawnInvocation,
getGeneratedModuleName,
+ isSourceLocaleFile,
renderRuntimeCatalogModule,
} from './generate-i18n-runtime.mjs';
const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url));
+const GENERATOR = fileURLToPath(
+ new URL('./generate-i18n-runtime.mjs', import.meta.url),
+);
+
+function waitForMatch(stream, pattern, timeoutMs = 5_000) {
+ return new Promise((resolve, reject) => {
+ let output = '';
+ const timeout = setTimeout(() => {
+ cleanup();
+ reject(new Error(`Timed out waiting for ${pattern} in:\n${output}`));
+ }, timeoutMs);
+ const onData = chunk => {
+ output += chunk;
+ const match = output.match(pattern);
+ if (match) {
+ cleanup();
+ resolve(match);
+ }
+ };
+ const cleanup = () => {
+ clearTimeout(timeout);
+ stream.off('data', onData);
+ };
+ stream.on('data', onData);
+ });
+}
describe('generator CLI', () => {
it('runs when invoked through a symlinked repository path', () => {
@@ -106,6 +135,92 @@ describe('generated module names', () => {
});
});
+describe('locale source watcher', () => {
+ it('regenerates for authored locale JSON but ignores generated pseudo output', () => {
+ expect(isSourceLocaleFile('en.json')).toBe(true);
+ expect(isSourceLocaleFile('fr-FR.json')).toBe(true);
+ expect(isSourceLocaleFile('pseudo.json')).toBe(false);
+ expect(isSourceLocaleFile('README.md')).toBe(false);
+ expect(isSourceLocaleFile(Buffer.from('en.json'))).toBe(false);
+ });
+
+ it('constructs Windows commands only from shell-safe tokens', () => {
+ expect(
+ createSpawnInvocation(
+ ['pnpm', '--parallel', '--filter', '@astryxdesign/core', 'dev:i18n'],
+ 'win32',
+ 'cmd.exe',
+ ),
+ ).toEqual({
+ file: 'cmd.exe',
+ args: [
+ '/d',
+ '/s',
+ '/c',
+ 'pnpm --parallel --filter @astryxdesign/core dev:i18n',
+ ],
+ });
+ expect(() =>
+ createSpawnInvocation(['tool', 'argument with spaces'], 'win32'),
+ ).toThrow('cannot contain spaces or shell metacharacters');
+ expect(() =>
+ createSpawnInvocation(['tool', 'value&next'], 'win32'),
+ ).toThrow('cannot contain spaces or shell metacharacters');
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'forwards repeated termination signals until the child exits',
+ async () => {
+ const childCode = `
+ let exitTimer;
+ process.on('SIGINT', () => {
+ clearTimeout(exitTimer);
+ exitTimer = setTimeout(() => process.exit(0), 250);
+ });
+ console.log('child-ready:' + process.pid);
+ setInterval(() => {}, 1_000);
+ `;
+ const wrapper = spawn(
+ process.execPath,
+ [GENERATOR, '--watch', '--', process.execPath, '-e', childCode],
+ {
+ cwd: REPO_ROOT,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ },
+ );
+ let childPid;
+
+ try {
+ const match = await waitForMatch(wrapper.stdout, /child-ready:(\d+)/);
+ childPid = Number(match[1]);
+ wrapper.kill('SIGINT');
+ await new Promise(resolve => setTimeout(resolve, 50));
+ wrapper.kill('SIGINT');
+ const [code, signal] = await Promise.race([
+ once(wrapper, 'exit'),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('wrapper did not exit')), 5_000),
+ ),
+ ]);
+
+ expect(signal).toBeNull();
+ expect(code).toBe(0);
+ expect(() => process.kill(childPid, 0)).toThrow();
+ } finally {
+ if (wrapper.exitCode === null) wrapper.kill('SIGKILL');
+ if (childPid !== undefined) {
+ try {
+ process.kill(childPid, 'SIGKILL');
+ } catch {
+ // The expected path: the wrapper already reaped its child.
+ }
+ }
+ }
+ },
+ 10_000,
+ );
+});
+
describe('renderRuntimeCatalogModule', () => {
it('emits a default-exported string map tied to its rich source', async () => {
const output = await renderRuntimeCatalogModule(