diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdx index 5b3fa5f05..1ad0b391d 100644 --- a/apps/docs/content/docs/cli.mdx +++ b/apps/docs/content/docs/cli.mdx @@ -62,6 +62,15 @@ Every write shows you what it would add and asks first. Pass `--yes` to accept e Change the aliases and imports are rewritten to match on the way in. +Aliases are import paths. The CLI writes them into the imports of every file it copies, and finds +the folder each one points to through `compilerOptions.paths` in your `tsconfig.json`. With +`"@/*": ["./src/*"]`, components go to `src/components/ui`. Without a matching entry, `@/` means the +project root. + +`init` takes the CSS entry from the `cssEntryFile` your Metro config already passes to Uniwind, and +puts `theme.css` beside it. Without one, it looks for `global.css` in the project root, `src/` and +`app/`. + Aliases are directories inside the project: letters, numbers, dots, dashes and underscores, separated by `/`, after an optional `@/`, `~/` or `./`. Anything else is refused. The alias is written between the quotes of every import in every file copied in, so it has to be a path and @@ -178,6 +187,11 @@ import resolves, everything type-checks, and nothing is styled. } ``` +**Components were written to the project root, not `src/`.** Older CLI versions read `@/` as the +project root whatever `tsconfig.json` said. Move `components/`, `lib/` and `hooks/` into `src/`, and +add `src/` to the start of each path in `panelui-lock.json` so `update` still recognises the files. +Then run `npx panelui-cli@latest doctor` and fix any `@source` lines it reports. + **`Property 'className' does not exist`.** `className` is not a React Native prop — Uniwind adds it. You need an ambient import somewhere in the project: diff --git a/packages/cli/README.md b/packages/cli/README.md index 2c7ec6e6b..43929f7e7 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -199,6 +199,15 @@ A value-taking flag without its value prints its usage and exits with status 1. Change the aliases and imports are rewritten to match on the way in. +Aliases are import paths. The CLI writes them into the imports of every file it copies, and finds +the folder each one points to through `compilerOptions.paths` in your `tsconfig.json`. With +`"@/*": ["./src/*"]`, components go to `src/components/ui`. Without a matching entry, `@/` means the +project root. + +`init` takes the CSS entry from the `cssEntryFile` your Metro config already passes to Uniwind, and +puts `theme.css` beside it. Without one, it looks for `global.css` in the project root, `src/` and +`app/`. + `panelui-lock.json` records SHA-256 digests, requested roots, and each root's registry dependency closure. That lets a named update remove an untouched dependency only after no other requested root needs it. Locally edited files and dependencies shared with another root are always retained. Commit diff --git a/packages/cli/src/config.mjs b/packages/cli/src/config.mjs index 1ba5aaafb..09983ad9a 100644 --- a/packages/cli/src/config.mjs +++ b/packages/cli/src/config.mjs @@ -5,6 +5,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { fail } from './ui.mjs'; +import { readTsconfigPaths, resolveAliasThroughPaths } from './tsconfig.mjs'; export const CONFIG_FILE = 'panelui.json'; export const DEFAULT_REGISTRY = 'https://panelui.dev/r'; @@ -95,12 +96,61 @@ export function validateAlias(alias) { } /** - * Turn an alias into a real directory. `@/components/ui` → `components/ui`, - * following the `@/*` → `./*` mapping Expo's base tsconfig already sets up. + * Turn an alias into a real directory, relative to the project root. + * + * Given the project's root (`cwd`), the alias is resolved through + * `compilerOptions.paths` in its tsconfig, so `@/components/ui` is + * `src/components/ui` where `@/*` maps to `./src/*`. The copied files keep the + * alias in their imports; this is only where they are written. + * + * Without a root, or when no `paths` entry covers the alias, the prefix is read + * as the project root: `@/components/ui` → `components/ui`. + */ +export function aliasToDir(alias, cwd) { + const tidied = validateAlias(alias); + const fallback = tidied.replace(/^@\//, '').replace(/^~\//, '').replace(/^\.\//, ''); + if (cwd === undefined) return fallback; + + const mapping = readTsconfigPaths(cwd); + const resolved = resolveAliasThroughPaths(tidied, mapping); + if (!resolved) return fallback; + + const root = path.resolve(cwd); + const relative = path.relative(root, resolved.dir).split(path.sep).join('/'); + const where = `"${resolved.key}" in ${mapping.file}`; + + /* + * The folder came from a project file, and it is about to be written into + * CSS (`@source '…'`) and used as a write destination, so it is held to the + * same characters an alias is. A mapping outside the app — a shared package + * in a monorepo — is refused rather than written into. + */ + if (relative === '..' || relative.startsWith('../') || path.isAbsolute(relative)) { + fail( + `Alias "${tidied}" resolves outside the project through ${where}.`, + 'Set an alias in panelui.json that resolves to a folder inside this app.' + ); + } + if (relative && !relative.split('/').every((segment) => ALIAS_SEGMENT.test(segment))) { + fail( + `Alias "${tidied}" resolves to "${relative}" through ${where}, which is not a plain directory path.`, + 'Use letters, numbers, dots, dashes and underscores, separated by /.' + ); + } + + return validateRelativePath(relative, 'Alias path', { allowEmpty: true }); +} + +/** + * The directory an alias's `@source` line scans: the alias's first segment, + * resolved. `@/components/ui` scans `components` (or `src/components`), so a + * later `add` that creates a sibling folder is covered without re-running init. */ -export function aliasToDir(alias) { +export function aliasSourceRoot(alias, cwd) { const tidied = validateAlias(alias); - return tidied.replace(/^@\//, '').replace(/^~\//, '').replace(/^\.\//, ''); + const prefix = tidied.match(/^(?:@\/|~\/|\.\/)?/)[0]; + const [first] = tidied.slice(prefix.length).split('/'); + return aliasToDir(first ? `${prefix}${first}` : tidied, cwd); } /** Rejects paths that could escape a project on the current platform or Windows. */ @@ -197,11 +247,11 @@ export function validateProjectName(name) { } /** Validate every configured path before it reaches a filesystem write boundary. */ -export function validateConfigPaths(config) { +export function validateConfigPaths(config, cwd) { const aliases = { ...CANONICAL_ALIASES, ...(config.aliases ?? {}) }; - aliasToDir(aliases.components); - aliasToDir(aliases.lib); - aliasToDir(aliases.hooks); + aliasToDir(aliases.components, cwd); + aliasToDir(aliases.lib, cwd); + aliasToDir(aliases.hooks, cwd); validateRelativePath(config.css ?? 'global.css', 'CSS path'); validateRelativePath(config.theme ?? 'theme.css', 'Theme path'); } @@ -227,7 +277,7 @@ export function targetPath(cwd, config, registryPath) { const alias = group === 'ui' ? aliases.components : group === 'lib' ? aliases.lib : aliases.hooks; - return projectPath(cwd, path.join(aliasToDir(alias), ...rest), 'Registry file path'); + return projectPath(cwd, path.join(aliasToDir(alias, cwd), ...rest), 'Registry file path'); } /** diff --git a/packages/cli/src/doctor.mjs b/packages/cli/src/doctor.mjs index 68b6de579..26b0b064e 100644 --- a/packages/cli/src/doctor.mjs +++ b/packages/cli/src/doctor.mjs @@ -3,6 +3,7 @@ import path from "node:path"; import { CANONICAL_ALIASES, DEFAULT_REGISTRY, + aliasSourceRoot, aliasToDir, projectPath, validateConfigPaths, @@ -28,7 +29,7 @@ function lockDiagnostics(cwd, config, aliases) { const lockFile = path.join(cwd, LOCK_FILE); if (!fs.existsSync(lockFile)) { const copiedRoots = Object.values(aliases) - .map(aliasToDir) + .map((alias) => aliasToDir(alias, cwd)) .filter((directory) => fs.existsSync(path.join(cwd, directory))) .sort(); return [ @@ -258,7 +259,7 @@ export function diagnose(cwd) { typeof config.aliases !== "object") ) throw new Error("aliases must be an object"); - validateConfigPaths(config); + validateConfigPaths(config, cwd); checks.push(check("config", "ok", "panelui.json is valid and contained")); } catch (error) { const message = fs.existsSync(configFile) @@ -287,9 +288,7 @@ export function diagnose(cwd) { if (!themeImport.startsWith(".")) themeImport = `./${themeImport}`; required.push(`@import '${themeImport}'`); const sourceDirs = new Set( - Object.values(aliases) - .map(aliasToDir) - .map((dir) => dir.split(/[\\/]/)[0]), + Object.values(aliases).map((alias) => aliasSourceRoot(alias, cwd)), ); for (const dir of sourceDirs) { let relative = path diff --git a/packages/cli/src/init.mjs b/packages/cli/src/init.mjs index c47bc959a..d72fd5bd2 100644 --- a/packages/cli/src/init.mjs +++ b/packages/cli/src/init.mjs @@ -20,7 +20,13 @@ import { writeConfig, } from './config.mjs'; import { fetchItem } from './registry.mjs'; -import { installDependencies, patchCss, patchMetro, patchTypeScript } from './patch.mjs'; +import { + detectCssEntry, + installDependencies, + patchCss, + patchMetro, + patchTypeScript, +} from './patch.mjs'; import { TEMPLATES, THEMES, @@ -89,6 +95,9 @@ export async function init(options) { } const config = defaultConfig(options.registry ?? DEFAULT_REGISTRY); + // Update the CSS entry the project already has, wherever it lives, and keep + // the tokens beside it. + config.css = detectCssEntry(cwd); if (!options.assumeYes && process.stdin.isTTY) { config.aliases.components = await ask('Where should components go?', config.aliases.components); @@ -97,7 +106,8 @@ export async function init(options) { config.css = await ask('Which file is your CSS entry?', config.css); } - validateConfigPaths(config); + config.theme = siblingOf(config.css, 'theme.css'); + validateConfigPaths(config, cwd); step(`Write ${CONFIG_FILE}`); if (!options.dryRun) { @@ -116,6 +126,7 @@ export async function init(options) { } else { step(`Write ${config.theme} ${dim('(design tokens, all themes)')}`); if (!options.dryRun) { + fs.mkdirSync(path.dirname(themePath), { recursive: true }); fs.writeFileSync(themePath, theme.files[0].content); success(`Wrote ${config.theme}`); } @@ -128,7 +139,7 @@ export async function init(options) { const missing = BASE_DEPENDENCIES.filter((dep) => !(dep in project.deps)); await installDependencies(cwd, missing, { ...options, isExpo: project.isExpo }); - printNextSteps(config); + printNextSteps(cwd, config); } /** @@ -230,8 +241,14 @@ function printCreated(projectName, template, theme, mode) { info(''); } -function printNextSteps(config) { - const componentsDir = aliasToDir(config.aliases.components); +/** `theme.css` beside `src/global.css` is `src/theme.css`. */ +function siblingOf(file, name) { + const dir = path.posix.dirname(file.split(path.sep).join('/')); + return dir === '.' ? name : `${dir}/${name}`; +} + +function printNextSteps(cwd, config) { + const componentsDir = aliasToDir(config.aliases.components, cwd); info(''); info(bold('Almost there. Two things left:')); diff --git a/packages/cli/src/mcp.mjs b/packages/cli/src/mcp.mjs index e1330b3b0..69c776cff 100644 --- a/packages/cli/src/mcp.mjs +++ b/packages/cli/src/mcp.mjs @@ -221,7 +221,7 @@ function safeComponentsDir(cwd, config) { try { return projectPath( cwd, - aliasToDir(config.aliases?.components ?? '@/components/ui'), + aliasToDir(config.aliases?.components ?? '@/components/ui', cwd), 'Components path' ); } catch { diff --git a/packages/cli/src/patch.mjs b/packages/cli/src/patch.mjs index 757b61239..80e9f434e 100644 --- a/packages/cli/src/patch.mjs +++ b/packages/cli/src/patch.mjs @@ -7,7 +7,14 @@ import fs from 'node:fs'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; -import { aliasToDir, projectPath, validateConfigPaths } from './config.mjs'; +import { + aliasSourceRoot, + aliasToDir, + projectPath, + validateConfigPaths, + validateRelativePath, +} from './config.mjs'; +import { readTsconfigPaths } from './tsconfig.mjs'; import { confirm, dim, fail, printAddition, step, success, warn } from './ui.mjs'; /** @@ -19,7 +26,7 @@ import { confirm, dim, fail, printAddition, step, success, warn } from './ui.mjs * miserable thing to debug. */ export async function patchCss(cwd, config, { assumeYes, dryRun }) { - validateConfigPaths(config); + validateConfigPaths(config, cwd); const cssPath = projectPath(cwd, config.css ?? 'global.css', 'CSS path'); const exists = fs.existsSync(cssPath); const current = exists ? fs.readFileSync(cssPath, 'utf8') : ''; @@ -28,10 +35,10 @@ export async function patchCss(cwd, config, { assumeYes, dryRun }) { const sourceDirs = [ ...new Set( Object.values(config.aliases ?? {}) - .map(aliasToDir) - // Scan the top-level directory rather than the leaf, so a later - // `add` that creates a sibling folder is covered without re-running. - .map((dir) => dir.split(/[\\/]/)[0]) + // Scan the alias's top-level directory rather than the leaf, so a + // later `add` that creates a sibling folder is covered without + // re-running. + .map((alias) => aliasSourceRoot(alias, cwd)) ), ]; @@ -81,6 +88,60 @@ function relativeCssSpecifier(fromDir, targetPath) { return relative.startsWith('.') ? relative : `./${relative}`; } +const METRO_FILES = ['metro.config.js', 'metro.config.cjs', 'metro.config.mjs', 'metro.config.ts']; +const CSS_CANDIDATES = ['global.css', 'src/global.css', 'app/global.css', 'src/app/global.css']; + +/** A detected path, tidied, or null when it is not one this CLI may write to. */ +function safeRelative(value) { + const tidied = value.trim().replace(/^\.\//, ''); + try { + return validateRelativePath(tidied, 'CSS path'); + } catch { + return null; + } +} + +/** + * Which file the project's CSS entry is, so `init` updates it instead of + * creating a second one beside it. + * + * In order: the `cssEntryFile` the Metro config already passes to Uniwind; an + * existing CSS file in a usual place that imports Uniwind; any existing CSS + * file in a usual place; and finally `global.css` in the folder `@/` resolves + * to, which is `src/` in an app laid out that way. + */ +export function detectCssEntry(cwd) { + for (const name of METRO_FILES) { + const file = path.join(cwd, name); + if (!fs.existsSync(file)) continue; + const match = codeOnlyKeepingStrings(fs.readFileSync(file, 'utf8')).match( + /\bcssEntryFile\s*:\s*(['"`])([^'"`\n]+)\1/ + ); + const found = match && safeRelative(match[2]); + if (found) return found; + } + + const existing = CSS_CANDIDATES.filter((file) => fs.existsSync(path.join(cwd, file))); + const withUniwind = existing.find((file) => + /@import\s+['"]uniwind['"]/.test(fs.readFileSync(path.join(cwd, file), 'utf8')) + ); + if (withUniwind ?? existing[0]) return withUniwind ?? existing[0]; + + try { + const root = aliasToDir('@/__panelui_probe__', cwd).replace(/\/?__panelui_probe__$/, ''); + return root ? `${root}/global.css` : 'global.css'; + } catch { + return 'global.css'; + } +} + +/** Blank out comments but keep string literals, so a commented-out option is not read. */ +function codeOnlyKeepingStrings(source) { + return source.replace(/\/\*[\s\S]*?\*\/|(^|[^:'"`\\])\/\/[^\n]*/g, (match, lead) => + lead === undefined ? ' ' : `${lead} ` + ); +} + const METRO_TEMPLATE = `const { getDefaultConfig } = require('expo/metro-config'); const { withUniwindConfig } = require('uniwind/metro'); @@ -247,20 +308,24 @@ export async function patchTypeScript(cwd, config, { assumeYes, dryRun }) { ['css.d.ts', "declare module '*.css';\n"], ].filter(([file]) => !fs.existsSync(path.join(cwd, file))); - const raw = fs.readFileSync(tsconfigPath, 'utf8'); - // Deliberately not a full JSONC parser — tsconfig commonly has comments, and - // if this cannot read it cleanly it says so rather than mangling the file. + const aliasPrefix = (config.aliases?.components ?? '@/components/ui').split('/')[0]; + const wildcard = `${aliasPrefix}/*`; + // Read leniently (comments, trailing commas, `extends`) to learn whether the + // alias is already mapped — to `./src/*` as readily as to `./*`. + const mapped = Boolean(readTsconfigPaths(cwd)?.paths?.[wildcard]); + + // Writing is strict: a file with comments would lose them on the way back + // out, so one this cannot parse plainly is reported rather than mangled. let tsconfig = null; - try { - tsconfig = JSON.parse(raw); - } catch { - warn('tsconfig.json has comments or trailing commas — not editing it.'); + if (!mapped) { + try { + tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf8')); + } catch { + warn('tsconfig.json has comments or trailing commas — not editing it.'); + } } - const aliasPrefix = (config.aliases?.components ?? '@/components/ui').split('/')[0]; - const wildcard = `${aliasPrefix}/*`; - const needsPaths = - tsconfig !== null && !tsconfig.compilerOptions?.paths?.[wildcard]; + const needsPaths = !mapped && tsconfig !== null; if (!declarations.length && !needsPaths) { success('TypeScript already set up'); diff --git a/packages/cli/src/tsconfig.mjs b/packages/cli/src/tsconfig.mjs new file mode 100644 index 000000000..d69595e7b --- /dev/null +++ b/packages/cli/src/tsconfig.mjs @@ -0,0 +1,258 @@ +/** + * Read the project's `compilerOptions.paths`, so an alias resolves to the + * folder TypeScript and Metro resolve it to. + * + * An alias does two jobs. It is the text written into every copied import, and + * it names the folder the copied file lands in. Those only agree when the + * folder is the one the project's tsconfig maps the alias to — `@/*` → + * `./src/*` in an app with a `src/` folder, `@/*` → `./*` in one without. + * Guessing the second from the first put files where no import could find + * them. + * + * Nothing here throws. A tsconfig that cannot be read is treated as one that + * says nothing, and the caller falls back to reading the alias as a path from + * the project root. + */ +import fs from 'node:fs'; +import path from 'node:path'; + +const MAX_EXTENDS_DEPTH = 5; + +/** + * Remove comments and trailing commas from JSONC, keeping string contents + * exactly. tsconfig files routinely carry both, and `JSON.parse` takes neither. + */ +export function stripJsonc(source) { + let output = ''; + let inString = false; + + for (let index = 0; index < source.length; index++) { + const char = source[index]; + const next = source[index + 1]; + + if (inString) { + output += char; + if (char === '\\' && next !== undefined) { + output += next; + index += 1; + } else if (char === '"') { + inString = false; + } + } else if (char === '"') { + inString = true; + output += char; + } else if (char === '/' && next === '/') { + while (index < source.length && source[index] !== '\n') index += 1; + output += '\n'; + } else if (char === '/' && next === '*') { + index += 2; + while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) { + index += 1; + } + index += 1; + } else { + output += char; + } + } + + // Trailing commas second, once no comment can sit between a comma and the + // bracket after it. + return removeTrailingCommas(output); +} + +function removeTrailingCommas(source) { + let output = ''; + let inString = false; + + for (let index = 0; index < source.length; index++) { + const char = source[index]; + + if (inString) { + output += char; + if (char === '\\') { + output += source[index + 1] ?? ''; + index += 1; + } else if (char === '"') { + inString = false; + } + continue; + } + + if (char === '"') { + inString = true; + output += char; + continue; + } + + if (char === ',') { + let lookahead = index + 1; + while (/\s/.test(source[lookahead] ?? '')) lookahead += 1; + if (source[lookahead] === '}' || source[lookahead] === ']') continue; + } + + output += char; + } + + return output; +} + +function readJsonc(file) { + try { + const value = JSON.parse(stripJsonc(fs.readFileSync(file, 'utf8'))); + return value && typeof value === 'object' && !Array.isArray(value) ? value : null; + } catch { + return null; + } +} + +/** Find the file an `extends` entry names, or null. */ +function resolveExtends(specifier, fromDir, cwd) { + if (typeof specifier !== 'string' || !specifier) return null; + + const candidates = []; + if (specifier.startsWith('.') || path.isAbsolute(specifier)) { + const base = path.resolve(fromDir, specifier); + candidates.push(base, `${base}.json`, path.join(base, 'tsconfig.json')); + } else { + // A package. Look in the project's node_modules and its ancestors', as + // Node does — a workspace's dependencies are often hoisted to the root. + let dir = path.resolve(cwd); + while (true) { + const base = path.join(dir, 'node_modules', specifier); + candidates.push(base, `${base}.json`, path.join(base, 'tsconfig.json')); + const parent = path.dirname(dir); + if (parent === dir) break; + dir = parent; + } + } + + return candidates.find((file) => { + try { + return fs.statSync(file).isFile(); + } catch { + return false; + } + }) ?? null; +} + +/** + * Collect `paths` and `baseUrl` through the `extends` chain. A config's own + * values override the ones it extends, as they do in TypeScript. + */ +function collect(file, cwd, depth, seen) { + if (depth > MAX_EXTENDS_DEPTH || seen.has(file)) return {}; + seen.add(file); + + const config = readJsonc(file); + if (!config) return {}; + + const dir = path.dirname(file); + let result = {}; + + const parents = Array.isArray(config.extends) ? config.extends : [config.extends]; + for (const specifier of parents) { + const parent = resolveExtends(specifier, dir, cwd); + if (parent) result = { ...result, ...collect(parent, cwd, depth + 1, seen) }; + } + + const options = config.compilerOptions; + if (options && typeof options === 'object') { + if (typeof options.baseUrl === 'string') { + result.baseUrl = path.resolve(dir, options.baseUrl); + } + if (options.paths && typeof options.paths === 'object' && !Array.isArray(options.paths)) { + result.paths = options.paths; + result.pathsDir = dir; + } + } + + return result; +} + +/** + * The project's path mappings, or null when it has none. + * + * `baseDir` is what the targets are relative to: `baseUrl` when it is set, + * otherwise the folder of the tsconfig that declared `paths`. + */ +export function readTsconfigPaths(cwd) { + const file = ['tsconfig.json', 'jsconfig.json'] + .map((name) => path.join(cwd, name)) + .find((candidate) => fs.existsSync(candidate)); + if (!file) return null; + + try { + const { paths, pathsDir, baseUrl } = collect(file, cwd, 0, new Set()); + if (!paths) return null; + return { file: path.basename(file), paths, baseDir: baseUrl ?? pathsDir }; + } catch { + return null; + } +} + +/** + * The first target `paths` maps a specifier to, with `*` filled in, or null. + * + * An exact key wins; otherwise the wildcard key with the longest prefix, the + * order TypeScript itself uses. + */ +function matchSpecifier(specifier, paths) { + const firstTarget = (key) => { + const targets = paths[key]; + return Array.isArray(targets) && typeof targets[0] === 'string' ? targets[0] : null; + }; + + if (Object.hasOwn(paths, specifier) && !specifier.includes('*')) { + const target = firstTarget(specifier); + if (target !== null) return { key: specifier, target }; + } + + let best = null; + for (const key of Object.keys(paths)) { + const star = key.indexOf('*'); + if (star === -1 || key.indexOf('*', star + 1) !== -1) continue; + const prefix = key.slice(0, star); + const suffix = key.slice(star + 1); + if ( + specifier.length >= prefix.length + suffix.length && + specifier.startsWith(prefix) && + specifier.endsWith(suffix) && + (!best || prefix.length > best.prefix.length) + ) { + best = { key, prefix, suffix }; + } + } + + if (!best) return null; + const target = firstTarget(best.key); + if (target === null) return null; + + const matched = specifier.slice(best.prefix.length, specifier.length - best.suffix.length); + return { key: best.key, target: target.replace('*', matched) }; +} + +/** + * Where an alias directory points according to `paths`, as an absolute path, + * plus the key that matched — or null when no key covers it. + * + * `@/components/ui` is a directory, not a module, so it is matched as if a + * file inside it were being imported (`@/components/ui/x`) and the file's name + * is taken back off. That is what lets `@/*` cover it. + */ +export function resolveAliasThroughPaths(alias, mapping) { + if (!mapping?.paths) return null; + + const direct = matchSpecifier(alias, mapping.paths); + if (direct && !direct.key.includes('*')) { + return { key: direct.key, dir: path.resolve(mapping.baseDir, direct.target) }; + } + + const probe = '__panelui_probe__'; + const inside = matchSpecifier(`${alias}/${probe}`, mapping.paths); + if (!inside || !inside.target.endsWith(probe)) { + return direct ? { key: direct.key, dir: path.resolve(mapping.baseDir, direct.target) } : null; + } + + const target = inside.target.slice(0, -probe.length) || '.'; + return { key: inside.key, dir: path.resolve(mapping.baseDir, target) }; +} diff --git a/packages/cli/test/tsconfig-paths.test.mjs b/packages/cli/test/tsconfig-paths.test.mjs new file mode 100644 index 000000000..0b22f616c --- /dev/null +++ b/packages/cli/test/tsconfig-paths.test.mjs @@ -0,0 +1,191 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { + aliasSourceRoot, + aliasToDir, + applyAliases, + defaultConfig, + targetPath, +} from '../src/config.mjs'; +import { diagnose } from '../src/doctor.mjs'; +import { detectCssEntry, patchCss } from '../src/patch.mjs'; +import { stripJsonc } from '../src/tsconfig.mjs'; +import { CliError } from '../src/ui.mjs'; + +function project(files) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'panelui-cli-paths-')); + for (const [file, content] of Object.entries(files)) { + const target = path.join(root, file); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, typeof content === 'string' ? content : JSON.stringify(content)); + } + return root; +} + +function withProject(files, run) { + const root = project(files); + return Promise.resolve(run(root)).finally(() => + fs.rmSync(root, { recursive: true, force: true }) + ); +} + +const srcTsconfig = { compilerOptions: { paths: { '@/*': ['./src/*'] } } }; +const relative = (root, file) => path.relative(root, file).split(path.sep).join('/'); + +test('a src/ mapping puts files under src/ and keeps the alias in imports', () => + withProject({ 'tsconfig.json': srcTsconfig }, (root) => { + const config = defaultConfig(); + + assert.equal(relative(root, targetPath(root, config, 'ui/button.tsx')), 'src/components/ui/button.tsx'); + assert.equal(relative(root, targetPath(root, config, 'lib/cn.ts')), 'src/lib/cn.ts'); + assert.equal(relative(root, targetPath(root, config, 'hooks/use-x.ts')), 'src/hooks/use-x.ts'); + + const source = "import { Text } from '@/components/ui/text';\n"; + assert.equal(applyAliases(source, config), source); + })); + +test('a tsconfig with comments and trailing commas is read', () => + withProject( + { + 'tsconfig.json': `{ + // Expo's base, plus our alias. + "extends": "expo/tsconfig.base", + "compilerOptions": { + /* src layout */ + "paths": { "@/*": ["./src/*"], }, + "strict": true, + }, + "include": ["**/*.ts", "src/**/*.tsx", "a // not a comment"], +}`, + }, + (root) => { + assert.equal(aliasToDir('@/components/ui', root), 'src/components/ui'); + } + )); + +test('stripJsonc leaves string contents alone', () => { + const source = '{ "a": "http://x/*y*/", "b": [1, 2,], }'; + assert.deepEqual(JSON.parse(stripJsonc(source)), { a: 'http://x/*y*/', b: [1, 2] }); +}); + +test('baseUrl, exact keys and the longest prefix decide the folder', () => + withProject( + { + 'tsconfig.json': { + compilerOptions: { + baseUrl: './src', + paths: { + '@/*': ['*'], + '@/lib': ['./shared/lib'], + '@/components/*': ['./view/*'], + }, + }, + }, + }, + (root) => { + assert.equal(aliasToDir('@/hooks', root), 'src/hooks'); + assert.equal(aliasToDir('@/lib', root), 'src/shared/lib'); + assert.equal(aliasToDir('@/components/ui', root), 'src/view/ui'); + } + )); + +test('paths in an extended config are followed', () => + withProject( + { + 'tsconfig.json': { extends: './config/tsconfig.base.json' }, + 'config/tsconfig.base.json': { compilerOptions: { paths: { '~/*': ['../app/*'] } } }, + }, + (root) => { + assert.equal(aliasToDir('~/components/ui', root), 'app/components/ui'); + } + )); + +test('without a matching mapping, the alias is a path from the project root', async () => { + await withProject({}, (root) => { + assert.equal(aliasToDir('@/components/ui', root), 'components/ui'); + }); + await withProject({ 'tsconfig.json': { compilerOptions: { paths: { '#/*': ['./src/*'] } } } }, (root) => { + assert.equal(aliasToDir('@/components/ui', root), 'components/ui'); + }); + await withProject({ 'tsconfig.json': '{ not json' }, (root) => { + assert.equal(aliasToDir('@/components/ui', root), 'components/ui'); + }); +}); + +test('a mapping that leaves the project, or is not a plain path, is refused', async () => { + await withProject( + { 'tsconfig.json': { compilerOptions: { paths: { '@/*': ['../shared/*'] } } } }, + (root) => { + assert.throws(() => aliasToDir('@/components/ui', root), CliError); + assert.throws(() => targetPath(root, defaultConfig(), 'ui/button.tsx'), CliError); + } + ); + await withProject( + { 'tsconfig.json': { compilerOptions: { paths: { '@/*': ["./src';evil/*"] } } } }, + (root) => { + assert.throws(() => aliasToDir('@/components/ui', root), CliError); + } + ); +}); + +test('the @source root is the first folder under the mapping', () => + withProject({ 'tsconfig.json': srcTsconfig }, (root) => { + assert.equal(aliasSourceRoot('@/components/ui', root), 'src/components'); + assert.equal(aliasSourceRoot('@/lib', root), 'src/lib'); + })); + +test('patchCss writes paths relative to a CSS entry under src/', () => + withProject({ 'tsconfig.json': srcTsconfig }, async (root) => { + const config = { ...defaultConfig(), css: 'src/global.css', theme: 'src/theme.css' }; + await patchCss(root, config, { assumeYes: true, dryRun: false }); + + assert.equal( + fs.readFileSync(path.join(root, 'src/global.css'), 'utf8'), + [ + "@import 'tailwindcss';", + "@import 'uniwind';", + "@import './theme.css';", + "@source './components';", + "@source './lib';", + "@source './hooks';", + '', + ].join('\n') + ); + assert.equal(fs.existsSync(path.join(root, 'global.css')), false); + + fs.writeFileSync(path.join(root, 'src/theme.css'), ''); + fs.writeFileSync(path.join(root, 'panelui.json'), JSON.stringify(config)); + const css = diagnose(root).checks.find((check) => check.id === 'css'); + assert.equal(css.status, 'ok', css.message); + })); + +test('detectCssEntry reads cssEntryFile from the Metro config', () => + withProject( + { + 'metro.config.js': `const { withUniwindConfig } = require('uniwind/metro'); +// cssEntryFile: './old.css', +module.exports = withUniwindConfig(config, { cssEntryFile: './src/global.css' }); +`, + }, + (root) => { + assert.equal(detectCssEntry(root), 'src/global.css'); + } + )); + +test('detectCssEntry finds an existing entry, then falls back to the alias root', async () => { + await withProject({ 'src/global.css': "@import 'tailwindcss';\n@import 'uniwind';\n" }, (root) => { + assert.equal(detectCssEntry(root), 'src/global.css'); + }); + await withProject({ 'tsconfig.json': srcTsconfig }, (root) => { + assert.equal(detectCssEntry(root), 'src/global.css'); + }); + await withProject({}, (root) => { + assert.equal(detectCssEntry(root), 'global.css'); + }); + await withProject({ 'metro.config.js': "withUniwindConfig(c, { cssEntryFile: '../outside.css' })" }, (root) => { + assert.equal(detectCssEntry(root), 'global.css'); + }); +});