UNPKG

@alyle/ui

Version:

Minimal Design, a set of components for Angular

457 lines • 18.8 kB
"use strict"; /* * Note: This file contains vendored TypeScript AST utils from "@schematics/angular". * Since there is no canonical place for common utils, and we don't want to use the AST * utils directly from "@schematics/angular" to avoid TypeScript version mismatches, we * copy the needed AST utils until there is a general place for such utility functions. * * Taken from: * (1) https://github.com/angular/angular-cli/blob/30df1470a0f18989db336d50b55a79021ab64c85/packages/schematics/angular/utility/ng-ast-utils.ts * (2) https://github.com/angular/angular-cli/blob/30df1470a0f18989db336d50b55a79021ab64c85/packages/schematics/angular/utility/ast-utils.ts */ Object.defineProperty(exports, "__esModule", { value: true }); exports.insertImport = insertImport; exports.findNodes = findNodes; exports.getSourceNodes = getSourceNodes; exports.findNode = findNode; exports.insertAfterLastOccurrence = insertAfterLastOccurrence; exports.getDecoratorMetadata = getDecoratorMetadata; exports.getMetadataField = getMetadataField; exports.addSymbolToNgModuleMetadata = addSymbolToNgModuleMetadata; exports.addDeclarationToModule = addDeclarationToModule; exports.addImportToModule = addImportToModule; exports.addExportToModule = addExportToModule; exports.findBootstrapModuleCall = findBootstrapModuleCall; exports.findBootstrapModulePath = findBootstrapModulePath; exports.getAppModulePath = getAppModulePath; exports.isImported = isImported; const core_1 = require("@angular-devkit/core"); const schematics_1 = require("@angular-devkit/schematics"); const change_1 = require("@schematics/angular/utility/change"); const path_1 = require("path"); const core_2 = require("@angular-devkit/core"); const ts = require("typescript"); /** * Add Import `import { symbolName } from fileName` if the import doesn't exit * already. Assumes fileToEdit can be resolved and accessed. * @param fileToEdit (file we want to add import to) * @param symbolName (item to import) * @param fileName (path to the file) * @param isDefault (if true, import follows style for importing default exports) * @return Change */ function insertImport(source, fileToEdit, symbolName, fileName, isDefault = false) { const rootNode = source; const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration); // get nodes that map to import statements from the file fileName const relevantImports = allImports.filter(node => { // StringLiteral of the ImportDeclaration is the import file (fileName in this case). const importFiles = node.getChildren() .filter(child => child.kind === ts.SyntaxKind.StringLiteral) .map(n => n.text); return importFiles.filter(file => file === fileName).length === 1; }); if (relevantImports.length > 0) { let importsAsterisk = false; // imports from import file const imports = []; relevantImports.forEach(n => { Array.prototype.push.apply(imports, findNodes(n, ts.SyntaxKind.Identifier)); if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) { importsAsterisk = true; } }); // if imports * from fileName, don't add symbolName if (importsAsterisk) { return new change_1.NoopChange(); } const importTextNodes = imports.filter(n => n.text === symbolName); // insert import if it's not there if (importTextNodes.length === 0) { const fallbackPos = findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() || findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart(); return insertAfterLastOccurrence(imports, `, ${symbolName}`, fileToEdit, fallbackPos); } return new change_1.NoopChange(); } // no such import declaration exists const useStrict = findNodes(rootNode, ts.SyntaxKind.StringLiteral) .filter(n => n.text === 'use strict'); let fallbackPos = 0; if (useStrict.length > 0) { fallbackPos = useStrict[0].end; } const open = isDefault ? '' : '{ '; const close = isDefault ? '' : ' }'; // if there are no imports or 'use strict' statement, insert import at beginning of file const insertAtBeginning = allImports.length === 0 && useStrict.length === 0; const separator = insertAtBeginning ? '' : ';\n'; const toInsert = `${separator}import ${open}${symbolName}${close}` + ` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`; return insertAfterLastOccurrence(allImports, toInsert, fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral); } function findNodes(node, kindOrGuard, max = Infinity, recursive = false) { if (!node || max == 0) { return []; } const test = typeof kindOrGuard === 'function' ? kindOrGuard : (node) => node.kind === kindOrGuard; const arr = []; if (test(node)) { arr.push(node); max--; } if (max > 0 && (recursive || !test(node))) { for (const child of node.getChildren()) { findNodes(child, test, max, recursive).forEach((node) => { if (max > 0) { arr.push(node); } max--; }); if (max <= 0) { break; } } } return arr; } /** * Get all the nodes from a source. * @param sourceFile The source file object. * @returns {Observable<ts.Node>} An observable of all the nodes in the source. */ function getSourceNodes(sourceFile) { const nodes = [sourceFile]; const result = []; while (nodes.length > 0) { const node = nodes.shift(); if (node) { result.push(node); if (node.getChildCount(sourceFile) >= 0) { nodes.unshift(...node.getChildren()); } } } return result; } function findNode(node, kind, text) { if (node.kind === kind && node.getText() === text) { // throw new Error(node.getText()); return node; } let foundNode = null; ts.forEachChild(node, childNode => { foundNode = foundNode || findNode(childNode, kind, text); }); return foundNode; } /** * Helper for sorting nodes. * @return function to sort nodes in increasing order of position in sourceFile */ function nodesByPosition(first, second) { return first.getStart() - second.getStart(); } /** * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]` * or after the last of occurence of `syntaxKind` if the last occurence is a sub child * of ts.SyntaxKind[nodes[i].kind] and save the changes in file. * * @param nodes insert after the last occurence of nodes * @param toInsert string to insert * @param file file to insert changes into * @param fallbackPos position to insert if toInsert happens to be the first occurence * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after * @return Change instance * @throw Error if toInsert is first occurence but fall back is not set */ function insertAfterLastOccurrence(nodes, toInsert, file, fallbackPos, syntaxKind) { let lastItem; for (const node of nodes) { if (!lastItem || lastItem.getStart() < node.getStart()) { lastItem = node; } } if (syntaxKind && lastItem) { lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop(); } if (!lastItem && fallbackPos == undefined) { throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`); } const lastItemPosition = lastItem ? lastItem.getEnd() : fallbackPos; return new change_1.InsertChange(file, lastItemPosition, toInsert); } function _angularImportsFromNode(node, _sourceFile) { const ms = node.moduleSpecifier; let modulePath; switch (ms.kind) { case ts.SyntaxKind.StringLiteral: modulePath = ms.text; break; default: return {}; } if (!modulePath.startsWith('@angular/')) { return {}; } if (node.importClause) { if (node.importClause.name) { // This is of the form `import Name from 'path'`. Ignore. return {}; } else if (node.importClause.namedBindings) { const nb = node.importClause.namedBindings; if (nb.kind == ts.SyntaxKind.NamespaceImport) { // This is of the form `import * as name from 'path'`. Return `name.`. return { [nb.name.text + '.']: modulePath, }; } else { // This is of the form `import {a,b,c} from 'path'` const namedImports = nb; return namedImports.elements .map((is) => is.propertyName ? is.propertyName.text : is.name.text) .reduce((acc, curr) => { acc[curr] = modulePath; return acc; }, {}); } } return {}; } else { // This is of the form `import 'path';`. Nothing to do. return {}; } } function getDecoratorMetadata(source, identifier, module) { const angularImports = findNodes(source, ts.SyntaxKind.ImportDeclaration) .map(node => _angularImportsFromNode(node, source)) .reduce((acc, current) => { for (const key of Object.keys(current)) { acc[key] = current[key]; } return acc; }, {}); return getSourceNodes(source) .filter(node => { return node.kind == ts.SyntaxKind.Decorator && node.expression.kind == ts.SyntaxKind.CallExpression; }) .map(node => node.expression) .filter(expr => { if (expr.expression.kind == ts.SyntaxKind.Identifier) { const id = expr.expression; return id.text == identifier && angularImports[id.text] === module; } else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) { // This covers foo.NgModule when importing * as foo. const paExpr = expr.expression; // If the left expression is not an identifier, just give up at that point. if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) { return false; } const id = paExpr.name.text; const moduleId = paExpr.expression.text; return id === identifier && (angularImports[moduleId + '.'] === module); } return false; }) .filter(expr => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression) .map(expr => expr.arguments[0]); } function getMetadataField(node, metadataField) { return node.properties .filter(prop => ts.isPropertyAssignment(prop)) // Filter out every fields that's not "metadataField". Also handles string literals // (but not expressions). .filter(node => { const name = node.name; return (ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.getText() === metadataField; }); } function addSymbolToNgModuleMetadata(source, ngModulePath, metadataField, symbolName, importPath = null) { const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core'); const node = nodes[0]; // Find the decorator declaration. if (!node || !ts.isObjectLiteralExpression(node)) { return []; } // Get all the children property assignment of object literals. const matchingProperties = getMetadataField(node, metadataField); if (matchingProperties.length == 0) { // We haven't found the field in the metadata declaration. Insert a new field. let position; let toInsert; if (node.properties.length == 0) { position = node.getEnd() - 1; toInsert = `\n ${metadataField}: [\n${core_2.tags.indentBy(4) `${symbolName}`}\n ]\n`; } else { const childNode = node.properties[node.properties.length - 1]; position = childNode.getEnd(); // Get the indentation of the last element, if any. const text = childNode.getFullText(source); const matches = text.match(/^(\r?\n)(\s*)/); if (matches) { toInsert = `,${matches[0]}${metadataField}: [${matches[1]}` + `${core_2.tags.indentBy(matches[2].length + 2) `${symbolName}`}${matches[0]}]`; } else { toInsert = `, ${metadataField}: [${symbolName}]`; } } if (importPath !== null) { return [ new change_1.InsertChange(ngModulePath, position, toInsert), insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath), ]; } else { return [new change_1.InsertChange(ngModulePath, position, toInsert)]; } } const assignment = matchingProperties[0]; // If it's not an array, nothing we can do really. if (!ts.isPropertyAssignment(assignment) || !ts.isArrayLiteralExpression(assignment.initializer)) { return []; } let expresssion; const assignmentInit = assignment.initializer; const elements = assignmentInit.elements; if (elements.length) { const symbolsArray = elements.map((node) => core_2.tags.oneLine `${node.getText()}`); if (symbolsArray.includes(core_2.tags.oneLine `${symbolName}`)) { return []; } expresssion = elements[elements.length - 1]; } else { expresssion = assignmentInit; } let toInsert; let position = expresssion.getEnd(); if (ts.isArrayLiteralExpression(expresssion)) { // We found the field but it's empty. Insert it just before the `]`. position--; toInsert = `\n${core_2.tags.indentBy(4) `${symbolName}`}\n `; } else { // Get the indentation of the last element, if any. const text = expresssion.getFullText(source); const matches = text.match(/^(\r?\n)(\s*)/); if (matches) { toInsert = `,${matches[1]}${core_2.tags.indentBy(matches[2].length) `${symbolName}`}`; } else { toInsert = `, ${symbolName}`; } } if (importPath !== null) { return [ new change_1.InsertChange(ngModulePath, position, toInsert), insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath), ]; } return [new change_1.InsertChange(ngModulePath, position, toInsert)]; } /** * Custom function to insert a declaration (component, pipe, directive) * into NgModule declarations. It also imports the component. */ function addDeclarationToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'declarations', classifiedName, importPath); } /** * Custom function to insert an NgModule into NgModule imports. It also imports the module. */ function addImportToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath); } /** * Custom function to insert an export into NgModule. It also imports it. */ function addExportToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath); } function findBootstrapModuleCall(host, mainPath) { const mainBuffer = host.read(mainPath); if (!mainBuffer) { throw new schematics_1.SchematicsException(`Main file (${mainPath}) not found`); } const mainText = mainBuffer.toString('utf-8'); const source = ts.createSourceFile(mainPath, mainText, ts.ScriptTarget.Latest, true); const allNodes = getSourceNodes(source); let bootstrapCall = null; for (const node of allNodes) { let bootstrapCallNode = null; bootstrapCallNode = findNode(node, ts.SyntaxKind.Identifier, 'bootstrapModule'); // Walk up the parent until CallExpression is found. while (bootstrapCallNode && bootstrapCallNode.parent && bootstrapCallNode.parent.kind !== ts.SyntaxKind.CallExpression) { bootstrapCallNode = bootstrapCallNode.parent; } if (bootstrapCallNode !== null && bootstrapCallNode.parent !== undefined && bootstrapCallNode.parent.kind === ts.SyntaxKind.CallExpression) { bootstrapCall = bootstrapCallNode.parent; break; } } return bootstrapCall; } function findBootstrapModulePath(host, mainPath) { const bootstrapCall = findBootstrapModuleCall(host, mainPath); if (!bootstrapCall) { throw new schematics_1.SchematicsException('Bootstrap call not found'); } const bootstrapModule = bootstrapCall.arguments[0]; const mainBuffer = host.read(mainPath); if (!mainBuffer) { throw new schematics_1.SchematicsException(`Client app main file (${mainPath}) not found`); } const mainText = mainBuffer.toString('utf-8'); const source = ts.createSourceFile(mainPath, mainText, ts.ScriptTarget.Latest, true); const allNodes = getSourceNodes(source); const bootstrapModuleRelativePath = allNodes .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration) .filter(imp => { return findNode(imp, ts.SyntaxKind.Identifier, bootstrapModule.getText()); }) .map(node => { const modulePath = node.moduleSpecifier; return modulePath.text; })[0]; return bootstrapModuleRelativePath; } function getAppModulePath(host, mainPath) { const moduleRelativePath = findBootstrapModulePath(host, mainPath); const mainDir = (0, path_1.dirname)(mainPath); const modulePath = (0, core_1.normalize)(`/${mainDir}/${moduleRelativePath}.ts`); return modulePath; } /** * Determine if an import already exists. */ function isImported(source, classifiedName, importPath) { const allNodes = getSourceNodes(source); const matchingNodes = allNodes .filter(ts.isImportDeclaration) .filter((imp) => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath) .filter((imp) => { if (!imp.importClause) { return false; } const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter((n) => n.getText() === classifiedName); return nodes.length > 0; }); return matchingNodes.length > 0; } //# sourceMappingURL=index.js.map