Skip to content

Commit

Permalink
feat(@schematics/angular): add bootstrap-agnostic utilities for writi…
Browse files Browse the repository at this point in the history
…ng ng-add schematics

Currently writing schematics that support both NgModule-based and standalone projects is tricky, because they have different layouts. These changes introduce two new APIs that work both on NgModule and standalone projects and can be used by library authors to create their `ng add` schematics. Example rule for adding a `ModuleWithProviders`-style library:

```ts
import { Rule } from '@angular-devkit/schematics';
import { addRootImport } from '@schematics/angular/utility';

export default function(): Rule {
  return addRootImport('default', ({code, external}) => {
    return code`${external('MyModule', '@my/module')}.forRoot({})`;
  });
}
```

This rulle will add `imports: [MyModule.forRoot({})]` to an NgModule app and `providers: [importProvidersFrom(MyModule.forRoot({}))]` to a standalone one. It also adds all of the necessary imports.
  • Loading branch information
crisbeto authored and alan-agius4 committed Jun 6, 2023
1 parent b36effd commit b14b959
Show file tree
Hide file tree
Showing 8 changed files with 1,128 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/schematics/angular/utility/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ function nodesByPosition(first: ts.Node, second: ts.Node): number {
* @throw Error if toInsert is first occurence but fall back is not set
*/
export function insertAfterLastOccurrence(
nodes: ts.Node[],
nodes: ts.Node[] | ts.NodeArray<ts.Node>,
toInsert: string,
file: string,
fallbackPos: number,
Expand Down
1 change: 1 addition & 0 deletions packages/schematics/angular/utility/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export {
writeWorkspace,
} from './workspace';
export { Builders as AngularBuilder } from './workspace-models';
export * from './standalone';

// Package dependency related rules and types
export { DependencyType, ExistingBehavior, InstallBehavior, addDependency } from './dependency';
127 changes: 127 additions & 0 deletions packages/schematics/angular/utility/standalone/app_config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import { Tree } from '@angular-devkit/schematics';
import { dirname, join } from 'path';
import ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { getSourceFile } from './util';

/** App config that was resolved to its source node. */
export interface ResolvedAppConfig {
/** Tree-relative path of the file containing the app config. */
filePath: string;

/** Node defining the app config. */
node: ts.ObjectLiteralExpression;
}

/**
* Resolves the node that defines the app config from a bootstrap call.
* @param bootstrapCall Call for which to resolve the config.
* @param tree File tree of the project.
* @param filePath File path of the bootstrap call.
*/
export function findAppConfig(
bootstrapCall: ts.CallExpression,
tree: Tree,
filePath: string,
): ResolvedAppConfig | null {
if (bootstrapCall.arguments.length > 1) {
const config = bootstrapCall.arguments[1];

if (ts.isObjectLiteralExpression(config)) {
return { filePath, node: config };
}

if (ts.isIdentifier(config)) {
return resolveAppConfigFromIdentifier(config, tree, filePath);
}
}

return null;
}

/**
* Resolves the app config from an identifier referring to it.
* @param identifier Identifier referring to the app config.
* @param tree File tree of the project.
* @param bootstapFilePath Path of the bootstrap call.
*/
function resolveAppConfigFromIdentifier(
identifier: ts.Identifier,
tree: Tree,
bootstapFilePath: string,
): ResolvedAppConfig | null {
const sourceFile = identifier.getSourceFile();

for (const node of sourceFile.statements) {
// Only look at relative imports. This will break if the app uses a path
// mapping to refer to the import, but in order to resolve those, we would
// need knowledge about the entire program.
if (
!ts.isImportDeclaration(node) ||
!node.importClause?.namedBindings ||
!ts.isNamedImports(node.importClause.namedBindings) ||
!ts.isStringLiteralLike(node.moduleSpecifier) ||
!node.moduleSpecifier.text.startsWith('.')
) {
continue;
}

for (const specifier of node.importClause.namedBindings.elements) {
if (specifier.name.text !== identifier.text) {
continue;
}

// Look for a variable with the imported name in the file. Note that ideally we would use
// the type checker to resolve this, but we can't because these utilities are set up to
// operate on individual files, not the entire program.
const filePath = join(dirname(bootstapFilePath), node.moduleSpecifier.text + '.ts');
const importedSourceFile = getSourceFile(tree, filePath);
const resolvedVariable = findAppConfigFromVariableName(
importedSourceFile,
(specifier.propertyName || specifier.name).text,
);

if (resolvedVariable) {
return { filePath, node: resolvedVariable };
}
}
}

const variableInSameFile = findAppConfigFromVariableName(sourceFile, identifier.text);

return variableInSameFile ? { filePath: bootstapFilePath, node: variableInSameFile } : null;
}

/**
* Finds an app config within the top-level variables of a file.
* @param sourceFile File in which to search for the config.
* @param variableName Name of the variable containing the config.
*/
function findAppConfigFromVariableName(
sourceFile: ts.SourceFile,
variableName: string,
): ts.ObjectLiteralExpression | null {
for (const node of sourceFile.statements) {
if (ts.isVariableStatement(node)) {
for (const decl of node.declarationList.declarations) {
if (
ts.isIdentifier(decl.name) &&
decl.name.text === variableName &&
decl.initializer &&
ts.isObjectLiteralExpression(decl.initializer)
) {
return decl.initializer;
}
}
}
}

return null;
}
115 changes: 115 additions & 0 deletions packages/schematics/angular/utility/standalone/code_block.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import { Rule, Tree } from '@angular-devkit/schematics';
import ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { hasTopLevelIdentifier, insertImport } from '../ast-utils';
import { applyToUpdateRecorder } from '../change';

/** Generated code that hasn't been interpolated yet. */
export interface PendingCode {
/** Code that will be inserted. */
expression: string;

/** Imports that need to be added to the file in which the code is inserted. */
imports: PendingImports;
}

/** Map keeping track of imports and aliases under which they're referred to in an expresion. */
type PendingImports = Map<string, Map<string, string>>;

/** Counter used to generate unique IDs. */
let uniqueIdCounter = 0;

/**
* Callback invoked by a Rule that produces the code
* that needs to be inserted somewhere in the app.
*/
export type CodeBlockCallback = (block: CodeBlock) => PendingCode;

/**
* Utility class used to generate blocks of code that
* can be inserted by the devkit into a user's app.
*/
export class CodeBlock {
private _imports: PendingImports = new Map<string, Map<string, string>>();

// Note: the methods here are defined as arrow function so that they can be destructured by
// consumers without losing their context. This makes the API more concise.

/** Function used to tag a code block in order to produce a `PendingCode` object. */
code = (strings: TemplateStringsArray, ...params: unknown[]): PendingCode => {
return {
expression: strings.map((part, index) => part + (params[index] || '')).join(''),
imports: this._imports,
};
};

/**
* Used inside of a code block to mark external symbols and which module they should be imported
* from. When the code is inserted, the required import statements will be produced automatically.
* @param symbolName Name of the external symbol.
* @param moduleName Module from which the symbol should be imported.
*/
external = (symbolName: string, moduleName: string): string => {
if (!this._imports.has(moduleName)) {
this._imports.set(moduleName, new Map());
}

const symbolsPerModule = this._imports.get(moduleName) as Map<string, string>;

if (!symbolsPerModule.has(symbolName)) {
symbolsPerModule.set(symbolName, `@@__SCHEMATIC_PLACEHOLDER_${uniqueIdCounter++}__@@`);
}

return symbolsPerModule.get(symbolName) as string;
};

/**
* Produces the necessary rules to transform a `PendingCode` object into valid code.
* @param initialCode Code pending transformed.
* @param filePath Path of the file in which the code will be inserted.
*/
static transformPendingCode(initialCode: PendingCode, filePath: string) {
const code = { ...initialCode };
const rules: Rule[] = [];

code.imports.forEach((symbols, moduleName) => {
symbols.forEach((placeholder, symbolName) => {
rules.push((tree: Tree) => {
const recorder = tree.beginUpdate(filePath);
const sourceFile = ts.createSourceFile(
filePath,
tree.readText(filePath),
ts.ScriptTarget.Latest,
true,
);

// Note that this could still technically clash if there's a top-level symbol called
// `${symbolName}_alias`, however this is unlikely. We can revisit this if it becomes
// a problem.
const alias = hasTopLevelIdentifier(sourceFile, symbolName, moduleName)
? symbolName + '_alias'
: undefined;

code.expression = code.expression.replace(
new RegExp(placeholder, 'g'),
alias || symbolName,
);

applyToUpdateRecorder(recorder, [
insertImport(sourceFile, filePath, symbolName, moduleName, false, alias),
]);
tree.commitUpdate(recorder);
});
});
});

return { code, rules };
}
}
10 changes: 10 additions & 0 deletions packages/schematics/angular/utility/standalone/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

export { addRootImport, addRootProvider } from './rules';
export { PendingCode, CodeBlockCallback, type CodeBlock } from './code_block';
Loading

0 comments on commit b14b959

Please sign in to comment.