Skip to content

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

TypeScript
17.8 KB
Raw Blame
#!/usr/bin/env node
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
 * Generates apps/docsite/src/generated/playground-scope.ts
 *
 * Maps Core exports and the integration packages this build documents into
 * the preview iframe.
 * @input Core package exports, the admitted integration packages recorded by
 *   generate-data.mjs, and the content target
 * @output The runtime module scope used by copyable Playground examples
 * @position Build-time companion to component and block registry generation
 * This runs as part of `pnpm generate` (before dev/build) so new components
 * are picked up automatically — no manual maintenance needed.
 *
 * Run: node scripts/generate-scope.mjs
 */

import {readFileSync, writeFileSync, mkdirSync} from 'node:fs';
import {dirname, resolve} from 'node:path';
import {fileURLToPath} from 'node:url';
import {getTarget} from './resolve-content-root.mjs';
import {readAdmittedIntegrationPackages} from '../src/lib/integrationTargets.mjs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, '..');
const CORE_PKG = resolve(ROOT, '../../packages/core/package.json');
const OUT = resolve(ROOT, 'src/generated/playground-scope.ts');
// The packages generate-data.mjs admitted for this target (canary: every
// configured integration; latest: the stable releases in its content
// snapshot), so the scope and the registries describe the same packages.
const integrationPackages = readAdmittedIntegrationPackages(
  resolve(ROOT, 'src/generated'),
  getTarget(),
);

const HEADER = `// Copyright (c) Meta Platforms, Inc. and affiliates.

// @generated by scripts/generate-scope.mjs — do not edit manually`;

// Read core package.json exports and extract PascalCase component subpaths
const corePkg = JSON.parse(readFileSync(CORE_PKG, 'utf-8'));
const exportKeys = Object.keys(corePkg.exports ?? {});

const SKIP =
  /\.(css|stylex)$|\/utils$|^\.\/theme|^\.\/hooks|^\.\/utils|^\.\/syntax|^\.\/docs|^\.\/groups|^\.$|^\.\/reset/;

const COMPONENT_NAME = /^[A-Z][A-Za-z0-9]*$/;
const NESTED_MODULE_NAME = /^[A-Z][A-Za-z0-9]*(?:\/[A-Za-z0-9][A-Za-z0-9-]*)+$/;

const components = exportKeys
  .filter(k => {
    if (SKIP.test(k)) return false;
    const name = k.replace('./', '');
    return COMPONENT_NAME.test(name);
  })
  .map(k => k.replace('./', ''));

const nestedModules = exportKeys
  .filter(k => {
    if (SKIP.test(k)) return false;
    return NESTED_MODULE_NAME.test(k.replace('./', ''));
  })
  .map(k => {
    const specifier = k.replace('./', '');
    return {
      specifier,
      identifier: `Core_${specifier.replace(/[^A-Za-z0-9_$]/g, '_')}`,
    };
  });

// Themes — add new themes here as they become available
const SCOPE_THEMES = [
  {pkg: '@astryxdesign/theme-neutral', name: 'neutralTheme', subpath: '/built'},
  {pkg: '@astryxdesign/theme-matcha', name: 'matchaTheme', subpath: '/built'},
];

// Heroicons variants — exposed alongside Lucide so playground snippets
// and shared template code that still imports from '@heroicons/react/*'
// keeps rendering. New docsite code authors against Lucide; these entries
// are purely for playground runtime compatibility.
const HEROICON_VARIANTS = [
  {path: '16/solid', alias: 'Heroicons16Solid'},
  {path: '20/solid', alias: 'Heroicons20Solid'},
  {path: '24/outline', alias: 'Heroicons24Outline'},
  {path: '24/solid', alias: 'Heroicons24Solid'},
];

// Build output — matches the structure of the previously committed scope.ts
const lines = [HEADER, ''];

// ── React ──────────────────────────────────────────────────────────────
lines.push(
  "import React, {useState, useCallback, useMemo, useEffect, useRef} from 'react';",
);
lines.push('');

