mirror of
https://github.com/giancarloerra/socraticode.git
synced 2026-07-03 14:05:21 +02:00
feat: add CSS @import tracking and path alias resolution to dependency graph
Add CSS @import extraction from Svelte/Vue <style> blocks and standalone CSS/SCSS/SASS/LESS files. Add path alias resolution from tsconfig.json / jsconfig.json compilerOptions.paths with extends chain support.
This commit is contained in:
@@ -8,6 +8,7 @@ import { Lang, registerDynamicLanguage } from "@ast-grep/napi";
|
||||
import { graphCollectionName, projectIdFromPath } from "../config.js";
|
||||
import { EXTRA_EXTENSIONS, getLanguageFromExtension, MAX_GRAPH_FILE_BYTES } from "../constants.js";
|
||||
import type { CodeGraph, CodeGraphEdge, CodeGraphNode } from "../types.js";
|
||||
import { loadPathAliases } from "./graph-aliases.js";
|
||||
import { extractImports } from "./graph-imports.js";
|
||||
import { resolveImport } from "./graph-resolution.js";
|
||||
import { createIgnoreFilter, shouldIgnore } from "./ignore.js";
|
||||
@@ -313,7 +314,7 @@ export function getAstGrepLang(ext: string): Lang | string | null {
|
||||
".ts": Lang.TypeScript,
|
||||
".tsx": Lang.Tsx,
|
||||
".html": Lang.Html, ".htm": Lang.Html,
|
||||
".css": Lang.Css, ".scss": Lang.Css,
|
||||
".css": Lang.Css, ".scss": Lang.Css, ".sass": Lang.Css, ".less": Lang.Css,
|
||||
};
|
||||
return map[ext] ?? null;
|
||||
}
|
||||
@@ -375,6 +376,7 @@ export async function buildCodeGraph(
|
||||
ensureDynamicLanguages();
|
||||
|
||||
const resolvedPath = path.resolve(projectPath);
|
||||
const aliases = await loadPathAliases(resolvedPath);
|
||||
const files = await getGraphableFiles(resolvedPath, extraExtensions);
|
||||
const fileSet = new Set(files);
|
||||
|
||||
@@ -444,7 +446,9 @@ export async function buildCodeGraph(
|
||||
node.imports.push(imp.moduleSpecifier);
|
||||
|
||||
// Try to resolve to a project file
|
||||
const resolved = resolveImport(imp.moduleSpecifier, absolutePath, resolvedPath, fileSet, language);
|
||||
// CSS imports from <style> blocks use CSS resolution even when the source file is Svelte/Vue
|
||||
const resolutionLanguage = imp.isCssImport ? "css" : language;
|
||||
const resolved = resolveImport(imp.moduleSpecifier, absolutePath, resolvedPath, fileSet, resolutionLanguage, aliases);
|
||||
if (resolved) {
|
||||
node.dependencies.push(resolved);
|
||||
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { logger } from "./logger.js";
|
||||
|
||||
// ── Path alias resolution ────────────────────────────────────────────────
|
||||
|
||||
/** Resolved path aliases from tsconfig/jsconfig */
|
||||
export interface PathAliases {
|
||||
/** Map of alias prefix → target directories (relative to project root) */
|
||||
entries: Map<string, string[]>;
|
||||
}
|
||||
|
||||
/** Empty aliases constant for when no config is found */
|
||||
const EMPTY_ALIASES: PathAliases = { entries: new Map() };
|
||||
|
||||
/**
|
||||
* Load path aliases from tsconfig.json or jsconfig.json.
|
||||
* Parses `compilerOptions.paths` and `compilerOptions.baseUrl` to build
|
||||
* a prefix → directory mapping used during import resolution.
|
||||
* Follows `extends` chains to find paths in parent configs.
|
||||
*
|
||||
* Returns empty aliases if no config is found (graceful degradation).
|
||||
*/
|
||||
export async function loadPathAliases(projectPath: string): Promise<PathAliases> {
|
||||
const configNames = ["tsconfig.json", "jsconfig.json"];
|
||||
|
||||
for (const name of configNames) {
|
||||
const configPath = path.join(projectPath, name);
|
||||
try {
|
||||
const raw = await fs.readFile(configPath, "utf-8");
|
||||
const aliases = parsePathAliases(raw, projectPath);
|
||||
if (aliases.entries.size > 0) {
|
||||
logger.info("Loaded path aliases", {
|
||||
config: name,
|
||||
aliases: Array.from(aliases.entries.keys()),
|
||||
});
|
||||
return aliases;
|
||||
}
|
||||
// Config exists but has no paths — follow extends chain
|
||||
const extended = await followExtendsChain(configPath, projectPath);
|
||||
if (extended.entries.size > 0) {
|
||||
logger.info("Loaded path aliases via extends", {
|
||||
config: name,
|
||||
aliases: Array.from(extended.entries.keys()),
|
||||
});
|
||||
return extended;
|
||||
}
|
||||
// No paths in entire chain — try next config file
|
||||
} catch {
|
||||
// Config not found — try next
|
||||
}
|
||||
}
|
||||
|
||||
return EMPTY_ALIASES;
|
||||
}
|
||||
|
||||
/** Maximum depth for tsconfig extends chains to prevent circular references */
|
||||
const MAX_EXTENDS_DEPTH = 10;
|
||||
|
||||
/**
|
||||
* Follow the `extends` chain of a tsconfig/jsconfig looking for `compilerOptions.paths`.
|
||||
* Resolves relative paths and package references. Caps at MAX_EXTENDS_DEPTH.
|
||||
*/
|
||||
async function followExtendsChain(
|
||||
configPath: string,
|
||||
projectPath: string,
|
||||
): Promise<PathAliases> {
|
||||
const visited = new Set<string>();
|
||||
let currentPath = configPath;
|
||||
|
||||
for (let depth = 0; depth < MAX_EXTENDS_DEPTH; depth++) {
|
||||
const resolved = path.resolve(currentPath);
|
||||
if (visited.has(resolved)) break; // circular
|
||||
visited.add(resolved);
|
||||
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await fs.readFile(resolved, "utf-8");
|
||||
} catch {
|
||||
break; // file not found
|
||||
}
|
||||
|
||||
const config = parseTsconfigJson(raw);
|
||||
if (!config) break;
|
||||
|
||||
// Check if this config has paths
|
||||
const co = config.compilerOptions as Record<string, unknown> | undefined;
|
||||
if (co?.paths) {
|
||||
const configDir = path.dirname(resolved);
|
||||
return parsePathAliases(raw, configDir);
|
||||
}
|
||||
|
||||
// Follow extends
|
||||
const extendsValue = config.extends;
|
||||
if (!extendsValue || typeof extendsValue !== "string") break;
|
||||
|
||||
const configDir = path.dirname(resolved);
|
||||
if (extendsValue.startsWith(".")) {
|
||||
// Relative path: "./tsconfig.base.json"
|
||||
currentPath = path.resolve(configDir, extendsValue);
|
||||
// Add .json if missing
|
||||
if (!currentPath.endsWith(".json")) currentPath += ".json";
|
||||
} else {
|
||||
// Package reference: "@tsconfig/node20/tsconfig.json"
|
||||
// Try to resolve from node_modules
|
||||
try {
|
||||
currentPath = path.resolve(configDir, "node_modules", extendsValue);
|
||||
if (!currentPath.endsWith(".json")) currentPath += ".json";
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return EMPTY_ALIASES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse tsconfig/jsconfig JSON with comment stripping.
|
||||
* Returns null if parsing fails.
|
||||
*/
|
||||
export function parseTsconfigJson(jsonContent: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const stripped = jsonContent.replace(
|
||||
/"(?:[^"\\]|\\.)*"|\/\/.*$|\/\*[\s\S]*?\*\//gm,
|
||||
(match) => match.startsWith('"') ? match : "",
|
||||
);
|
||||
return JSON.parse(stripped);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse path aliases from tsconfig/jsconfig JSON content.
|
||||
* Handles JSON with comments (// and /* ... *\/) which tsconfig allows.
|
||||
*/
|
||||
export function parsePathAliases(jsonContent: string, projectPath: string): PathAliases {
|
||||
const entries = new Map<string, string[]>();
|
||||
|
||||
try {
|
||||
const config = parseTsconfigJson(jsonContent);
|
||||
if (!config) return EMPTY_ALIASES;
|
||||
|
||||
const compilerOptions = config.compilerOptions as Record<string, unknown> | undefined;
|
||||
if (!compilerOptions?.paths) return EMPTY_ALIASES;
|
||||
|
||||
const baseUrl = (compilerOptions.baseUrl as string) ?? ".";
|
||||
const baseDir = path.resolve(projectPath, baseUrl);
|
||||
const paths = compilerOptions.paths as Record<string, string[]>;
|
||||
|
||||
for (const [pattern, targets] of Object.entries(paths)) {
|
||||
if (!Array.isArray(targets) || targets.length === 0) continue;
|
||||
|
||||
// Convert wildcard pattern: "$lib/*" → prefix "$lib/"
|
||||
// Convert exact pattern: "~" → prefix "~"
|
||||
const prefix = pattern.endsWith("/*")
|
||||
? pattern.slice(0, -1) // "$lib/*" → "$lib/"
|
||||
: pattern;
|
||||
|
||||
const resolvedTargets: string[] = [];
|
||||
for (const target of targets) {
|
||||
if (typeof target !== "string") continue;
|
||||
// Convert wildcard target: "src/lib/*" → "src/lib/"
|
||||
// Convert exact target: "./src" → "src"
|
||||
const targetPath = target.endsWith("/*")
|
||||
? target.slice(0, -1) // "src/lib/*" → "src/lib/"
|
||||
: target;
|
||||
|
||||
// Resolve relative to baseUrl, then make relative to project root
|
||||
const absolute = path.resolve(baseDir, targetPath);
|
||||
const relative = path.relative(projectPath, absolute);
|
||||
resolvedTargets.push(relative);
|
||||
}
|
||||
|
||||
if (resolvedTargets.length > 0) {
|
||||
entries.set(prefix, resolvedTargets);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("Failed to parse path aliases from config", { error: String(err) });
|
||||
}
|
||||
|
||||
return { entries };
|
||||
}
|
||||
@@ -8,6 +8,25 @@ import { logger } from "./logger.js";
|
||||
export interface ImportInfo {
|
||||
moduleSpecifier: string; // The raw import string
|
||||
isDynamic: boolean;
|
||||
isCssImport?: boolean; // True when extracted from a CSS/style context
|
||||
}
|
||||
|
||||
/** Extract CSS/SCSS/Stylus @import statements from raw style source text. */
|
||||
function extractCssImports(source: string): ImportInfo[] {
|
||||
const imports: ImportInfo[] = [];
|
||||
// CSS/SCSS: @import "./foo.css"; @import url("./foo.css");
|
||||
for (const match of source.matchAll(/@import\s+(?:url\(\s*)?['"]([^'"]+)['"]\s*\)?/gm)) {
|
||||
const spec = match[1];
|
||||
if (spec.startsWith("http://") || spec.startsWith("https://")) continue;
|
||||
imports.push({ moduleSpecifier: spec, isDynamic: false, isCssImport: true });
|
||||
}
|
||||
// Stylus: @require "foo" (quoted form only; bare-identifier syntax not supported)
|
||||
for (const match of source.matchAll(/@require\s+['"]([^'"]+)['"]/gm)) {
|
||||
const spec = match[1];
|
||||
if (spec.startsWith("http://") || spec.startsWith("https://")) continue;
|
||||
imports.push({ moduleSpecifier: spec, isDynamic: false, isCssImport: true });
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
|
||||
/** Extract JS/TS imports from an ast-grep root node. Shared by JS/TS and Svelte/Vue handlers. */
|
||||
@@ -100,6 +119,13 @@ export function extractImports(source: string, lang: Lang | string, _ext: string
|
||||
const scriptRoot = parse(Lang.TypeScript, scriptContent).root();
|
||||
imports.push(...extractJsTsImportsFromNode(scriptRoot));
|
||||
}
|
||||
|
||||
// Also extract CSS @import from <style> blocks
|
||||
const styleElements = htmlRoot.findAll({ rule: { kind: "style_element" } });
|
||||
for (const styleEl of styleElements) {
|
||||
const rawText = styleEl.find({ rule: { kind: "raw_text" } });
|
||||
if (rawText) imports.push(...extractCssImports(rawText.text()));
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("Failed to parse Svelte/Vue file for imports", { error: String(err) });
|
||||
}
|
||||
@@ -134,6 +160,11 @@ export function extractImports(source: string, lang: Lang | string, _ext: string
|
||||
break;
|
||||
}
|
||||
|
||||
case "Css": {
|
||||
imports.push(...extractCssImports(source));
|
||||
break;
|
||||
}
|
||||
|
||||
case "JavaScript":
|
||||
case "TypeScript":
|
||||
case "Tsx": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
import path from "node:path";
|
||||
import type { PathAliases } from "./graph-aliases.js";
|
||||
|
||||
// ── Module resolution ────────────────────────────────────────────────────
|
||||
|
||||
@@ -14,6 +15,7 @@ export function resolveImport(
|
||||
projectPath: string,
|
||||
fileSet: Set<string>,
|
||||
language: string,
|
||||
aliases?: PathAliases,
|
||||
): string | null {
|
||||
// Skip obvious external/stdlib modules
|
||||
if (isExternalModule(moduleSpecifier, language)) return null;
|
||||
@@ -25,13 +27,26 @@ export function resolveImport(
|
||||
case "typescript":
|
||||
case "svelte":
|
||||
case "vue": {
|
||||
const jsExtensions = [".svelte", ".vue", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
|
||||
// Relative imports: ./foo, ../bar
|
||||
if (moduleSpecifier.startsWith(".")) {
|
||||
return resolveRelativePath(moduleSpecifier, sourceDir, projectPath, fileSet, [
|
||||
".svelte", ".vue", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
|
||||
]);
|
||||
return resolveRelativePath(moduleSpecifier, sourceDir, projectPath, fileSet, jsExtensions);
|
||||
}
|
||||
return null; // npm packages
|
||||
// Try path alias resolution
|
||||
return resolveAliasPath(moduleSpecifier, projectPath, fileSet, jsExtensions, aliases);
|
||||
}
|
||||
|
||||
case "css":
|
||||
case "scss":
|
||||
case "sass":
|
||||
case "less": {
|
||||
const cssExtensions = [".css", ".scss", ".sass", ".less", ".styl"];
|
||||
// CSS @import: ./variables.css, ../mixins.scss
|
||||
if (moduleSpecifier.startsWith(".")) {
|
||||
return resolveRelativePath(moduleSpecifier, sourceDir, projectPath, fileSet, cssExtensions);
|
||||
}
|
||||
// Try path alias resolution (e.g., $lib/styles/vars.css)
|
||||
return resolveAliasPath(moduleSpecifier, projectPath, fileSet, cssExtensions, aliases);
|
||||
}
|
||||
|
||||
case "python": {
|
||||
@@ -240,6 +255,36 @@ function isExternalModule(spec: string, language: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/** Try resolving a module specifier via path aliases (tsconfig/jsconfig paths) */
|
||||
function resolveAliasPath(
|
||||
moduleSpecifier: string,
|
||||
projectPath: string,
|
||||
fileSet: Set<string>,
|
||||
extensions: string[],
|
||||
aliases?: PathAliases,
|
||||
): string | null {
|
||||
if (!aliases?.entries) return null;
|
||||
for (const [prefix, targets] of aliases.entries) {
|
||||
// Wildcard aliases end with "/" (from "$lib/*") — match as prefix
|
||||
// Exact aliases (no trailing "/") — match only the exact specifier
|
||||
const isWildcard = prefix.endsWith("/");
|
||||
const matches = isWildcard
|
||||
? moduleSpecifier.startsWith(prefix)
|
||||
: moduleSpecifier === prefix;
|
||||
|
||||
if (matches) {
|
||||
const rest = moduleSpecifier.slice(prefix.length);
|
||||
for (const target of targets) {
|
||||
const resolved = resolveRelativePath(
|
||||
path.join(target, rest), projectPath, projectPath, fileSet, extensions,
|
||||
);
|
||||
if (resolved) return resolved;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Resolve a potentially extensionless path to an actual file */
|
||||
function resolveRelativePath(
|
||||
modulePath: string,
|
||||
@@ -279,6 +324,22 @@ function resolveRelativePath(
|
||||
if (fileSet.has(indexFile)) return indexFile;
|
||||
}
|
||||
|
||||
// SCSS/Sass partial: @import "variables" → _variables.scss
|
||||
if (extensions.some((e) => [".scss", ".sass", ".less", ".styl"].includes(e))) {
|
||||
const dir = path.dirname(relPath);
|
||||
const base = path.basename(relPath);
|
||||
if (!base.startsWith("_")) {
|
||||
// Try _name (direct)
|
||||
const partial = path.join(dir, `_${base}`);
|
||||
if (fileSet.has(partial)) return partial;
|
||||
// Try _name with extensions
|
||||
for (const ext of extensions) {
|
||||
const partialExt = path.join(dir, `_${base}${ext}`);
|
||||
if (fileSet.has(partialExt)) return partialExt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Python: try __init__.py
|
||||
if (extensions.includes(".py")) {
|
||||
const initFile = path.join(relPath, "__init__.py");
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { loadPathAliases, parsePathAliases } from "../../src/services/graph-aliases.js";
|
||||
|
||||
describe("parsePathAliases", () => {
|
||||
const projectPath = "/project";
|
||||
|
||||
it("parses tsconfig paths with wildcard patterns", () => {
|
||||
const json = JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: {
|
||||
"$lib/*": ["src/lib/*"],
|
||||
"@/*": ["./src/*"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.get("$lib/")).toEqual(["src/lib"]);
|
||||
expect(aliases.entries.get("@/")).toEqual(["src"]);
|
||||
});
|
||||
|
||||
it("respects baseUrl", () => {
|
||||
const json = JSON.stringify({
|
||||
compilerOptions: {
|
||||
baseUrl: "./app",
|
||||
paths: {
|
||||
"@/*": ["src/*"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.get("@/")).toEqual([path.join("app", "src")]);
|
||||
});
|
||||
|
||||
it("handles exact (non-wildcard) patterns", () => {
|
||||
const json = JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: {
|
||||
"~": ["./src"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.get("~")).toEqual(["src"]);
|
||||
});
|
||||
|
||||
it("handles multiple targets for a single alias", () => {
|
||||
const json = JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: {
|
||||
"@/*": ["src/*", "generated/*"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.get("@/")).toEqual(["src", "generated"]);
|
||||
});
|
||||
|
||||
it("handles JSON with single-line comments", () => {
|
||||
const json = `{
|
||||
// This is a comment
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"$lib/*": ["src/lib/*"] // inline comment
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.get("$lib/")).toEqual(["src/lib"]);
|
||||
});
|
||||
|
||||
it("handles JSON with multi-line comments", () => {
|
||||
const json = `{
|
||||
/* Multi-line
|
||||
comment */
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.get("@/")).toEqual(["src"]);
|
||||
});
|
||||
|
||||
it("preserves // inside string values when stripping comments", () => {
|
||||
const json = `{
|
||||
// comment
|
||||
"compilerOptions": {
|
||||
"baseUrl": "./dist//subdir", // trailing comment
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.get("@/")).toEqual([path.join("dist//subdir", "src")]);
|
||||
});
|
||||
|
||||
it("returns empty entries for config without paths", () => {
|
||||
const json = JSON.stringify({
|
||||
compilerOptions: {
|
||||
strict: true,
|
||||
},
|
||||
});
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.size).toBe(0);
|
||||
});
|
||||
|
||||
it("returns empty entries for invalid JSON", () => {
|
||||
const aliases = parsePathAliases("not json at all", projectPath);
|
||||
|
||||
expect(aliases.entries.size).toBe(0);
|
||||
});
|
||||
|
||||
it("skips entries with empty targets array", () => {
|
||||
const json = JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: {
|
||||
"@/*": [],
|
||||
"$lib/*": ["src/lib/*"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.has("@/")).toBe(false);
|
||||
expect(aliases.entries.get("$lib/")).toEqual(["src/lib"]);
|
||||
});
|
||||
|
||||
it("skips non-string targets gracefully", () => {
|
||||
const json = '{"compilerOptions":{"paths":{"@/*":[42, null, "./src/*"]}}}';
|
||||
|
||||
const aliases = parsePathAliases(json, projectPath);
|
||||
|
||||
expect(aliases.entries.get("@/")).toEqual(["src"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loadPathAliases", () => {
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
if (tmpDir) {
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ }
|
||||
tmpDir = null;
|
||||
}
|
||||
});
|
||||
|
||||
it("returns empty aliases for non-existent project", async () => {
|
||||
const aliases = await loadPathAliases("/non/existent/path");
|
||||
|
||||
expect(aliases.entries.size).toBe(0);
|
||||
});
|
||||
|
||||
it("reads aliases from tsconfig.json", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.json"), JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: { "$lib/*": ["src/lib/*"] },
|
||||
},
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
expect(aliases.entries.get("$lib/")).toEqual(["src/lib"]);
|
||||
});
|
||||
|
||||
it("falls back to jsconfig.json when tsconfig.json is absent", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "jsconfig.json"), JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: { "@/*": ["./src/*"] },
|
||||
},
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
expect(aliases.entries.get("@/")).toEqual(["src"]);
|
||||
});
|
||||
|
||||
it("falls through to jsconfig.json when tsconfig.json has no paths", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.json"), JSON.stringify({
|
||||
compilerOptions: { strict: true },
|
||||
}));
|
||||
fs.writeFileSync(path.join(tmpDir, "jsconfig.json"), JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: { "@/*": ["./src/*"] },
|
||||
},
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
expect(aliases.entries.get("@/")).toEqual(["src"]);
|
||||
});
|
||||
|
||||
it("prefers tsconfig.json over jsconfig.json", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.json"), JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: { "$lib/*": ["src/lib/*"] },
|
||||
},
|
||||
}));
|
||||
fs.writeFileSync(path.join(tmpDir, "jsconfig.json"), JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: { "@/*": ["./src/*"] },
|
||||
},
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
// Should use tsconfig.json paths, not jsconfig.json
|
||||
expect(aliases.entries.has("$lib/")).toBe(true);
|
||||
expect(aliases.entries.has("@/")).toBe(false);
|
||||
});
|
||||
|
||||
it("follows extends chain to find paths in parent config", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.json"), JSON.stringify({
|
||||
extends: "./tsconfig.base.json",
|
||||
compilerOptions: { strict: true },
|
||||
}));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.base.json"), JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: { "$lib/*": ["src/lib/*"] },
|
||||
},
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
expect(aliases.entries.get("$lib/")).toEqual(["src/lib"]);
|
||||
});
|
||||
|
||||
it("follows multi-level extends chain", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.json"), JSON.stringify({
|
||||
extends: "./tsconfig.app.json",
|
||||
}));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.app.json"), JSON.stringify({
|
||||
extends: "./tsconfig.base.json",
|
||||
compilerOptions: { strict: true },
|
||||
}));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.base.json"), JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: { "@/*": ["src/*"] },
|
||||
},
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
expect(aliases.entries.get("@/")).toEqual(["src"]);
|
||||
});
|
||||
|
||||
it("handles extends without .json extension", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.json"), JSON.stringify({
|
||||
extends: "./base",
|
||||
}));
|
||||
fs.writeFileSync(path.join(tmpDir, "base.json"), JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: { "$lib/*": ["src/lib/*"] },
|
||||
},
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
expect(aliases.entries.get("$lib/")).toEqual(["src/lib"]);
|
||||
});
|
||||
|
||||
it("handles circular extends gracefully", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.json"), JSON.stringify({
|
||||
extends: "./tsconfig.base.json",
|
||||
}));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.base.json"), JSON.stringify({
|
||||
extends: "./tsconfig.json",
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
// Should not infinite loop, returns empty
|
||||
expect(aliases.entries.size).toBe(0);
|
||||
});
|
||||
|
||||
it("stops when extended file does not exist", async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "socraticode-aliases-"));
|
||||
fs.writeFileSync(path.join(tmpDir, "tsconfig.json"), JSON.stringify({
|
||||
extends: "./nonexistent.json",
|
||||
}));
|
||||
|
||||
const aliases = await loadPathAliases(tmpDir);
|
||||
|
||||
expect(aliases.entries.size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -188,6 +188,228 @@ function hello() {
|
||||
});
|
||||
});
|
||||
|
||||
// ── CSS @import in Svelte/Vue <style> blocks ────────────────────────────
|
||||
|
||||
describe("CSS @import in Svelte style blocks", () => {
|
||||
it("extracts @import from <style> block", () => {
|
||||
const source = `
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@import "./variables.css";
|
||||
@import "../mixins.scss";
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "svelte", ".svelte");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).toContain("svelte");
|
||||
expect(specs).toContain("./variables.css");
|
||||
expect(specs).toContain("../mixins.scss");
|
||||
});
|
||||
|
||||
it("extracts @import url(...) variant", () => {
|
||||
const source = `
|
||||
<style>
|
||||
@import url("./theme.css");
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "svelte", ".svelte");
|
||||
expect(imports.some((i) => i.moduleSpecifier === "./theme.css")).toBe(true);
|
||||
});
|
||||
|
||||
it("skips external URLs", () => {
|
||||
const source = `
|
||||
<style>
|
||||
@import "https://fonts.googleapis.com/css2?family=Inter";
|
||||
@import "./local.css";
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "svelte", ".svelte");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).not.toContain("https://fonts.googleapis.com/css2?family=Inter");
|
||||
expect(specs).toContain("./local.css");
|
||||
});
|
||||
|
||||
it("extracts @import from <style global>", () => {
|
||||
const source = `
|
||||
<style global>
|
||||
@import "./global-reset.css";
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "svelte", ".svelte");
|
||||
expect(imports.some((i) => i.moduleSpecifier === "./global-reset.css")).toBe(true);
|
||||
});
|
||||
|
||||
it("marks CSS imports with isCssImport flag", () => {
|
||||
const source = `
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@import "./variables.css";
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "svelte", ".svelte");
|
||||
const jsImport = imports.find((i) => i.moduleSpecifier === "svelte");
|
||||
const cssImport = imports.find((i) => i.moduleSpecifier === "./variables.css");
|
||||
|
||||
expect(jsImport?.isCssImport).toBeFalsy();
|
||||
expect(cssImport?.isCssImport).toBe(true);
|
||||
});
|
||||
|
||||
it("handles no style block", () => {
|
||||
const source = `
|
||||
<script>
|
||||
import { writable } from "svelte/store";
|
||||
</script>
|
||||
<div>content</div>
|
||||
`;
|
||||
const imports = extractImports(source, "svelte", ".svelte");
|
||||
// Should only have script imports, no CSS imports
|
||||
expect(imports).toHaveLength(1);
|
||||
expect(imports[0].moduleSpecifier).toBe("svelte/store");
|
||||
});
|
||||
});
|
||||
|
||||
describe("CSS @import in Vue style blocks", () => {
|
||||
it("extracts @import from <style> block", () => {
|
||||
const source = `
|
||||
<script lang="ts">
|
||||
import { ref } from "vue";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>content</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
@import "./component.css";
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "vue", ".vue");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).toContain("vue");
|
||||
expect(specs).toContain("./component.css");
|
||||
});
|
||||
|
||||
it("extracts @import url(...) from Vue style", () => {
|
||||
const source = `
|
||||
<style>
|
||||
@import url("./variables.scss");
|
||||
@import url('./mixins.css');
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "vue", ".vue");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).toContain("./variables.scss");
|
||||
expect(specs).toContain("./mixins.css");
|
||||
});
|
||||
|
||||
it("extracts @import from all style tag variants (scoped, module, lang)", () => {
|
||||
const source = `
|
||||
<script lang="ts">
|
||||
import { ref } from "vue";
|
||||
</script>
|
||||
|
||||
<template><div /></template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@import "./scoped-scss.scss";
|
||||
</style>
|
||||
|
||||
<style module>
|
||||
@import "./module.css";
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
@import "./theme.less";
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "vue", ".vue");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).toContain("vue");
|
||||
expect(specs).toContain("./scoped-scss.scss");
|
||||
expect(specs).toContain("./module.css");
|
||||
expect(specs).toContain("./theme.less");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Stylus @require in style blocks ──────────────────────────────────────
|
||||
|
||||
describe("Stylus @require in style blocks", () => {
|
||||
it("extracts @require from Svelte <style lang=\"stylus\">", () => {
|
||||
const source = `
|
||||
<script>
|
||||
import App from "./App.svelte";
|
||||
</script>
|
||||
|
||||
<style lang="stylus">
|
||||
@require "./variables.styl"
|
||||
@require "../mixins.styl"
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "svelte", ".svelte");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).toContain("./variables.styl");
|
||||
expect(specs).toContain("../mixins.styl");
|
||||
});
|
||||
|
||||
it("extracts @import and @require from Vue <style lang=\"stylus\">", () => {
|
||||
const source = `
|
||||
<template><div /></template>
|
||||
|
||||
<style lang="stylus">
|
||||
@import "./base.styl"
|
||||
@require "./theme.styl"
|
||||
</style>
|
||||
`;
|
||||
const imports = extractImports(source, "vue", ".vue");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).toContain("./base.styl");
|
||||
expect(specs).toContain("./theme.styl");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Standalone CSS ──────────────────────────────────────────────────────
|
||||
|
||||
describe("Standalone CSS imports", () => {
|
||||
it("extracts @import from CSS files", () => {
|
||||
const source = `
|
||||
@import "./variables.css";
|
||||
@import url("./mixins.css");
|
||||
|
||||
body { color: red; }
|
||||
`;
|
||||
const imports = extractImports(source, Lang.Css, ".css");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).toContain("./variables.css");
|
||||
expect(specs).toContain("./mixins.css");
|
||||
});
|
||||
|
||||
it("skips external URLs in CSS files", () => {
|
||||
const source = `
|
||||
@import "https://cdn.example.com/reset.css";
|
||||
@import "./local.css";
|
||||
`;
|
||||
const imports = extractImports(source, Lang.Css, ".css");
|
||||
const specs = imports.map((i) => i.moduleSpecifier);
|
||||
|
||||
expect(specs).not.toContain("https://cdn.example.com/reset.css");
|
||||
expect(specs).toContain("./local.css");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Python ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("Python imports", () => {
|
||||
|
||||
@@ -817,4 +817,393 @@ describe("graph-resolution", () => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Path alias resolution ──────────────────────────────────────────────
|
||||
|
||||
describe("Path alias resolution", () => {
|
||||
it("resolves $lib/ alias to src/lib/", () => {
|
||||
project = createTempProject({
|
||||
"src/lib/Component.svelte": "",
|
||||
"src/routes/page.svelte": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["$lib/", ["src/lib/"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"$lib/Component.svelte",
|
||||
path.join(project.root, "src/routes/page.svelte"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"svelte",
|
||||
aliases,
|
||||
);
|
||||
|
||||
expect(result).toBe("src/lib/Component.svelte");
|
||||
});
|
||||
|
||||
it("resolves @/ alias to src/", () => {
|
||||
project = createTempProject({
|
||||
"src/utils/helper.ts": "",
|
||||
"src/index.ts": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["@/", ["src/"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"@/utils/helper",
|
||||
path.join(project.root, "src/index.ts"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"typescript",
|
||||
aliases,
|
||||
);
|
||||
|
||||
expect(result).toBe("src/utils/helper.ts");
|
||||
});
|
||||
|
||||
it("resolves alias with extensionless import", () => {
|
||||
project = createTempProject({
|
||||
"src/lib/utils.ts": "",
|
||||
"src/app.ts": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["$lib/", ["src/lib/"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"$lib/utils",
|
||||
path.join(project.root, "src/app.ts"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"typescript",
|
||||
aliases,
|
||||
);
|
||||
|
||||
expect(result).toBe("src/lib/utils.ts");
|
||||
});
|
||||
|
||||
it("returns null when alias does not match any file", () => {
|
||||
project = createTempProject({
|
||||
"src/index.ts": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["$lib/", ["src/lib/"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"$lib/NonExistent",
|
||||
path.join(project.root, "src/index.ts"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"typescript",
|
||||
aliases,
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to null without aliases (backwards compatible)", () => {
|
||||
project = createTempProject({
|
||||
"src/index.ts": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"$lib/Component",
|
||||
path.join(project.root, "src/index.ts"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"typescript",
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("tries multiple alias targets in order (first match wins)", () => {
|
||||
project = createTempProject({
|
||||
"src/types.ts": "",
|
||||
"generated/types.ts": "",
|
||||
"src/index.ts": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["@/", ["src", "generated"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"@/types",
|
||||
path.join(project.root, "src/index.ts"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"typescript",
|
||||
aliases,
|
||||
);
|
||||
|
||||
// src/ is listed first, so it should win over generated/
|
||||
expect(result).toBe("src/types.ts");
|
||||
});
|
||||
|
||||
it("falls back to second alias target when first has no match", () => {
|
||||
project = createTempProject({
|
||||
"generated/types.ts": "",
|
||||
"src/index.ts": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["@/", ["src", "generated"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"@/types",
|
||||
path.join(project.root, "src/index.ts"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"typescript",
|
||||
aliases,
|
||||
);
|
||||
|
||||
expect(result).toBe("generated/types.ts");
|
||||
});
|
||||
|
||||
it("resolves CSS alias imports", () => {
|
||||
project = createTempProject({
|
||||
"src/lib/styles/variables.css": "",
|
||||
"src/app.css": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["$lib/", ["src/lib/"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"$lib/styles/variables.css",
|
||||
path.join(project.root, "src/app.css"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"css",
|
||||
aliases,
|
||||
);
|
||||
|
||||
expect(result).toBe("src/lib/styles/variables.css");
|
||||
});
|
||||
|
||||
it("resolves extensionless CSS alias import via extension-try loop", () => {
|
||||
project = createTempProject({
|
||||
"src/lib/styles/variables.scss": "",
|
||||
"src/app.css": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["$lib/", ["src/lib"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"$lib/styles/variables",
|
||||
path.join(project.root, "src/app.css"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"css",
|
||||
aliases,
|
||||
);
|
||||
|
||||
expect(result).toBe("src/lib/styles/variables.scss");
|
||||
});
|
||||
|
||||
it("resolves CSS relative imports", () => {
|
||||
project = createTempProject({
|
||||
"src/styles/variables.css": "",
|
||||
"src/styles/main.css": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"./variables.css",
|
||||
path.join(project.root, "src/styles/main.css"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"css",
|
||||
);
|
||||
|
||||
expect(result).toBe("src/styles/variables.css");
|
||||
});
|
||||
|
||||
it("resolves SCSS relative imports (language=scss)", () => {
|
||||
project = createTempProject({
|
||||
"src/styles/theme.scss": "",
|
||||
"src/styles/main.scss": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"./theme.scss",
|
||||
path.join(project.root, "src/styles/main.scss"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"scss",
|
||||
);
|
||||
|
||||
expect(result).toBe("src/styles/theme.scss");
|
||||
});
|
||||
|
||||
it("resolves SCSS partial with _ prefix", () => {
|
||||
project = createTempProject({
|
||||
"src/styles/_variables.scss": "",
|
||||
"src/styles/main.scss": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"./variables",
|
||||
path.join(project.root, "src/styles/main.scss"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"scss",
|
||||
);
|
||||
|
||||
expect(result).toBe("src/styles/_variables.scss");
|
||||
});
|
||||
|
||||
it("resolves SCSS partial via alias", () => {
|
||||
project = createTempProject({
|
||||
"src/lib/styles/_colors.scss": "",
|
||||
"src/app.scss": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["$lib/", ["src/lib"]]]),
|
||||
};
|
||||
|
||||
const result = resolveImport(
|
||||
"$lib/styles/colors",
|
||||
path.join(project.root, "src/app.scss"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"scss",
|
||||
aliases,
|
||||
);
|
||||
|
||||
expect(result).toBe("src/lib/styles/_colors.scss");
|
||||
});
|
||||
|
||||
it("prefers non-partial over partial when both exist", () => {
|
||||
project = createTempProject({
|
||||
"src/styles/variables.scss": "",
|
||||
"src/styles/_variables.scss": "",
|
||||
"src/styles/main.scss": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"./variables",
|
||||
path.join(project.root, "src/styles/main.scss"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"scss",
|
||||
);
|
||||
|
||||
// Direct match with extension should win before trying _ prefix
|
||||
expect(result).toBe("src/styles/variables.scss");
|
||||
});
|
||||
|
||||
it("resolves SCSS partial when import has explicit .scss extension", () => {
|
||||
project = createTempProject({
|
||||
"src/styles/_variables.scss": "",
|
||||
"src/styles/main.scss": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"./variables.scss",
|
||||
path.join(project.root, "src/styles/main.scss"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"scss",
|
||||
);
|
||||
|
||||
expect(result).toBe("src/styles/_variables.scss");
|
||||
});
|
||||
|
||||
it("resolves Less relative imports (language=less)", () => {
|
||||
project = createTempProject({
|
||||
"src/styles/theme.less": "",
|
||||
"src/styles/main.less": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"./theme.less",
|
||||
path.join(project.root, "src/styles/main.less"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"less",
|
||||
);
|
||||
|
||||
expect(result).toBe("src/styles/theme.less");
|
||||
});
|
||||
|
||||
it("resolves Sass relative imports (language=sass)", () => {
|
||||
project = createTempProject({
|
||||
"src/styles/_base.sass": "",
|
||||
"src/styles/main.sass": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"./base",
|
||||
path.join(project.root, "src/styles/main.sass"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"sass",
|
||||
);
|
||||
|
||||
expect(result).toBe("src/styles/_base.sass");
|
||||
});
|
||||
|
||||
it("exact alias pattern only matches exact specifier", () => {
|
||||
project = createTempProject({
|
||||
"src/index.ts": "",
|
||||
"src/utils/helper.ts": "",
|
||||
});
|
||||
|
||||
const aliases = {
|
||||
entries: new Map([["~", ["src"]]]),
|
||||
};
|
||||
|
||||
// "~utils/helper" should NOT match exact alias "~"
|
||||
const noMatch = resolveImport(
|
||||
"~utils/helper",
|
||||
path.join(project.root, "src/index.ts"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"typescript",
|
||||
aliases,
|
||||
);
|
||||
expect(noMatch).toBeNull();
|
||||
|
||||
// Exact "~" should resolve to src directory index
|
||||
const exactMatch = resolveImport(
|
||||
"~",
|
||||
path.join(project.root, "src/index.ts"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"typescript",
|
||||
aliases,
|
||||
);
|
||||
expect(exactMatch).toBe("src/index.ts");
|
||||
});
|
||||
|
||||
it("returns null for bare CSS package specifier", () => {
|
||||
project = createTempProject({
|
||||
"src/styles/main.css": "",
|
||||
});
|
||||
|
||||
const result = resolveImport(
|
||||
"normalize.css",
|
||||
path.join(project.root, "src/styles/main.css"),
|
||||
project.root,
|
||||
project.fileSet,
|
||||
"css",
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user