From 67eed64b5260f0627a22b1a3f3aa90df40cffeae Mon Sep 17 00:00:00 2001 From: Matthieu Riegler Date: Tue, 22 Jul 2025 18:07:44 +0200 Subject: [PATCH] feat(@angular-devkit/schematics): add schematics to generate ai context files. * `ng generate ai-config` to prompt support tools. * `ng generate config ai --tool=gemini` to specify the tool. * `ng new --aiConfig=gemini` to create a new project with AI configuration. Supported ai tools: gemini, claude, copilot, windsurf, cursor. --- .../angular_devkit/schematics/index.api.md | 5 +- .../schematics/src/rules/move.ts | 2 + .../ai-config/files/__rulesName__.template | 54 +++++++++++ .../schematics/angular/ai-config/index.ts | 91 +++++++++++++++++ .../angular/ai-config/index_spec.ts | 97 +++++++++++++++++++ .../schematics/angular/ai-config/schema.json | 29 ++++++ packages/schematics/angular/collection.json | 5 + packages/schematics/angular/ng-new/index.ts | 9 ++ .../schematics/angular/ng-new/index_spec.ts | 12 +++ .../schematics/angular/ng-new/schema.json | 10 ++ 10 files changed, 313 insertions(+), 1 deletion(-) create mode 100644 packages/schematics/angular/ai-config/files/__rulesName__.template create mode 100644 packages/schematics/angular/ai-config/index.ts create mode 100644 packages/schematics/angular/ai-config/index_spec.ts create mode 100644 packages/schematics/angular/ai-config/schema.json diff --git a/goldens/public-api/angular_devkit/schematics/index.api.md b/goldens/public-api/angular_devkit/schematics/index.api.md index 3e3a0bc97ead..505bd2c39920 100644 --- a/goldens/public-api/angular_devkit/schematics/index.api.md +++ b/goldens/public-api/angular_devkit/schematics/index.api.md @@ -637,7 +637,10 @@ export enum MergeStrategy { export function mergeWith(source: Source, strategy?: MergeStrategy): Rule; // @public (undocumented) -export function move(from: string, to?: string): Rule; +export function move(from: string, to: string): Rule; + +// @public (undocumented) +export function move(to: string): Rule; // @public (undocumented) export function noop(): Rule; diff --git a/packages/angular_devkit/schematics/src/rules/move.ts b/packages/angular_devkit/schematics/src/rules/move.ts index 05cd2b36634e..4c6c1e8d2f39 100644 --- a/packages/angular_devkit/schematics/src/rules/move.ts +++ b/packages/angular_devkit/schematics/src/rules/move.ts @@ -10,6 +10,8 @@ import { join, normalize } from '@angular-devkit/core'; import { Rule } from '../engine/interface'; import { noop } from './base'; +export function move(from: string, to: string): Rule; +export function move(to: string): Rule; export function move(from: string, to?: string): Rule { if (to === undefined) { to = from; diff --git a/packages/schematics/angular/ai-config/files/__rulesName__.template b/packages/schematics/angular/ai-config/files/__rulesName__.template new file mode 100644 index 000000000000..c3df3ccf17e5 --- /dev/null +++ b/packages/schematics/angular/ai-config/files/__rulesName__.template @@ -0,0 +1,54 @@ +<% if (frontmatter) { %><%= frontmatter %> + +<% } %>You are an expert in TypeScript, Angular, and scalable web application development. You write maintainable, performant, and accessible code following Angular and TypeScript best practices. + +## TypeScript Best Practices + +- Use strict type checking +- Prefer type inference when the type is obvious +- Avoid the `any` type; use `unknown` when type is uncertain + +## Angular Best Practices + +- Always use standalone components over NgModules +- Must NOT set `standalone: true` inside Angular decorators. It's the default. +- Use signals for state management +- Implement lazy loading for feature routes +- Do NOT use the `@HostBinding` and `@HostListener` decorators. Put host bindings inside the `host` object of the `@Component` or `@Directive` decorator instead +- Use `NgOptimizedImage` for all static images. + - `NgOptimizedImage` does not work for inline base64 images. + +## Components + +- Keep components small and focused on a single responsibility +- Use `input()` and `output()` functions instead of decorators +- Use `computed()` for derived state +- Set `changeDetection: ChangeDetectionStrategy.OnPush` in `@Component` decorator +- Prefer inline templates for small components +- Prefer Reactive forms instead of Template-driven ones +- Do NOT use `ngClass`, use `class` bindings instead +- DO NOT use `ngStyle`, use `style` bindings instead + +## State Management + +- Use signals for local component state +- Use `computed()` for derived state +- Keep state transformations pure and predictable +- Do NOT use `mutate` on signals, use `update` or `set` instead + +## Templates + +- Keep templates simple and avoid complex logic +- Use native control flow (`@if`, `@for`, `@switch`) instead of `*ngIf`, `*ngFor`, `*ngSwitch` +- Use the async pipe to handle observables + +## Services + +- Design services around a single responsibility +- Use the `providedIn: 'root'` option for singleton services +- Use the `inject()` function instead of constructor injection + +## Common pitfalls + +- Control flow (`@if`): + - You cannot use `as` expressions in `@else if (...)`. E.g. invalid code: `@else if (bla(); as x)`. diff --git a/packages/schematics/angular/ai-config/index.ts b/packages/schematics/angular/ai-config/index.ts new file mode 100644 index 000000000000..6cc1defa313a --- /dev/null +++ b/packages/schematics/angular/ai-config/index.ts @@ -0,0 +1,91 @@ +/** + * @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.dev/license + */ + +import { + Rule, + SchematicsException, + apply, + applyTemplates, + chain, + filter, + mergeWith, + move, + strings, + url, +} from '@angular-devkit/schematics'; +import { posix as path } from 'node:path'; +import { getWorkspace as readWorkspace } from '../utility/workspace'; +import { Schema as ConfigOptions, Tool } from './schema'; + +const geminiFile: ContextFileInfo = { rulesName: 'GEMINI.md', directory: '.gemini' }; +const copilotFile: ContextFileInfo = { + rulesName: 'copilot-instructions.md', + directory: '.github', +}; +const claudeFile: ContextFileInfo = { rulesName: 'CLAUDE.md', directory: '.claude' }; +const windsurfFile: ContextFileInfo = { + rulesName: 'guidelines.md', + directory: path.join('.windsurf', 'rules'), +}; + +// Cursor file is a bit different, it has a front matter section. +const cursorFile: ContextFileInfo = { + rulesName: 'cursor.mdc', + directory: path.join('.cursor', 'rules'), + frontmatter: `---\ncontext: true\npriority: high\nscope: project\n---`, +}; + +const AI_TOOLS = { + 'gemini': geminiFile, + 'claude': claudeFile, + 'copilot': copilotFile, + 'cursor': cursorFile, + 'windsurf': windsurfFile, +}; + +export default function (options: ConfigOptions): Rule { + return addAiContextFile(options); +} + +interface ContextFileInfo { + rulesName: string; + directory: string; + frontmatter?: string; +} + +function addAiContextFile(options: ConfigOptions): Rule { + const selectedTools: Tool[] = options.tool; + const files: ContextFileInfo[] = selectedTools.map( + (selectedTool: keyof typeof AI_TOOLS) => AI_TOOLS[selectedTool], + ); + + return async (host) => { + const workspace = await readWorkspace(host); + const project = workspace.projects.get(options.project); + if (!project) { + throw new SchematicsException(`Project name "${options.project}" doesn't not exist.`); + } + + const rules = files.map(({ rulesName, directory, frontmatter }) => + mergeWith( + apply(url('./files'), [ + // Keep only the single source template + filter((p) => p.endsWith('__rulesName__.template')), + applyTemplates({ + ...strings, + rulesName, + frontmatter: frontmatter ?? '', + }), + move(directory), + ]), + ), + ); + + return chain(rules); + }; +} diff --git a/packages/schematics/angular/ai-config/index_spec.ts b/packages/schematics/angular/ai-config/index_spec.ts new file mode 100644 index 000000000000..e5802cce686c --- /dev/null +++ b/packages/schematics/angular/ai-config/index_spec.ts @@ -0,0 +1,97 @@ +/** + * @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.dev/license + */ + +import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; +import { Schema as ApplicationOptions } from '../application/schema'; +import { Schema as WorkspaceOptions } from '../workspace/schema'; +import { Schema as ConfigOptions, Tool as ConfigTool } from './schema'; + +describe('Ai Config Schematic', () => { + const schematicRunner = new SchematicTestRunner( + '@schematics/angular', + require.resolve('../collection.json'), + ); + + const workspaceOptions: WorkspaceOptions = { + name: 'workspace', + newProjectRoot: 'projects', + version: '15.0.0', + }; + + const defaultAppOptions: ApplicationOptions = { + name: 'foo', + inlineStyle: true, + inlineTemplate: true, + routing: false, + skipPackageJson: false, + }; + + let applicationTree: UnitTestTree; + function runConfigSchematic(tool: ConfigTool[]): Promise { + return schematicRunner.runSchematic( + 'ai-config', + { + project: 'foo', + tool, + }, + applicationTree, + ); + } + + beforeEach(async () => { + const workspaceTree = await schematicRunner.runSchematic('workspace', workspaceOptions); + applicationTree = await schematicRunner.runSchematic( + 'application', + defaultAppOptions, + workspaceTree, + ); + }); + + it('should create a GEMINI.MD file', async () => { + const tree = await runConfigSchematic([ConfigTool.Gemini]); + expect(tree.readContent('.gemini/GEMINI.md')).toMatch(/^You are an expert in TypeScript/); + }); + + it('should create a copilot-instructions.md file', async () => { + const tree = await runConfigSchematic([ConfigTool.Copilot]); + expect(tree.readContent('.github/copilot-instructions.md')).toContain( + 'You are an expert in TypeScript', + ); + }); + + it('should create a cursor file', async () => { + const tree = await runConfigSchematic([ConfigTool.Cursor]); + const cursorFile = tree.readContent('.cursor/rules/cursor.mdc'); + expect(cursorFile).toContain('You are an expert in TypeScript'); + expect(cursorFile).toContain('context: true'); + expect(cursorFile).toContain('---\n\nYou are an expert in TypeScript'); + }); + + it('should create a windsurf file', async () => { + const tree = await runConfigSchematic([ConfigTool.Windsurf]); + expect(tree.readContent('.windsurf/rules/guidelines.md')).toContain( + 'You are an expert in TypeScript', + ); + }); + + it('should create a claude file', async () => { + const tree = await runConfigSchematic([ConfigTool.Claude]); + expect(tree.readContent('.claude/CLAUDE.md')).toContain('You are an expert in TypeScript'); + }); + + it('should create multiple files when multiple tools are selected', async () => { + const tree = await runConfigSchematic([ + ConfigTool.Gemini, + ConfigTool.Copilot, + ConfigTool.Cursor, + ]); + expect(tree.readContent('.gemini/GEMINI.md').length).toBeGreaterThan(0); + expect(tree.readContent('.github/copilot-instructions.md').length).toBeGreaterThan(0); + expect(tree.readContent('.cursor/rules/cursor.mdc').length).toBeGreaterThan(0); + }); +}); diff --git a/packages/schematics/angular/ai-config/schema.json b/packages/schematics/angular/ai-config/schema.json new file mode 100644 index 000000000000..3efcfbf586ee --- /dev/null +++ b/packages/schematics/angular/ai-config/schema.json @@ -0,0 +1,29 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "$id": "SchematicsAngularConfig", + "title": "Angular Config File Options Schema", + "type": "object", + "additionalProperties": false, + "description": "Generates configuration files for your project. These files control various aspects of your project's build process, testing, and browser compatibility. This schematic helps you create or update essential configuration files with ease.", + "properties": { + "project": { + "type": "string", + "description": "The name of the project where the configuration file should be created or updated.", + "$default": { + "$source": "projectName" + } + }, + "tool": { + "type": "array", + "uniqueItems": true, + "x-prompt": "Which AI tool would you like to configure?", + "description": "The AI tool for which the configuration file is being generated. This can include tools like Gemini, Copilot, Claude, Cursor, or Windsurf.", + "minItems": 1, + "items": { + "type": "string", + "enum": ["gemini", "copilot", "claude", "cursor", "windsurf"] + } + } + }, + "required": ["project", "tool"] +} diff --git a/packages/schematics/angular/collection.json b/packages/schematics/angular/collection.json index 5f691819544f..fcd6d330b166 100755 --- a/packages/schematics/angular/collection.json +++ b/packages/schematics/angular/collection.json @@ -131,6 +131,11 @@ "factory": "./config", "schema": "./config/schema.json", "description": "Generates a configuration file." + }, + "ai-config": { + "factory": "./ai-config", + "schema": "./ai-config/schema.json", + "description": "Generates an AI tool configuration file." } } } diff --git a/packages/schematics/angular/ng-new/index.ts b/packages/schematics/angular/ng-new/index.ts index e9362726d4d1..860e30acbbd3 100644 --- a/packages/schematics/angular/ng-new/index.ts +++ b/packages/schematics/angular/ng-new/index.ts @@ -22,6 +22,7 @@ import { NodePackageInstallTask, RepositoryInitializerTask, } from '@angular-devkit/schematics/tasks'; +import { Tool as AiTool, Schema as ConfigOptions } from '../ai-config/schema'; import { Schema as ApplicationOptions } from '../application/schema'; import { Schema as WorkspaceOptions } from '../workspace/schema'; import { Schema as NgNewOptions } from './schema'; @@ -60,11 +61,19 @@ export default function (options: NgNewOptions): Rule { zoneless: options.zoneless, }; + const configOptions: ConfigOptions | undefined = options.aiConfig?.length + ? { + project: options.name, + tool: options.aiConfig as unknown as AiTool[], + } + : undefined; + return chain([ mergeWith( apply(empty(), [ schematic('workspace', workspaceOptions), options.createApplication ? schematic('application', applicationOptions) : noop, + configOptions ? schematic('ai-config', configOptions) : noop, move(options.directory), ]), ), diff --git a/packages/schematics/angular/ng-new/index_spec.ts b/packages/schematics/angular/ng-new/index_spec.ts index 413cc6841934..e8ddf5aa985e 100644 --- a/packages/schematics/angular/ng-new/index_spec.ts +++ b/packages/schematics/angular/ng-new/index_spec.ts @@ -103,4 +103,16 @@ describe('Ng New Schematic', () => { const { cli } = JSON.parse(tree.readContent('/bar/angular.json')); expect(cli.packageManager).toBe('npm'); }); + + it('should add ai config file when aiConfig is set', async () => { + const options = { ...defaultOptions, aiConfig: ['gemini', 'claude'] }; + + const tree = await schematicRunner.runSchematic('ng-new', options); + const files = tree.files; + expect(files).toContain('/bar/.gemini/GEMINI.md'); + expect(files).toContain('/bar/.claude/CLAUDE.md'); + + expect(tree.readContent('/bar/.gemini/GEMINI.md')).toMatch(/^You are an expert in TypeScript/); + expect(tree.readContent('/bar/.claude/CLAUDE.md')).toMatch(/^You are an expert in TypeScript/); + }); }); diff --git a/packages/schematics/angular/ng-new/schema.json b/packages/schematics/angular/ng-new/schema.json index d6381afce198..c0b4019458c0 100644 --- a/packages/schematics/angular/ng-new/schema.json +++ b/packages/schematics/angular/ng-new/schema.json @@ -144,6 +144,16 @@ "x-prompt": "Do you want to create a 'zoneless' application without zone.js (Developer Preview)?", "type": "boolean", "default": false + }, + "aiConfig": { + "type": "array", + "default": [], + "uniqueItems": true, + "description": "Create an AI configuration file for the project. This file is used to improve the outputs of AI tools by following the best practices.", + "items": { + "type": "string", + "enum": ["gemini", "copilot", "claude", "cursor", "windsurf"] + } } }, "required": ["name", "version"]