UNPKG

tsdk

Version:

Type-safe API development and code share tool for TypeScript projects.

67 lines (66 loc) 2.42 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.aliasToRelativePath = void 0; const path_1 = __importDefault(require("path")); function aliasToRelativePath({ filePath, imports, config, cwd, }) { if (!config) { config = {}; } if (!config.paths) { config.paths = {}; // throw new Error( // "Unable to find the 'paths' property in the supplied configuration!" // ); } if (config.baseUrl === undefined || config.baseUrl === '.') { config.baseUrl = './'; } const { baseUrl, paths } = config; const aliases = {}; for (const alias in paths) { /* istanbul ignore else */ if (paths.hasOwnProperty(alias)) { let resolved = alias; if (alias.endsWith('/*')) { resolved = alias.replace('/*', '/'); } aliases[resolved] = paths[alias]; } } const lines = [...imports]; let idx = -1; for (const line of imports) { idx++; let resolved = ''; for (const alias in aliases) { /* istanbul ignore else */ if (aliases.hasOwnProperty(alias) && line.startsWith(alias)) { const choices = aliases[alias]; if (choices !== undefined) { resolved = choices[0]; if (resolved.endsWith('/*')) { resolved = resolved.replace('/*', '/'); } resolved = line.replace(alias, resolved); break; } } } if (resolved.length < 1) { continue; } const base = path_1.default.join(cwd, path_1.default.relative(cwd, baseUrl || './')); const current = path_1.default.relative(base, path_1.default.dirname(filePath)); const target = path_1.default.relative(base, resolved); const relative = path_1.default.relative(current, target).replace(/\\/g, '/'); lines[idx] = line.replace(line, relative); if (lines[idx].indexOf('/') < 0 || target.startsWith(current)) { lines[idx] = './' + lines[idx]; } } return lines; } exports.aliasToRelativePath = aliasToRelativePath;