// ── StyleX mock ────────────────────────────────────────────────────────
// The playground transpiles code in-browser without the StyleX compiler, so the
// mock reimplements stylex.create/props: each property becomes an atomic class
// injected into a shared <style> sheet, so @container/@media/pseudo conditions
// apply instead of collapsing to the `default` value an inline style would force.
//
// create() returns `$$css: true` objects of class names — the same shape the real
// compiled stylex.props() understands, so `xstyle` passed into @astryxdesign/core components
// merges correctly too.
lines.push(`type PGStyleValue =
  | string
  | number
  | {[condition: string]: string | number};
type PGRule = Record<string, PGStyleValue>;

const PG_UNITLESS = new Set([
  'opacity', 'zIndex', 'fontWeight', 'lineHeight', 'flex', 'flexGrow',
  'flexShrink', 'order', 'gridColumn', 'gridRow', 'gridColumnStart',
  'gridColumnEnd', 'gridRowStart', 'gridRowEnd', 'columnCount', 'aspectRatio',
  'scale', 'tabSize',
]);

const PG_CAMEL_RE = /[A-Z]/g;
const pgKebab = (prop: string): string =>
  prop.startsWith('--')
    ? prop
    : prop.replace(PG_CAMEL_RE, m => '-' + m.toLowerCase());

const pgCssValue = (prop: string, value: string | number): string =>
  typeof value === 'number' && !PG_UNITLESS.has(prop) ? value + 'px' : String(value);

const pgHash = (input: string): string => {
  let h = 5381;
  for (let i = 0; i < input.length; i++) h = (h * 33) ^ input.charCodeAt(i);
  return 'pg' + (h >>> 0).toString(36);
};

const pgSheetCache = new Set<string>();
let pgSheetEl: HTMLStyleElement | null = null;
const pgInject = (rule: string): void => {
  if (typeof document === 'undefined' || pgSheetCache.has(rule)) return;
  pgSheetCache.add(rule);
  if (!pgSheetEl) {
    pgSheetEl = document.createElement('style');
    pgSheetEl.id = 'pg-stylex';
    document.head.appendChild(pgSheetEl);
  }
  pgSheetEl.appendChild(document.createTextNode(rule));
};

const pgClassForProp = (prop: string, value: PGStyleValue): string => {
  const cls = pgHash(prop + ':' + JSON.stringify(value));
  if (value != null && typeof value === 'object') {
    for (const [cond, condVal] of Object.entries(value)) {
      if (condVal == null) continue;
      const decl = pgSelector(cls, cond) + '{' + pgKebab(prop) + ':' + pgCssValue(prop, condVal) + '}';
      pgInject(pgWrapAtRule(cond, decl));
    }
  } else {
    pgInject('.' + cls + '{' + pgKebab(prop) + ':' + pgCssValue(prop, value) + '}');
  }
  return cls;
};

const pgPseudoSuffix = (cond: string): string =>
  cond === 'default' || cond.startsWith('@') ? '' : cond;

// A marker rides along as a class so an ancestor can be named in a selector.
// Tagged with a prop key rather than a bare string because \`props\` only keeps
// string values, and this way one shows up in className like any other class.
const PG_MARKER_PROP = '--pg-marker';
const PG_DEFAULT_MARKER = 'pgmarkdefault';
let pgMarkerSeq = 0;
const pgMarker = (cls: string): Record<string, unknown> => ({
  $$css: true,
  [PG_MARKER_PROP]: cls,
});

// Every other condition narrows the element's own selector, so it appends.
// \`when.ancestor\` instead qualifies a *parent*, which has to prepend — hence a
// tag the rule builder can spot rather than another pseudo suffix.
const PG_ANCESTOR_TAG = '%pg-ancestor%';

const pgSelector = (cls: string, cond: string): string =>
  cond.startsWith(PG_ANCESTOR_TAG)
    ? cond.slice(PG_ANCESTOR_TAG.length) + ' .' + cls
    : '.' + cls + pgPseudoSuffix(cond);

const pgWrapAtRule = (cond: string, decl: string): string =>
  cond.startsWith('@') ? cond + '{' + decl + '}' : decl;

const pgCompileRule = (rule: Record<string, unknown>): Record<string, unknown> => {
  const compiled: Record<string, unknown> = {$$css: true};
  for (const [prop, value] of Object.entries(rule)) {
    if (value == null) continue;
    compiled[prop] = pgClassForProp(prop, value as PGStyleValue);
  }
  return compiled;
};

const stylexMock = {
  create: <T extends Record<string, unknown>>(styles: T): T => {
    const out: Record<string, unknown> = {};
    for (const [key, rule] of Object.entries(styles)) {
      if (typeof rule === 'function') {
        // Dynamic styles must compile at call time so runtime values become classes.
        const fn = rule as (...args: unknown[]) => Record<string, unknown>;
        out[key] = (...args: unknown[]) => pgCompileRule(fn(...args));
      } else if (typeof rule === 'object' && rule != null) {
        out[key] = pgCompileRule(rule as Record<string, unknown>);
      } else {
        out[key] = rule;
      }
    }
    return out as T;
  },
  // Later styles override earlier ones per property key (matching real StyleX),
  // returning a className (not inline style) so @container/@media survive.
  props: (...styles: unknown[]) => {
    const byProp: Record<string, string> = {};
    for (const s of (styles.flat(Infinity) as unknown[])) {
      if (s == null || s === false || typeof s !== 'object') continue;
      for (const [prop, cls] of Object.entries(s as Record<string, unknown>)) {
        if (prop === '$$css' || typeof cls !== 'string') continue;
        byProp[prop] = cls;
      }
    }
    return {className: Object.values(byProp).join(' '), style: {}};
  },
  defineVars: <T extends Record<string, unknown>>(tokens: T): T => tokens,
  keyframes: (kf: Record<string, Record<string, string>>) => kf,
  defaultMarker: () => pgMarker(PG_DEFAULT_MARKER),
  defineMarker: () => pgMarker('pgmark' + pgMarkerSeq++),
  when: {
    ancestor: (cond: string, marker?: Record<string, unknown>) =>
      PG_ANCESTOR_TAG +
      '.' +
      ((marker?.[PG_MARKER_PROP] as string) ?? PG_DEFAULT_MARKER) +
      cond,
  },
  types: {
    angle: (v: string) => v,
    color: (v: string) => v,
    image: (v: string) => v,
    integer: (v: string) => v,
    length: (v: string) => v,
    lengthPercentage: (v: string) => v,
    number: (v: string) => v,
    percentage: (v: string) => v,
    resolution: (v: string) => v,
    time: (v: string) => v,
    transformFunction: (v: string) => v,
    transformList: (v: string) => v,
    url: (v: string) => v,
  },
};`);
lines.push('');

