UNPKG

@carlosv2/glue

Version:

Dependency injection library that stays out of the way

85 lines (84 loc) 3.33 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Importer = void 0; const typescript_1 = __importDefault(require("typescript")); const utils_1 = require("./utils"); const { factory } = typescript_1.default; class Importer { constructor() { this.imports = {}; } randomise(name) { return `${name}_${(0, utils_1.gibberish)(10)}`; } initPath(path) { if (!(path in this.imports)) { this.imports[path] = { module: undefined, default: undefined, symbols: {}, }; } } module(path) { this.initPath(path); if (!(0, utils_1.isString)(this.imports[path].module)) { this.imports[path].module = this.randomise('Module'); } return this.imports[path].module; } default(path) { this.initPath(path); if (!(0, utils_1.isString)(this.imports[path].default)) { this.imports[path].default = this.randomise('Default'); } return this.imports[path].default; } symbol(path, symbol) { this.initPath(path); if (!(symbol in this.imports[path].symbols)) { this.imports[path].symbols[symbol] = this.randomise(symbol); } return this.imports[path].symbols[symbol]; } sanitise(path) { if (path.endsWith('.ts') || path.endsWith('js')) { return path.substring(0, path.length - 3); } return path; } compile() { return Object.entries(this.imports) .map(([path, importee]) => { const declarations = []; if ((0, utils_1.isString)(importee.module)) { declarations.push(factory.createImportDeclaration(undefined, factory.createImportClause(false, undefined, factory.createNamespaceImport(factory.createIdentifier(importee.module))), factory.createStringLiteral(this.sanitise(path)))); } let defaultImport = undefined; if ((0, utils_1.isString)(importee.default)) { defaultImport = factory.createIdentifier(importee.default); } let symbolsImport = undefined; if (Object.keys(importee.symbols).length) { symbolsImport = factory.createNamedImports(Object.entries(importee.symbols).map(([symbol, as]) => { let propertyName = undefined; let name = factory.createIdentifier(symbol); if ((0, utils_1.isString)(as)) { propertyName = factory.createIdentifier(symbol); name = factory.createIdentifier(as); } return factory.createImportSpecifier(false, propertyName, name); })); } if (defaultImport || symbolsImport) { declarations.push(factory.createImportDeclaration(undefined, factory.createImportClause(false, defaultImport, symbolsImport), factory.createStringLiteral(this.sanitise(path)))); } return declarations; }) .flat(); } } exports.Importer = Importer;