import path from 'path';
import fs from 'fs';
import { BaseResolver } from './base-resolver.js';
export class JSResolver extends BaseResolver {
    constructor(workspaceRoot) {
        super();
        this.language = 'javascript';
        this.aliasMap = {};
        this.loadAliases(workspaceRoot);
    }
    resolveImport(source, currentFilePath, workspaceRoot) {
        // 1. Handle Aliases
        let resolvedSource = source;
        for (const [alias, aliasPath] of Object.entries(this.aliasMap)) {
            if (source.startsWith(alias)) {
                resolvedSource = source.replace(alias, aliasPath);
                // If aliasPath is absolute, use it; if relative, join with workspaceRoot
                if (!path.isAbsolute(resolvedSource)) {
                    resolvedSource = path.join(workspaceRoot, resolvedSource);
                }
                break;
            }
        }
        // 2. Resolve Path
        let absolutePath = '';
        if (path.isAbsolute(resolvedSource)) {
            absolutePath = resolvedSource;
        }
        else if (resolvedSource.startsWith('.')) {
            absolutePath = path.resolve(path.dirname(currentFilePath), resolvedSource);
        }
        else {
            // Node modules or other non-relative imports - typically we ignore for taint
            // unless it's a known internal package. For now, we skip.
            return null;
        }
        // 3. Handle Extensions (.js, .ts, /index.js, etc.)
        const extensions = ['', '.js', '.ts', '.jsx', '.tsx', '/index.js', '/index.ts'];
        for (const ext of extensions) {
            const fullPath = absolutePath + ext;
            if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
                return fullPath;
            }
        }
        return null;
    }
    loadAliases(workspaceRoot) {
        const tsconfigPath = path.join(workspaceRoot, 'tsconfig.json');
        if (fs.existsSync(tsconfigPath)) {
            try {
                const tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf-8'));
                const paths = tsconfig.compilerOptions?.paths;
                if (paths) {
                    for (const [alias, targets] of Object.entries(paths)) {
                        // Simplified: just take the first target and strip asterisk
                        const cleanAlias = alias.replace('/*', '');
                        const cleanTarget = targets[0]?.replace('/*', '') || '';
                        this.aliasMap[cleanAlias] = cleanTarget;
                    }
                }
            }
            catch (e) {
                console.log(e);
                // Ignore parse errors
            }
        }
    }
}
//# sourceMappingURL=js-resolver.js.map