// ── Component and nested-module imports ───────────────────────────────
for (const name of components) {
  lines.push(`import * as ${name} from '@astryxdesign/core/${name}';`);
}
for (const {specifier, identifier} of nestedModules) {
  lines.push(
    `import * as ${identifier} from '@astryxdesign/core/${specifier}';`,
  );
}
lines.push('');

// Use the same configured package roots as the canary component/block catalog.
// Otherwise an example's import silently resolves to an empty placeholder.
for (const [index, pkg] of integrationPackages.entries()) {
  lines.push(`import * as Integration${index} from '${pkg}';`);
}
lines.push('');

// ── Theme imports ──────────────────────────────────────────────────────
for (const t of SCOPE_THEMES) {
  lines.push(`import {${t.name}} from '${t.pkg}${t.subpath}';`);
}
lines.push('');

// ── Theme + tokens ──────────────────────────────────────────────────
lines.push("import {Theme, defineTheme} from '@astryxdesign/core/theme';");
lines.push("import type {DefinedTheme} from '@astryxdesign/core/theme';");
lines.push(
  "import {createContext, createElement, useContext, type ComponentProps} from 'react';",
);
lines.push(
  "import * as astryxTokens from '@astryxdesign/core/theme/tokens.stylex';",
);
lines.push('');

// ── Hooks ──────────────────────────────────────────────────────────────
// camelCase, so the PascalCase component scan skips it — add it explicitly so
// templates using useMediaQuery etc. render.
lines.push("import * as Hooks from '@astryxdesign/core/hooks';");
lines.push('');

// ── Utils ──────────────────────────────────────────────────────────────
// camelCase too, and skipped for the same reason. Page templates mirror their
// directional icons in right-to-left with `rtlStyles` from here.
lines.push("import * as Utils from '@astryxdesign/core/utils';");
lines.push('');

// ── Icon and chart libraries ───────────────────────────────────────────
lines.push("import * as LucideIcons from 'lucide-react';");
lines.push("import * as Recharts from 'recharts';");
lines.push(
  '// Heroicons kept available in the playground scope alongside Lucide',
);
lines.push('// so template / example code that still imports from');
lines.push(
  "// '@heroicons/react/*' continues to render. New docsite code authors",
);
lines.push('// against Lucide; these entries are purely for backwards compat.');
for (const h of HEROICON_VARIANTS) {
  lines.push(`import * as ${h.alias} from '@heroicons/react/${h.path}';`);
}
lines.push('');

// ── ControlledTheme wrapper ─────────────────────────────────────────
const themeEntries = SCOPE_THEMES.map(
  t => `  ${t.name.replace('Theme', '').toLowerCase()}: ${t.name},`,
).join('\n');

