ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/shadcn/actions/shadcnlib.ts

actions/shadcnlib.ts

128 líneas, 5.9 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // Shared parts of the shadcn action and checks. The working directory is the project root.
  2. // The registry (vendored shadcn/ui code) lives in .shtukbase/packages/shadcn/registry. `place` copies the chosen
  3. // components into the folder of the `ui` alias of components.json, cn() into the `utils` alias, the theme into
  4. // `tailwind.css`, and writes .shadcn.json: the components placed and the hash of every file it laid.
  5. import { createHash } from 'node:crypto';
  6. import { existsSync, readFileSync } from 'node:fs';
  7. import { join } from 'node:path';
  8. import { readPage } from '../../collections/checks/lib/pages.ts';
  9. export const PAGE = 'design/shadcn.md';
  10. export const CONFIG = 'components.json';
  11. export const MANIFEST = '.shadcn.json';
  12. export const REGISTRY = join(import.meta.dir, '..', 'registry');
  13. export const SCHEMA_URL = 'https://ui.shadcn.com/schema.json';
  14. /** What every component needs from npm (beyond each item's own dependencies). */
  15. export const BASE_DEPS = ['react', 'cn', 'class-variance-authority', 'lucide-react', 'tailwindcss@4', 'tw-animate-css'];
  16. export type Item = { file: string; dependencies: string[]; registryDependencies: string[] };
  17. export type Manifest = { version: string; components: string[]; files: Record<string, string> };
  18. export type Components = {
  19. $schema?: string; style?: string; rsc?: boolean; tsx?: boolean;
  20. tailwind?: { config?: string; css?: string; baseColor?: string; cssVariables?: boolean; prefix?: string };
  21. aliases?: Record<string, string>; iconLibrary?: string; [k: string]: unknown;
  22. };
  23. export function sha(text: string): string {
  24. return createHash('sha256').update(text).digest('hex');
  25. }
  26. /** JSON with // and /* comments and trailing commas (tsconfig.json). */
  27. export function readJsonc(path: string): any {
  28. const text = readFileSync(path, 'utf8')
  29. .replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, s) => s ?? '')
  30. .replace(/,(\s*[}\]])/g, '$1');
  31. return JSON.parse(text);
  32. }
  33. export function index(): Record<string, Item> {
  34. return JSON.parse(readFileSync(join(REGISTRY, 'index.json'), 'utf8')).items;
  35. }
  36. export function page(root = process.cwd()): { components: string[]; aliasRoot: string | null } {
  37. const p = join(root, PAGE);
  38. const fm = existsSync(p) ? readPage(p).fm : {};
  39. const list = Array.isArray(fm.components) ? fm.components.map(String) : [];
  40. return { components: list, aliasRoot: typeof fm.aliasRoot === 'string' && fm.aliasRoot.trim() ? fm.aliasRoot.trim().replace(/^\.?\/+|\/+$/g, '') : null };
  41. }
  42. /** components.json, parsed; `error` when it is missing or not JSON. */
  43. export function components(root = process.cwd()): { cfg: Components | null; error: string | null } {
  44. const p = join(root, CONFIG);
  45. if (!existsSync(p)) return { cfg: null, error: 'no components.json' };
  46. try {
  47. const cfg = JSON.parse(readFileSync(p, 'utf8'));
  48. return cfg && typeof cfg === 'object' && !Array.isArray(cfg) ? { cfg, error: null } : { cfg: null, error: 'components.json is not a JSON object' };
  49. } catch (e) {
  50. return { cfg: null, error: `components.json cannot be read as JSON: ${(e as Error).message}` };
  51. }
  52. }
  53. /** Where the `@/` of aliases points: aliasRoot of the page, else tsconfig paths "@/*", else src. */
  54. export function aliasRoot(root = process.cwd()): string {
  55. const own = page(root).aliasRoot;
  56. if (own) return own;
  57. for (const name of ['tsconfig.json', 'jsconfig.json']) {
  58. const p = join(root, name);
  59. if (!existsSync(p)) continue;
  60. try {
  61. const target = readJsonc(p)?.compilerOptions?.paths?.['@/*']?.[0];
  62. if (typeof target === 'string') return target.replace(/^\.\/?/, '').replace(/\/?\*$/, '');
  63. } catch { /* unreadable tsconfig: fall through */ }
  64. }
  65. return 'src';
  66. }
  67. /** An alias (@/components/ui) → a project folder (src/components/ui). A path without @/ is taken as it is. */
  68. export function aliasPath(alias: string, root = process.cwd()): string {
  69. const r = aliasRoot(root);
  70. const rest = alias.replace(/^[@~]\//, '');
  71. return /^[@~]\//.test(alias) ? (r ? `${r}/${rest}` : rest) : alias.replace(/^\.?\/+/, '');
  72. }
  73. export function aliases(cfg: Components): { ui: string; utils: string } {
  74. const a = cfg.aliases ?? {};
  75. return { ui: a.ui ?? `${a.components ?? '@/components'}/ui`, utils: a.utils ?? '@/lib/utils' };
  76. }
  77. /** The names and every registry dependency of them, in a stable order. Unknown names are returned apart. */
  78. export function closure(names: string[], items: Record<string, Item>): { all: string[]; unknown: string[] } {
  79. const seen = new Set<string>();
  80. const unknown: string[] = [];
  81. const visit = (n: string) => {
  82. if (seen.has(n)) return;
  83. if (!items[n]) { if (!unknown.includes(n)) unknown.push(n); return; }
  84. seen.add(n);
  85. for (const d of items[n].registryDependencies) visit(d);
  86. };
  87. for (const n of names) visit(n);
  88. return { all: [...seen].sort(), unknown };
  89. }
  90. /** A registry file as it lies in the project: imports point at the project's aliases. */
  91. export function render(text: string, cfg: Components): string {
  92. const a = aliases(cfg);
  93. return text.split('@/components/ui/').join(`${a.ui}/`).split('"@/lib/utils"').join(`"${a.utils}"`);
  94. }
  95. export function readManifest(root = process.cwd()): Manifest | null {
  96. const p = join(root, MANIFEST);
  97. if (!existsSync(p)) return null;
  98. try {
  99. return JSON.parse(readFileSync(p, 'utf8')) as Manifest;
  100. } catch {
  101. return null;
  102. }
  103. }
  104. export function version(): string {
  105. const p = join(import.meta.dir, '..', 'package.md');
  106. return existsSync(p) ? String(readPage(p).fm.version ?? '') : '';
  107. }
  108. /** Where the package's files go in this project: ui folder, utils file, theme file. */
  109. export function targets(cfg: Components, root = process.cwd()): { ui: string; utils: string; theme: string } {
  110. const a = aliases(cfg);
  111. const utils = aliasPath(a.utils, root);
  112. return { ui: aliasPath(a.ui, root), utils: /\.[jt]sx?$/.test(utils) ? utils : `${utils}.ts`, theme: (cfg.tailwind?.css ?? 'src/styles/globals.css').replace(/^\.?\/+/, '') };
  113. }