Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/css/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@knighted/css",
"version": "1.0.0-rc.9",
"version": "1.0.0-rc.10",
"description": "A build-time utility that traverses JavaScript/TypeScript module dependency graphs to extract, compile, and optimize all imported CSS into a single, in-memory string.",
"type": "module",
"main": "./dist/css.js",
Expand Down
146 changes: 143 additions & 3 deletions packages/css/src/generateTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
import { init, parse } from 'es-module-lexer'
import { moduleType } from 'node-module-type'

import { getTsconfig, type TsConfigResult } from 'get-tsconfig'
import { createMatchPath, type MatchPath } from 'tsconfig-paths'

import { cssWithMeta } from './css.js'
import {
determineSelectorVariant,
Expand Down Expand Up @@ -34,12 +37,22 @@ interface DeclarationRecord {
filePath: string
}

interface TsconfigResolutionContext {
absoluteBaseUrl?: string
matchPath?: MatchPath
}

type CssWithMetaFn = typeof cssWithMeta

let activeCssWithMeta: CssWithMetaFn = cssWithMeta

interface GenerateTypesInternalOptions {
rootDir: string
include: string[]
outDir: string
typesRoot: string
stableNamespace?: string
tsconfig?: TsconfigResolutionContext
}

export interface GenerateTypesResult {
Expand Down Expand Up @@ -84,12 +97,17 @@ const SUPPORTED_EXTENSIONS = new Set([
'.cjs',
])

type ModuleTypeDetector = () => ReturnType<typeof moduleType>

let moduleTypeDetector: ModuleTypeDetector = moduleType
let importMetaUrlProvider: () => string | undefined = getImportMetaUrl

function resolvePackageRoot(): string {
const detectedType = moduleType()
const detectedType = moduleTypeDetector()
if (detectedType === 'commonjs' && typeof __dirname === 'string') {
return path.resolve(__dirname, '..')
}
const moduleUrl = getImportMetaUrl()
const moduleUrl = importMetaUrlProvider()
if (moduleUrl) {
return path.resolve(path.dirname(fileURLToPath(moduleUrl)), '..')
}
Expand All @@ -115,6 +133,7 @@ export async function generateTypes(
const include = normalizeIncludeOptions(options.include, rootDir)
const outDir = path.resolve(options.outDir ?? DEFAULT_OUT_DIR)
const typesRoot = path.resolve(options.typesRoot ?? DEFAULT_TYPES_ROOT)
const tsconfig = loadTsconfigResolutionContext(rootDir)
await init
await fs.mkdir(outDir, { recursive: true })
await fs.mkdir(typesRoot, { recursive: true })
Expand All @@ -125,6 +144,7 @@ export async function generateTypes(
outDir,
typesRoot,
stableNamespace: options.stableNamespace,
tsconfig,
}

return generateDeclarations(internalOptions)
Expand Down Expand Up @@ -162,6 +182,7 @@ async function generateDeclarations(
resource,
match.importer,
options.rootDir,
options.tsconfig,
)
if (!resolvedPath) {
warnings.push(
Expand All @@ -174,7 +195,7 @@ async function generateDeclarations(
let selectorMap = selectorCache.get(cacheKey)
if (!selectorMap) {
try {
const { css } = await cssWithMeta(resolvedPath, {
const { css } = await activeCssWithMeta(resolvedPath, {
cwd: options.rootDir,
peerResolver,
})
Expand Down Expand Up @@ -342,6 +363,7 @@ async function resolveImportPath(
resourceSpecifier: string,
importerPath: string,
rootDir: string,
tsconfig?: TsconfigResolutionContext,
): Promise<string | undefined> {
if (!resourceSpecifier) return undefined
if (resourceSpecifier.startsWith('.')) {
Expand All @@ -350,6 +372,10 @@ async function resolveImportPath(
if (resourceSpecifier.startsWith('/')) {
return path.resolve(rootDir, resourceSpecifier.slice(1))
}
const tsconfigResolved = await resolveWithTsconfigPaths(resourceSpecifier, tsconfig)
if (tsconfigResolved) {
return tsconfigResolved
}
const requireFromRoot = getProjectRequire(rootDir)
try {
return requireFromRoot.resolve(resourceSpecifier)
Expand Down Expand Up @@ -491,6 +517,93 @@ async function fileExists(target: string): Promise<boolean> {
}
}

async function resolveWithTsconfigPaths(
specifier: string,
tsconfig?: TsconfigResolutionContext,
): Promise<string | undefined> {
if (!tsconfig) {
return undefined
}
if (tsconfig.matchPath) {
const matched = tsconfig.matchPath(specifier)
if (matched && (await fileExists(matched))) {
return matched
}
}
if (tsconfig.absoluteBaseUrl && isNonRelativeSpecifier(specifier)) {
const candidate = path.join(
tsconfig.absoluteBaseUrl,
specifier.split('/').join(path.sep),
)
if (await fileExists(candidate)) {
return candidate
}
}
return undefined
}

function loadTsconfigResolutionContext(
rootDir: string,
loader: typeof getTsconfig = getTsconfig,
): TsconfigResolutionContext | undefined {
let result: TsConfigResult | null
try {
result = loader(rootDir) as TsConfigResult | null
} catch {
return undefined
}
if (!result) {
return undefined
}
const compilerOptions = result.config.compilerOptions ?? {}
const configDir = path.dirname(result.path)
const absoluteBaseUrl = compilerOptions.baseUrl
? path.resolve(configDir, compilerOptions.baseUrl)
: undefined
const normalizedPaths = normalizeTsconfigPaths(compilerOptions.paths)
const matchPath =
absoluteBaseUrl && normalizedPaths
? createMatchPath(absoluteBaseUrl, normalizedPaths)
: undefined
if (!absoluteBaseUrl && !matchPath) {
return undefined
}
return { absoluteBaseUrl, matchPath }
}

function normalizeTsconfigPaths(
paths: Record<string, string[] | string> | undefined,
): Record<string, string[]> | undefined {
if (!paths) {
return undefined
}
const normalized: Record<string, string[]> = {}
for (const [pattern, replacements] of Object.entries(paths)) {
if (!replacements) {
continue
}
const values = Array.isArray(replacements) ? replacements : [replacements]
if (values.length === 0) {
continue
}
normalized[pattern] = values
}
return Object.keys(normalized).length > 0 ? normalized : undefined
}

function isNonRelativeSpecifier(specifier: string): boolean {
if (!specifier) {
return false
}
if (specifier.startsWith('.') || specifier.startsWith('/')) {
return false
}
if (/^[a-z][\w+.-]*:/i.test(specifier)) {
return false
}
return true
}

function createProjectPeerResolver(rootDir: string) {
const resolver = getProjectRequire(rootDir)
return async (name: string) => {
Expand Down Expand Up @@ -643,13 +756,40 @@ function reportCliResult(result: GenerateTypesResult): void {
}
}

function setCssWithMetaImplementation(impl?: CssWithMetaFn): void {
activeCssWithMeta = impl ?? cssWithMeta
}

function setModuleTypeDetector(detector?: ModuleTypeDetector): void {
moduleTypeDetector = detector ?? moduleType
}

function setImportMetaUrlProvider(provider?: () => string | undefined): void {
importMetaUrlProvider = provider ?? getImportMetaUrl
}

export const __generateTypesInternals = {
writeTypesIndex,
stripInlineLoader,
splitResourceAndQuery,
findSpecifierImports,
resolveImportPath,
resolvePackageRoot,
buildDeclarationFileName,
formatModuleDeclaration,
formatSelectorType,
relativeToRoot,
collectCandidateFiles,
normalizeIncludeOptions,
normalizeTsconfigPaths,
setCssWithMetaImplementation,
setModuleTypeDetector,
setImportMetaUrlProvider,
isNonRelativeSpecifier,
createProjectPeerResolver,
getProjectRequire,
loadTsconfigResolutionContext,
resolveWithTsconfigPaths,
parseCliArgs,
printHelp,
reportCliResult,
Expand Down
Loading