lines.push(`const SCOPE_THEMES: Record<string, DefinedTheme> = {
${themeEntries}
};

const IsNestedTheme = createContext(false);

const ControlledTheme = (props: ComponentProps<typeof Theme>) => {
  const isNested = useContext(IsNestedTheme);
  // A nested Theme is part of what the code being previewed is showing — a
  // poster's display face, a slider track painted as a spectrum — so it keeps
  // the theme and mode it asked for. Only the outermost one answers to the
  // playground's theme and mode pickers.
  if (isNested) {
    return createElement(Theme, props);
  }
  const win =
    typeof window !== 'undefined'
      ? (window as unknown as Record<string, unknown>)
      : null;
  const mode =
    (win?.__xds_preview_mode__ as 'light' | 'dark' | 'system') || 'system';
  const themeName = (win?.__xds_preview_theme__ as string) || 'default';
  const theme = SCOPE_THEMES[themeName] ?? ${SCOPE_THEMES[0].name};
  return createElement(
    IsNestedTheme.Provider,
    {value: true},
    createElement(Theme, {...props, theme, mode}),
  );
};`);
lines.push('');

// ── Scope map ──────────────────────────────────────────────────────────
lines.push('export const scope: Record<string, Record<string, unknown>> = {');

// react
lines.push(`  react: {
    default: React,
    ...React,
    useState,
    useCallback,
    useMemo,
    useEffect,
    useRef,
  },`);

// stylex
lines.push("  '@stylexjs/stylex': {default: stylexMock, ...stylexMock},");
lines.push('  stylex: {default: stylexMock, ...stylexMock},');

// Recharts comes before Astryx so Astryx components win global name collisions.
lines.push('  recharts: Recharts,');

// Core entries follow these so Core keeps precedence for unqualified globals.
//
// Whole-package admission is deliberate (owner-ratified): every export of a
// configured integration is available so a NEW integration component needs no
// scope edits. Each package keeps its own namespace entry, so QUALIFIED
// imports (`import {Chart} from '@astryxdesign/charts'`) always resolve to
// their own package. For UNQUALIFIED globals the preview runner iterates this
// map in insertion order with later-wins (see runner.ts buildGlobalScope), so
// on shared export names a later-configured integration shadows an earlier
// one — @astryxdesign/lab and @astryxdesign/charts currently share 14 names
// (Chart, ChartAxis, ChartGrid, ChartTooltip, ChartLegend, useChart,
// useChartColors, getChartColors, getChartColorsFromResolver, compactNumber,
// currency, percent, shortDate, monthYear), which charts wins — and the Core
// entries below shadow every integration. Covered by playground-scope.test.ts.
for (const [index, pkg] of integrationPackages.entries()) {
  lines.push(`  '${pkg}': Integration${index},`);
}

// themes
for (const t of SCOPE_THEMES) {
  lines.push(`  '${t.pkg}': {default: ${t.name}, ${t.name}},`);
  lines.push(`  '${t.pkg}/built': {default: ${t.name}, ${t.name}},`);
}

// Theme (controlled wrapper)
lines.push(
  "  '@astryxdesign/core/theme': {Theme: ControlledTheme, defineTheme},",
);

// tokens.stylex
lines.push("  '@astryxdesign/core/theme/tokens.stylex': astryxTokens,");

// hooks (useMediaQuery, etc.)
lines.push("  '@astryxdesign/core/hooks': Hooks,");

// utils (rtlStyles, etc.)
lines.push("  '@astryxdesign/core/utils': Utils,");

// Per-component and nested-module subpath entries
for (const name of components) {
  lines.push(`  '@astryxdesign/core/${name}': ${name},`);
}
for (const {specifier, identifier} of nestedModules) {
  lines.push(`  '@astryxdesign/core/${specifier}': ${identifier},`);
}

// Barrel export — all components spread
const spreads = components.map(n => `    ...${n},`).join('\n');
lines.push(`  '@astryxdesign/core': {
${spreads}
  },`);

// Lucide icons + Heroicons
lines.push("  'lucide-react': LucideIcons,");
for (const h of HEROICON_VARIANTS) {
  lines.push(`  '@heroicons/react/${h.path}': ${h.alias},`);
}

// next/image stub
lines.push(`  'next/image': {
    default: (props: Record<string, unknown>) =>
      React.createElement('img', props),
  },`);

lines.push('};');
lines.push('');

// Write output
mkdirSync(dirname(OUT), {recursive: true});
writeFileSync(OUT, lines.join('\n'));
console.log(`✓ Generated ${OUT}`);
console.log(`  ${components.length} components`);
console.log(`  ${nestedModules.length} nested modules`);
console.log(`  ${integrationPackages.length} integration packages`);
console.log(`  ${SCOPE_THEMES.length} themes`);
console.log(
  `  lucide-react icons + ${HEROICON_VARIANTS.length} heroicon variants`,
);
console.log('  recharts');