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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ coverage/
playwright-report/
test-results/
blob-report/
.knighted-css/
1 change: 1 addition & 0 deletions docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- The loader walks the module graph and gathers style-producing files (`.css`, `.scss`, `.sass`, `.less`, `.css.ts`, etc.).
- It walks the module graph with a built-in depth-first resolver so imports are visited in source order.
- Resolution is powered by [`oxc-resolver`](https://github.com/oxc-project/oxc-resolver), so tsconfig `paths`, package `exports` conditions, and extension aliasing (like `.css.js` → `.css.ts`) all map to the same targets you’d get in a bundler.
- JSX/TSX is supported: if `es-module-lexer` can’t parse a file or the extension is `.jsx`/`.tsx`, we fall back to `oxc-parser` to read imports and defaults without any user configuration.
- CSS from those files is concatenated in that discovery order and returned as `knightedCss` for injection (e.g., Lit ` css`` `, SSR, SSG).
- We do **not** sort or reorder; first-seen order is kept, so the CSS cascade mirrors the original import sequence.

Expand Down
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: 2 additions & 0 deletions packages/css/loader-queries.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
*/
declare module '*?knighted-css' {
export const knightedCss: string
export default knightedCss
}

type KnightedCssStableSelectorMap = Readonly<Record<string, string>>

declare module '*?knighted-css&types' {
export const knightedCss: string
export const stableSelectors: KnightedCssStableSelectorMap
export default knightedCss
}

/**
Expand Down
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.8",
"version": "1.0.9",
"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
17 changes: 10 additions & 7 deletions packages/css/src/generateTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import path from 'node:path'
import { createRequire } from 'node:module'
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 { analyzeModule } from './lexer.js'
import { buildStableSelectorsLiteral } from './stableSelectorsLiteral.js'
import { resolveStableNamespace } from './stableNamespace.js'

Expand Down Expand Up @@ -117,7 +117,7 @@ export async function generateTypes(
const include = normalizeIncludeOptions(options.include, rootDir)
const cacheDir = path.resolve(options.outDir ?? path.join(rootDir, '.knighted-css'))
const tsconfig = loadTsconfigResolutionContext(rootDir)
await init

await fs.mkdir(cacheDir, { recursive: true })

const internalOptions: GenerateTypesInternalOptions = {
Expand Down Expand Up @@ -296,12 +296,15 @@ async function findSpecifierImports(filePath: string): Promise<ImportMatch[]> {
return []
}
const matches: ImportMatch[] = []
const [imports] = parse(source, filePath)
for (const record of imports) {
const specifier = record.n ?? source.slice(record.s, record.e)
if (specifier && specifier.includes(SELECTOR_REFERENCE)) {
matches.push({ specifier, importer: filePath })
try {
const { imports } = await analyzeModule(source, filePath)
for (const specifier of imports) {
if (specifier.includes(SELECTOR_REFERENCE)) {
matches.push({ specifier, importer: filePath })
}
}
} catch {
// ignore and fall back to regex below
}
const requireRegex = /require\((['"])([^'"`]+?\.knighted-css[^'"`]*)\1\)/g
let reqMatch: RegExpExecArray | null
Expand Down
278 changes: 278 additions & 0 deletions packages/css/src/lexer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,278 @@
import path from 'node:path'

import { init, parse, type ImportSpecifier } from 'es-module-lexer'
import { parseSync, Visitor } from 'oxc-parser'
import type {
Argument,
ExportAllDeclaration,
ExportNamedDeclaration,
Expression,
ImportExpression,
TSExportAssignment,
TSImportEqualsDeclaration,
} from 'oxc-parser'

export type DefaultExportSignal = 'has-default' | 'no-default' | 'unknown'

interface AnalyzeOptions {
esParse?: typeof parse
}

interface ModuleAnalysis {
imports: string[]
defaultSignal: DefaultExportSignal
}

const JSX_EXTENSIONS = new Set(['.jsx', '.tsx'])

export async function analyzeModule(
sourceText: string,
filePath: string,
options?: AnalyzeOptions,
): Promise<ModuleAnalysis> {
const ext = path.extname(filePath).toLowerCase()

if (JSX_EXTENSIONS.has(ext)) {
return parseWithOxc(sourceText, filePath)
}

const esParse = options?.esParse ?? parse

try {
await init
const [imports, exports] = esParse(sourceText, filePath)
return {
imports: normalizeEsImports(imports, sourceText),
defaultSignal: classifyDefault(exports),
}
} catch {
// fall through to oxc fallback
}

return parseWithOxc(sourceText, filePath)
}

function normalizeEsImports(
records: readonly ImportSpecifier[],
sourceText: string,
): string[] {
const imports: string[] = []

for (const record of records) {
const raw = record.n ?? sourceText.slice(record.s, record.e)
const normalized = normalizeSpecifier(raw)
if (normalized) {
imports.push(normalized)
}
}

return imports
}

function classifyDefault(
exports: readonly { n: string | undefined }[],
): DefaultExportSignal {
if (exports.some(entry => entry.n === 'default')) {
return 'has-default'
}
if (exports.length === 0) {
return 'unknown'
}
return 'no-default'
}

function parseWithOxc(sourceText: string, filePath: string): ModuleAnalysis {
const ext = path.extname(filePath).toLowerCase()
const attempts: Array<{ path: string; sourceType: 'module' | 'unambiguous' }> = [
...(ext === '.js'
? [{ path: `${filePath}.tsx`, sourceType: 'module' as const }]
: []),
{ path: filePath, sourceType: 'module' },
{ path: filePath, sourceType: 'unambiguous' },
]
let program

for (const attempt of attempts) {
try {
;({ program } = parseSync(attempt.path, sourceText, {
sourceType: attempt.sourceType,
}))
break
} catch {
program = undefined
}
}

if (!program) {
return { imports: [], defaultSignal: 'unknown' }
}

const imports: string[] = []
let defaultSignal: DefaultExportSignal = 'unknown'
const addSpecifier = (raw?: string | null) => {
if (!raw) {
return
}
const normalized = normalizeSpecifier(raw)
if (normalized) {
imports.push(normalized)
}
}

const visitor = new Visitor({
ImportDeclaration(node) {
addSpecifier(node.source?.value)
},
ExportNamedDeclaration(node: ExportNamedDeclaration) {
if (node.source) {
addSpecifier(node.source.value)
}
if (hasDefaultSpecifier(node)) {
defaultSignal = 'has-default'
} else if (defaultSignal === 'unknown' && hasAnySpecifier(node)) {
defaultSignal = 'no-default'
}
},
ExportAllDeclaration(node: ExportAllDeclaration) {
addSpecifier(node.source?.value)
if (node.exported && isExportedAsDefault(node.exported)) {
defaultSignal = 'has-default'
}
},
ExportDefaultDeclaration() {
defaultSignal = 'has-default'
},
TSExportAssignment(node: TSExportAssignment) {
if (node.expression) {
defaultSignal = 'has-default'
}
},
TSImportEqualsDeclaration(node: TSImportEqualsDeclaration) {
const specifier = extractImportEqualsSpecifier(node)
if (specifier) {
addSpecifier(specifier)
}
},
ImportExpression(node: ImportExpression) {
const specifier = getStringFromExpression(node.source)
if (specifier) {
addSpecifier(specifier)
}
},
CallExpression(node) {
if (!isRequireLikeCallee(node.callee)) {
return
}
const specifier = getStringFromArgument(node.arguments[0])
if (specifier) {
addSpecifier(specifier)
}
},
})

visitor.visit(program)

return { imports, defaultSignal }
}

function normalizeSpecifier(raw: string): string {
if (!raw) return ''
const trimmed = raw.trim()
if (!trimmed || trimmed.startsWith('\0')) {
return ''
}
const querySearchOffset = trimmed.startsWith('#') ? 1 : 0
const remainder = trimmed.slice(querySearchOffset)
const queryMatchIndex = remainder.search(/[?#]/)
const queryIndex = queryMatchIndex === -1 ? -1 : querySearchOffset + queryMatchIndex
const withoutQuery = queryIndex === -1 ? trimmed : trimmed.slice(0, queryIndex)
if (!withoutQuery) {
return ''
}
if (/^[a-z][\w+.-]*:/i.test(withoutQuery) && !withoutQuery.startsWith('file:')) {
return ''
}
return withoutQuery
}

function hasDefaultSpecifier(node: ExportNamedDeclaration): boolean {
return node.specifiers?.some(spec => isExportedAsDefault(spec.exported)) ?? false
}

function hasAnySpecifier(node: ExportNamedDeclaration): boolean {
return Array.isArray(node.specifiers) && node.specifiers.length > 0
}

function isExportedAsDefault(
exported: { name?: string; value?: string } | null | undefined,
): boolean {
if (!exported) return false
if (typeof exported.name === 'string' && exported.name === 'default') {
return true
}
if (typeof exported.value === 'string' && exported.value === 'default') {
return true
}
return false
}

function extractImportEqualsSpecifier(
node: TSImportEqualsDeclaration,
): string | undefined {
if (node.moduleReference.type === 'TSExternalModuleReference') {
return node.moduleReference.expression.value
}
return undefined
}

function getStringFromArgument(argument: Argument | undefined): string | undefined {
if (!argument || argument.type === 'SpreadElement') {
return undefined
}
return getStringFromExpression(argument)
}

function getStringFromExpression(
expression: Expression | null | undefined,
): string | undefined {
if (!expression) {
return undefined
}
if (expression.type === 'Literal') {
const literalValue = (expression as { value: unknown }).value
return typeof literalValue === 'string' ? literalValue : undefined
}
if (expression.type === 'TemplateLiteral' && expression.expressions.length === 0) {
const [first] = expression.quasis
return first?.value.cooked ?? first?.value.raw ?? undefined
}
return undefined
}

function isRequireLikeCallee(expression: Expression): boolean {
const target = unwrapExpression(expression)
if (target.type === 'Identifier') {
return target.name === 'require'
}
if (target.type === 'MemberExpression') {
const object = target.object
if (object.type === 'Identifier') {
return object.name === 'require'
}
}
return false
}

function unwrapExpression(expression: Expression): Expression {
if (expression.type === 'ChainExpression') {
const inner = expression.expression as Expression
if (inner.type === 'CallExpression') {
return unwrapExpression(inner.callee)
}
return unwrapExpression(inner)
}
if (expression.type === 'TSNonNullExpression') {
return unwrapExpression(expression.expression)
}
return expression
}
Loading