UNPKG

@o3r/core

Version:
81 lines 3.79 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ngAddContext = void 0; exports.ngAddContextFn = ngAddContextFn; const node_path_1 = require("node:path"); const schematics_1 = require("@angular-devkit/schematics"); const schematics_2 = require("@o3r/schematics"); const ts = require("typescript"); const checkContext = (componentPath, tree) => { const files = [ node_path_1.posix.join((0, node_path_1.dirname)(componentPath), `${(0, node_path_1.basename)(componentPath, '.component.ts')}.context.ts`) ]; if (files.some((file) => tree.exists(file))) { throw new schematics_2.O3rCliError(`Unable to add context to this component because it already has at least one of these files: ${files.join(', ')}.`); } }; /** * Add context to an existing component * @param options */ function ngAddContextFn(options) { return async (tree, context) => { const componentPath = options.path; try { const { name } = (0, schematics_2.getO3rComponentInfoOrThrowIfNotFound)(tree, componentPath); checkContext(componentPath, tree); const properties = { componentContext: name.concat('Context'), name: (0, node_path_1.basename)(componentPath, '.component.ts') }; const createConfigFilesRule = (0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)('./templates'), [ (0, schematics_1.template)(properties), (0, schematics_1.renameTemplateFiles)(), (0, schematics_1.move)((0, node_path_1.dirname)(componentPath)) ]), schematics_1.MergeStrategy.Overwrite); const updateComponentRule = (0, schematics_1.chain)([ (0, schematics_2.addImportsRule)(componentPath, [ { from: `./${properties.name}.context`, importNames: [ properties.componentContext ] } ]), () => { const componentSourceFile = ts.createSourceFile(componentPath, tree.readText(componentPath), ts.ScriptTarget.ES2020, true); const result = ts.transform(componentSourceFile, [ (0, schematics_2.addInterfaceToClassTransformerFactory)(properties.componentContext, schematics_2.isO3rClassComponent) ]); const printer = ts.createPrinter({ removeComments: false, newLine: ts.NewLineKind.LineFeed }); tree.overwrite(componentPath, printer.printFile(result.transformed[0])); return tree; } ]); return (0, schematics_1.chain)([ createConfigFilesRule, updateComponentRule, options.skipLinter ? (0, schematics_1.noop)() : (0, schematics_2.applyEsLintFix)() ]); } catch (e) { if (e instanceof schematics_2.NoOtterComponent && context.interactive) { const shouldConvertComponent = await (0, schematics_2.askConfirmationToConvertComponent)(); if (shouldConvertComponent) { return (0, schematics_1.chain)([ (0, schematics_1.schematic)('convert-component', { path: options.path }), ngAddContextFn(options) ]); } } throw e; } }; } exports.ngAddContext = (0, schematics_2.createOtterSchematic)(ngAddContextFn); //# sourceMappingURL=index.js.map