diff --git a/.cz-config.js b/.cz-config.js index f2a0a0bb3a9db..8352d94e37171 100644 --- a/.cz-config.js +++ b/.cz-config.js @@ -6,12 +6,12 @@ module.exports = { { value: 'cleanup', name: - 'cleanup: A code change that neither fixes a bug nor adds a feature' + 'cleanup: A code change that neither fixes a bug nor adds a feature', }, { value: 'chore', - name: "chore: Other changes that don't modify src or test files" - } + name: "chore: Other changes that don't modify src or test files", + }, ], scopes: [ @@ -28,13 +28,13 @@ module.exports = { { name: 'storybook', description: 'anything Storybook specific' }, { name: 'testing', - description: 'anything testing specific (e.g., jest or cypress)' + description: 'anything testing specific (e.g., jest or cypress)', }, { name: 'repo', - description: 'anything related to managing the repo itself' + description: 'anything related to managing the repo itself', }, - { name: 'misc', description: 'misc stuff' } + { name: 'misc', description: 'misc stuff' }, ], allowTicketNumber: true, @@ -66,7 +66,7 @@ module.exports = { breaking: 'List any BREAKING CHANGES (optional):\n', footer: 'List any ISSUES CLOSED by this change (optional). E.g.: #31, #34:\n', - confirmCommit: 'Are you sure you want to proceed with the commit above?' + confirmCommit: 'Are you sure you want to proceed with the commit above?', }, allowCustomScopes: false, @@ -75,7 +75,7 @@ module.exports = { skipQuestions: ['ticketNumber'], // limit subject length - subjectLimit: 100 + subjectLimit: 100, // breaklineChar: '|', // It is supported for fields body and footer. // footerPrefix : 'ISSUES CLOSED:' // askForBreakingChangeFirst : true, // default is false diff --git a/docs/angular/guides/misc-data-persistence.md b/docs/angular/guides/misc-data-persistence.md index fe25f94076378..b4b84ad4e0d01 100644 --- a/docs/angular/guides/misc-data-persistence.md +++ b/docs/angular/guides/misc-data-persistence.md @@ -27,9 +27,9 @@ class TodoEffects { // dispatch an undo action to undo the changes in the client state return { type: 'UNDO_TODO_UPDATE', - todo: action.todo + todo: action.todo, }; - } + }, }) ) ); @@ -57,9 +57,9 @@ class TodoEffects { // update the backend first, and then dispatch an action that will // update the client side return this.backend.updateTodo(action.todo.id, action.todo).pipe( - map(updated => ({ + map((updated) => ({ type: 'UPDATE_TODO_SUCCESS', - todo: updated + todo: updated, })) ); }, @@ -67,7 +67,7 @@ class TodoEffects { // we don't need to undo the changes on the client side. // we can dispatch an error, or simply log the error here and return `null` return null; - } + }, }) ) ); @@ -93,9 +93,9 @@ class TodoEffects { // provides an action run: (a: GetTodos) => { return this.backend.getAll().pipe( - map(response => ({ + map((response) => ({ type: 'TODOS', - todos: response.todos + todos: response.todos, })) ); }, @@ -103,7 +103,7 @@ class TodoEffects { onError: (action: GetTodos, error: any) => { // dispatch an undo action to undo the changes in the client state return null; - } + }, }) ) ); @@ -130,16 +130,16 @@ class TodoEffects { // provides an action run: (todo: GetTodo) => { - return this.backend.getTodo(todo.id).map(response => ({ + return this.backend.getTodo(todo.id).map((response) => ({ type: 'LOAD_TODO_SUCCESS', - todo: response.todo + todo: response.todo, })); }, onError: (action: GetTodo, error: any) => { // dispatch an undo action to undo the changes in the client state return null; - } + }, }) ) ); @@ -170,9 +170,9 @@ class TodoEffects { return this.backend .fetchTodo(activatedRouteSnapshot.params['id']) .pipe( - map(todo => ({ + map((todo) => ({ type: 'LOAD_TODO_SUCCESS', - todo: todo + todo: todo, })) ); }, @@ -184,7 +184,7 @@ class TodoEffects { // we can log and error here and return null // we can also navigate back return null; - } + }, }) ) ); diff --git a/docs/angular/guides/misc-upgrade.md b/docs/angular/guides/misc-upgrade.md index a2ab8be587407..b840a290289cb 100644 --- a/docs/angular/guides/misc-upgrade.md +++ b/docs/angular/guides/misc-upgrade.md @@ -78,7 +78,7 @@ If you have an Angular component that has an AngularJS child component you may n @Component({ selector: 'app-ticket-list', templateUrl: './ticket-list.component.html', - styleUrls: ['./ticket-list.component.css'] + styleUrls: ['./ticket-list.component.css'], }) export class TicketListComponent implements OnInit { @Input() tuskTickets; @@ -87,7 +87,7 @@ export class TicketListComponent implements OnInit { constructor(@Inject('$rootScope') private rootScope: any) {} onNotifyAll() { - this.notifyList = this.tuskTickets.map(function(t) { + this.notifyList = this.tuskTickets.map(function (t) { return t.id; }); // we need to force digest to trigger angularjs change detection diff --git a/docs/angular/guides/react-and-angular.md b/docs/angular/guides/react-and-angular.md index b55365ea86378..a5a9f26e0dc9d 100644 --- a/docs/angular/guides/react-and-angular.md +++ b/docs/angular/guides/react-and-angular.md @@ -93,7 +93,7 @@ if (environment.production) { platformBrowserDynamic() .bootstrapModule(AppModule) - .catch(err => console.error(err)); + .catch((err) => console.error(err)); ``` And the template of the generated component will look as follows: @@ -313,7 +313,7 @@ if (environment.production) { platformBrowserDynamic() .bootstrapModule(AppModule) - .catch(err => console.error(err)); + .catch((err) => console.error(err)); ``` ### Registering CUSTOM_ELEMENTS_SCHEMA @@ -326,7 +326,7 @@ Next, let's register the `CUSTOM_ELEMENTS_SCHEMA` schema, which will tell the An imports: [BrowserModule], providers: [], schemas: [CUSTOM_ELEMENTS_SCHEMA], - bootstrap: [AppComponent] + bootstrap: [AppComponent], }) export class AppModule {} ``` diff --git a/docs/angular/guides/storybook-plugin.md b/docs/angular/guides/storybook-plugin.md index 6d85084e70b7a..bc2240a5cb842 100644 --- a/docs/angular/guides/storybook-plugin.md +++ b/docs/angular/guides/storybook-plugin.md @@ -98,19 +98,19 @@ import { text, number, boolean } from '@storybook/addon-knobs'; import { ButtonComponent } from './button.component'; export default { - title: 'ButtonComponent' + title: 'ButtonComponent', }; export const primary = () => ({ moduleMetadata: { - imports: [] + imports: [], }, component: ButtonComponent, props: { text: text('text', 'Click me!'), padding: number('padding', 0), - style: text('style', 'default') - } + style: text('style', 'default'), + }, }); ``` diff --git a/docs/angular/tutorial/02-add-e2e-test.md b/docs/angular/tutorial/02-add-e2e-test.md index c759aace18438..360204d96900b 100644 --- a/docs/angular/tutorial/02-add-e2e-test.md +++ b/docs/angular/tutorial/02-add-e2e-test.md @@ -20,9 +20,9 @@ describe('TodoApps', () => { beforeEach(() => cy.visit('/')); it('should display todos', () => { - getTodos().should(t => expect(t.length).equal(2)); + getTodos().should((t) => expect(t.length).equal(2)); getAddTodoButton().click(); - getTodos().should(t => expect(t.length).equal(3)); + getTodos().should((t) => expect(t.length).equal(3)); }); }); ``` diff --git a/docs/angular/tutorial/03-display-todos.md b/docs/angular/tutorial/03-display-todos.md index e64d6d0f22b52..16dfea6885d27 100644 --- a/docs/angular/tutorial/03-display-todos.md +++ b/docs/angular/tutorial/03-display-todos.md @@ -20,7 +20,7 @@ interface Todo { @Component({ selector: 'myorg-root', templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] + styleUrls: ['./app.component.css'], }) export class AppComponent { todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }]; @@ -53,14 +53,14 @@ interface Todo { @Component({ selector: 'myorg-root', templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] + styleUrls: ['./app.component.css'], }) export class AppComponent { todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }]; addTodo() { this.todos.push({ - title: `New todo ${Math.floor(Math.random() * 1000)}` + title: `New todo ${Math.floor(Math.random() * 1000)}`, }); } } diff --git a/docs/angular/tutorial/04-connect-to-api.md b/docs/angular/tutorial/04-connect-to-api.md index c42d3b9c14f1d..88f27717705b3 100644 --- a/docs/angular/tutorial/04-connect-to-api.md +++ b/docs/angular/tutorial/04-connect-to-api.md @@ -15,7 +15,7 @@ import { HttpClientModule } from '@angular/common/http'; declarations: [AppComponent], imports: [BrowserModule, HttpClientModule], providers: [], - bootstrap: [AppComponent] + bootstrap: [AppComponent], }) export class AppModule {} ``` @@ -33,7 +33,7 @@ interface Todo { @Component({ selector: 'myorg-root', templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] + styleUrls: ['./app.component.css'], }) export class AppComponent { todos: Todo[] = []; @@ -43,7 +43,7 @@ export class AppComponent { } fetch() { - this.http.get('/api/todos').subscribe(t => (this.todos = t)); + this.http.get('/api/todos').subscribe((t) => (this.todos = t)); } addTodo() { diff --git a/docs/angular/tutorial/05-add-node-app.md b/docs/angular/tutorial/05-add-node-app.md index c177818c2e564..d52de68306a67 100644 --- a/docs/angular/tutorial/05-add-node-app.md +++ b/docs/angular/tutorial/05-add-node-app.md @@ -122,7 +122,7 @@ import { AppService } from './app.service'; @Module({ imports: [], controllers: [AppController], - providers: [AppService] + providers: [AppService], }) export class AppModule {} ``` @@ -150,7 +150,7 @@ export class AppService { addTodo() { this.todos.push({ - title: `New todo ${Math.floor(Math.random() * 1000)}` + title: `New todo ${Math.floor(Math.random() * 1000)}`, }); } } diff --git a/docs/angular/tutorial/07-share-code.md b/docs/angular/tutorial/07-share-code.md index b17cd05b4a533..bee7c00618b10 100644 --- a/docs/angular/tutorial/07-share-code.md +++ b/docs/angular/tutorial/07-share-code.md @@ -65,7 +65,7 @@ export class AppService { addTodo() { this.todos.push({ - title: `New todo ${Math.floor(Math.random() * 1000)}` + title: `New todo ${Math.floor(Math.random() * 1000)}`, }); } } @@ -83,7 +83,7 @@ import { Todo } from '@myorg/data'; @Component({ selector: 'myorg-root', templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] + styleUrls: ['./app.component.css'], }) export class AppComponent { todos: Todo[] = []; @@ -93,7 +93,7 @@ export class AppComponent { } fetch() { - this.http.get('/api/todos').subscribe(t => (this.todos = t)); + this.http.get('/api/todos').subscribe((t) => (this.todos = t)); } addTodo() { diff --git a/docs/angular/tutorial/08-create-libs.md b/docs/angular/tutorial/08-create-libs.md index 121130bdb5af6..86fcd72043152 100644 --- a/docs/angular/tutorial/08-create-libs.md +++ b/docs/angular/tutorial/08-create-libs.md @@ -47,7 +47,7 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @NgModule({ - imports: [CommonModule] + imports: [CommonModule], }) export class UiModule {} ``` @@ -100,7 +100,7 @@ import { Todo } from '@myorg/data'; @Component({ selector: 'myorg-todos', templateUrl: './todos.component.html', - styleUrls: ['./todos.component.css'] + styleUrls: ['./todos.component.css'], }) export class TodosComponent implements OnInit { @Input() todos: Todo[]; @@ -135,7 +135,7 @@ import { UiModule } from '@myorg/ui'; declarations: [AppComponent], imports: [BrowserModule, HttpClientModule, UiModule], providers: [], - bootstrap: [AppComponent] + bootstrap: [AppComponent], }) export class AppModule {} ``` diff --git a/docs/react/tutorial/02-add-e2e-test.md b/docs/react/tutorial/02-add-e2e-test.md index 36162a3ac21d4..0d4cf29262118 100644 --- a/docs/react/tutorial/02-add-e2e-test.md +++ b/docs/react/tutorial/02-add-e2e-test.md @@ -20,9 +20,9 @@ describe('TodoApps', () => { beforeEach(() => cy.visit('/')); it('should display todos', () => { - getTodos().should(t => expect(t.length).equal(2)); + getTodos().should((t) => expect(t.length).equal(2)); getAddTodoButton().click(); - getTodos().should(t => expect(t.length).equal(3)); + getTodos().should((t) => expect(t.length).equal(3)); }); }); ``` diff --git a/docs/react/tutorial/03-display-todos.md b/docs/react/tutorial/03-display-todos.md index 74c55149f4be3..a5e6ca42cdf8d 100644 --- a/docs/react/tutorial/03-display-todos.md +++ b/docs/react/tutorial/03-display-todos.md @@ -20,14 +20,14 @@ interface Todo { export const App = () => { const [todos, setTodos] = useState([ { title: 'Todo 1' }, - { title: 'Todo 2' } + { title: 'Todo 2' }, ]); return ( <>

Todos

    - {todos.map(t => ( + {todos.map((t) => (
  • {t.title}
  • ))}
@@ -54,15 +54,15 @@ interface Todo { export const App = () => { const [todos, setTodos] = useState([ { title: 'Todo 1' }, - { title: 'Todo 2' } + { title: 'Todo 2' }, ]); function addTodo() { setTodos([ ...todos, { - title: `New todo ${Math.floor(Math.random() * 1000)}` - } + title: `New todo ${Math.floor(Math.random() * 1000)}`, + }, ]); } @@ -70,7 +70,7 @@ export const App = () => { <>

Todos

    - {todos.map(t => ( + {todos.map((t) => (
  • {t.title}
  • ))}
diff --git a/docs/react/tutorial/04-connect-to-api.md b/docs/react/tutorial/04-connect-to-api.md index 477f8b26f0bee..d4a6922bacca3 100644 --- a/docs/react/tutorial/04-connect-to-api.md +++ b/docs/react/tutorial/04-connect-to-api.md @@ -16,17 +16,17 @@ const App = () => { useEffect(() => { fetch('/api/todos') - .then(_ => _.json()) + .then((_) => _.json()) .then(setTodos); }, []); function addTodo() { fetch('/api/addTodo', { method: 'POST', - body: '' + body: '', }) - .then(_ => _.json()) - .then(newTodo => { + .then((_) => _.json()) + .then((newTodo) => { setTodos([...todos, newTodo]); }); } @@ -35,7 +35,7 @@ const App = () => { <>

Todos

    - {todos.map(t => ( + {todos.map((t) => (
  • {t.title}
  • ))}
diff --git a/docs/react/tutorial/05-add-node-app.md b/docs/react/tutorial/05-add-node-app.md index 894d1bccad38f..7b8d580e5daf5 100644 --- a/docs/react/tutorial/05-add-node-app.md +++ b/docs/react/tutorial/05-add-node-app.md @@ -117,7 +117,7 @@ export function addTodoRoutes(app: Express) { app.get('/api/todos', (req, resp) => resp.send(todos)); app.post('/api/addTodo', (req, resp) => { const newTodo = { - title: `New todo ${Math.floor(Math.random() * 1000)}` + title: `New todo ${Math.floor(Math.random() * 1000)}`, }; todos.push(newTodo); resp.send(newTodo); diff --git a/docs/react/tutorial/07-share-code.md b/docs/react/tutorial/07-share-code.md index 8b04d69f711b4..b6a50f5efd41d 100644 --- a/docs/react/tutorial/07-share-code.md +++ b/docs/react/tutorial/07-share-code.md @@ -58,7 +58,7 @@ export function addTodoRoutes(app: Express) { app.get('/api/todos', (req, resp) => resp.send(todos)); app.post('/api/addTodo', (req, resp) => { const newTodo = { - title: `New todo ${Math.floor(Math.random() * 1000)}` + title: `New todo ${Math.floor(Math.random() * 1000)}`, }; todos.push(newTodo); resp.send(newTodo); diff --git a/docs/react/tutorial/08-create-libs.md b/docs/react/tutorial/08-create-libs.md index b972e35589c51..e3c2616d2afde 100644 --- a/docs/react/tutorial/08-create-libs.md +++ b/docs/react/tutorial/08-create-libs.md @@ -114,7 +114,7 @@ import { Todo } from '@myorg/data'; export const Todos = (props: { todos: Todo[] }) => { return (
    - {props.todos.map(t => ( + {props.todos.map((t) => (
  • {t.title}
  • ))}
@@ -138,17 +138,17 @@ const App = () => { useEffect(() => { fetch('/api/todos') - .then(_ => _.json()) + .then((_) => _.json()) .then(setTodos); }, []); function addTodo() { fetch('/api/addTodo', { method: 'POST', - body: '' + body: '', }) - .then(_ => _.json()) - .then(newTodo => { + .then((_) => _.json()) + .then((newTodo) => { setTodos([...todos, newTodo]); }); } diff --git a/docs/react/tutorial/11-test-affected-projects.md b/docs/react/tutorial/11-test-affected-projects.md index cc6c21c686eda..e092ae1b41548 100644 --- a/docs/react/tutorial/11-test-affected-projects.md +++ b/docs/react/tutorial/11-test-affected-projects.md @@ -19,7 +19,7 @@ import { Todo } from '@myorg/data'; export const Todos = (props: { todos: Todo[] }) => { return (
    - {props.todos.map(t => ( + {props.todos.map((t) => (
  • {t.title}!!
  • ))}
diff --git a/docs/shared/monorepo-ci-azure.md b/docs/shared/monorepo-ci-azure.md index 0525cb9c21307..464c20fa734b1 100644 --- a/docs/shared/monorepo-ci-azure.md +++ b/docs/shared/monorepo-ci-azure.md @@ -139,7 +139,7 @@ console.log( JSON.stringify({ ...commands('lint'), ...commands('test'), - ...commands('build') + ...commands('build'), }) ); @@ -148,7 +148,7 @@ function commands(target) { execSync(`npx nx print-affected --base=${baseSha} --target=${target}`) .toString() .trim() - ).tasks.map(t => t.target.project); + ).tasks.map((t) => t.target.project); array.sort(() => 0.5 - Math.random()); const third = Math.floor(array.length / 3); @@ -158,7 +158,7 @@ function commands(target) { return { [target + '1']: a1, [target + '2']: a2, - [target + '3']: a3 + [target + '3']: a3, }; } ``` @@ -221,7 +221,7 @@ execSync( ',' )} --parallel`, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], } ); ``` diff --git a/docs/shared/nx-plugin.md b/docs/shared/nx-plugin.md index d480974a0c47c..8ed0c00244de7 100644 --- a/docs/shared/nx-plugin.md +++ b/docs/shared/nx-plugin.md @@ -186,7 +186,7 @@ When the plugin is generated, a test file is created in the `my-plugin-e2e` app. We'll go over a few parts of a test file below: ```typescript -it('should create my-plugin', async done => { +it('should create my-plugin', async (done) => { const plugin = uniq('my-plugin'); ensureNxProject('@my-org/my-plugin', 'dist/libs/my-plugin'); await runNxCommandAsync(`generate @my-org/my-plugin:myPlugin ${plugin}`); diff --git a/docs/shared/tools-workspace-schematics.md b/docs/shared/tools-workspace-schematics.md index 9543be76df537..10a4b303448e3 100644 --- a/docs/shared/tools-workspace-schematics.md +++ b/docs/shared/tools-workspace-schematics.md @@ -34,11 +34,11 @@ The initial schematic entry point contains a rule to generate a library. ```ts import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; -export default function(schema: any): Rule { +export default function (schema: any): Rule { return chain([ externalSchematic('@nrwl/workspace', 'lib', { - name: schema.name - }) + name: schema.name, + }), ]); } ``` @@ -112,13 +112,13 @@ import { SchematicContext, Tree, url, - externalSchematic + externalSchematic, } from '@angular-devkit/schematics'; import { getProjectConfig } from '@nrwl/workspace'; function generateLibrary(schema: any): Rule { return externalSchematic('@nrwl/workspace', 'lib', { - name: schema.name + name: schema.name, }); } @@ -127,14 +127,14 @@ function generateFiles(schema: any): Rule { context.logger.info('adding NOTES.md to lib'); const templateSource = apply(url('./files'), [ - move(getProjectConfig(tree, schema.name).root) + move(getProjectConfig(tree, schema.name).root), ]); return chain([mergeWith(templateSource)])(tree, context); }; } -export default function(schema: any): Rule { +export default function (schema: any): Rule { return (tree: Tree, context: SchematicContext) => { return chain([generateLibrary(schema), generateFiles(schema)])( tree, @@ -193,12 +193,12 @@ Import the TypeScript schema into your schematic file and replace the any in you import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; import { SchematicOptions } from './schema'; -export default function(schema: SchematicOptions): Rule { +export default function (schema: SchematicOptions): Rule { return chain([ externalSchematic('@nrwl/workspace', 'lib', { name: `${schema.name}-${schema.type || ''}`, - unitTestRunner: 'none' - }) + unitTestRunner: 'none', + }), ]); } ``` diff --git a/e2e/angular-package.test.ts b/e2e/angular-package.test.ts index b06d4d515fc5e..622aa071c90e5 100644 --- a/e2e/angular-package.test.ts +++ b/e2e/angular-package.test.ts @@ -5,10 +5,10 @@ import { readJson, runCLI, uniq, - updateFile + updateFile, } from './utils'; -forEachCli('angular', cli => { +forEachCli('angular', (cli) => { describe('Build Angular library', () => { /** * Graph: @@ -51,7 +51,7 @@ forEachCli('angular', cli => { import { CommonModule } from '@angular/common'; ${children .map( - entry => + (entry) => `import { ${toClassName( entry )}Module } from '@proj/${entry}';` @@ -60,7 +60,7 @@ forEachCli('angular', cli => { @NgModule({ imports: [CommonModule, ${children - .map(entry => `${toClassName(entry)}Module`) + .map((entry) => `${toClassName(entry)}Module`) .join(',')}] }) export class ${toClassName(parent)}Module {} @@ -101,7 +101,7 @@ forEachCli('angular', cli => { const jsonFile = readJson(`dist/libs/${parentLib}/package.json`); expect(jsonFile.dependencies).toEqual({ [`@proj/${childLib}`]: '0.0.1', - [`@proj/${childLib2}`]: '0.0.1' + [`@proj/${childLib2}`]: '0.0.1', }); }); }); diff --git a/e2e/angular.test.ts b/e2e/angular.test.ts index 998fd458b83fa..d0e1a2f2cd0ba 100644 --- a/e2e/angular.test.ts +++ b/e2e/angular.test.ts @@ -10,7 +10,7 @@ import { forEachCli, checkFilesExist, tmpProjPath, - supportUi + supportUi, } from './utils'; import { toClassName } from '@nrwl/workspace'; diff --git a/e2e/bazel.test.ts b/e2e/bazel.test.ts index f85d5240fd9f8..701b19a90cdb0 100644 --- a/e2e/bazel.test.ts +++ b/e2e/bazel.test.ts @@ -6,10 +6,10 @@ import { runCLI, runCommand, uniq, - updateFile + updateFile, } from './utils'; -forEachCli(currentCLIName => { +forEachCli((currentCLIName) => { describe('Bazel', () => { const ngapp = uniq('ngapp'); const reactapp = uniq('reactapp'); diff --git a/e2e/cli.test.ts b/e2e/cli.test.ts index 4e892fe089bad..06c0c769156d6 100644 --- a/e2e/cli.test.ts +++ b/e2e/cli.test.ts @@ -10,7 +10,7 @@ import { runCommand, tmpProjPath, uniq, - updateFile + updateFile, } from './utils'; forEachCli('nx', () => { @@ -84,7 +84,7 @@ forEachCli(() => { const reportOutput = runCommand('npm run nx report'); - packagesWeCareAbout.forEach(p => { + packagesWeCareAbout.forEach((p) => { expect(reportOutput).toContain(p); }); }, 120000); @@ -157,7 +157,7 @@ forEachCli(() => { `./node_modules/migrate-parent-package/package.json`, JSON.stringify({ version: '1.0.0', - 'nx-migrations': './migrations.json' + 'nx-migrations': './migrations.json', }) ); @@ -168,14 +168,14 @@ forEachCli(() => { run11: { version: '1.1.0', description: '1.1.0', - factory: './run11' + factory: './run11', }, run20: { version: '2.0.0', description: '2.0.0', - factory: './run20' - } - } + factory: './run20', + }, + }, }) ); @@ -204,13 +204,13 @@ forEachCli(() => { updateFile( `./node_modules/migrate-child-package/package.json`, JSON.stringify({ - version: '1.0.0' + version: '1.0.0', }) ); updateFile( './node_modules/@nrwl/tao/src/commands/migrate.js', - content => { + (content) => { const start = content.indexOf('// testing-fetch-start'); const end = content.indexOf('// testing-fetch-end'); @@ -262,14 +262,14 @@ forEachCli(() => { { package: 'migrate-parent-package', version: '1.1.0', - name: 'run11' + name: 'run11', }, { package: 'migrate-parent-package', version: '2.0.0', - name: 'run20' - } - ] + name: 'run20', + }, + ], }); // runs migrations diff --git a/e2e/commands/create-nx-workspace.test.ts b/e2e/commands/create-nx-workspace.test.ts index fea3434b362a4..a7d55beb3eb4f 100644 --- a/e2e/commands/create-nx-workspace.test.ts +++ b/e2e/commands/create-nx-workspace.test.ts @@ -8,7 +8,7 @@ describe('create-nx-workspace', () => { execSync(`yarn local-registry disable`); }); - it('creates a new project', async done => { + it('creates a new project', async (done) => { if (!process.env.PUBLISHED_VERSION) { console.error(`Please provision the version you are publishing`); process.exit(1); @@ -54,7 +54,7 @@ describe('create-nx-workspace', () => { expect( execSync(`npm_config_registry=http://localhost:4873/ && npm audit`, { - cwd: workspaceDir + cwd: workspaceDir, }).toString() ).toContain(`0 vulnerabilities`); @@ -66,7 +66,7 @@ describe('create-nx-workspace', () => { // filtering out rxjs in the listr package. const rxjs = allVersionsOf(workspaceDir, 'rxjs').filter( - value => value !== '5.5.12' + (value) => value !== '5.5.12' ); if (rxjs.length > 1) { console.log(`more than one version of rxjs: ${rxjs.join(', ')}`); @@ -83,7 +83,7 @@ describe('create-nx-workspace', () => { }); function wait(value = 500) { - return new Promise(r => { + return new Promise((r) => { setTimeout(() => r(), value); }); } @@ -91,13 +91,13 @@ function wait(value = 500) { function startRegistry() { return new Promise((res, rej) => { const server = exec('yarn local-registry start'); - server.stdout.on('data', d => { + server.stdout.on('data', (d) => { if (d.toString().indexOf('http address') > -1) { res(); } }); - server.on('exit', s => { + server.on('exit', (s) => { if (s !== 0) { rej(`Cannot start local registry`); } @@ -107,7 +107,7 @@ function startRegistry() { function allVersionsOf(dir: string, packageToCheck: string) { const r = packageJsonFilesInNodeModules(`${dir}/node_modules`) - .map(p => { + .map((p) => { try { const parsed = JSON.parse(readFileSync(p).toString()); if (parsed.name == packageToCheck) { @@ -118,7 +118,7 @@ function allVersionsOf(dir: string, packageToCheck: string) { return null; } }) - .filter(p => !!p); + .filter((p) => !!p); return r.filter((value, index, self) => self.indexOf(value) === index); } @@ -133,7 +133,7 @@ function addReact(workspaceDir: string) { ); execSync(`npm install --registry=http://localhost:4873/`, { stdio: [0, 1, 2], - cwd: workspaceDir + cwd: workspaceDir, }); } @@ -141,7 +141,7 @@ async function execCommand(description: string, cmd: string, cwd?: string) { console.log(description); execSync(`npm_config_registry=http://localhost:4873/ && ${cmd}`, { stdio: [0, 1, 2], - cwd + cwd, }); await wait(); } @@ -149,7 +149,7 @@ async function execCommand(description: string, cmd: string, cwd?: string) { function packageJsonFilesInNodeModules(dirName: string): string[] { let res = []; try { - readdirSync(dirName).forEach(c => { + readdirSync(dirName).forEach((c) => { try { const child = path.join(dirName, c); const s = statSync(child); diff --git a/e2e/cypress.test.ts b/e2e/cypress.test.ts index dec7a68377691..2a78521527d81 100644 --- a/e2e/cypress.test.ts +++ b/e2e/cypress.test.ts @@ -8,10 +8,10 @@ import { runCLI, supportUi, uniq, - updateFile + updateFile, } from './utils'; -forEachCli(currentCLIName => { +forEachCli((currentCLIName) => { const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint'; const nrwlPackageName = currentCLIName === 'angular' ? 'angular' : 'react'; diff --git a/e2e/downgrade-module.test.ts b/e2e/downgrade-module.test.ts index aa987e35766ee..b19cb5361ad61 100644 --- a/e2e/downgrade-module.test.ts +++ b/e2e/downgrade-module.test.ts @@ -5,7 +5,7 @@ import { updateFile, forEachCli, supportUi, - patchKarmaToWorkOnWSL + patchKarmaToWorkOnWSL, } from './utils'; forEachCli('angular', () => { diff --git a/e2e/jest.test.ts b/e2e/jest.test.ts index 26d18b47df414..e3125a73f18d4 100644 --- a/e2e/jest.test.ts +++ b/e2e/jest.test.ts @@ -4,13 +4,13 @@ import { uniq, runCLI, forEachCli, - updateFile + updateFile, } from './utils'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; forEachCli(() => { describe('Jest', () => { - it('should be able test projects using jest', async done => { + it('should be able test projects using jest', async (done) => { ensureProject(); const mylib = uniq('mylib'); const myapp = uniq('myapp'); @@ -21,7 +21,7 @@ forEachCli(() => { runCLIAsync(`generate @nrwl/angular:service test --project ${myapp}`), runCLIAsync(`generate @nrwl/angular:component test --project ${myapp}`), runCLIAsync(`generate @nrwl/angular:service test --project ${mylib}`), - runCLIAsync(`generate @nrwl/angular:component test --project ${mylib}`) + runCLIAsync(`generate @nrwl/angular:component test --project ${mylib}`), ]); const appResult = await runCLIAsync(`test ${myapp} --no-watch`); expect(appResult.stderr).toContain('Test Suites: 3 passed, 3 total'); @@ -30,7 +30,7 @@ forEachCli(() => { done(); }, 45000); - it('should merge with jest config globals', async done => { + it('should merge with jest config globals', async (done) => { ensureProject(); const testGlobal = `'My Test Global'`; const mylib = uniq('mylib'); @@ -68,7 +68,7 @@ forEachCli(() => { done(); }, 45000); - it('should set the NODE_ENV to `test`', async done => { + it('should set the NODE_ENV to `test`', async (done) => { ensureProject(); const mylib = uniq('mylib'); runCLI(`generate @nrwl/workspace:lib ${mylib} --unit-test-runner jest`); diff --git a/e2e/karma.test.ts b/e2e/karma.test.ts index 11baa0b93cac0..ac765963e345c 100644 --- a/e2e/karma.test.ts +++ b/e2e/karma.test.ts @@ -5,12 +5,12 @@ import { uniq, forEachCli, supportUi, - patchKarmaToWorkOnWSL + patchKarmaToWorkOnWSL, } from './utils'; forEachCli(() => { describe('Karma', () => { - it('should be able to generate a testable library using karma', async done => { + it('should be able to generate a testable library using karma', async (done) => { ensureProject(); const mylib = uniq('mylib'); @@ -19,7 +19,7 @@ forEachCli(() => { await Promise.all([ runCLIAsync(`generate @nrwl/angular:service test --project ${mylib}`), - runCLIAsync(`generate @nrwl/angular:component test --project ${mylib}`) + runCLIAsync(`generate @nrwl/angular:component test --project ${mylib}`), ]); const karmaResult = await runCLIAsync(`test ${mylib}`); @@ -27,7 +27,7 @@ forEachCli(() => { done(); }, 30000); - it('should be able to generate a testable application using karma', async done => { + it('should be able to generate a testable application using karma', async (done) => { ensureProject(); const myapp = uniq('myapp'); runCLI(`generate @nrwl/angular:app ${myapp} --unit-test-runner karma`); @@ -35,7 +35,7 @@ forEachCli(() => { await Promise.all([ runCLIAsync(`generate @nrwl/angular:service test --project ${myapp}`), - runCLIAsync(`generate @nrwl/angular:component test --project ${myapp}`) + runCLIAsync(`generate @nrwl/angular:component test --project ${myapp}`), ]); const karmaResult = await runCLIAsync(`test ${myapp}`); expect(karmaResult.stdout).toContain('5 SUCCESS'); diff --git a/e2e/linter.test.ts b/e2e/linter.test.ts index b39bfcd3cf6e6..3c4067559eb99 100644 --- a/e2e/linter.test.ts +++ b/e2e/linter.test.ts @@ -7,7 +7,7 @@ import { updateFile, ensureProject, uniq, - forEachCli + forEachCli, } from './utils'; forEachCli('nx', () => { @@ -100,7 +100,7 @@ forEachCli('nx', () => { expect(() => checkFilesExist(`my-cache`)).toThrow(); runCLI(`lint ${myapp} --cache --cache-location="my-cache"`, { - silenceError: true + silenceError: true, }); expect(() => checkFilesExist(`my-cache`)).not.toThrow(); const cacheInfo = readFile('my-cache'); @@ -125,14 +125,16 @@ forEachCli('nx', () => { const stdout = runCLI( `lint ${myapp} --output-file="${outputFile}" --format=json`, { - silenceError: true + silenceError: true, } ); expect(stdout).toContain('Unexpected console statement'); expect(() => checkFilesExist(outputFile)).not.toThrow(); const outputContents = JSON.parse(readFile(outputFile)); - const outputForApp: any = Object.values(outputContents).filter( - (result: any) => result.filePath.includes(`${myapp}/src/main.ts`) + const outputForApp: any = Object.values( + outputContents + ).filter((result: any) => + result.filePath.includes(`${myapp}/src/main.ts`) )[0]; expect(outputForApp.errorCount).toBe(1); expect(outputForApp.messages[0].ruleId).toBe('no-console'); diff --git a/e2e/next.test.ts b/e2e/next.test.ts index 6e8362a2b0f8f..f14267feae93f 100644 --- a/e2e/next.test.ts +++ b/e2e/next.test.ts @@ -9,7 +9,7 @@ import { runCLIAsync, supportUi, uniq, - updateFile + updateFile, } from './utils'; forEachCli('nx', () => { @@ -24,9 +24,9 @@ forEachCli('nx', () => { '/external-api': { target: 'http://localhost:4200', pathRewrite: { - '^/external-api/hello': '/api/hello' - } - } + '^/external-api/hello': '/api/hello', + }, + }, }; updateFile(`apps/${appName}/proxy.conf.json`, JSON.stringify(proxyConf)); diff --git a/e2e/ng-add.test.ts b/e2e/ng-add.test.ts index 18fefac2c5081..b5879dbe26218 100644 --- a/e2e/ng-add.test.ts +++ b/e2e/ng-add.test.ts @@ -9,7 +9,7 @@ import { runNew, updateFile, forEachCli, - runNgAdd + runNgAdd, } from './utils'; forEachCli('angular', () => { @@ -43,10 +43,10 @@ forEachCli('angular', () => { // update angular-cli.json const angularCLIJson = readJson('angular.json'); angularCLIJson.projects.proj.architect.build.options.scripts = angularCLIJson.projects.proj.architect.test.options.scripts = [ - 'src/scripts.ts' + 'src/scripts.ts', ]; angularCLIJson.projects.proj.architect.test.options.styles = [ - 'src/styles.css' + 'src/styles.css', ]; updateFile('angular.json', JSON.stringify(angularCLIJson, null, 2)); @@ -66,7 +66,7 @@ forEachCli('angular', () => { 'nrwl.angular-console', 'angular.ng-template', 'ms-vscode.vscode-typescript-tslint-plugin', - 'esbenp.prettier-vscode' + 'esbenp.prettier-vscode', ]); // check that package.json got merged @@ -95,7 +95,7 @@ forEachCli('angular', () => { 'update:check': 'ng update', 'dep-graph': 'nx dep-graph', 'workspace-schematic': 'nx workspace-schematic', - help: 'nx help' + help: 'nx help', }); expect( updatedPackageJson.devDependencies['@nrwl/workspace'] @@ -110,16 +110,16 @@ forEachCli('angular', () => { 'package.json': '*', 'tslint.json': '*', 'tsconfig.json': '*', - 'nx.json': '*' + 'nx.json': '*', }, projects: { proj: { - tags: [] + tags: [], }, 'proj-e2e': { - tags: [] - } - } + tags: [], + }, + }, }); // check if angular-cli.json get merged @@ -140,27 +140,27 @@ forEachCli('angular', () => { tsConfig: 'apps/proj/tsconfig.app.json', assets: ['apps/proj/src/favicon.ico', 'apps/proj/src/assets'], styles: ['apps/proj/src/styles.css'], - scripts: ['apps/proj/src/scripts.ts'] + scripts: ['apps/proj/src/scripts.ts'], }, configurations: { production: { fileReplacements: [ { replace: 'apps/proj/src/environments/environment.ts', - with: 'apps/proj/src/environments/environment.prod.ts' - } + with: 'apps/proj/src/environments/environment.prod.ts', + }, ], budgets: [ { maximumError: '5mb', maximumWarning: '2mb', - type: 'initial' + type: 'initial', }, { maximumError: '10kb', maximumWarning: '6kb', - type: 'anyComponentStyle' - } + type: 'anyComponentStyle', + }, ], optimization: true, outputHashing: 'all', @@ -169,20 +169,20 @@ forEachCli('angular', () => { namedChunks: false, extractLicenses: true, vendorChunk: false, - buildOptimizer: true - } - } + buildOptimizer: true, + }, + }, }); expect(updatedAngularCLIJson.projects.proj.architect.serve).toEqual({ builder: '@angular-devkit/build-angular:dev-server', options: { - browserTarget: 'proj:build' + browserTarget: 'proj:build', }, configurations: { production: { - browserTarget: 'proj:build:production' - } - } + browserTarget: 'proj:build:production', + }, + }, }); expect(updatedAngularCLIJson.projects.proj.architect.test).toEqual({ @@ -194,8 +194,8 @@ forEachCli('angular', () => { karmaConfig: 'apps/proj/karma.conf.js', styles: ['apps/proj/src/styles.css'], scripts: ['apps/proj/src/scripts.ts'], - assets: ['apps/proj/src/favicon.ico', 'apps/proj/src/assets'] - } + assets: ['apps/proj/src/favicon.ico', 'apps/proj/src/assets'], + }, }); expect(updatedAngularCLIJson.projects.proj.architect.lint).toEqual({ @@ -203,10 +203,10 @@ forEachCli('angular', () => { options: { tsConfig: [ 'apps/proj/tsconfig.app.json', - 'apps/proj/tsconfig.spec.json' + 'apps/proj/tsconfig.spec.json', ], - exclude: ['**/node_modules/**'] - } + exclude: ['**/node_modules/**'], + }, }); expect(updatedAngularCLIJson.projects['proj-e2e'].root).toEqual( @@ -216,21 +216,21 @@ forEachCli('angular', () => { builder: '@angular-devkit/build-angular:protractor', configurations: { production: { - devServerTarget: 'proj:serve:production' - } + devServerTarget: 'proj:serve:production', + }, }, options: { protractorConfig: 'apps/proj-e2e/protractor.conf.js', - devServerTarget: 'proj:serve' - } + devServerTarget: 'proj:serve', + }, }); expect(updatedAngularCLIJson.projects['proj-e2e'].architect.lint).toEqual( { builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: 'apps/proj-e2e/tsconfig.json', - exclude: ['**/node_modules/**'] - } + exclude: ['**/node_modules/**'], + }, } ); @@ -239,8 +239,8 @@ forEachCli('angular', () => { true, { allow: [], - depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }] - } + depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }], + }, ]); runCLI('build --prod --outputHashing none'); @@ -267,7 +267,7 @@ forEachCli('angular', () => { updateFile( '.vscode/extensions.json', JSON.stringify({ - recommendations: ['eamodio.gitlens', 'angular.ng-template'] + recommendations: ['eamodio.gitlens', 'angular.ng-template'], }) ); // run the command @@ -292,7 +292,7 @@ forEachCli('angular', () => { 'angular.ng-template', 'nrwl.angular-console', 'ms-vscode.vscode-typescript-tslint-plugin', - 'esbenp.prettier-vscode' + 'esbenp.prettier-vscode', ]); }); diff --git a/e2e/ngrx.test.ts b/e2e/ngrx.test.ts index b1c19306459d3..ebc6982a90683 100644 --- a/e2e/ngrx.test.ts +++ b/e2e/ngrx.test.ts @@ -5,7 +5,7 @@ import { uniq, ensureProject, readJson, - forEachCli + forEachCli, } from './utils'; forEachCli(() => { diff --git a/e2e/node.test.ts b/e2e/node.test.ts index 6ab6c1c8e7c07..e44b5ac33a06d 100644 --- a/e2e/node.test.ts +++ b/e2e/node.test.ts @@ -20,15 +20,15 @@ import { tmpProjPath, uniq, updateFile, - workspaceConfigName + workspaceConfigName, } from './utils'; function getData(): Promise { - return new Promise(resolve => { - http.get('http://localhost:3333/api', res => { + return new Promise((resolve) => { + http.get('http://localhost:3333/api', (res) => { expect(res.statusCode).toEqual(200); let data = ''; - res.on('data', chunk => { + res.on('data', (chunk) => { data += chunk; }); res.once('end', () => { @@ -38,7 +38,7 @@ function getData(): Promise { }); } -forEachCli(currentCLIName => { +forEachCli((currentCLIName) => { const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint'; describe('Node Applications', () => { @@ -56,12 +56,12 @@ forEachCli(currentCLIName => { checkFilesExist(`dist/apps/${nodeapp}/main.js`); const result = execSync(`node dist/apps/${nodeapp}/main.js`, { - cwd: tmpProjPath() + cwd: tmpProjPath(), }).toString(); expect(result).toContain('Hello World!'); }, 60000); - it('should be able to generate an express application', async done => { + it('should be able to generate an express application', async (done) => { ensureProject(); const nodeapp = uniq('nodeapp'); @@ -93,18 +93,18 @@ forEachCli(currentCLIName => { const server = fork(`./dist/apps/${nodeapp}/main.js`, [], { cwd: tmpProjPath(), - silent: true + silent: true, }); expect(server).toBeTruthy(); - await new Promise(resolve => { - server.stdout.once('data', async data => { + await new Promise((resolve) => { + server.stdout.once('data', async (data) => { expect(data.toString()).toContain( 'Listening at http://localhost:3333' ); const result = await getData(); expect(result.message).toEqual(`Welcome to ${nodeapp}!`); - treeKill(server.pid, 'SIGTERM', err => { + treeKill(server.pid, 'SIGTERM', (err) => { expect(err).toBeFalsy(); resolve(); }); @@ -116,22 +116,22 @@ forEachCli(currentCLIName => { options: { commands: [ { - command: 'sleep 1 && echo DONE' - } + command: 'sleep 1 && echo DONE', + }, ], - readyWhen: 'DONE' - } + readyWhen: 'DONE', + }, }; config.projects[nodeapp].architect.serve.options.waitUntilTargets = [ - `${nodeapp}:waitAndPrint` + `${nodeapp}:waitAndPrint`, ]; updateFile(workspaceConfigName(), JSON.stringify(config)); const process = spawn( 'node', ['./node_modules/.bin/nx', 'serve', nodeapp], { - cwd: tmpProjPath() + cwd: tmpProjPath(), } ); let collectedOutput = ''; @@ -143,7 +143,7 @@ forEachCli(currentCLIName => { const result = await getData(); expect(result.message).toEqual(`Welcome to ${nodeapp}!`); - treeKill(process.pid, 'SIGTERM', err => { + treeKill(process.pid, 'SIGTERM', (err) => { expect(collectedOutput.indexOf('DONE') > -1).toBeTruthy(); expect(err).toBeFalsy(); done(); @@ -182,7 +182,7 @@ forEachCli(currentCLIName => { cleanup(); }, 120000); - it('should be able to generate a nest application', async done => { + it('should be able to generate a nest application', async (done) => { ensureProject(); const nestapp = uniq('nestapp'); runCLI(`generate @nrwl/nest:app ${nestapp} --linter=${linter}`); @@ -204,18 +204,18 @@ forEachCli(currentCLIName => { const server = fork(`./dist/apps/${nestapp}/main.js`, [], { cwd: tmpProjPath(), - silent: true + silent: true, }); expect(server).toBeTruthy(); - await new Promise(resolve => { - server.stdout.on('data', async data => { + await new Promise((resolve) => { + server.stdout.on('data', async (data) => { const message = data.toString(); if (message.includes('Listening at http://localhost:3333')) { const result = await getData(); expect(result.message).toEqual(`Welcome to ${nestapp}!`); - treeKill(server.pid, 'SIGTERM', err => { + treeKill(server.pid, 'SIGTERM', (err) => { expect(err).toBeFalsy(); resolve(); }); @@ -227,7 +227,7 @@ forEachCli(currentCLIName => { 'node', ['./node_modules/@nrwl/cli/bin/nx', 'serve', nestapp], { - cwd: tmpProjPath() + cwd: tmpProjPath(), } ); @@ -237,7 +237,7 @@ forEachCli(currentCLIName => { } const result = await getData(); expect(result.message).toEqual(`Welcome to ${nestapp}!`); - treeKill(process.pid, 'SIGTERM', err => { + treeKill(process.pid, 'SIGTERM', (err) => { expect(err).toBeFalsy(); done(); }); @@ -273,10 +273,10 @@ forEachCli(currentCLIName => { outDir: '../../dist/out-tsc', declaration: true, rootDir: './src', - types: ['node'] + types: ['node'], }, exclude: ['**/*.spec.ts'], - include: ['**/*.ts'] + include: ['**/*.ts'], }); await runCLIAsync(`build ${nodeLib}`); checkFilesExist( @@ -290,7 +290,7 @@ forEachCli(currentCLIName => { name: `@proj/${nodeLib}`, version: '0.0.1', main: 'index.js', - typings: 'index.d.ts' + typings: 'index.d.ts', }); }, 60000); @@ -310,7 +310,7 @@ forEachCli(currentCLIName => { workspace.projects[nodelib].architect.build.options.assets.push({ input: `./dist/libs/${nglib}`, glob: '**/*', - output: '.' + output: '.', }); updateFile(workspaceConfigName(), JSON.stringify(workspace)); @@ -321,7 +321,7 @@ forEachCli(currentCLIName => { }, 60000); }); - describe('nest libraries', function() { + describe('nest libraries', function () { it('should be able to generate a nest library', async () => { ensureProject(); const nestlib = uniq('nestlib'); @@ -424,12 +424,12 @@ forEachCli(currentCLIName => { `libs/${parent}/src/lib/${parent}.ts`, ` ${children - .map(entry => `import { ${entry} } from '@proj/${entry}';`) + .map((entry) => `import { ${entry} } from '@proj/${entry}';`) .join('\n')} export function ${parent}(): string { return '${parent}' + ' ' + ${children - .map(entry => `${entry}()`) + .map((entry) => `${entry}()`) .join('+')} } ` @@ -446,7 +446,7 @@ forEachCli(currentCLIName => { ); // we are setting paths to {} to make sure built libs are read from dist - updateFile('tsconfig.json', c => { + updateFile('tsconfig.json', (c) => { const json = JSON.parse(c); json.compilerOptions.paths = {}; return JSON.stringify(json, null, 2); diff --git a/e2e/nx-plugin.test.ts b/e2e/nx-plugin.test.ts index 8fe00a9604acf..8887a7ed7b03a 100644 --- a/e2e/nx-plugin.test.ts +++ b/e2e/nx-plugin.test.ts @@ -8,14 +8,14 @@ import { runCLIAsync, checkFilesExist, readJson, - workspaceConfigName + workspaceConfigName, } from './utils'; -forEachCli(currentCLIName => { +forEachCli((currentCLIName) => { const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint'; describe('Nx Plugin', () => { - it('should be able to generate a Nx Plugin ', async done => { + it('should be able to generate a Nx Plugin ', async (done) => { ensureProject(); const plugin = uniq('plugin'); @@ -44,18 +44,18 @@ forEachCli(currentCLIName => { expect(nxJson).toMatchObject({ projects: expect.objectContaining({ [plugin]: { - tags: [] + tags: [], }, [`${plugin}-e2e`]: { tags: [], - implicitDependencies: [`${plugin}`] - } - }) + implicitDependencies: [`${plugin}`], + }, + }), }); done(); }, 45000); - it(`should run the plugin's e2e tests`, async done => { + it(`should run the plugin's e2e tests`, async (done) => { ensureProject(); const plugin = uniq('plugin'); runCLI(`generate @nrwl/nx-plugin:plugin ${plugin} --linter=${linter}`); @@ -66,7 +66,7 @@ forEachCli(currentCLIName => { done(); }, 150000); - it('should be able to generate a migration', async done => { + it('should be able to generate a migration', async (done) => { ensureProject(); const plugin = uniq('plugin'); const version = '1.0.0'; @@ -96,14 +96,14 @@ forEachCli(currentCLIName => { [`update-${version}`]: { version: version, description: `update-${version}`, - factory: `./src/migrations/update-${version}/update-${version}` - } - }) + factory: `./src/migrations/update-${version}/update-${version}`, + }, + }), }); done(); }, 45000); - it('should be able to generate a schematic', async done => { + it('should be able to generate a schematic', async (done) => { ensureProject(); const plugin = uniq('plugin'); const schematic = uniq('schematic'); @@ -136,14 +136,14 @@ forEachCli(currentCLIName => { [schematic]: { factory: `./src/schematics/${schematic}/schematic`, schema: `./src/schematics/${schematic}/schema.json`, - description: `${schematic} schematic` - } - }) + description: `${schematic} schematic`, + }, + }), }); done(); }, 45000); - it('should be able to generate a builder', async done => { + it('should be able to generate a builder', async (done) => { ensureProject(); const plugin = uniq('plugin'); const builder = uniq('builder'); @@ -174,9 +174,9 @@ forEachCli(currentCLIName => { [builder]: { implementation: `./src/builders/${builder}/builder`, schema: `./src/builders/${builder}/schema.json`, - description: `${builder} builder` - } - }) + description: `${builder} builder`, + }, + }), }); done(); }, 45000); diff --git a/e2e/react-package.test.ts b/e2e/react-package.test.ts index 6136809479734..097c60b226996 100644 --- a/e2e/react-package.test.ts +++ b/e2e/react-package.test.ts @@ -5,10 +5,10 @@ import { readJson, runCLI, uniq, - updateFile + updateFile, } from './utils'; -forEachCli('nx', cli => { +forEachCli('nx', (cli) => { describe('Build React libraries and apps', () => { /** * Graph: @@ -50,7 +50,7 @@ forEachCli('nx', cli => { updateFile( `libs/${parent}/src/lib/${parent}.tsx`, ` - ${children.map(entry => `import '@proj/${entry}';`).join('\n')} + ${children.map((entry) => `import '@proj/${entry}';`).join('\n')} ` ); @@ -66,7 +66,7 @@ forEachCli('nx', cli => { ); // we are setting paths to {} to make sure built libs are read from dist - updateFile('tsconfig.json', c => { + updateFile('tsconfig.json', (c) => { const json = JSON.parse(c); json.compilerOptions.paths = {}; return JSON.stringify(json, null, 2); @@ -112,7 +112,7 @@ forEachCli('nx', cli => { const jsonFile = readJson(`dist/libs/${parentLib}/package.json`); expect(jsonFile.dependencies).toEqual({ [`@proj/${childLib}`]: '0.0.1', - [`@proj/${childLib2}`]: '0.0.1' + [`@proj/${childLib2}`]: '0.0.1', }); }); diff --git a/e2e/react.test.ts b/e2e/react.test.ts index 961872e10eea7..ae6f0328876dc 100644 --- a/e2e/react.test.ts +++ b/e2e/react.test.ts @@ -11,10 +11,10 @@ import { runCLIAsync, uniq, updateFile, - workspaceConfigName + workspaceConfigName, } from './utils'; -forEachCli(currentCLIName => { +forEachCli((currentCLIName) => { const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint'; describe('React Applications', () => { @@ -40,7 +40,7 @@ forEachCli(currentCLIName => { await testGeneratedApp(appName, { checkStyles: true, checkLinter: true, - checkE2E: true + checkE2E: true, }); }, 120000); @@ -123,7 +123,7 @@ forEachCli(currentCLIName => { await testGeneratedApp(appName, { checkStyles: true, checkLinter: true, - checkE2E: false + checkE2E: false, }); }, 120000); @@ -157,7 +157,7 @@ forEachCli(currentCLIName => { await testGeneratedApp(appName, { checkStyles: true, checkLinter: true, - checkE2E: false + checkE2E: false, }); }, 120000); @@ -172,7 +172,7 @@ forEachCli(currentCLIName => { await testGeneratedApp(appName, { checkStyles: false, checkLinter: true, - checkE2E: false + checkE2E: false, }); }, 120000); @@ -187,7 +187,7 @@ forEachCli(currentCLIName => { await testGeneratedApp(appName, { checkStyles: false, checkLinter: true, - checkE2E: false + checkE2E: false, }); expect(() => checkFilesExist(`dist/apps/${appName}/styles.css`)).toThrow( @@ -281,7 +281,7 @@ forEachCli(currentCLIName => { await testGeneratedApp(appName, { checkStyles: true, checkLinter: false, - checkE2E: false + checkE2E: false, }); }, 30000); @@ -300,7 +300,7 @@ forEachCli(currentCLIName => { `dist/apps/${appName}/polyfills.js`, `dist/apps/${appName}/runtime.js`, `dist/apps/${appName}/vendor.js`, - `dist/apps/${appName}/main.js` + `dist/apps/${appName}/main.js`, ]; if (opts.checkStyles) { filesToCheck.push(`dist/apps/${appName}/styles.js`); @@ -316,7 +316,7 @@ forEachCli(currentCLIName => { `dist/apps/${appName}/polyfills.esm.js`, `dist/apps/${appName}/main.esm.js`, `dist/apps/${appName}/polyfills.es5.js`, - `dist/apps/${appName}/main.es5.js` + `dist/apps/${appName}/main.es5.js`, ]; if (opts.checkStyles) { filesToCheck.push(`dist/apps/${appName}/styles.css`); diff --git a/e2e/storybook.test.ts b/e2e/storybook.test.ts index 59dc6a37fd8dd..fd2e1da75050f 100644 --- a/e2e/storybook.test.ts +++ b/e2e/storybook.test.ts @@ -6,7 +6,7 @@ import { ensureProject, tmpProjPath, checkFilesExist, - readFile + readFile, } from './utils'; import { writeFileSync, mkdirSync } from 'fs'; diff --git a/e2e/upgrade-module.test.ts b/e2e/upgrade-module.test.ts index 3bed2380f7f74..6c0ef91a747e5 100644 --- a/e2e/upgrade-module.test.ts +++ b/e2e/upgrade-module.test.ts @@ -5,7 +5,7 @@ import { updateFile, forEachCli, supportUi, - patchKarmaToWorkOnWSL + patchKarmaToWorkOnWSL, } from './utils'; forEachCli('angular', () => { diff --git a/e2e/utils.ts b/e2e/utils.ts index 2539fb5af3690..99f7755fa4e9a 100644 --- a/e2e/utils.ts +++ b/e2e/utils.ts @@ -4,7 +4,7 @@ import { readFileSync, renameSync, statSync, - writeFileSync + writeFileSync, } from 'fs'; import { ensureDirSync } from 'fs-extra'; import * as path from 'path'; @@ -38,7 +38,7 @@ export function forEachCli( } const cb: any = callback ? callback : selectedCliOrFunction; - clis.forEach(c => { + clis.forEach((c) => { describe(`[${c}]`, () => { beforeEach(() => { cli = c; @@ -91,7 +91,7 @@ function patchPackageJsonDeps(addWorkspace = true) { export function runYarnInstall(silent: boolean = true) { const install = execSync('yarn install', { cwd: tmpProjPath(), - ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) + ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}), }); return install ? install.toString() : ''; } @@ -102,7 +102,7 @@ export function runNgcc(silent: boolean = true, async: boolean = true) { (!async ? ' --async=false' : ''), { cwd: tmpProjPath(), - ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) + ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}), } ); return install ? install.toString() : ''; @@ -123,20 +123,22 @@ export function runNew( let gen; if (cli === 'angular') { gen = execSync( - `../../node_modules/.bin/ng new proj --no-interactive --skip-install ${args || - ''}`, + `../../node_modules/.bin/ng new proj --no-interactive --skip-install ${ + args || '' + }`, { cwd: `./tmp/${cli}`, - ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) + ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}), } ); } else { gen = execSync( - `node ../../node_modules/@nrwl/tao/index.js new proj --no-interactive --skip-install ${args || - ''}`, + `node ../../node_modules/@nrwl/tao/index.js new proj --no-interactive --skip-install ${ + args || '' + }`, { cwd: `./tmp/${cli}`, - ...(silent && false ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) + ...(silent && false ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}), } ); } @@ -310,9 +312,9 @@ export function copyMissingPackages(): void { 'less', 'send', - '@bazel' + '@bazel', ]; - modulesToCopy.forEach(m => copyNodeModule(m)); + modulesToCopy.forEach((m) => copyNodeModule(m)); updateFile( 'node_modules/@angular-devkit/schematics/tasks/node-package/executor.js', ` @@ -357,14 +359,14 @@ export function runCommandAsync( command: string, opts: RunCmdOpts = { silenceError: false, - env: process.env + env: process.env, } ): Promise<{ stdout: string; stderr: string }> { return new Promise((resolve, reject) => { exec( `${command}`, { - cwd: tmpProjPath() + cwd: tmpProjPath(), }, (err, stdout, stderr) => { if (!opts.silenceError && err) { @@ -380,7 +382,7 @@ export function runCLIAsync( command: string, opts: RunCmdOpts = { silenceError: false, - env: process.env + env: process.env, } ): Promise<{ stdout: string; stderr: string }> { return runCommandAsync( @@ -393,13 +395,13 @@ export function runNgAdd( command?: string, opts: RunCmdOpts = { silenceError: false, - env: process.env + env: process.env, } ): string { try { return execSync(`./node_modules/.bin/ng ${command}`, { cwd: tmpProjPath(), - env: opts.env + env: opts.env, }) .toString() .replace( @@ -420,13 +422,13 @@ export function runCLI( command?: string, opts: RunCmdOpts = { silenceError: false, - env: process.env + env: process.env, } ): string { try { const r = execSync(`node ./node_modules/@nrwl/cli/bin/nx.js ${command}`, { cwd: tmpProjPath(), - env: opts.env + env: opts.env, }) .toString() .replace( @@ -460,7 +462,7 @@ export function runCommand(command: string): string { try { const r = execSync(command, { cwd: tmpProjPath(), - stdio: ['pipe', 'pipe', 'pipe'] + stdio: ['pipe', 'pipe', 'pipe'], }).toString(); console.log(r); return r; @@ -480,9 +482,9 @@ function setMaxWorkers() { const workspaceFile = workspaceConfigName(); const workspace = readJson(workspaceFile); - Object.keys(workspace.projects).forEach(appName => { + Object.keys(workspace.projects).forEach((appName) => { const { - architect: { build } + architect: { build }, } = workspace.projects[appName]; if (!build) { @@ -520,7 +522,7 @@ export function renameFile(f: string, newPath: string): void { } export function checkFilesExist(...expectedFiles: string[]) { - expectedFiles.forEach(f => { + expectedFiles.forEach((f) => { const ff = f.startsWith('/') ? f : tmpProjPath(f); if (!exists(ff)) { throw new Error(`File '${ff}' does not exist`); @@ -529,7 +531,7 @@ export function checkFilesExist(...expectedFiles: string[]) { } export function checkFilesDoNotExist(...expectedFiles: string[]) { - expectedFiles.forEach(f => { + expectedFiles.forEach((f) => { const ff = f.startsWith('/') ? f : tmpProjPath(f); if (exists(ff)) { throw new Error(`File '${ff}' does not exist`); diff --git a/e2e/web.test.ts b/e2e/web.test.ts index 3ab48d851fa43..04f2f01da3709 100644 --- a/e2e/web.test.ts +++ b/e2e/web.test.ts @@ -8,10 +8,10 @@ import { runCLIAsync, supportUi, uniq, - updateFile + updateFile, } from './utils'; -forEachCli(currentCLIName => { +forEachCli((currentCLIName) => { describe('Web Components Applications', () => { it('should be able to generate a web app', async () => { ensureProject(); @@ -137,7 +137,7 @@ forEachCli(currentCLIName => { updateFile(main, `${newCode}\n${content}`); runCLI(`build ${appName}`, { - env: { ...process.env, NODE_ENV: 'test', NX_BUILD: '52', NX_API: 'QA' } + env: { ...process.env, NODE_ENV: 'test', NX_BUILD: '52', NX_API: 'QA' }, }); expect(readFile(`dist/apps/${appName}/main.js`)).toContain( 'var envVars = ["test", "52", "QA"];' diff --git a/e2e/workspace-aux-commands.test.ts b/e2e/workspace-aux-commands.test.ts index eccc8025c4a58..5323d57bf917c 100644 --- a/e2e/workspace-aux-commands.test.ts +++ b/e2e/workspace-aux-commands.test.ts @@ -14,10 +14,10 @@ import { tmpProjPath, uniq, updateFile, - workspaceConfigName + workspaceConfigName, } from './utils'; -forEachCli(cli => { +forEachCli((cli) => { describe('lint', () => { it('lint should ensure module boundaries', () => { ensureProject(); @@ -39,7 +39,7 @@ forEachCli(cli => { const tslint = readJson('tslint.json'); tslint.rules['nx-enforce-module-boundaries'][1].depConstraints = [ { sourceTag: 'validtag', onlyDependOnLibsWithTags: ['validtag'] }, - ...tslint.rules['nx-enforce-module-boundaries'][1].depConstraints + ...tslint.rules['nx-enforce-module-boundaries'][1].depConstraints, ]; updateFile('tslint.json', JSON.stringify(tslint, null, 2)); @@ -178,11 +178,11 @@ forEachCli(cli => { const json = readJson(`tools/schematics/${custom}/schema.json`); json.properties['directory'] = { type: 'string', - description: 'lib directory' + description: 'lib directory', }; json.properties['skipTsConfig'] = { type: 'boolean', - description: 'skip changes to tsconfig' + description: 'skip changes to tsconfig', }; updateFile( `tools/schematics/${custom}/schema.json`, @@ -299,47 +299,47 @@ forEachCli(cli => { { source: 'myapp3-e2e', target: 'myapp3', - type: 'implicit' - } + type: 'implicit', + }, ], myapp2: [ { source: 'myapp2', target: 'mylib', - type: 'static' - } + type: 'static', + }, ], 'myapp2-e2e': [ { source: 'myapp2-e2e', target: 'myapp2', - type: 'implicit' - } + type: 'implicit', + }, ], mylib: [ { source: 'mylib', target: 'mylib2', - type: 'static' - } + type: 'static', + }, ], mylib2: [], myapp: [ { source: 'myapp', target: 'mylib', - type: 'static' + type: 'static', }, - { source: 'myapp', target: 'mylib2', type: 'dynamic' } + { source: 'myapp', target: 'mylib2', type: 'dynamic' }, ], 'myapp-e2e': [ { source: 'myapp-e2e', target: 'myapp', - type: 'implicit' - } + type: 'implicit', + }, ], - myapp3: [] + myapp3: [], }); runCommand( @@ -592,7 +592,7 @@ forEachCli(cli => { const nxJson = JSON.parse(readFile('nx.json')) as NxJson; expect(nxJson.projects[`${lib1}-data-access`]).toBeUndefined(); expect(nxJson.projects[newName]).toEqual({ - tags: [] + tags: [], }); expect(moveOutput).toContain('UPDATE tsconfig.json'); @@ -613,7 +613,7 @@ forEachCli(cli => { expect(project.sourceRoot).toBe(`${newPath}/src`); expect(project.architect.lint.options.tsConfig).toEqual([ `libs/shared/${lib1}/data-access/tsconfig.lib.json`, - `libs/shared/${lib1}/data-access/tsconfig.spec.json` + `libs/shared/${lib1}/data-access/tsconfig.spec.json`, ]); /** diff --git a/e2e/workspace.test.ts b/e2e/workspace.test.ts index 4c6ff3563ff58..4da7e62c28234 100644 --- a/e2e/workspace.test.ts +++ b/e2e/workspace.test.ts @@ -11,12 +11,12 @@ import { runCommand, uniq, updateFile, - workspaceConfigName + workspaceConfigName, } from './utils'; let originalCIValue: any; -forEachCli(cliName => { +forEachCli((cliName) => { const cliCommand = cliName === 'angular' ? 'ng' : 'nx'; /** @@ -269,8 +269,8 @@ forEachCli(cliName => { results: { [myapp]: false, [mylib]: true, - [mypublishablelib]: true - } + [mypublishablelib]: true, + }, }); // Fix failing Unit Test @@ -429,11 +429,11 @@ forEachCli(cliName => { overrides: {}, target: { project: myapp, - target: 'test' + target: 'test', }, command: `npm run ${cliCommand} -- test ${myapp}`, - outputs: [] - } + outputs: [], + }, ]); compareTwoArrays(resWithTarget.projects, [`${myapp}-e2e`, myapp]); @@ -448,27 +448,27 @@ forEachCli(cliName => { overrides: {}, target: { project: mypublishablelib, - target: 'build' + target: 'build', }, command: `npm run ${cliCommand} -- build ${mypublishablelib}`, - outputs: [`dist/libs/${mypublishablelib}`] + outputs: [`dist/libs/${mypublishablelib}`], }, { id: `${myapp}:build`, overrides: {}, target: { project: myapp, - target: 'build' + target: 'build', }, command: `npm run ${cliCommand} -- build ${myapp}`, - outputs: [`dist/apps/${myapp}`] - } + outputs: [`dist/apps/${myapp}`], + }, ]); compareTwoArrays(resWithDeps.projects, [ mylib, mypublishablelib, myapp, - `${myapp}-e2e` + `${myapp}-e2e`, ]); const resWithTargetWithSelect1 = runCommand( @@ -487,8 +487,8 @@ forEachCli(cliName => { function compareTwoSerializedArrays(a: string, b: string) { compareTwoArrays( - a.split(',').map(_ => _.trim()), - b.split(',').map(_ => _.trim()) + a.split(',').map((_) => _.trim()), + b.split(',').map((_) => _.trim()) ); } @@ -543,7 +543,7 @@ forEachCli(cliName => { // touch myapp1 // -------------------------------------------- - updateFile(`apps/${myapp1}/src/main.ts`, c => { + updateFile(`apps/${myapp1}/src/main.ts`, (c) => { return `${c}\n//some comment`; }); const outputWithBuildApp2Cached = runCommand( @@ -554,7 +554,7 @@ forEachCli(cliName => { // touch package.json // -------------------------------------------- - updateFile(`package.json`, c => { + updateFile(`package.json`, (c) => { const r = JSON.parse(c); r.description = 'different'; return JSON.stringify(r); @@ -597,7 +597,7 @@ forEachCli(cliName => { myapp1, myapp2, `${myapp1}-e2e`, - `${myapp2}-e2e` + `${myapp2}-e2e`, ]); // run without caching @@ -605,14 +605,14 @@ forEachCli(cliName => { // disable caching // -------------------------------------------- - updateFile('nx.json', c => { + updateFile('nx.json', (c) => { const nxJson = JSON.parse(c); nxJson.tasksRunnerOptions = { default: { options: { - cacheableOperations: [] - } - } + cacheableOperations: [], + }, + }, }; return JSON.stringify(nxJson, null, 2); }); diff --git a/karma.conf.js b/karma.conf.js index fe9a8f0747e63..e70ea8e653f6b 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,4 +1,4 @@ -module.exports = function(config) { +module.exports = function (config) { const webpackConfig = { node: { fs: 'empty', @@ -9,8 +9,8 @@ module.exports = function(config) { process: true, module: false, clearImmediate: false, - setImmediate: false - } + setImmediate: false, + }, }; config.set({ basePath: '.', @@ -28,7 +28,7 @@ module.exports = function(config) { // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { - 'build/test.js': ['webpack'] + 'build/test.js': ['webpack'], }, reporters: ['dots'], @@ -36,13 +36,13 @@ module.exports = function(config) { webpack: webpackConfig, webpackMiddleware: { - stats: 'errors-only' + stats: 'errors-only', }, plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), - require('karma-webpack') + require('karma-webpack'), ], // web server port @@ -60,14 +60,14 @@ module.exports = function(config) { customLaunchers: { Chrome_travis_ci: { base: 'Chrome', - flags: ['--no-sandbox'] - } + flags: ['--no-sandbox'], + }, }, browsers: process.env.TRAVIS ? ['Chrome_travis_ci'] : ['Chrome'], // Concurrency level // how many browser should be started simultaneous - concurrency: Infinity + concurrency: Infinity, }); }; diff --git a/package.json b/package.json index 9919374218f69..848a24c3e6886 100644 --- a/package.json +++ b/package.json @@ -91,7 +91,7 @@ "@types/jasminewd2": "~2.0.3", "@types/jest": "25.1.4", "@types/node": "10.0.1", - "@types/prettier": "^1.10.0", + "@types/prettier": "2.0.0", "@types/react": "16.9.17", "@types/react-dom": "16.9.4", "@types/react-redux": "7.1.5", @@ -186,7 +186,7 @@ "postcss-import": "12.0.1", "postcss-loader": "3.0.0", "precise-commits": "1.0.2", - "prettier": "1.18.2", + "prettier": "2.0.4", "protractor": "5.4.3", "raw-loader": "3.1.0", "react": "16.10.2", diff --git a/packages/angular/index.ts b/packages/angular/index.ts index 5feb02415d355..ba5e98d619b4c 100644 --- a/packages/angular/index.ts +++ b/packages/angular/index.ts @@ -3,6 +3,6 @@ export { fetch, navigation, optimisticUpdate, - pessimisticUpdate + pessimisticUpdate, } from './src/runtime/nx/data-persistence'; export { NxModule } from './src/runtime/nx/nx.module'; diff --git a/packages/angular/scripts/nx-cli-warning.js b/packages/angular/scripts/nx-cli-warning.js index cc150d07e5d68..0767a98d0921e 100644 --- a/packages/angular/scripts/nx-cli-warning.js +++ b/packages/angular/scripts/nx-cli-warning.js @@ -14,8 +14,8 @@ try { "If you want to use 'ng', you need to create a new workspace powered by the Angular CLI.", 'You can do it by selecting Angular CLI when creating a new workspace.', "Or by providing --cli as follows: 'create-nx-workspace --cli=angular'.", - "You can invoke the Angular schematics with 'nx generate @nrwl/angular' to generate artifacts." - ] + "You can invoke the Angular schematics with 'nx generate @nrwl/angular' to generate artifacts.", + ], }); } } diff --git a/packages/angular/spec/data-persistence.spec.ts b/packages/angular/spec/data-persistence.spec.ts index 47c96c6d325d5..1e3d8717f9128 100644 --- a/packages/angular/spec/data-persistence.spec.ts +++ b/packages/angular/spec/data-persistence.spec.ts @@ -6,7 +6,7 @@ import { Actions, Effect, EffectsModule, ofType } from '@ngrx/effects'; import { provideMockActions } from '@ngrx/effects/testing'; import { StoreRouterConnectingModule, - DefaultRouterStateSerializer + DefaultRouterStateSerializer, } from '@ngrx/router-store'; import { Store, StoreModule } from '@ngrx/store'; import { Observable, of, Subject, throwError } from 'rxjs'; @@ -17,7 +17,7 @@ import { pessimisticUpdate, optimisticUpdate, fetch, - NxModule + NxModule, } from '../index'; import { readAll } from '../testing'; @@ -59,9 +59,7 @@ function userReducer(): string { } @Component({ - template: ` - ROOT[] - ` + template: ` ROOT[] `, }) class RootCmp {} @@ -70,7 +68,7 @@ class RootCmp {} Todo [
ID {{ t.id }} User {{ t.user }}
] - ` + `, }) class TodoComponent { todo = this.store.select('todos', 'selected'); @@ -88,18 +86,18 @@ describe('DataPersistence', () => { { runtimeChecks: { strictStateImmutability: false, - strictStateSerializability: false - } + strictStateSerializability: false, + }, } ), StoreRouterConnectingModule.forRoot({ - serializer: DefaultRouterStateSerializer + serializer: DefaultRouterStateSerializer, }), RouterTestingModule.withRoutes([ - { path: 'todo/:id', component: TodoComponent } + { path: 'todo/:id', component: TodoComponent }, ]), - NxModule.forRoot() - ] + NxModule.forRoot(), + ], }); }); @@ -111,10 +109,10 @@ describe('DataPersistence', () => { run: (a, state) => { return { type: 'TODO_LOADED', - payload: { id: a.params['id'], user: state.user } + payload: { id: a.params['id'], user: state.user }, }; }, - onError: () => null + onError: () => null, }); constructor(private s: DataPersistence) {} @@ -122,7 +120,7 @@ describe('DataPersistence', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [EffectsModule.forRoot([TodoEffects])] + imports: [EffectsModule.forRoot([TodoEffects])], }); }); @@ -150,18 +148,18 @@ describe('DataPersistence', () => { } else { return { type: 'TODO_LOADED', - payload: { id: a.params['id'], user: state.user } + payload: { id: a.params['id'], user: state.user }, }; } }, - onError: (a, e) => ({ type: 'ERROR', payload: { error: e } }) + onError: (a, e) => ({ type: 'ERROR', payload: { error: e } }), }); constructor(private s: DataPersistence) {} } beforeEach(() => { TestBed.configureTestingModule({ - imports: [EffectsModule.forRoot([TodoEffects])] + imports: [EffectsModule.forRoot([TodoEffects])], }); }); @@ -176,9 +174,9 @@ describe('DataPersistence', () => { tick(0); root.detectChanges(false); expect(root.elementRef.nativeElement.innerHTML).not.toContain('ID 123'); - expect(actions.map(a => a.type)).toContain('ERROR'); + expect(actions.map((a) => a.type)).toContain('ERROR'); expect( - actions.find(a => a.type === 'ERROR').payload.error.message + actions.find((a) => a.type === 'ERROR').payload.error.message ).toEqual('boom'); // can recover after an error @@ -200,18 +198,18 @@ describe('DataPersistence', () => { } else { return { type: 'TODO_LOADED', - payload: { id: a.params['id'], user: state.user } + payload: { id: a.params['id'], user: state.user }, }; } }, - onError: (a, e) => ({ type: 'ERROR', payload: { error: e } }) + onError: (a, e) => ({ type: 'ERROR', payload: { error: e } }), }); constructor(private s: DataPersistence) {} } beforeEach(() => { TestBed.configureTestingModule({ - imports: [EffectsModule.forRoot([TodoEffects])] + imports: [EffectsModule.forRoot([TodoEffects])], }); }); @@ -226,8 +224,8 @@ describe('DataPersistence', () => { tick(0); root.detectChanges(false); expect(root.elementRef.nativeElement.innerHTML).not.toContain('ID 123'); - expect(actions.map(a => a.type)).toContain('ERROR'); - expect(actions.find(a => a.type === 'ERROR').payload.error).toEqual( + expect(actions.map((a) => a.type)).toContain('ERROR'); + expect(actions.find((a) => a.type === 'ERROR').payload.error).toEqual( 'boom' ); @@ -257,11 +255,11 @@ describe('DataPersistence', () => { // we need to introduce the delay to "enable" switchMap return of({ type: 'TODOS', - payload: { user: state.user, todos: 'some todos' } + payload: { user: state.user, todos: 'some todos' }, }).pipe(delay(1)); }, - onError: () => null + onError: () => null, }); @Effect() @@ -272,9 +270,9 @@ describe('DataPersistence', () => { run: (action, state) => { return of({ type: 'TODOS', - payload: { user: state.user, todos: 'some todos' } + payload: { user: state.user, todos: 'some todos' }, }).pipe(delay(1)); - } + }, }) ); @@ -297,15 +295,15 @@ describe('DataPersistence', () => { { runtimeChecks: { strictStateImmutability: false, - strictStateSerializability: false - } + strictStateSerializability: false, + }, } - ) - ] + ), + ], }); }); - it('should work', async done => { + it('should work', async (done) => { actions = of( { type: 'GET_TODOS', payload: {} }, { type: 'GET_TODOS', payload: {} } @@ -313,13 +311,13 @@ describe('DataPersistence', () => { expect(await readAll(TestBed.get(TodoEffects).loadTodos)).toEqual([ { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } }, - { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } } + { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } }, ]); done(); }); - it('should work with an operator', async done => { + it('should work with an operator', async (done) => { actions = of( { type: 'GET_TODOS', payload: {} }, { type: 'GET_TODOS', payload: {} } @@ -329,7 +327,7 @@ describe('DataPersistence', () => { await readAll(TestBed.get(TodoEffects).loadTodosWithOperator) ).toEqual([ { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } }, - { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } } + { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } }, ]); done(); @@ -346,9 +344,9 @@ describe('DataPersistence', () => { class TodoEffects { @Effect() loadTodo = this.s.fetch('GET_TODO', { - id: a => a.payload.id, - run: a => of({ type: 'TODO', payload: a.payload }).pipe(delay(1)), - onError: () => null + id: (a) => a.payload.id, + run: (a) => of({ type: 'TODO', payload: a.payload }).pipe(delay(1)), + onError: () => null, }); constructor(private s: DataPersistence) {} @@ -370,15 +368,15 @@ describe('DataPersistence', () => { { runtimeChecks: { strictStateImmutability: false, - strictStateSerializability: false - } + strictStateSerializability: false, + }, } - ) - ] + ), + ], }); }); - it('should work', async done => { + it('should work', async (done) => { actions = of( { type: 'GET_TODO', payload: { id: 1, value: '1' } }, { type: 'GET_TODO', payload: { id: 2, value: '2a' } }, @@ -387,7 +385,7 @@ describe('DataPersistence', () => { expect(await readAll(TestBed.get(TodoEffects).loadTodo)).toEqual([ { type: 'TODO', payload: { id: 1, value: '1' } }, - { type: 'TODO', payload: { id: 2, value: '2b' } } + { type: 'TODO', payload: { id: 2, value: '2b' } }, ]); done(); @@ -407,9 +405,9 @@ describe('DataPersistence', () => { loadTodo = this.s.pessimisticUpdate('UPDATE_TODO', { run: (a, state) => ({ type: 'TODO_UPDATED', - payload: { user: state.user, newTitle: a.payload.newTitle } + payload: { user: state.user, newTitle: a.payload.newTitle }, }), - onError: () => null + onError: () => null, }); @Effect() @@ -419,9 +417,9 @@ describe('DataPersistence', () => { pessimisticUpdate({ run: (a, state) => ({ type: 'TODO_UPDATED', - payload: { user: state.user, newTitle: a.payload.newTitle } + payload: { user: state.user, newTitle: a.payload.newTitle }, }), - onError: () => null + onError: () => null, }) ); @@ -444,34 +442,34 @@ describe('DataPersistence', () => { { runtimeChecks: { strictStateImmutability: false, - strictStateSerializability: false - } + strictStateSerializability: false, + }, } - ) - ] + ), + ], }); }); - it('should work', async done => { + it('should work', async (done) => { actions = of({ type: 'UPDATE_TODO', - payload: { newTitle: 'newTitle' } + payload: { newTitle: 'newTitle' }, }); expect(await readAll(TestBed.get(TodoEffects).loadTodo)).toEqual([ { type: 'TODO_UPDATED', - payload: { user: 'bob', newTitle: 'newTitle' } - } + payload: { user: 'bob', newTitle: 'newTitle' }, + }, ]); done(); }); - it('should work with an operator', async done => { + it('should work with an operator', async (done) => { actions = of({ type: 'UPDATE_TODO', - payload: { newTitle: 'newTitle' } + payload: { newTitle: 'newTitle' }, }); expect( @@ -479,8 +477,8 @@ describe('DataPersistence', () => { ).toEqual([ { type: 'TODO_UPDATED', - payload: { user: 'bob', newTitle: 'newTitle' } - } + payload: { user: 'bob', newTitle: 'newTitle' }, + }, ]); done(); @@ -498,8 +496,8 @@ describe('DataPersistence', () => { onError: (a, e: any) => ({ type: 'ERROR', - payload: { error: e } - }) + payload: { error: e }, + }), }); constructor(private s: DataPersistence) {} @@ -521,18 +519,18 @@ describe('DataPersistence', () => { { runtimeChecks: { strictStateImmutability: false, - strictStateSerializability: false - } + strictStateSerializability: false, + }, } - ) - ] + ), + ], }); }); - it('should work', async done => { + it('should work', async (done) => { actions = of({ type: 'UPDATE_TODO', - payload: { newTitle: 'newTitle' } + payload: { newTitle: 'newTitle' }, }); const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo); @@ -555,8 +553,8 @@ describe('DataPersistence', () => { onError: (a, e: any) => ({ type: 'ERROR', - payload: { error: e } - }) + payload: { error: e }, + }), }); constructor(private s: DataPersistence) {} @@ -578,18 +576,18 @@ describe('DataPersistence', () => { { runtimeChecks: { strictStateImmutability: false, - strictStateSerializability: false - } + strictStateSerializability: false, + }, } - ) - ] + ), + ], }); }); - it('should work', async done => { + it('should work', async (done) => { actions = of({ type: 'UPDATE_TODO', - payload: { newTitle: 'newTitle' } + payload: { newTitle: 'newTitle' }, }); const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo); @@ -616,10 +614,10 @@ describe('DataPersistence', () => { throw new Error('boom'); }, - undoAction: a => ({ + undoAction: (a) => ({ type: 'UNDO_UPDATE_TODO', - payload: a.payload - }) + payload: a.payload, + }), }); @Effect() @@ -631,10 +629,10 @@ describe('DataPersistence', () => { throw new Error('boom'); }, - undoAction: a => ({ + undoAction: (a) => ({ type: 'UNDO_UPDATE_TODO', - payload: a.payload - }) + payload: a.payload, + }), }) ); @@ -657,18 +655,18 @@ describe('DataPersistence', () => { { runtimeChecks: { strictStateImmutability: false, - strictStateSerializability: false - } + strictStateSerializability: false, + }, } - ) - ] + ), + ], }); }); - it('should work', async done => { + it('should work', async (done) => { actions = of({ type: 'UPDATE_TODO', - payload: { newTitle: 'newTitle' } + payload: { newTitle: 'newTitle' }, }); const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo); @@ -679,10 +677,10 @@ describe('DataPersistence', () => { done(); }); - it('should work with an operator', async done => { + it('should work with an operator', async (done) => { actions = of({ type: 'UPDATE_TODO', - payload: { newTitle: 'newTitle' } + payload: { newTitle: 'newTitle' }, }); const [a]: any = await readAll( diff --git a/packages/angular/spec/testing-utils.spec.ts b/packages/angular/spec/testing-utils.spec.ts index dde9e788ba74c..165ba98b63645 100644 --- a/packages/angular/spec/testing-utils.spec.ts +++ b/packages/angular/spec/testing-utils.spec.ts @@ -3,7 +3,7 @@ import { readAll, readFirst } from '../testing/src/testing-utils'; describe('TestingUtils', () => { describe('readAll', () => { - it('should transform Observable to Promise>', async done => { + it('should transform Observable to Promise>', async (done) => { const obs = from([1, 2, 3]); const result = await readAll(obs); @@ -14,7 +14,7 @@ describe('TestingUtils', () => { }); describe('readFirst', () => { - it('should transform first item emitted from Observable to Promise', async done => { + it('should transform first item emitted from Observable to Promise', async (done) => { const obs = from([1, 2, 3]); const result = await readFirst(obs); diff --git a/packages/angular/src/builders/package/package.impl.spec.ts b/packages/angular/src/builders/package/package.impl.spec.ts index c65354412099c..75aaa2e2bdb14 100644 --- a/packages/angular/src/builders/package/package.impl.spec.ts +++ b/packages/angular/src/builders/package/package.impl.spec.ts @@ -5,7 +5,7 @@ import { getMockContext } from '../../utils/testing'; import * as projectGraphUtils from '@nrwl/workspace/src/core/project-graph'; import { ProjectGraph, - ProjectType + ProjectType, } from '@nrwl/workspace/src/core/project-graph'; import * as fileUtils from '@nrwl/workspace/src/utils/fileutils'; @@ -48,21 +48,21 @@ describe('AngularLibraryWebBuildBuilder', () => { return { options: { paths: { - '@proj/buildable-child': [] - } - } + '@proj/buildable-child': [], + }, + }, }; }); spyOn(fileUtils, 'fileExists').and.returnValue(true); context.target = { project: 'buildable-parent', - target: 'build' + target: 'build', }; testOptions = { tsConfig: 'libs/publishable-parent/tsconfig.lib.json', - project: 'libs/publishable-parent/ng-package.json' + project: 'libs/publishable-parent/ng-package.json', }; }); @@ -73,10 +73,10 @@ describe('AngularLibraryWebBuildBuilder', () => { 'buildable-parent': { type: ProjectType.lib, name: 'buildable-parent', - data: { files: [], root: 'libs/buildable-parent' } - } + data: { files: [], root: 'libs/buildable-parent' }, + }, }, - dependencies: {} + dependencies: {}, } as ProjectGraph; }); @@ -101,10 +101,10 @@ describe('AngularLibraryWebBuildBuilder', () => { root: 'libs/buildable-parent', architect: { build: { - builder: 'any builder' - } - } - } + builder: 'any builder', + }, + }, + }, }, 'buildable-child': { type: ProjectType.lib, @@ -115,22 +115,22 @@ describe('AngularLibraryWebBuildBuilder', () => { prefix: 'proj', architect: { build: { - builder: 'any builder' - } - } - } - } + builder: 'any builder', + }, + }, + }, + }, }, dependencies: { 'buildable-parent': [ { type: ProjectType.lib, target: 'buildable-child', - source: null - } + source: null, + }, ], - 'buildable-child': [] - } + 'buildable-child': [], + }, } as ProjectGraph; }); }); @@ -138,7 +138,7 @@ describe('AngularLibraryWebBuildBuilder', () => { it('should properly set the TSConfig paths', async () => { spyOn(fileUtils, 'readJsonFile').and.returnValue({ name: '@proj/buildable-child', - version: '1.2.3' + version: '1.2.3', }); // act @@ -149,8 +149,8 @@ describe('AngularLibraryWebBuildBuilder', () => { expect(ngPackagrMock.withTsConfig).toHaveBeenCalledWith( jasmine.objectContaining({ options: { - paths: { '@proj/buildable-child': ['dist/libs/buildable-child'] } - } + paths: { '@proj/buildable-child': ['dist/libs/buildable-child'] }, + }, }) ); }); @@ -160,12 +160,12 @@ describe('AngularLibraryWebBuildBuilder', () => { if (path.endsWith('buildable-parent/package.json')) { return { name: '@proj/buildable-parent', - version: '3.3.3' + version: '3.3.3', }; } else { return { name: '@proj/buildable-child', - version: '1.2.3' + version: '1.2.3', }; } }); @@ -179,8 +179,8 @@ describe('AngularLibraryWebBuildBuilder', () => { 'dist/libs/buildable-parent/package.json', jasmine.objectContaining({ dependencies: { - '@proj/buildable-child': '1.2.3' - } + '@proj/buildable-child': '1.2.3', + }, }) ); }); @@ -194,13 +194,13 @@ describe('AngularLibraryWebBuildBuilder', () => { name: '@proj/buildable-parent', version: '1.2.3', [depConfigName]: { - '@proj/buildable-child': '1.1.1' - } + '@proj/buildable-child': '1.1.1', + }, }; } else { return { name: '@proj/buildable-child', - version: '1.2.3' + version: '1.2.3', }; } }); diff --git a/packages/angular/src/builders/package/package.impl.ts b/packages/angular/src/builders/package/package.impl.ts index e63a952a9354a..245b3096a9345 100644 --- a/packages/angular/src/builders/package/package.impl.ts +++ b/packages/angular/src/builders/package/package.impl.ts @@ -1,7 +1,7 @@ import { BuilderContext, BuilderOutput, - createBuilder + createBuilder, } from '@angular-devkit/architect'; import { JsonObject } from '@angular-devkit/core'; import * as ng from '@angular/compiler-cli'; @@ -13,7 +13,7 @@ import { checkDependentProjectsHaveBeenBuilt, DependentBuildableProjectNode, updateBuildableProjectPackageJsonDependencies, - updatePaths + updatePaths, } from '@nrwl/workspace/src/utils/buildable-libs-utils'; import { createProjectGraph } from '@nrwl/workspace/src/core/project-graph'; @@ -61,10 +61,10 @@ export function run( context ); return of(checkDependentProjectsHaveBeenBuilt(context, dependencies)).pipe( - switchMap(result => { + switchMap((result) => { if (result) { return from(initializeNgPackagr(options, context, dependencies)).pipe( - switchMap(packager => + switchMap((packager) => options.watch ? packager.watch() : packager.build() ), tap(() => { diff --git a/packages/angular/src/migrations/update-8-12-0/change-angular-lib-builder.spec.ts b/packages/angular/src/migrations/update-8-12-0/change-angular-lib-builder.spec.ts index 284c3164f3420..27617f30c6d63 100644 --- a/packages/angular/src/migrations/update-8-12-0/change-angular-lib-builder.spec.ts +++ b/packages/angular/src/migrations/update-8-12-0/change-angular-lib-builder.spec.ts @@ -4,7 +4,7 @@ import { createEmptyWorkspace } from '@nrwl/workspace/testing'; import { runMigration } from '@nrwl/workspace/src/utils/testing'; import { SchematicTestRunner, - UnitTestTree + UnitTestTree, } from '@angular-devkit/schematics/testing'; import { join } from 'path'; @@ -30,23 +30,23 @@ describe('Update Angular library builder', () => { projectType: 'library', architect: { build: { - builder: '@angular-devkit/build-ng-packagr:build' - } - } + builder: '@angular-devkit/build-ng-packagr:build', + }, + }, }, ['anotherbuildable-lib']: { projectType: 'library', architect: { build: { - builder: '@angular-devkit/build-ng-packagr:build' - } - } + builder: '@angular-devkit/build-ng-packagr:build', + }, + }, }, ['nonbuildable-lib']: { projectType: 'library', - architect: {} - } - } + architect: {}, + }, + }, }) ); diff --git a/packages/angular/src/migrations/update-8-12-0/change-angular-lib-builder.ts b/packages/angular/src/migrations/update-8-12-0/change-angular-lib-builder.ts index 63ef346f0f9d7..9e2cf49f21ebd 100644 --- a/packages/angular/src/migrations/update-8-12-0/change-angular-lib-builder.ts +++ b/packages/angular/src/migrations/update-8-12-0/change-angular-lib-builder.ts @@ -2,16 +2,16 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { formatFiles } from '@nrwl/workspace/src/utils/rules/format-files'; import { readWorkspaceJson, updateWorkspaceInTree } from '@nrwl/workspace'; -export default function(): Rule { +export default function (): Rule { return chain([ - updateWorkspaceInTree(config => { - Object.keys(config.projects).forEach(name => { + updateWorkspaceInTree((config) => { + Object.keys(config.projects).forEach((name) => { if ( config.projects[name].architect && config.projects[name].architect.build && @@ -25,6 +25,6 @@ export default function(): Rule { return config; }), , - formatFiles() + formatFiles(), ]); } diff --git a/packages/angular/src/migrations/update-8-3-0/upgrade-ngrx-8-0.ts b/packages/angular/src/migrations/update-8-3-0/upgrade-ngrx-8-0.ts index f5a88f7ebc0f9..c5492d3f558ac 100644 --- a/packages/angular/src/migrations/update-8-3-0/upgrade-ngrx-8-0.ts +++ b/packages/angular/src/migrations/update-8-3-0/upgrade-ngrx-8-0.ts @@ -5,14 +5,14 @@ import { formatFiles, updateJsonInTree, checkAndCleanWithSemver, - addInstallTask + addInstallTask, } from '@nrwl/workspace'; import { gt } from 'semver'; function updateCLI() { const tasks: TaskId[] = []; const rule = chain([ - updateJsonInTree('package.json', json => { + updateJsonInTree('package.json', (json) => { json.devDependencies = json.devDependencies || {}; const cliVersion = json.devDependencies['@angular/cli']; const cleanCliVersion = checkAndCleanWithSemver( @@ -39,7 +39,7 @@ function updateCLI() { return json; }), - addInstallTask() + addInstallTask(), ]); return { rule, tasks }; @@ -52,7 +52,7 @@ function updateNgrx(updateDeps: TaskId[]) { if (dependencies && dependencies['@ngrx/store']) { return chain([ addUpdateTask('@ngrx/store', '8.1.0', updateDeps), - formatFiles() + formatFiles(), ]); } @@ -60,7 +60,7 @@ function updateNgrx(updateDeps: TaskId[]) { }; } -export default function() { +export default function () { const { rule: updateCLIRule, tasks } = updateCLI(); return chain([updateCLIRule, updateNgrx(tasks), formatFiles()]); } diff --git a/packages/angular/src/migrations/update-8-5-0/update-8-5-0.spec.ts b/packages/angular/src/migrations/update-8-5-0/update-8-5-0.spec.ts index 15ed7c314890e..e50290116b7e0 100644 --- a/packages/angular/src/migrations/update-8-5-0/update-8-5-0.spec.ts +++ b/packages/angular/src/migrations/update-8-5-0/update-8-5-0.spec.ts @@ -2,7 +2,7 @@ import { Tree } from '@angular-devkit/schematics'; import { readJsonInTree } from '@nrwl/workspace'; import { SchematicTestRunner, - UnitTestTree + UnitTestTree, } from '@angular-devkit/schematics/testing'; import { serializeJson } from '@nrwl/workspace'; import { runMigration } from '../../utils/testing'; @@ -21,8 +21,8 @@ describe('Update 8.5.0', () => { 'package.json', serializeJson({ devDependencies: { - '@angular/cli': '8.0.0' - } + '@angular/cli': '8.0.0', + }, }) ); @@ -38,8 +38,8 @@ describe('Update 8.5.0', () => { 'package.json', serializeJson({ devDependencies: { - '@angular/cli': '^8.0.0' - } + '@angular/cli': '^8.0.0', + }, }) ); @@ -55,8 +55,8 @@ describe('Update 8.5.0', () => { 'package.json', serializeJson({ devDependencies: { - '@angular/cli': '~8.0.0' - } + '@angular/cli': '~8.0.0', + }, }) ); @@ -74,8 +74,8 @@ describe('Update 8.5.0', () => { 'package.json', serializeJson({ devDependencies: { - '@angular/cli': '>=8.0.0' - } + '@angular/cli': '>=8.0.0', + }, }) ); diff --git a/packages/angular/src/migrations/update-8-5-0/upgrade-cli-8-3.ts b/packages/angular/src/migrations/update-8-5-0/upgrade-cli-8-3.ts index 1f00b1716bdfa..430ca98928cb4 100644 --- a/packages/angular/src/migrations/update-8-5-0/upgrade-cli-8-3.ts +++ b/packages/angular/src/migrations/update-8-5-0/upgrade-cli-8-3.ts @@ -5,7 +5,7 @@ import { formatFiles, updateJsonInTree, checkAndCleanWithSemver, - addInstallTask + addInstallTask, } from '@nrwl/workspace'; import { gt } from 'semver'; @@ -14,7 +14,7 @@ const updateAngular = addUpdateTask('@angular/core', '8.2.4'); function updateCLI() { const tasks: TaskId[] = []; const rule = chain([ - updateJsonInTree('package.json', json => { + updateJsonInTree('package.json', (json) => { json.devDependencies = json.devDependencies || {}; const cliVersion = json.devDependencies['@angular/cli']; const cleanCliVersion = checkAndCleanWithSemver( @@ -41,7 +41,7 @@ function updateCLI() { return json; }), - addInstallTask() + addInstallTask(), ]); return { rule, tasks }; @@ -54,7 +54,7 @@ function updateNgrx(updateDeps: TaskId[]) { if (dependencies && dependencies['@ngrx/store']) { return chain([ addUpdateTask('@ngrx/store', '8.3.0', updateDeps), - formatFiles() + formatFiles(), ]); } @@ -62,12 +62,12 @@ function updateNgrx(updateDeps: TaskId[]) { }; } -export default function() { +export default function () { const { rule: updateCLIRule, tasks } = updateCLI(); return chain([ updateAngular, updateCLIRule, updateNgrx(tasks), - formatFiles() + formatFiles(), ]); } diff --git a/packages/angular/src/migrations/update-9-0-0/add-postinstall.spec.ts b/packages/angular/src/migrations/update-9-0-0/add-postinstall.spec.ts index 976ba6dca907b..b37b91242a6ce 100644 --- a/packages/angular/src/migrations/update-9-0-0/add-postinstall.spec.ts +++ b/packages/angular/src/migrations/update-9-0-0/add-postinstall.spec.ts @@ -6,7 +6,10 @@ describe('add-postinstall', () => { let tree: Tree; beforeEach(async () => { tree = Tree.empty(); - tree = await callRule(updateJsonInTree('package.json', () => ({})), tree); + tree = await callRule( + updateJsonInTree('package.json', () => ({})), + tree + ); }); it('should add a postinstall for "ngcc"', async () => { const result = await runMigration('add-postinstall', {}, tree); @@ -20,9 +23,9 @@ describe('add-postinstall', () => { it('should not add a postinstall if one exists', async () => { tree = await callRule( - updateJsonInTree('package.json', json => { + updateJsonInTree('package.json', (json) => { json.scripts = { - postinstall: './postinstall.sh' + postinstall: './postinstall.sh', }; return json; }), diff --git a/packages/angular/src/migrations/update-9-0-0/add-postinstall.ts b/packages/angular/src/migrations/update-9-0-0/add-postinstall.ts index 139f3f13eee7b..7b189a16c98f7 100644 --- a/packages/angular/src/migrations/update-9-0-0/add-postinstall.ts +++ b/packages/angular/src/migrations/update-9-0-0/add-postinstall.ts @@ -2,7 +2,7 @@ import { formatFiles, updateJsonInTree } from '@nrwl/workspace'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { chain } from '@angular-devkit/schematics'; -export default function() { +export default function () { return chain([ updateJsonInTree('package.json', (json, context) => { json.scripts = json.scripts || {}; @@ -24,6 +24,6 @@ export default function() { } return json; }), - formatFiles() + formatFiles(), ]); } diff --git a/packages/angular/src/migrations/update-9-0-0/update-9-0-0.ts b/packages/angular/src/migrations/update-9-0-0/update-9-0-0.ts index 51ccb1bf5fb9a..c04f3037bd343 100644 --- a/packages/angular/src/migrations/update-9-0-0/update-9-0-0.ts +++ b/packages/angular/src/migrations/update-9-0-0/update-9-0-0.ts @@ -3,7 +3,7 @@ import { addUpdateTask, formatFiles } from '@nrwl/workspace'; import { RunSchematicTask } from '@angular-devkit/schematics/tasks'; import { join } from 'path'; -export default function() { +export default function () { return (_, context: SchematicContext) => { const postInstallTask = context.addTask( new RunSchematicTask( @@ -15,7 +15,7 @@ export default function() { return chain([ addUpdateTask('@angular/core', '9.0.0', [postInstallTask]), addUpdateTask('@angular/cli', '9.0.1', [postInstallTask]), - formatFiles() + formatFiles(), ]); }; } diff --git a/packages/angular/src/runtime/nx/data-persistence.ts b/packages/angular/src/runtime/nx/data-persistence.ts index 82fa237c784f4..2b324920c5280 100644 --- a/packages/angular/src/runtime/nx/data-persistence.ts +++ b/packages/angular/src/runtime/nx/data-persistence.ts @@ -12,7 +12,7 @@ import { map, mergeMap, switchMap, - withLatestFrom + withLatestFrom, } from 'rxjs/operators'; /** @@ -83,7 +83,7 @@ export function fetch(opts: FetchOpts) { ); return groupedFetches.pipe( - mergeMap(pairs => + mergeMap((pairs) => pairs.pipe(switchMap(runWithErrorHandling(opts.run, opts.onError))) ) ); @@ -113,7 +113,7 @@ export function navigation( return [ findSnapshot(component, action.payload.routerState.root), - state + state, ] as [ActivatedRouteSnapshot, T]; }), filter(([snapshot, state]) => !!snapshot) @@ -136,7 +136,7 @@ function runWithErrorHandling( return ([action, state]: [A, T]): Observable => { try { const r = wrapIntoObservable(run(action, state)); - return r.pipe(catchError(e => wrapIntoObservable(onError(action, e)))); + return r.pipe(catchError((e) => wrapIntoObservable(onError(action, e)))); } catch (e) { return wrapIntoObservable(onError(action, e)); } @@ -150,7 +150,7 @@ function runWithErrorHandling( function mapActionAndState() { return (source: Observable>) => { return source.pipe( - map(value => { + map((value) => { const [action, store] = normalizeActionAndState(value); return [action, store] as [A, T]; }) diff --git a/packages/angular/src/schematics/application/application.spec.ts b/packages/angular/src/schematics/application/application.spec.ts index 0743a7ee421c0..4bfceed05f507 100644 --- a/packages/angular/src/schematics/application/application.spec.ts +++ b/packages/angular/src/schematics/application/application.spec.ts @@ -45,12 +45,12 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-app': { - tags: ['one', 'two'] + tags: ['one', 'two'], }, 'my-app-e2e': { implicitDependencies: ['my-app'], - tags: [] - } + tags: [], + }, }); }); @@ -138,9 +138,9 @@ describe('app', () => { xit('should work if the new project root is changed', async () => { appTree = await callRule( - updateJsonInTree('/workspace.json', json => ({ + updateJsonInTree('/workspace.json', (json) => ({ ...json, - newProjectRoot: 'newProjectRoot' + newProjectRoot: 'newProjectRoot', })), appTree ); @@ -191,12 +191,12 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-app': { - tags: ['one', 'two'] + tags: ['one', 'two'], }, 'my-dir-my-app-e2e': { implicitDependencies: ['my-dir-my-app'], - tags: [] - } + tags: [], + }, }); }); @@ -222,8 +222,8 @@ describe('app', () => { 'apps/my-dir/my-app/src/main.ts', 'apps/my-dir/my-app/src/app/app.module.ts', 'apps/my-dir/my-app/src/app/app.component.ts', - 'apps/my-dir/my-app-e2e/cypress.json' - ].forEach(path => { + 'apps/my-dir/my-app-e2e/cypress.json', + ].forEach((path) => { expect(tree.exists(path)).toBeTruthy(); }); @@ -231,18 +231,18 @@ describe('app', () => { [ { path: 'apps/my-dir/my-app/tsconfig.json', - lookupFn: json => json.extends, - expectedValue: '../../../tsconfig.json' + lookupFn: (json) => json.extends, + expectedValue: '../../../tsconfig.json', }, { path: 'apps/my-dir/my-app/tsconfig.app.json', - lookupFn: json => json.compilerOptions.outDir, - expectedValue: '../../../dist/out-tsc' + lookupFn: (json) => json.compilerOptions.outDir, + expectedValue: '../../../dist/out-tsc', }, { path: 'apps/my-dir/my-app-e2e/tsconfig.json', - lookupFn: json => json.extends, - expectedValue: '../../../tsconfig.json' + lookupFn: (json) => json.extends, + expectedValue: '../../../tsconfig.json', }, // { // path: 'apps/my-dir/my-app-e2e/tsconfig.e2e.json', @@ -251,9 +251,9 @@ describe('app', () => { // }, { path: 'apps/my-dir/my-app/tslint.json', - lookupFn: json => json.extends, - expectedValue: '../../../tslint.json' - } + lookupFn: (json) => json.extends, + expectedValue: '../../../tslint.json', + }, ].forEach(hasJsonValue); }); }); @@ -349,8 +349,8 @@ describe('app', () => { expect(workspaceJson.projects['my-app'].schematics).toEqual({ '@nrwl/angular:component': { - style: 'scss' - } + style: 'scss', + }, }); }); }); @@ -390,7 +390,7 @@ describe('app', () => { workspaceJson.projects['my-app'].architect.lint.options.tsConfig ).toEqual([ 'apps/my-app/tsconfig.app.json', - 'apps/my-app/tsconfig.spec.json' + 'apps/my-app/tsconfig.spec.json', ]); const tsconfigAppJson = readJsonInTree( tree, @@ -444,22 +444,22 @@ describe('app', () => { builder: '@angular-devkit/build-angular:protractor', options: { devServerTarget: 'my-app:serve', - protractorConfig: 'apps/my-app-e2e/protractor.conf.js' + protractorConfig: 'apps/my-app-e2e/protractor.conf.js', }, configurations: { production: { - devServerTarget: 'my-app:serve:production' - } - } + devServerTarget: 'my-app:serve:production', + }, + }, }, lint: { builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: 'apps/my-app-e2e/tsconfig.e2e.json', - exclude: ['**/node_modules/**', '!apps/my-app-e2e/**'] - } - } - } + exclude: ['**/node_modules/**', '!apps/my-app-e2e/**'], + }, + }, + }, }); }); @@ -527,8 +527,8 @@ describe('app', () => { { '/customer-api': { target: 'http://localhost:3333', - secure: false - } + secure: false, + }, }, null, 2 diff --git a/packages/angular/src/schematics/application/application.ts b/packages/angular/src/schematics/application/application.ts index 9153e17293d47..f3e487d80bffd 100644 --- a/packages/angular/src/schematics/application/application.ts +++ b/packages/angular/src/schematics/application/application.ts @@ -10,7 +10,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { Schema } from './schema'; import * as ts from 'typescript'; @@ -27,19 +27,19 @@ import { updateJsonInTree, updateWorkspace, addLintFiles, - NxJson + NxJson, } from '@nrwl/workspace'; import { join, normalize } from '@angular-devkit/core'; import init from '../init/init'; import { addImportToModule, addImportToTestBed, - getDecoratorPropertyValueNode + getDecoratorPropertyValueNode, } from '../../utils/ast-utils'; import { insertImport, getProjectConfig, - updateWorkspaceInTree + updateWorkspaceInTree, } from '@nrwl/workspace/src/utils/ast-utils'; interface NormalizedSchema extends Schema { @@ -272,7 +272,7 @@ summary { width: 16px; margin-right: 4px; } - ` + `, }; function addRouterRootConfiguration(options: NormalizedSchema): Rule { @@ -291,7 +291,7 @@ function addRouterRootConfiguration(options: NormalizedSchema): Rule { sourceFile, modulePath, `RouterModule.forRoot([], {initialNavigation: 'enabled'})` - ) + ), ]); return host; @@ -307,7 +307,7 @@ function updateComponentStyles(options: NormalizedSchema): Rule { css: `${options.appProjectRoot}/src/app/app.component.css`, scss: `${options.appProjectRoot}/src/app/app.component.scss`, less: `${options.appProjectRoot}/src/app/app.component.less`, - styl: `${options.appProjectRoot}/src/app/app.component.styl` + styl: `${options.appProjectRoot}/src/app/app.component.styl`, }; return host.overwrite(filesMap[options.style], content); } @@ -401,7 +401,7 @@ function updateComponentSpec(options: NormalizedSchema) { componentSpecSourceFile, componentSpecPath, `RouterTestingModule` - ) + ), ]); } } @@ -412,7 +412,7 @@ function updateComponentSpec(options: NormalizedSchema) { function updateLinting(options: NormalizedSchema): Rule { return chain([ - updateJsonInTree('tslint.json', json => { + updateJsonInTree('tslint.json', (json) => { if ( json.rulesDirectory && json.rulesDirectory.indexOf('node_modules/codelyzer') === -1 @@ -434,18 +434,18 @@ function updateLinting(options: NormalizedSchema): Rule { 'template-banana-in-box': true, 'template-no-negated-async': true, 'use-lifecycle-interface': true, - 'use-pipe-transform-interface': true + 'use-pipe-transform-interface': true, }; } return json; }), - updateJsonInTree(`${options.appProjectRoot}/tslint.json`, json => { + updateJsonInTree(`${options.appProjectRoot}/tslint.json`, (json) => { json.extends = `${offsetFromRoot(options.appProjectRoot)}tslint.json`; json.linterOptions = { - exclude: ['!**/*'] + exclude: ['!**/*'], }; return json; - }) + }), ]); } @@ -454,23 +454,23 @@ function addSchematicFiles( options: NormalizedSchema ): Rule { return chain([ - host => host.delete(`${appProjectRoot}/src/favicon.ico`), + (host) => host.delete(`${appProjectRoot}/src/favicon.ico`), mergeWith( apply(url('./files'), [ template({ ...options, - offsetFromRoot: offsetFromRoot(options.appProjectRoot) + offsetFromRoot: offsetFromRoot(options.appProjectRoot), }), - move(options.appProjectRoot) + move(options.appProjectRoot), ]) - ) + ), ]); } function updateProject(options: NormalizedSchema): Rule { return (host: Tree) => { return chain([ - updateJsonInTree(getWorkspacePath(host), json => { + updateJsonInTree(getWorkspacePath(host), (json) => { const project = json.projects[options.name]; let fixedProject = replaceAppNameWithPath( project, @@ -485,11 +485,11 @@ function updateProject(options: NormalizedSchema): Rule { 'guard', 'module', 'pipe', - 'service' + 'service', ]; if (fixedProject.schematics) { - angularSchematicNames.forEach(type => { + angularSchematicNames.forEach((type) => { const schematic = `@schematics/angular:${type}`; if (schematic in fixedProject.schematics) { fixedProject.schematics[`@nrwl/angular:${type}`] = @@ -502,7 +502,7 @@ function updateProject(options: NormalizedSchema): Rule { delete fixedProject.architect.test; fixedProject.architect.lint.options.tsConfig = fixedProject.architect.lint.options.tsConfig.filter( - path => + (path) => path !== join(normalize(options.appProjectRoot), 'tsconfig.spec.json') && path !== @@ -518,53 +518,56 @@ function updateProject(options: NormalizedSchema): Rule { json.projects[options.name] = fixedProject; return json; }), - updateJsonInTree(`${options.appProjectRoot}/tsconfig.app.json`, json => { - return { - ...json, - extends: `./tsconfig.json`, - compilerOptions: { - ...json.compilerOptions, - outDir: `${offsetFromRoot(options.appProjectRoot)}dist/out-tsc` - }, - exclude: options.enableIvy - ? undefined - : options.unitTestRunner === 'jest' - ? ['src/test-setup.ts', '**/*.spec.ts'] - : ['src/test.ts', '**/*.spec.ts'], - include: options.enableIvy ? undefined : ['src/**/*.d.ts'] - }; - }), - host => { + updateJsonInTree( + `${options.appProjectRoot}/tsconfig.app.json`, + (json) => { + return { + ...json, + extends: `./tsconfig.json`, + compilerOptions: { + ...json.compilerOptions, + outDir: `${offsetFromRoot(options.appProjectRoot)}dist/out-tsc`, + }, + exclude: options.enableIvy + ? undefined + : options.unitTestRunner === 'jest' + ? ['src/test-setup.ts', '**/*.spec.ts'] + : ['src/test.ts', '**/*.spec.ts'], + include: options.enableIvy ? undefined : ['src/**/*.d.ts'], + }; + } + ), + (host) => { host.delete(`${options.appProjectRoot}/tsconfig.spec.json`); return host; }, - updateJsonInTree(`/nx.json`, json => { + updateJsonInTree(`/nx.json`, (json) => { const resultJson = { ...json, projects: { ...json.projects, - [options.name]: { tags: options.parsedTags } - } + [options.name]: { tags: options.parsedTags }, + }, }; if (options.e2eTestRunner === 'protractor') { resultJson.projects[options.e2eProjectName] = { tags: [] }; resultJson.projects[options.e2eProjectName].implicitDependencies = [ - options.name + options.name, ]; } return resultJson; }), - host => { + (host) => { host.delete(`${options.appProjectRoot}/karma.conf.js`); host.delete(`${options.appProjectRoot}/src/test.ts`); - } + }, ]); }; } function removeE2e(options: NormalizedSchema, e2eProjectRoot: string): Rule { return chain([ - host => { + (host) => { if (host.read(`${e2eProjectRoot}/src/app.e2e-spec.ts`)) { host.delete(`${e2eProjectRoot}/src/app.e2e-spec.ts`); } @@ -578,9 +581,9 @@ function removeE2e(options: NormalizedSchema, e2eProjectRoot: string): Rule { host.delete(`${e2eProjectRoot}/tsconfig.json`); } }, - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.get(options.name).targets.delete('e2e'); - }) + }), ]); } @@ -602,7 +605,7 @@ function updateE2eProject(options: NormalizedSchema): Rule { host.overwrite(page, pageContent.replace(`.content span`, `header h1`)); return chain([ - updateJsonInTree(getWorkspacePath(host), json => { + updateJsonInTree(getWorkspacePath(host), (json) => { const project = { root: options.e2eProjectRoot, projectType: 'application', @@ -614,11 +617,11 @@ function updateE2eProject(options: NormalizedSchema): Rule { tsConfig: `${options.e2eProjectRoot}/tsconfig.e2e.json`, exclude: [ '**/node_modules/**', - '!' + join(normalize(options.e2eProjectRoot), '**') - ] - } - } - } + '!' + join(normalize(options.e2eProjectRoot), '**'), + ], + }, + }, + }, }; project.architect.e2e.options.protractorConfig = `${options.e2eProjectRoot}/protractor.conf.js`; @@ -627,16 +630,19 @@ function updateE2eProject(options: NormalizedSchema): Rule { delete json.projects[options.name].architect.e2e; return json; }), - updateJsonInTree(`${options.e2eProjectRoot}/tsconfig.e2e.json`, json => { - return { - ...json, - extends: `./tsconfig.json`, - compilerOptions: { - ...json.compilerOptions, - outDir: `${offsetFromRoot(options.e2eProjectRoot)}dist/out-tsc` - } - }; - }) + updateJsonInTree( + `${options.e2eProjectRoot}/tsconfig.e2e.json`, + (json) => { + return { + ...json, + extends: `./tsconfig.json`, + compilerOptions: { + ...json.compilerOptions, + outDir: `${offsetFromRoot(options.e2eProjectRoot)}dist/out-tsc`, + }, + }; + } + ), ]); }; } @@ -648,25 +654,25 @@ function addProxyConfig(options: NormalizedSchema): Rule { const pathToProxyFile = `${projectConfig.root}/proxy.conf.json`; return chain([ - updateJsonInTree(pathToProxyFile, json => { + updateJsonInTree(pathToProxyFile, (json) => { return { [`/${options.backendProject}`]: { target: 'http://localhost:3333', - secure: false - } + secure: false, + }, }; }), - updateWorkspaceInTree(json => { + updateWorkspaceInTree((json) => { projectConfig.architect.serve.options.proxyConfig = pathToProxyFile; json.projects[options.name] = projectConfig; return json; - }) + }), ])(host, context); } }; } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); @@ -684,10 +690,10 @@ export default function(schema: Schema): Rule { return chain([ init({ ...options, - skipFormat: true + skipFormat: true, }), addLintFiles(options.appProjectRoot, options.linter, { - onlyGlobal: true + onlyGlobal: true, }), externalSchematic('@schematics/angular', 'application', { name: options.name, @@ -700,7 +706,7 @@ export default function(schema: Schema): Rule { enableIvy: options.enableIvy, routing: false, skipInstall: true, - skipPackageJson: false + skipPackageJson: false, }), addSchematicFiles(appProjectRoot, options), options.e2eTestRunner === 'protractor' @@ -721,12 +727,12 @@ export default function(schema: Schema): Rule { project: options.name, supportTsx: false, skipSerializers: false, - setupFile: 'angular' + setupFile: 'angular', }) : noop(), options.unitTestRunner === 'karma' ? schematic('karma-project', { - project: options.name + project: options.name, }) : noop(), options.e2eTestRunner === 'cypress' @@ -734,11 +740,11 @@ export default function(schema: Schema): Rule { name: options.e2eProjectName, directory: options.directory, project: options.name, - linter: options.linter + linter: options.linter, }) : noop(), options.backendProject ? addProxyConfig(options) : noop(), - formatFiles(options) + formatFiles(options), ])(host, context); }; } @@ -758,7 +764,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { const e2eProjectRoot = `apps/${appDirectory}-e2e`; const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const defaultPrefix = getNpmScope(host); @@ -769,6 +775,6 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { appProjectRoot, e2eProjectRoot, e2eProjectName, - parsedTags + parsedTags, }; } diff --git a/packages/angular/src/schematics/component-cypress-spec/component-cypress-spec.ts b/packages/angular/src/schematics/component-cypress-spec/component-cypress-spec.ts index afd69f09da84c..93d16545b4fa9 100644 --- a/packages/angular/src/schematics/component-cypress-spec/component-cypress-spec.ts +++ b/packages/angular/src/schematics/component-cypress-spec/component-cypress-spec.ts @@ -8,22 +8,22 @@ import { SchematicsException, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { findNodes, getProjectConfig } from '@nrwl/workspace'; import { PropertyAssignment, PropertyDeclaration, - SyntaxKind + SyntaxKind, } from 'typescript'; import { getTsSourceFile, getDecoratorMetadata } from '../../utils/ast-utils'; import { getInputPropertyDeclarations, - getKnobType + getKnobType, } from '../component-story/component-story'; import { applyWithSkipExisting } from '@nrwl/workspace/src/utils/ast-utils'; -export default function(schema: CreateComponentSpecFileSchema): Rule { +export default function (schema: CreateComponentSpecFileSchema): Rule { return chain([createComponentSpecFile(schema)]); } @@ -40,7 +40,7 @@ export function createComponentSpecFile({ libPath, componentName, componentPath, - componentFileName + componentFileName, }: CreateComponentSpecFileSchema): Rule { return (tree: Tree, context: SchematicContext): Rule => { const e2eLibIntegrationFolderPath = @@ -48,7 +48,7 @@ export function createComponentSpecFile({ const fullComponentPath = libPath + '/' + componentPath + '/' + componentFileName + '.ts'; const props = getInputPropertyDeclarations(tree, fullComponentPath).map( - node => { + (node) => { const decoratorContent = findNodes( findNodes(node, SyntaxKind.Decorator)[0], SyntaxKind.StringLiteral @@ -63,7 +63,7 @@ export function createComponentSpecFile({ return { name, type, - defaultValue + defaultValue, }; } ); @@ -75,9 +75,9 @@ export function createComponentSpecFile({ componentName: componentName, componentSelector, props, - tmpl: '' + tmpl: '', }), - move(e2eLibIntegrationFolderPath + '/' + componentPath) + move(e2eLibIntegrationFolderPath + '/' + componentPath), ]); }; } diff --git a/packages/angular/src/schematics/component-story/component-story.ts b/packages/angular/src/schematics/component-story/component-story.ts index c548827319978..855b7d54b6aa7 100644 --- a/packages/angular/src/schematics/component-story/component-story.ts +++ b/packages/angular/src/schematics/component-story/component-story.ts @@ -5,14 +5,14 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { findNodes } from '@nrwl/workspace'; import { PropertyDeclaration, SyntaxKind } from 'typescript'; import { getTsSourceFile } from '../../utils/ast-utils'; import { getSourceNodes, - applyWithSkipExisting + applyWithSkipExisting, } from '@nrwl/workspace/src/utils/ast-utils'; export interface CreateComponentStoriesFileSchema { @@ -22,7 +22,7 @@ export interface CreateComponentStoriesFileSchema { componentFileName: string; } -export default function(schema: CreateComponentStoriesFileSchema): Rule { +export default function (schema: CreateComponentStoriesFileSchema): Rule { return chain([createComponentStoriesFile(schema)]); } @@ -30,7 +30,7 @@ export function createComponentStoriesFile({ libPath, componentName, componentPath, - componentFileName + componentFileName, }: CreateComponentStoriesFileSchema): Rule { return (tree: Tree, context: SchematicContext): Rule => { const props = getInputDescriptors( @@ -42,9 +42,9 @@ export function createComponentStoriesFile({ componentFileName: componentFileName, componentName: componentName, props, - tmpl: '' + tmpl: '', }), - move(libPath + '/' + componentPath) + move(libPath + '/' + componentPath), ]); }; } @@ -63,23 +63,23 @@ export function getInputPropertyDeclarations( const file = getTsSourceFile(tree, path); const decorators = getSourceNodes(file).filter( - node => node.kind === SyntaxKind.Decorator + (node) => node.kind === SyntaxKind.Decorator ); return decorators - .filter(decorator => + .filter((decorator) => findNodes(decorator, SyntaxKind.Identifier).some( - node => node.getText() === 'Input' + (node) => node.getText() === 'Input' ) ) - .map(node => node.parent as PropertyDeclaration); + .map((node) => node.parent as PropertyDeclaration); } export function getInputDescriptors( tree: Tree, path: string ): InputDescriptor[] { - return getInputPropertyDeclarations(tree, path).map(node => { + return getInputPropertyDeclarations(tree, path).map((node) => { const decoratorContent = findNodes( findNodes(node, SyntaxKind.Decorator)[0], SyntaxKind.StringLiteral @@ -94,7 +94,7 @@ export function getInputDescriptors( return { name, type, - defaultValue + defaultValue, }; }); } @@ -105,7 +105,7 @@ export function getKnobType(property: PropertyDeclaration): KnobType { const typeNameToKnobType: Record = { string: 'text', number: 'number', - boolean: 'boolean' + boolean: 'boolean', }; return typeNameToKnobType[typeName] || 'text'; } @@ -114,7 +114,7 @@ export function getKnobType(property: PropertyDeclaration): KnobType { [SyntaxKind.StringLiteral]: 'text', [SyntaxKind.NumericLiteral]: 'number', [SyntaxKind.TrueKeyword]: 'boolean', - [SyntaxKind.FalseKeyword]: 'boolean' + [SyntaxKind.FalseKeyword]: 'boolean', }; return initializerKindToKnobType[property.initializer.kind] || 'text'; } @@ -125,7 +125,7 @@ export function getKnobDefaultValue(property: PropertyDeclaration): string { const typeNameToDefault = { string: "''", number: '0', - boolean: 'false' + boolean: 'false', }; return property.initializer ? property.initializer.getText() diff --git a/packages/angular/src/schematics/downgrade-module/downgrade-module.spec.ts b/packages/angular/src/schematics/downgrade-module/downgrade-module.spec.ts index 68fc947db92b4..fc3af6cadade1 100644 --- a/packages/angular/src/schematics/downgrade-module/downgrade-module.spec.ts +++ b/packages/angular/src/schematics/downgrade-module/downgrade-module.spec.ts @@ -17,7 +17,7 @@ describe('downgrade-module', () => { 'downgrade-module', { name: 'legacy', - project: 'myapp' + project: 'myapp', }, appTree ); @@ -35,7 +35,7 @@ describe('downgrade-module', () => { 'downgrade-module', { name: 'legacy', - project: 'myapp' + project: 'myapp', }, appTree ); @@ -51,8 +51,8 @@ describe('downgrade-module', () => { `/package.json`, JSON.stringify({ dependencies: { - '@angular/core': '4.4.4' - } + '@angular/core': '4.4.4', + }, }) ); @@ -60,7 +60,7 @@ describe('downgrade-module', () => { 'downgrade-module', { name: 'legacy', - project: 'myapp' + project: 'myapp', }, appTree ); @@ -75,8 +75,8 @@ describe('downgrade-module', () => { `/package.json`, JSON.stringify({ dependencies: { - '@angular/core': '4.4.4' - } + '@angular/core': '4.4.4', + }, }) ); @@ -85,7 +85,7 @@ describe('downgrade-module', () => { { name: 'legacy', skipPackageJson: true, - project: 'myapp' + project: 'myapp', }, appTree ); @@ -100,7 +100,7 @@ describe('downgrade-module', () => { { name: 'legacy', angularJsImport: 'legacy-app', - project: 'myapp' + project: 'myapp', }, appTree ); diff --git a/packages/angular/src/schematics/downgrade-module/downgrade-module.ts b/packages/angular/src/schematics/downgrade-module/downgrade-module.ts index 3fa4c6b222499..a219c72830047 100644 --- a/packages/angular/src/schematics/downgrade-module/downgrade-module.ts +++ b/packages/angular/src/schematics/downgrade-module/downgrade-module.ts @@ -6,7 +6,7 @@ import { addUpgradeToPackageJson } from '../../utils/upgrade'; import { addEntryComponents, readBootstrapInfo, - removeFromNgModule + removeFromNgModule, } from '../../utils/ast-utils'; function updateMain(angularJsImport: string, options: Schema): Rule { @@ -16,7 +16,7 @@ function updateMain(angularJsImport: string, options: Schema): Rule { moduleClassName, moduleSpec, bootstrapComponentClassName, - bootstrapComponentFileName + bootstrapComponentFileName, } = readBootstrapInfo(host, options.project); host.overwrite( @@ -64,9 +64,9 @@ function rewriteBootstrapLogic(options: Schema): Rule { ...addMethod(moduleSource, modulePath, { className: moduleClassName, methodHeader: 'ngDoBootstrap(): void', - body: `` + body: ``, }), - ...removeFromNgModule(moduleSource, modulePath, 'bootstrap') + ...removeFromNgModule(moduleSource, modulePath, 'bootstrap'), ]); return host; }; @@ -76,7 +76,7 @@ function addEntryComponentsToModule(options: Schema): Rule { const { modulePath, moduleSource, - bootstrapComponentClassName + bootstrapComponentClassName, } = readBootstrapInfo(host, options.project); insert( host, @@ -87,7 +87,7 @@ function addEntryComponentsToModule(options: Schema): Rule { }; } -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { const angularJsImport = options.angularJsImport ? options.angularJsImport : options.name; @@ -97,6 +97,6 @@ export default function(options: Schema): Rule { addEntryComponentsToModule(options), rewriteBootstrapLogic(options), options.skipPackageJson ? noop() : addUpgradeToPackageJson(), - formatFiles(options) + formatFiles(options), ]); } diff --git a/packages/angular/src/schematics/init/init.spec.ts b/packages/angular/src/schematics/init/init.spec.ts index c8a7e9130ff8d..ba8bb47dead4a 100644 --- a/packages/angular/src/schematics/init/init.spec.ts +++ b/packages/angular/src/schematics/init/init.spec.ts @@ -36,7 +36,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - unitTestRunner: 'karma' + unitTestRunner: 'karma', }, appTree ); @@ -54,7 +54,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - unitTestRunner: 'karma' + unitTestRunner: 'karma', }, appTree ); @@ -75,7 +75,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - unitTestRunner: 'karma' + unitTestRunner: 'karma', }, appTree ); @@ -86,7 +86,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - unitTestRunner: 'karma' + unitTestRunner: 'karma', }, appTree ); @@ -105,7 +105,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - unitTestRunner: 'jest' + unitTestRunner: 'jest', }, appTree ); @@ -119,7 +119,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - unitTestRunner: 'jest' + unitTestRunner: 'jest', }, appTree ); @@ -130,7 +130,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - unitTestRunner: 'jest' + unitTestRunner: 'jest', }, appTree ); @@ -152,7 +152,7 @@ describe('init', () => { 'init', { unitTestRunner: 'none', - e2eTestRunner: 'cypress' + e2eTestRunner: 'cypress', }, appTree ); @@ -165,7 +165,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - e2eTestRunner: 'cypress' + e2eTestRunner: 'cypress', }, appTree ); @@ -181,7 +181,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - e2eTestRunner: 'protractor' + e2eTestRunner: 'protractor', }, appTree ); @@ -197,7 +197,7 @@ describe('init', () => { const tree = await runSchematic( 'init', { - e2eTestRunner: 'protractor' + e2eTestRunner: 'protractor', }, appTree ); diff --git a/packages/angular/src/schematics/init/init.ts b/packages/angular/src/schematics/init/init.ts index 73b37b0932223..dc3604af27255 100755 --- a/packages/angular/src/schematics/init/init.ts +++ b/packages/angular/src/schematics/init/init.ts @@ -4,20 +4,20 @@ import { noop, Rule, schematic, - Tree + Tree, } from '@angular-devkit/schematics'; import { addDepsToPackageJson, formatFiles, readJsonInTree, updateJsonInTree, - updateWorkspace + updateWorkspace, } from '@nrwl/workspace'; import { angularDevkitVersion, angularVersion, jestPresetAngularVersion, - rxjsVersion + rxjsVersion, } from '../../utils/versions'; import { Schema } from './schema'; import { E2eTestRunner, UnitTestRunner } from '../../utils/test-runners'; @@ -36,13 +36,13 @@ const updateDependencies = addDepsToPackageJson( '@angular/router': angularVersion, 'core-js': '^2.5.4', rxjs: rxjsVersion, - 'zone.js': '^0.10.2' + 'zone.js': '^0.10.2', }, { '@angular/compiler-cli': angularVersion, '@angular/language-service': angularVersion, '@angular-devkit/build-angular': angularDevkitVersion, - codelyzer: '~5.0.1' + codelyzer: '~5.0.1', } ); @@ -57,7 +57,7 @@ export function addUnitTestRunner( addDepsToPackageJson( {}, { - 'jest-preset-angular': jestPresetAngularVersion + 'jest-preset-angular': jestPresetAngularVersion, } ), (host: Tree) => { @@ -70,10 +70,10 @@ export function addUnitTestRunner( 'init', {}, { - interactive: false + interactive: false, } ); - } + }, ]); default: return noop(); @@ -95,7 +95,7 @@ export function addE2eTestRunner(options: Pick): Rule { 'jasmine-core': '~2.99.1', 'jasmine-spec-reporter': '~4.2.1', '@types/jasmine': '~2.8.6', - '@types/jasminewd2': '~2.0.3' + '@types/jasminewd2': '~2.0.3', } ); }; @@ -110,7 +110,7 @@ export function addE2eTestRunner(options: Pick): Rule { 'ng-add', {}, { - interactive: false + interactive: false, } ); }; @@ -120,7 +120,7 @@ export function addE2eTestRunner(options: Pick): Rule { } export function setDefaults(options: Schema): Rule { - const updateAngularWorkspace = updateWorkspace(workspace => { + const updateAngularWorkspace = updateWorkspace((workspace) => { workspace.extensions.schematics = workspace.extensions.schematics || {}; workspace.extensions.schematics['@nrwl/angular:application'] = @@ -165,7 +165,7 @@ function addPostinstall(): Rule { }); } -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { return chain([ setDefaults(options), // TODO: Remove this when ngcc can be run in parallel @@ -173,6 +173,6 @@ export default function(options: Schema): Rule { updateDependencies, addUnitTestRunner(options), addE2eTestRunner(options), - formatFiles() + formatFiles(), ]); } diff --git a/packages/angular/src/schematics/karma-project/karma-project.spec.ts b/packages/angular/src/schematics/karma-project/karma-project.spec.ts index b3e65243e4e14..053ae37bc899c 100644 --- a/packages/angular/src/schematics/karma-project/karma-project.spec.ts +++ b/packages/angular/src/schematics/karma-project/karma-project.spec.ts @@ -13,7 +13,7 @@ describe('karmaProject', () => { 'lib', { name: 'lib1', - unitTestRunner: 'none' + unitTestRunner: 'none', }, appTree ); @@ -21,7 +21,7 @@ describe('karmaProject', () => { 'app', { name: 'app1', - unitTestRunner: 'none' + unitTestRunner: 'none', }, appTree ); @@ -31,7 +31,7 @@ describe('karmaProject', () => { const resultTree = await runSchematic( 'karma-project', { - project: 'lib1' + project: 'lib1', }, appTree ); @@ -43,7 +43,7 @@ describe('karmaProject', () => { const resultTree = await runSchematic( 'karma-project', { - project: 'lib1' + project: 'lib1', }, appTree ); @@ -71,7 +71,7 @@ module.exports = function(config) { const resultTree = await runSchematic( 'karma-project', { - project: 'lib1' + project: 'lib1', }, appTree ); @@ -85,7 +85,7 @@ module.exports = function(config) { const resultTree = await runSchematic( 'karma-project', { - project: 'lib1' + project: 'lib1', }, appTree ); @@ -95,8 +95,8 @@ module.exports = function(config) { options: { main: 'libs/lib1/src/test.ts', tsConfig: 'libs/lib1/tsconfig.spec.json', - karmaConfig: 'libs/lib1/karma.conf.js' - } + karmaConfig: 'libs/lib1/karma.conf.js', + }, }); expect( workspaceJson.projects.lib1.architect.lint.options.tsConfig @@ -107,7 +107,7 @@ module.exports = function(config) { const resultTree = await runSchematic( 'karma-project', { - project: 'lib1' + project: 'lib1', }, appTree ); @@ -119,10 +119,10 @@ module.exports = function(config) { extends: './tsconfig.json', compilerOptions: { outDir: '../../dist/out-tsc', - types: ['jasmine', 'node'] + types: ['jasmine', 'node'], }, files: ['src/test.ts'], - include: ['**/*.spec.ts', '**/*.d.ts'] + include: ['**/*.spec.ts', '**/*.d.ts'], }); }); @@ -130,7 +130,7 @@ module.exports = function(config) { const resultTree = await runSchematic( 'karma-project', { - project: 'lib1' + project: 'lib1', }, appTree ); @@ -145,7 +145,7 @@ module.exports = function(config) { const resultTree = await runSchematic( 'karma-project', { - project: 'app1' + project: 'app1', }, appTree ); @@ -159,8 +159,8 @@ module.exports = function(config) { karmaConfig: 'apps/app1/karma.conf.js', styles: [], scripts: [], - assets: [] - } + assets: [], + }, }); expect( workspaceJson.projects.app1.architect.lint.options.tsConfig @@ -171,7 +171,7 @@ module.exports = function(config) { const resultTree = await runSchematic( 'karma-project', { - project: 'app1' + project: 'app1', }, appTree ); @@ -183,10 +183,10 @@ module.exports = function(config) { extends: './tsconfig.json', compilerOptions: { outDir: '../../dist/out-tsc', - types: ['jasmine', 'node'] + types: ['jasmine', 'node'], }, files: ['src/test.ts', 'src/polyfills.ts'], - include: ['**/*.spec.ts', '**/*.d.ts'] + include: ['**/*.spec.ts', '**/*.d.ts'], }); }); @@ -194,7 +194,7 @@ module.exports = function(config) { const resultTree = await runSchematic( 'karma-project', { - project: 'app1' + project: 'app1', }, appTree ); diff --git a/packages/angular/src/schematics/karma-project/karma-project.ts b/packages/angular/src/schematics/karma-project/karma-project.ts index 63e4401dcb771..29d7e52925ec6 100644 --- a/packages/angular/src/schematics/karma-project/karma-project.ts +++ b/packages/angular/src/schematics/karma-project/karma-project.ts @@ -8,13 +8,13 @@ import { SchematicContext, move, template, - schematic + schematic, } from '@angular-devkit/schematics'; import { readJsonInTree, updateJsonInTree, offsetFromRoot, - updateWorkspaceInTree + updateWorkspaceInTree, } from '@nrwl/workspace'; import { join, normalize } from '@angular-devkit/core'; import { getProjectConfig } from '@nrwl/workspace'; @@ -35,9 +35,9 @@ function generateFiles(options: KarmaProjectSchema): Rule { ...options, projectRoot: projectConfig.root, isLibrary: projectConfig.projectType === 'library', - offsetFromRoot: offsetFromRoot(projectConfig.root) + offsetFromRoot: offsetFromRoot(projectConfig.root), }), - move(projectConfig.root) + move(projectConfig.root), ]) )(host, context); }; @@ -46,17 +46,20 @@ function generateFiles(options: KarmaProjectSchema): Rule { function updateTsConfig(options: KarmaProjectSchema): Rule { return (host: Tree) => { const projectConfig = getProjectConfig(host, options.project); - return updateJsonInTree(join(projectConfig.root, 'tsconfig.json'), json => { - return { - ...json, - compilerOptions: { - ...json.compilerOptions, - types: Array.from( - new Set([...(json.compilerOptions.types || []), 'jasmine']) - ) - } - }; - }); + return updateJsonInTree( + join(projectConfig.root, 'tsconfig.json'), + (json) => { + return { + ...json, + compilerOptions: { + ...json.compilerOptions, + types: Array.from( + new Set([...(json.compilerOptions.types || []), 'jasmine']) + ), + }, + }; + } + ); }; } @@ -67,10 +70,10 @@ function updateTsSpecConfig(options: KarmaProjectSchema): Rule { projectConfig.projectType === 'library' ? [] : ['src/polyfills.ts']; return updateJsonInTree( join(projectConfig.root, 'tsconfig.spec.json'), - json => { + (json) => { return { ...json, - files: [...json.files, ...extraFiles] + files: [...json.files, ...extraFiles], }; } ); @@ -78,15 +81,15 @@ function updateTsSpecConfig(options: KarmaProjectSchema): Rule { } function updateworkspaceJson(options: KarmaProjectSchema): Rule { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const projectConfig = json.projects[options.project]; projectConfig.architect.test = { builder: '@angular-devkit/build-angular:karma', options: { main: join(normalize(projectConfig.sourceRoot), 'test.ts'), tsConfig: join(normalize(projectConfig.root), 'tsconfig.spec.json'), - karmaConfig: join(normalize(projectConfig.root), 'karma.conf.js') - } + karmaConfig: join(normalize(projectConfig.root), 'karma.conf.js'), + }, }; if (projectConfig.projectType === 'application') { @@ -95,13 +98,13 @@ function updateworkspaceJson(options: KarmaProjectSchema): Rule { polyfills: join(normalize(projectConfig.sourceRoot), 'polyfills.ts'), styles: [], scripts: [], - assets: [] + assets: [], }; } if (projectConfig.architect.lint) { projectConfig.architect.lint.options.tsConfig = [ ...projectConfig.architect.lint.options.tsConfig, - join(normalize(projectConfig.root), 'tsconfig.spec.json') + join(normalize(projectConfig.root), 'tsconfig.spec.json'), ]; } return json; @@ -119,12 +122,12 @@ function check(options: KarmaProjectSchema): Rule { }; } -export default function(options: KarmaProjectSchema): Rule { +export default function (options: KarmaProjectSchema): Rule { return chain([ check(options), generateFiles(options), updateTsConfig(options), updateTsSpecConfig(options), - updateworkspaceJson(options) + updateworkspaceJson(options), ]); } diff --git a/packages/angular/src/schematics/karma/files/karma/karma.conf.js b/packages/angular/src/schematics/karma/files/karma/karma.conf.js index 1056f2baa9a76..2c5a16ceedb8c 100644 --- a/packages/angular/src/schematics/karma/files/karma/karma.conf.js +++ b/packages/angular/src/schematics/karma/files/karma/karma.conf.js @@ -13,15 +13,15 @@ module.exports = () => { require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), - require('@angular-devkit/build-angular/plugins/karma') + require('@angular-devkit/build-angular/plugins/karma'), ], client: { - clearContext: false // leave Jasmine Spec Runner output visible in browser + clearContext: false, // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: join(__dirname, '../../coverage'), reports: ['html', 'lcovonly'], - fixWebpackSourcePaths: true + fixWebpackSourcePaths: true, }, reporters: ['progress', 'kjhtml'], port: 9876, @@ -29,6 +29,6 @@ module.exports = () => { logLevel: constants.LOG_INFO, autoWatch: true, browsers: ['Chrome'], - singleRun: true + singleRun: true, }; }; diff --git a/packages/angular/src/schematics/karma/karma.ts b/packages/angular/src/schematics/karma/karma.ts index e1fa6450c13ab..9b82c5cb75b6d 100644 --- a/packages/angular/src/schematics/karma/karma.ts +++ b/packages/angular/src/schematics/karma/karma.ts @@ -1,7 +1,7 @@ import { Tree, noop, chain, mergeWith, url } from '@angular-devkit/schematics'; import { readJsonInTree, addDepsToPackageJson } from '@nrwl/workspace'; -export default function() { +export default function () { return (host: Tree) => { const packageJson = readJsonInTree(host, 'package.json'); if (packageJson.devDependencies['karma']) { @@ -19,9 +19,9 @@ export default function() { 'karma-jasmine-html-reporter': '^0.2.2', 'jasmine-core': '~2.99.1', 'jasmine-spec-reporter': '~4.2.1', - '@types/jasmine': '~2.8.8' + '@types/jasmine': '~2.8.8', } - ) + ), ]); }; } diff --git a/packages/angular/src/schematics/library/library.spec.ts b/packages/angular/src/schematics/library/library.spec.ts index 20d669d096a0c..378ec2dad0983 100644 --- a/packages/angular/src/schematics/library/library.spec.ts +++ b/packages/angular/src/schematics/library/library.spec.ts @@ -6,7 +6,7 @@ import { NxJson, readJsonInTree } from '@nrwl/workspace'; import { UnitTestTree } from '@angular-devkit/schematics/testing'; import { stripIndents, - stripIndent + stripIndent, } from '@angular-devkit/core/src/utils/literals'; describe('lib', () => { @@ -97,7 +97,7 @@ describe('lib', () => { workspaceJson.projects['my-lib'].architect.lint.options.tsConfig ).toEqual([ 'libs/my-lib/tsconfig.lib.json', - 'libs/my-lib/tsconfig.spec.json' + 'libs/my-lib/tsconfig.spec.json', ]); expect( workspaceJson.projects['my-lib'].architect.lint.options.exclude @@ -139,8 +139,8 @@ describe('lib', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-lib': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -148,7 +148,7 @@ describe('lib', () => { const tree = await runSchematic('lib', { name: 'myLib' }, appTree); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ - 'libs/my-lib/src/index.ts' + 'libs/my-lib/src/index.ts', ]); }); @@ -158,9 +158,9 @@ describe('lib', () => { expect(tsconfigJson).toEqual({ extends: '../../tsconfig.json', compilerOptions: { - types: ['node', 'jest'] + types: ['node', 'jest'], }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); }); @@ -195,7 +195,7 @@ describe('lib', () => { ); expect(tsconfigJson.exclude).toEqual([ 'src/test-setup.ts', - '**/*.spec.ts' + '**/*.spec.ts', ]); }); @@ -300,7 +300,7 @@ describe('lib', () => { 'lib', { name: 'myLib', - framework: 'none' + framework: 'none', }, appTree ); @@ -328,15 +328,15 @@ describe('lib', () => { name: 'myLib', directory: 'myDir', framework: 'angular', - tags: 'one' + tags: 'one', }, appTree ); const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] - } + tags: ['one'], + }, }); const tree2 = await runSchematic( @@ -346,18 +346,18 @@ describe('lib', () => { directory: 'myDir', framework: 'angular', tags: 'one,two', - simpleModuleName: true + simpleModuleName: true, }, tree ); const nxJson2 = readJsonInTree(tree2, '/nx.json'); expect(nxJson2.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] + tags: ['one'], }, 'my-dir-my-lib2': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -392,7 +392,7 @@ describe('lib', () => { name: 'myLib2', directory: 'myDir', framework: 'angular', - simpleModuleName: true + simpleModuleName: true, }, tree ); @@ -423,7 +423,7 @@ describe('lib', () => { name: 'myLib', directory: 'myDir', framework: 'angular', - publishable: true + publishable: true, }, appTree ); @@ -451,7 +451,7 @@ describe('lib', () => { workspaceJson.projects['my-dir-my-lib'].architect.lint.options.tsConfig ).toEqual([ 'libs/my-dir/my-lib/tsconfig.lib.json', - 'libs/my-dir/my-lib/tsconfig.spec.json' + 'libs/my-dir/my-lib/tsconfig.spec.json', ]); expect( workspaceJson.projects['my-dir-my-lib'].architect.lint.options.exclude @@ -465,9 +465,9 @@ describe('lib', () => { appTree ); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); - expect(tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib']).toEqual( - ['libs/my-dir/my-lib/src/index.ts'] - ); + expect( + tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib'] + ).toEqual(['libs/my-dir/my-lib/src/index.ts']); expect( tsconfigJson.compilerOptions.paths['my-dir-my-lib/*'] ).toBeUndefined(); @@ -487,9 +487,9 @@ describe('lib', () => { expect(tsconfigJson).toEqual({ extends: '../../../tsconfig.json', compilerOptions: { - types: ['node', 'jest'] + types: ['node', 'jest'], }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); }); }); @@ -513,7 +513,7 @@ describe('lib', () => { directory: 'myDir', framework: 'angular', routing: true, - lazy: true + lazy: true, }, appTree ); @@ -536,7 +536,7 @@ describe('lib', () => { routing: true, framework: 'angular', lazy: true, - simpleModuleName: true + simpleModuleName: true, }, tree ); @@ -559,7 +559,7 @@ describe('lib', () => { routing: true, lazy: true, framework: 'angular', - parentModule: 'apps/myapp/src/app/app.module.ts' + parentModule: 'apps/myapp/src/app/app.module.ts', }, appTree ); @@ -572,7 +572,9 @@ describe('lib', () => { { path: 'my-dir-my-lib', loadChildren: () => - import('@proj/my-dir/my-lib').then(module => module.MyDirMyLibModule) + import('@proj/my-dir/my-lib').then( + (module) => module.MyDirMyLibModule + ), }`); const tsConfigAppJson = JSON.parse( @@ -582,7 +584,7 @@ describe('lib', () => { ); expect(tsConfigAppJson.include).toEqual([ '**/*.ts', - '../../libs/my-dir/my-lib/src/index.ts' + '../../libs/my-dir/my-lib/src/index.ts', ]); const tree2 = await runSchematic( @@ -593,7 +595,7 @@ describe('lib', () => { routing: true, framework: 'angular', lazy: true, - parentModule: 'apps/myapp/src/app/app.module.ts' + parentModule: 'apps/myapp/src/app/app.module.ts', }, tree ); @@ -606,15 +608,17 @@ describe('lib', () => { { path: 'my-dir-my-lib', loadChildren: () => - import('@proj/my-dir/my-lib').then(module => module.MyDirMyLibModule) + import('@proj/my-dir/my-lib').then( + (module) => module.MyDirMyLibModule + ), }`); expect(moduleContents2).toContain(` { path: 'my-dir-my-lib2', loadChildren: () => import('@proj/my-dir/my-lib2').then( - module => module.MyDirMyLib2Module - ) + (module) => module.MyDirMyLib2Module + ), }`); const tsConfigAppJson2 = JSON.parse( @@ -625,7 +629,7 @@ describe('lib', () => { expect(tsConfigAppJson2.include).toEqual([ '**/*.ts', '../../libs/my-dir/my-lib/src/index.ts', - '../../libs/my-dir/my-lib2/src/index.ts' + '../../libs/my-dir/my-lib2/src/index.ts', ]); const tree3 = await runSchematic( @@ -637,7 +641,7 @@ describe('lib', () => { framework: 'angular', lazy: true, parentModule: 'apps/myapp/src/app/app.module.ts', - simpleModuleName: true + simpleModuleName: true, }, tree2 ); @@ -650,21 +654,23 @@ describe('lib', () => { { path: 'my-dir-my-lib', loadChildren: () => - import('@proj/my-dir/my-lib').then(module => module.MyDirMyLibModule) + import('@proj/my-dir/my-lib').then( + (module) => module.MyDirMyLibModule + ), }`); expect(moduleContents3).toContain(` { path: 'my-dir-my-lib2', loadChildren: () => import('@proj/my-dir/my-lib2').then( - module => module.MyDirMyLib2Module - ) + (module) => module.MyDirMyLib2Module + ), }`); expect(moduleContents3).toContain(` { path: 'my-lib3', loadChildren: () => - import('@proj/my-dir/my-lib3').then(module => module.MyLib3Module) + import('@proj/my-dir/my-lib3').then((module) => module.MyLib3Module), }`); const tsConfigAppJson3 = JSON.parse( @@ -676,7 +682,7 @@ describe('lib', () => { '**/*.ts', '../../libs/my-dir/my-lib/src/index.ts', '../../libs/my-dir/my-lib2/src/index.ts', - '../../libs/my-dir/my-lib3/src/index.ts' + '../../libs/my-dir/my-lib3/src/index.ts', ]); }); @@ -709,7 +715,7 @@ describe('lib', () => { routing: true, lazy: true, framework: 'angular', - parentModule: 'apps/myapp/src/app/app.module.ts' + parentModule: 'apps/myapp/src/app/app.module.ts', }, appTree ); @@ -724,8 +730,8 @@ describe('lib', () => { { path: 'my-dir-my-lib', loadChildren: () => - import('@proj/my-dir/my-lib').then(module => module.MyDirMyLibModule) - } + import('@proj/my-dir/my-lib').then((module) => module.MyDirMyLibModule), + }, ];`); }); }); @@ -738,7 +744,7 @@ describe('lib', () => { name: 'myLib', directory: 'myDir', framework: 'angular', - routing: true + routing: true, }, appTree ); @@ -765,7 +771,7 @@ describe('lib', () => { directory: 'myDir', routing: true, framework: 'angular', - simpleModuleName: true + simpleModuleName: true, }, tree ); @@ -789,7 +795,7 @@ describe('lib', () => { directory: 'myDir', routing: true, framework: 'angular', - parentModule: 'apps/myapp/src/app/app.module.ts' + parentModule: 'apps/myapp/src/app/app.module.ts', }, appTree ); @@ -810,7 +816,7 @@ describe('lib', () => { directory: 'myDir', routing: true, framework: 'angular', - parentModule: 'apps/myapp/src/app/app.module.ts' + parentModule: 'apps/myapp/src/app/app.module.ts', }, tree ); @@ -835,7 +841,7 @@ describe('lib', () => { routing: true, framework: 'angular', parentModule: 'apps/myapp/src/app/app.module.ts', - simpleModuleName: true + simpleModuleName: true, }, tree2 ); @@ -884,7 +890,7 @@ describe('lib', () => { directory: 'myDir', routing: true, framework: 'angular', - parentModule: 'apps/myapp/src/app/app.module.ts' + parentModule: 'apps/myapp/src/app/app.module.ts', }, appTree ); @@ -913,8 +919,8 @@ describe('lib', () => { expect(workspaceJson.projects['my-lib'].schematics).toEqual({ '@nrwl/angular:component': { - style: 'scss' - } + style: 'scss', + }, }); }); }); @@ -939,7 +945,7 @@ describe('lib', () => { workspaceJson.projects['my-lib'].architect.lint.options.tsConfig ).toEqual([ 'libs/my-lib/tsconfig.lib.json', - 'libs/my-lib/tsconfig.spec.json' + 'libs/my-lib/tsconfig.spec.json', ]); expect( workspaceJson.projects['my-lib'].architect.lint.options.exclude diff --git a/packages/angular/src/schematics/library/library.ts b/packages/angular/src/schematics/library/library.ts index 1eb275cd0850f..c7618296069c5 100644 --- a/packages/angular/src/schematics/library/library.ts +++ b/packages/angular/src/schematics/library/library.ts @@ -12,7 +12,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { Schema } from './schema'; import * as path from 'path'; @@ -34,7 +34,7 @@ import { toClassName, toFileName, toPropertyName, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import { addUnitTestRunner } from '../init/init'; import { addImportToModule, addRoute } from '../../utils/ast-utils'; @@ -74,7 +74,7 @@ function addLazyLoadedRouterConfiguration(options: NormalizedSchema): Rule { RouterModule.forChild([ /* {path: '', pathMatch: 'full', component: InsertYourComponentHere} */ ]) ` - ) + ), ]); return host; }; @@ -107,7 +107,7 @@ function addRouterConfiguration(options: NormalizedSchema): Rule { moduleSourceFile, options.modulePath, `export const ${constName}: Route[] = [];` - ) + ), ]); return host; }; @@ -138,7 +138,7 @@ function addLoadChildren(options: NormalizedSchema): Rule { )}', loadChildren: () => import('@${npmScope}/${ options.projectDirectory }').then(module => module.${options.moduleName})}` - ) + ), ]); const tsConfig = findClosestTsConfigApp(host, options.parentModule); @@ -157,7 +157,7 @@ function addLoadChildren(options: NormalizedSchema): Rule { tsConfig, tsConfigAppFile, `\n , "${offset}${options.projectRoot}/src/index.ts"\n` - ) + ), ]); } else { // we should warn the user about not finding the config @@ -213,7 +213,7 @@ function addChildren(options: NormalizedSchema): Rule { options.parentModule, sourceFile, `{path: '${toFileName(options.fileName)}', children: ${constName}}` - ) + ), ]); return host; }; @@ -227,7 +227,7 @@ function updateNgPackage(options: NormalizedSchema): Rule { options.projectDirectory }`; return chain([ - updateJsonInTree(`${options.projectRoot}/ng-package.json`, json => { + updateJsonInTree(`${options.projectRoot}/ng-package.json`, (json) => { let $schema = json.$schema; if (json.$schema && json.$schema.indexOf('node_modules') >= 0) { $schema = `${offsetFromRoot( @@ -240,9 +240,9 @@ function updateNgPackage(options: NormalizedSchema): Rule { return { ...json, dest, - $schema + $schema, }; - }) + }), ]); } @@ -315,13 +315,13 @@ function updateProject(options: NormalizedSchema): Rule { apply(url('./files/lib'), [ template({ ...options, - offsetFromRoot: offsetFromRoot(options.projectRoot) + offsetFromRoot: offsetFromRoot(options.projectRoot), }), - move(options.projectRoot) + move(options.projectRoot), ]), MergeStrategy.Overwrite ), - updateJsonInTree(getWorkspacePath(host), json => { + updateJsonInTree(getWorkspacePath(host), (json) => { const project = json.projects[options.name]; const fixedProject = replaceAppNameWithPath( project, @@ -334,8 +334,8 @@ function updateProject(options: NormalizedSchema): Rule { fixedProject.schematics = { ...fixedProject.schematics, '@nrwl/angular:component': { - style: options.style - } + style: options.style, + }, }; } @@ -349,7 +349,7 @@ function updateProject(options: NormalizedSchema): Rule { delete fixedProject.architect.test; fixedProject.architect.lint.options.tsConfig = fixedProject.architect.lint.options.tsConfig.filter( - path => + (path) => path !== join(normalize(options.projectRoot), 'tsconfig.spec.json') ); fixedProject.architect.lint.options.exclude.push( @@ -359,7 +359,7 @@ function updateProject(options: NormalizedSchema): Rule { json.projects[options.name] = fixedProject; return json; }), - updateJsonInTree(`${options.projectRoot}/tsconfig.lib.json`, json => { + updateJsonInTree(`${options.projectRoot}/tsconfig.lib.json`, (json) => { if (options.unitTestRunner === 'jest') { json.exclude = ['src/test-setup.ts', '**/*.spec.ts']; } else if (options.unitTestRunner === 'none') { @@ -373,29 +373,29 @@ function updateProject(options: NormalizedSchema): Rule { extends: `./tsconfig.json`, compilerOptions: { ...json.compilerOptions, - outDir: `${offsetFromRoot(options.projectRoot)}dist/out-tsc` - } + outDir: `${offsetFromRoot(options.projectRoot)}dist/out-tsc`, + }, }; }), - updateJsonInTree(`${options.projectRoot}/tslint.json`, json => { + updateJsonInTree(`${options.projectRoot}/tslint.json`, (json) => { return { ...json, extends: `${offsetFromRoot(options.projectRoot)}tslint.json`, linterOptions: { - exclude: ['!**/*'] - } + exclude: ['!**/*'], + }, }; }), - updateJsonInTree(`/nx.json`, json => { + updateJsonInTree(`/nx.json`, (json) => { return { ...json, projects: { ...json.projects, - [options.name]: { tags: options.parsedTags } - } + [options.name]: { tags: options.parsedTags }, + }, }; }), - updateNgPackage(options) + updateNgPackage(options), ])(host, context); }; } @@ -404,21 +404,21 @@ function updateTsConfig(options: NormalizedSchema): Rule { return chain([ (host: Tree, context: SchematicContext) => { const nxJson = readJsonInTree(host, 'nx.json'); - return updateJsonInTree('tsconfig.json', json => { + return updateJsonInTree('tsconfig.json', (json) => { const c = json.compilerOptions; delete c.paths[options.name]; c.paths[`@${nxJson.npmScope}/${options.projectDirectory}`] = [ - `libs/${options.projectDirectory}/src/index.ts` + `libs/${options.projectDirectory}/src/index.ts`, ]; return json; })(host, context); - } + }, ]); } function updateLibPackageNpmScope(options: NormalizedSchema): Rule { return (host: Tree) => { - return updateJsonInTree(`${options.projectRoot}/package.json`, json => { + return updateJsonInTree(`${options.projectRoot}/package.json`, (json) => { json.name = `@${getNpmScope(host)}/${options.name}`; return json; }); @@ -436,11 +436,11 @@ function addModule(options: NormalizedSchema): Rule { options.routing && !options.lazy ? addRouterConfiguration(options) : noop(), options.routing && !options.lazy && options.parentModule ? addChildren(options) - : noop() + : noop(), ]); } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); if (!options.routing && options.lazy) { @@ -456,7 +456,7 @@ export default function(schema: Schema): Rule { style: options.style, entryFile: 'index', skipPackageJson: !options.publishable, - skipTsConfig: true + skipTsConfig: true, }), move(options.name, options.projectRoot), @@ -467,17 +467,17 @@ export default function(schema: Schema): Rule { project: options.name, setupFile: 'angular', supportTsx: false, - skipSerializers: false + skipSerializers: false, }) : noop(), options.unitTestRunner === 'karma' ? schematic('karma-project', { - project: options.name + project: options.name, }) : noop(), options.publishable ? updateLibPackageNpmScope(options) : noop(), addModule(options), - formatFiles(options) + formatFiles(options), ])(host, context); }; } @@ -494,7 +494,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { const moduleName = `${toClassName(fileName)}Module`; const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const modulePath = `${projectRoot}/src/lib/${fileName}.module.ts`; const defaultPrefix = getNpmScope(host); @@ -509,6 +509,6 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { projectDirectory, modulePath, parsedTags, - fileName + fileName, }; } diff --git a/packages/angular/src/schematics/move/lib/update-module-name.spec.ts b/packages/angular/src/schematics/move/lib/update-module-name.spec.ts index 1e9b6afb9f733..3d5ebfb42186c 100644 --- a/packages/angular/src/schematics/move/lib/update-module-name.spec.ts +++ b/packages/angular/src/schematics/move/lib/update-module-name.spec.ts @@ -9,7 +9,7 @@ describe('updateModuleName Rule', () => { let tree: UnitTestTree; const schema: Schema = { projectName: 'my-source', - destination: 'my-destination' + destination: 'my-destination', }; const modulePath = '/libs/my-destination/src/lib/my-destination.module.ts'; diff --git a/packages/angular/src/schematics/move/lib/update-module-name.ts b/packages/angular/src/schematics/move/lib/update-module-name.ts index 0aa4bf3e2010e..241ce481281cb 100644 --- a/packages/angular/src/schematics/move/lib/update-module-name.ts +++ b/packages/angular/src/schematics/move/lib/update-module-name.ts @@ -17,7 +17,7 @@ import { Schema } from '../schema'; export function updateModuleName(schema: Schema) { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const newProjectName = getNewProjectName(schema.destination); const project = workspace.projects.get(newProjectName); @@ -29,14 +29,14 @@ export function updateModuleName(schema: Schema) { const moduleName = { from: classify(schema.projectName), - to: classify(newProjectName) + to: classify(newProjectName), }; const findModuleName = new RegExp(`\\b${moduleName.from}`, 'g'); const moduleFile = { from: `${schema.projectName}.module`, - to: `${newProjectName}.module` + to: `${newProjectName}.module`, }; const replaceImport = new RegExp(moduleFile.from, 'g'); @@ -44,16 +44,16 @@ export function updateModuleName(schema: Schema) { const filesToChange = [ { from: `${project.sourceRoot}/lib/${moduleFile.from}.ts`, - to: `${project.sourceRoot}/lib/${moduleFile.to}.ts` + to: `${project.sourceRoot}/lib/${moduleFile.to}.ts`, }, { from: `${project.sourceRoot}/lib/${moduleFile.from}.spec.ts`, - to: `${project.sourceRoot}/lib/${moduleFile.to}.spec.ts` - } + to: `${project.sourceRoot}/lib/${moduleFile.to}.spec.ts`, + }, ]; // Update the module file and its spec file - filesToChange.forEach(file => { + filesToChange.forEach((file) => { if (tree.exists(file.from)) { let content = tree.read(file.from).toString('utf-8'); @@ -78,7 +78,7 @@ export function updateModuleName(schema: Schema) { } const projectDir = tree.getDir(definition.root); - projectDir.visit(file => { + projectDir.visit((file) => { const contents = tree.read(file).toString('utf-8'); if (!findModuleName.test(contents)) { return; diff --git a/packages/angular/src/schematics/move/move.ts b/packages/angular/src/schematics/move/move.ts index 2c64e54d50849..9592980c2f26a 100644 --- a/packages/angular/src/schematics/move/move.ts +++ b/packages/angular/src/schematics/move/move.ts @@ -9,9 +9,9 @@ import { Schema } from './schema'; * to the workspace, so it can't use the same tricks as the `@nrwl/workspace` rules * to get the before and after names and paths. */ -export default function(schema: Schema) { +export default function (schema: Schema) { return chain([ externalSchematic('@nrwl/workspace', 'move', schema), - updateModuleName(schema) + updateModuleName(schema), ]); } diff --git a/packages/angular/src/schematics/ngrx/ngrx.spec.ts b/packages/angular/src/schematics/ngrx/ngrx.spec.ts index 718ba2e93c4c9..2a28771ae6539 100644 --- a/packages/angular/src/schematics/ngrx/ngrx.spec.ts +++ b/packages/angular/src/schematics/ngrx/ngrx.spec.ts @@ -10,7 +10,7 @@ import { createLib, getAppConfig, getLibConfig, - runSchematic + runSchematic, } from '../../utils/testing'; import { createEmptyWorkspace } from '@nrwl/workspace/testing'; @@ -31,7 +31,7 @@ describe('ngrx', () => { module: 'apps/myapp/src/app/app.module.ts', onlyEmptyRoot: true, minimal: false, - root: true + root: true, }, appTree ); @@ -56,7 +56,7 @@ describe('ngrx', () => { module: 'apps/myapp/src/app/app.module.ts', root: true, onlyEmptyRoot: false, - minimal: true + minimal: true, }, appTree ); @@ -80,7 +80,7 @@ describe('ngrx', () => { name: 'app', module: 'apps/myapp/src/app/app.module.ts', root: true, - minimal: false + minimal: false, }, appTree ); @@ -92,8 +92,8 @@ describe('ngrx', () => { '/apps/myapp/src/app/+state/app.reducer.ts', '/apps/myapp/src/app/+state/app.reducer.spec.ts', '/apps/myapp/src/app/+state/app.selectors.ts', - '/apps/myapp/src/app/+state/app.selectors.spec.ts' - ].forEach(fileName => { + '/apps/myapp/src/app/+state/app.selectors.spec.ts', + ].forEach((fileName) => { expect(tree.exists(fileName)).toBeTruthy(); }); @@ -128,7 +128,7 @@ describe('ngrx', () => { module: 'apps/myapp/src/app/app.module.ts', root: true, facade: true, - minimal: false + minimal: false, }, appTree ); @@ -155,8 +155,8 @@ describe('ngrx', () => { '/apps/myapp/src/app/+state/app.facade.ts', '/apps/myapp/src/app/+state/app.facade.spec.ts', '/apps/myapp/src/app/+state/app.selectors.ts', - '/apps/myapp/src/app/+state/app.selectors.spec.ts' - ].forEach(fileName => { + '/apps/myapp/src/app/+state/app.selectors.spec.ts', + ].forEach((fileName) => { expect(tree.exists(fileName)).toBeTruthy(); }); }); @@ -168,7 +168,7 @@ describe('ngrx', () => { { name: 'app', module: 'apps/myapp-norouter/src/app/app.module.ts', - root: true + root: true, }, newTree ); @@ -185,7 +185,7 @@ describe('ngrx', () => { { name: 'state', module: 'apps/myapp/src/app/app.module.ts', - minimal: false + minimal: false, }, appTree ); @@ -207,7 +207,7 @@ describe('ngrx', () => { name: 'state', module: 'apps/myapp/src/app/app.module.ts', directory: 'myCustomState', - minimal: false + minimal: false, }, appTree ); @@ -230,7 +230,7 @@ describe('ngrx', () => { module: 'apps/myapp/src/app/app.module.ts', onlyAddFiles: true, facade: true, - minimal: false + minimal: false, }, appTree ); @@ -246,8 +246,8 @@ describe('ngrx', () => { '/apps/myapp/src/app/+state/state.selectors.ts', '/apps/myapp/src/app/+state/state.effects.spec.ts', '/apps/myapp/src/app/+state/state.facade.spec.ts', - '/apps/myapp/src/app/+state/state.selectors.spec.ts' - ].forEach(fileName => { + '/apps/myapp/src/app/+state/state.selectors.spec.ts', + ].forEach((fileName) => { expect(tree.exists(fileName)).toBeTruthy(); }); }); @@ -261,7 +261,7 @@ describe('ngrx', () => { onlyAddFiles: false, skipImport: true, facade: true, - minimal: false + minimal: false, }, appTree ); @@ -277,8 +277,8 @@ describe('ngrx', () => { '/apps/myapp/src/app/+state/state.selectors.ts', '/apps/myapp/src/app/+state/state.effects.spec.ts', '/apps/myapp/src/app/+state/state.facade.spec.ts', - '/apps/myapp/src/app/+state/state.selectors.spec.ts' - ].forEach(fileName => { + '/apps/myapp/src/app/+state/state.selectors.spec.ts', + ].forEach((fileName) => { expect(tree.exists(fileName)).toBeTruthy(); }); }); @@ -288,7 +288,7 @@ describe('ngrx', () => { 'ngrx', { name: 'state', - module: 'apps/myapp/src/app/app.module.ts' + module: 'apps/myapp/src/app/app.module.ts', }, appTree ); @@ -306,7 +306,7 @@ describe('ngrx', () => { 'ngrx', { name: 'state', - module: '' + module: '', }, appTree ); @@ -322,7 +322,7 @@ describe('ngrx', () => { 'ngrx', { name: 'state', - module: 'does-not-exist.ts' + module: 'does-not-exist.ts', }, appTree ); @@ -334,8 +334,8 @@ describe('ngrx', () => { describe('code generation', () => { it('should scaffold the ngrx "user" files without a facade', async () => { const appConfig = getAppConfig(); - const hasFile = file => expect(tree.exists(file)).toBeTruthy(); - const missingFile = file => expect(tree.exists(file)).not.toBeTruthy(); + const hasFile = (file) => expect(tree.exists(file)).toBeTruthy(); + const missingFile = (file) => expect(tree.exists(file)).not.toBeTruthy(); const statePath = `${findModuleParent(appConfig.appModule)}/+state`; const tree = await buildNgrxTree(appConfig); @@ -352,7 +352,7 @@ describe('ngrx', () => { it('should scaffold the ngrx "user" files WITH a facade', async () => { const appConfig = getAppConfig(); - const hasFile = file => expect(tree.exists(file)).toBeTruthy(); + const hasFile = (file) => expect(tree.exists(file)).toBeTruthy(); const tree = await buildNgrxTree(appConfig, 'user', true); const statePath = `${findModuleParent(appConfig.appModule)}/+state`; @@ -398,8 +398,8 @@ describe('ngrx', () => { [ `import { USERS_FEATURE_KEY, UsersState } from './users.reducer'`, - `export const usersQuery` - ].forEach(text => { + `export const usersQuery`, + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -415,8 +415,8 @@ describe('ngrx', () => { [ `import { UsersPartialState } from './users.reducer'`, `import { usersQuery } from './users.selectors'`, - `export class UsersFacade` - ].forEach(text => { + `export class UsersFacade`, + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -436,8 +436,8 @@ describe('ngrx', () => { 'state: UserState = initialState', 'action: UserAction', '): UserState', - 'case UserActionTypes.UserLoaded' - ].forEach(text => { + 'case UserActionTypes.UserLoaded', + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -455,15 +455,15 @@ import { LoadUsers, UsersLoaded, UsersLoadError, - UsersActionTypes + UsersActionTypes, } from './users.actions';`, `loadUsers$`, `run: (action: LoadUsers, state: UsersPartialState)`, `return new UsersLoaded([])`, `return new UsersLoadError(error)`, 'private actions$: Actions', - 'private dataPersistence: DataPersistence' - ].forEach(text => { + 'private dataPersistence: DataPersistence', + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -491,7 +491,7 @@ import { { name: 'super-users', module: libConfig.module, - facade: true + facade: true, }, appTree ); @@ -510,7 +510,7 @@ import { { name: 'super-users', module: libConfig.module, - facade: false + facade: false, }, appTree ); @@ -528,7 +528,7 @@ import { { name: 'super-users', module: appConfig.appModule, - minimal: false + minimal: false, }, appTree ); @@ -560,7 +560,7 @@ import { syntax: 'creators', minimal: false, facade: true, - useDataPersistance: false + useDataPersistance: false, }, appTree ); @@ -576,8 +576,8 @@ import { '[Users] Load Users Success', 'props<{ users: UsersEntity[] }>()', '[Users] Load Users Failure', - 'props<{ error: any }>()' - ].forEach(text => { + 'props<{ error: any }>()', + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -588,8 +588,8 @@ import { [ `export const USERS_FEATURE_KEY = 'users';`, `const usersReducer = createReducer`, - 'export function reducer(state: State | undefined, action: Action) {' - ].forEach(text => { + 'export function reducer(state: State | undefined, action: Action) {', + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -599,8 +599,8 @@ import { [ `import { createEffect, Actions, ofType } from '@ngrx/effects';`, - 'fetch({' - ].forEach(text => { + 'fetch({', + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -614,10 +614,10 @@ import { USERS_FEATURE_KEY, State, UsersPartialState, - usersAdapter + usersAdapter, } from './users.reducer';`, - `const { selectAll, selectEntities } = usersAdapter.getSelectors();` - ].forEach(text => { + `const { selectAll, selectEntities } = usersAdapter.getSelectors();`, + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -628,8 +628,8 @@ import { [ `loaded$ = this.store.pipe(select(UsersSelectors.getUsersLoaded));`, `allUsers$ = this.store.pipe(select(UsersSelectors.getAllUsers));`, - `selectedUsers$ = this.store.pipe(select(UsersSelectors.getSelected));` - ].forEach(text => { + `selectedUsers$ = this.store.pipe(select(UsersSelectors.getSelected));`, + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -639,8 +639,8 @@ import { [ 'export interface UsersEntity', - 'id: string | number; // Primary ID' - ].forEach(text => { + 'id: string | number; // Primary ID', + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -656,14 +656,14 @@ import { module: appConfig.appModule, syntax: 'creators', facade: true, - minimal: false + minimal: false, }, appTree ); const content = tree.readContent(`${statePath}/users.effects.ts`); [`{ fetch }`, `, ofType`, `ofType(UsersActions.loadUsers),`].forEach( - text => { + (text) => { expect(content).toContain(text); } ); @@ -683,7 +683,7 @@ import { name: 'users', module: appConfig.appModule, syntax: 'creators', - barrels: true + barrels: true, }, appTree ); @@ -695,8 +695,8 @@ import { `import * as UsersFeature from './lib/+state/users.reducer';`, `import * as UsersSelectors from './lib/+state/users.selectors';`, `export { UsersActions, UsersFeature, UsersSelectors };`, - `export * from './lib/+state/users.models';` - ].forEach(text => { + `export * from './lib/+state/users.models';`, + ].forEach((text) => { expect(content).toContain(text); }); }); @@ -715,7 +715,7 @@ import { facade: withFacade, syntax: 'classes', minimal: false, - useDataPersistance: true + useDataPersistance: true, }, appTree ); diff --git a/packages/angular/src/schematics/ngrx/ngrx.ts b/packages/angular/src/schematics/ngrx/ngrx.ts index 5144aabaded98..9a96741e42c47 100644 --- a/packages/angular/src/schematics/ngrx/ngrx.ts +++ b/packages/angular/src/schematics/ngrx/ngrx.ts @@ -9,7 +9,7 @@ import { filter, Rule, Tree, - SchematicContext + SchematicContext, } from '@angular-devkit/schematics'; import { Schema } from './schema'; @@ -21,7 +21,7 @@ import { addImportsToModule, addNgRxToPackageJson, addExportsToBarrel, - RequestContext + RequestContext, } from './rules'; import { formatFiles } from '@nrwl/workspace'; @@ -43,7 +43,7 @@ export default function generateNgrxCollection(_options: Schema): Rule { featureName: options.name, moduleDir: path.dirname(options.module), options, - host + host, }; if (options.minimal) { @@ -62,7 +62,7 @@ export default function generateNgrxCollection(_options: Schema): Rule { const moduleModification = !options.onlyAddFiles ? [ addImportsToModule(requestContext), - addExportsToBarrel(requestContext.options) + addExportsToBarrel(requestContext.options), ] : []; @@ -74,7 +74,7 @@ export default function generateNgrxCollection(_options: Schema): Rule { ...fileGeneration, ...moduleModification, ...packageJsonModification, - formatFiles(options) + formatFiles(options), ])(host, context); }; } @@ -89,14 +89,14 @@ export default function generateNgrxCollection(_options: Schema): Rule { function generateNgrxFilesFromTemplates(options: Schema) { const name = options.name; const moduleDir = path.dirname(options.module); - const excludeFacade = path => path.match(/^((?!facade).)*$/); + const excludeFacade = (path) => path.match(/^((?!facade).)*$/); const templateSource = apply( url(options.syntax === 'creators' ? './creator-files' : './files'), [ !options.facade ? filter(excludeFacade) : noop(), template({ ...options, tmpl: '', ...names(name) }), - move(moduleDir) + move(moduleDir), ] ); @@ -109,6 +109,6 @@ function generateNgrxFilesFromTemplates(options: Schema) { function normalizeOptions(options: Schema): Schema { return { ...options, - directory: toFileName(options.directory) + directory: toFileName(options.directory), }; } diff --git a/packages/angular/src/schematics/ngrx/rules/add-exports-barrel.ts b/packages/angular/src/schematics/ngrx/rules/add-exports-barrel.ts index b22e226c55357..9deddcacba1e8 100644 --- a/packages/angular/src/schematics/ngrx/rules/add-exports-barrel.ts +++ b/packages/angular/src/schematics/ngrx/rules/add-exports-barrel.ts @@ -83,7 +83,7 @@ export function addExportsToBarrel(options: Schema): Rule { indexFilePath, `export * from '${statePath}.facade';` ) - : []) + : []), ]); } } diff --git a/packages/angular/src/schematics/ngrx/rules/add-imports-to-module.ts b/packages/angular/src/schematics/ngrx/rules/add-imports-to-module.ts index dbea16b994e7e..48d60547d4064 100644 --- a/packages/angular/src/schematics/ngrx/rules/add-imports-to-module.ts +++ b/packages/angular/src/schematics/ngrx/rules/add-imports-to-module.ts @@ -5,7 +5,7 @@ import { insert } from '@nrwl/workspace'; import { RequestContext } from './request-context'; import { addImportToModule, - addProviderToModule + addProviderToModule, } from '../../../utils/ast-utils'; import { Change, insertImport } from '@nrwl/workspace/src/utils/ast-utils'; @@ -85,20 +85,20 @@ export function addImportsToModule(context: RequestContext): Rule { ...addImportToModule(source, modulePath, devTools), ...(hasRouter ? addImportToModule(source, modulePath, storeRouterModule) - : []) + : []), ]); } else { let common = [ addImport.apply(this, storeModule), addImport.apply(this, effectsModule), addImport(reducerImports, reducerPath, true), - addImport(effectsName, effectsPath) + addImport(effectsName, effectsPath), ]; if (context.options.facade) { common = [ ...common, addImport(facadeName, facadePath), - ...addProviderToModule(source, modulePath, `${facadeName}`) + ...addProviderToModule(source, modulePath, `${facadeName}`), ]; } @@ -118,13 +118,13 @@ export function addImportsToModule(context: RequestContext): Rule { ...(hasRouter ? addImportToModule(source, modulePath, storeRouterModule) : []), - ...addImportToModule(source, modulePath, storeForFeature) + ...addImportToModule(source, modulePath, storeForFeature), ]); } else { insert(host, modulePath, [ ...common, ...addImportToModule(source, modulePath, storeForFeature), - ...addImportToModule(source, modulePath, effectsForFeature) + ...addImportToModule(source, modulePath, effectsForFeature), ]); } } diff --git a/packages/angular/src/schematics/ngrx/rules/add-ngrx-to-package-json.ts b/packages/angular/src/schematics/ngrx/rules/add-ngrx-to-package-json.ts index e88abf3608f7c..50d4bae30317e 100644 --- a/packages/angular/src/schematics/ngrx/rules/add-ngrx-to-package-json.ts +++ b/packages/angular/src/schematics/ngrx/rules/add-ngrx-to-package-json.ts @@ -8,11 +8,11 @@ export function addNgRxToPackageJson(): Rule { '@ngrx/store': ngrxVersion, '@ngrx/effects': ngrxVersion, '@ngrx/entity': ngrxVersion, - '@ngrx/router-store': ngrxVersion + '@ngrx/router-store': ngrxVersion, }, { '@ngrx/schematics': ngrxVersion, - '@ngrx/store-devtools': ngrxVersion + '@ngrx/store-devtools': ngrxVersion, } ); } diff --git a/packages/angular/src/schematics/stories/stories.spec.ts b/packages/angular/src/schematics/stories/stories.spec.ts index b0629a1c9ce30..461103f88c5f5 100644 --- a/packages/angular/src/schematics/stories/stories.spec.ts +++ b/packages/angular/src/schematics/stories/stories.spec.ts @@ -3,7 +3,7 @@ import { StorybookStoriesSchema } from './stories'; import { runSchematic, runExternalSchematic, - callRule + callRule, } from '../../utils/testing'; import { createEmptyWorkspace } from '@nrwl/workspace/testing'; @@ -41,12 +41,12 @@ describe('schematic:stories', () => { `buttonType: text('buttonType', 'button'),`, `style: text('style', 'default'),`, `age: number('age', ''),`, - `isOn: boolean('isOn', false), ` + `isOn: boolean('isOn', false), `, ]; const storyContent = tree.readContent( 'libs/test-ui-lib/src/lib/test-button/test-button.component.stories.ts' ); - propLines.forEach(propLine => { + propLines.forEach((propLine) => { storyContent.includes(propLine); }); }); @@ -78,12 +78,12 @@ describe('schematic:stories', () => { `buttonType: text('buttonType', 'button'),`, `style: text('style', 'default'),`, `age: number('age', ''),`, - `isOn: boolean('isOn', false), ` + `isOn: boolean('isOn', false), `, ]; const storyContent = tree.readContent( 'libs/test-ui-lib/src/lib/test-button/test-button.component.stories.ts' ); - propLines.forEach(propLine => { + propLines.forEach((propLine) => { storyContent.includes(propLine); }); @@ -125,14 +125,14 @@ export async function createTestUILib(libName: string): Promise { appTree = createEmptyWorkspace(appTree); appTree = await callRule( externalSchematic('@nrwl/angular', 'library', { - name: libName + name: libName, }), appTree ); appTree = await callRule( externalSchematic('@schematics/angular', 'component', { name: 'test-button', - project: libName + project: libName, }), appTree ); @@ -146,7 +146,7 @@ export async function createTestUILib(libName: string): Promise { externalSchematic('@schematics/angular', 'module', { name: 'nested', project: libName, - path: `libs/${libName}/src/lib` + path: `libs/${libName}/src/lib`, }), appTree ); @@ -155,7 +155,7 @@ export async function createTestUILib(libName: string): Promise { name: 'nested-button', project: libName, module: 'nested', - path: `libs/${libName}/src/lib/nested` + path: `libs/${libName}/src/lib/nested`, }), appTree ); @@ -192,7 +192,7 @@ export class TestButtonComponent implements OnInit { appTree = await callRule( externalSchematic('@schematics/angular', 'component', { name: 'test-other', - project: libName + project: libName, }), appTree ); diff --git a/packages/angular/src/schematics/stories/stories.ts b/packages/angular/src/schematics/stories/stories.ts index ac9d2132cfff8..d0c154be8b5d6 100644 --- a/packages/angular/src/schematics/stories/stories.ts +++ b/packages/angular/src/schematics/stories/stories.ts @@ -4,7 +4,7 @@ import { schematic, SchematicContext, SchematicsException, - Tree + Tree, } from '@angular-devkit/schematics'; import { getProjectConfig } from '@nrwl/workspace'; import { SyntaxKind } from 'typescript'; @@ -17,7 +17,7 @@ export interface StorybookStoriesSchema { generateCypressSpecs: boolean; } -export default function(schema: StorybookStoriesSchema): Rule { +export default function (schema: StorybookStoriesSchema): Rule { return chain([createAllStories(schema.name, schema.generateCypressSpecs)]); } @@ -30,14 +30,14 @@ export function createAllStories( const libPath = getProjectConfig(tree, projectName).sourceRoot + '/lib'; let moduleFilePaths = [] as string[]; - tree.getDir(libPath).visit(filePath => { + tree.getDir(libPath).visit((filePath) => { if (!filePath.endsWith('.module.ts')) { return; } moduleFilePaths.push(filePath); }); return chain( - moduleFilePaths.map(filePath => { + moduleFilePaths.map((filePath) => { const file = getTsSourceFile(tree, filePath); const ngModuleDecorators = getDecoratorMetadata( @@ -51,12 +51,12 @@ export function createAllStories( ); } const ngModuleDecorator = ngModuleDecorators[0]; - const syntaxList = ngModuleDecorator.getChildren().find(node => { + const syntaxList = ngModuleDecorator.getChildren().find((node) => { return node.kind === SyntaxKind.SyntaxList; }); const declarationsPropertyAssignment = syntaxList .getChildren() - .find(node => { + .find((node) => { return ( node.kind === SyntaxKind.PropertyAssignment && node.getChildren()[0].getText() === 'declarations' @@ -69,38 +69,38 @@ export function createAllStories( } const declaredComponents = declarationsPropertyAssignment .getChildren() - .find(node => node.kind === SyntaxKind.ArrayLiteralExpression) + .find((node) => node.kind === SyntaxKind.ArrayLiteralExpression) .getChildren() - .find(node => node.kind === SyntaxKind.SyntaxList) + .find((node) => node.kind === SyntaxKind.SyntaxList) .getChildren() - .filter(node => node.kind === SyntaxKind.Identifier) - .map(node => node.getText()) - .filter(name => name.endsWith('Component')); + .filter((node) => node.kind === SyntaxKind.Identifier) + .map((node) => node.getText()) + .filter((name) => name.endsWith('Component')); const imports = file.statements.filter( - statement => statement.kind === SyntaxKind.ImportDeclaration + (statement) => statement.kind === SyntaxKind.ImportDeclaration ); - const componentInfo = declaredComponents.map(componentName => { + const componentInfo = declaredComponents.map((componentName) => { try { - const importStatement = imports.find(statement => { + const importStatement = imports.find((statement) => { const namedImports = statement .getChildren() - .find(node => node.kind === SyntaxKind.ImportClause) + .find((node) => node.kind === SyntaxKind.ImportClause) .getChildren() - .find(node => node.kind === SyntaxKind.NamedImports); + .find((node) => node.kind === SyntaxKind.NamedImports); if (namedImports === undefined) return false; const importedIdentifiers = namedImports .getChildren() - .find(node => node.kind === SyntaxKind.SyntaxList) + .find((node) => node.kind === SyntaxKind.SyntaxList) .getChildren() - .filter(node => node.kind === SyntaxKind.ImportSpecifier) - .map(node => node.getText()); + .filter((node) => node.kind === SyntaxKind.ImportSpecifier) + .map((node) => node.getText()); return importedIdentifiers.includes(componentName); }); const fullPath = importStatement .getChildren() - .find(node => node.kind === SyntaxKind.StringLiteral) + .find((node) => node.kind === SyntaxKind.StringLiteral) .getText() .slice(1, -1); const path = fullPath.slice(0, fullPath.lastIndexOf('/')); @@ -119,14 +119,14 @@ export function createAllStories( const modulePath = filePath.substr(0, filePath.lastIndexOf('/')); return chain( componentInfo - .filter(info => info !== undefined) - .map(info => + .filter((info) => info !== undefined) + .map((info) => chain([ schematic('component-story', { libPath: modulePath, componentName: info.name, componentPath: info.path, - componentFileName: info.componentFileName + componentFileName: info.componentFileName, }), generateCypressSpecs ? schematic( @@ -136,10 +136,10 @@ export function createAllStories( libPath: modulePath, componentName: info.name, componentPath: info.path, - componentFileName: info.componentFileName + componentFileName: info.componentFileName, } ) - : () => {} + : () => {}, ]) ) ); diff --git a/packages/angular/src/schematics/storybook-configuration/configuration.spec.ts b/packages/angular/src/schematics/storybook-configuration/configuration.spec.ts index 6ea6c8cab0e69..9422e20be23b3 100644 --- a/packages/angular/src/schematics/storybook-configuration/configuration.spec.ts +++ b/packages/angular/src/schematics/storybook-configuration/configuration.spec.ts @@ -17,7 +17,7 @@ describe('schematic:configuration', () => { name: 'test-ui-lib', configureCypress: false, generateCypressSpecs: false, - generateStories: false + generateStories: false, }, appTree ); @@ -56,7 +56,7 @@ describe('schematic:configuration', () => { name: 'test-ui-lib', configureCypress: true, generateCypressSpecs: true, - generateStories: true + generateStories: true, }, appTree ); diff --git a/packages/angular/src/schematics/storybook-configuration/configuration.ts b/packages/angular/src/schematics/storybook-configuration/configuration.ts index 1f5b82380cafe..e34c90da96d26 100644 --- a/packages/angular/src/schematics/storybook-configuration/configuration.ts +++ b/packages/angular/src/schematics/storybook-configuration/configuration.ts @@ -3,12 +3,12 @@ import { externalSchematic, Rule, schematic, - noop + noop, } from '@angular-devkit/schematics'; import { StorybookStoriesSchema } from '../stories/stories'; import { StorybookConfigureSchema } from './schema'; -export default function(schema: StorybookConfigureSchema): Rule { +export default function (schema: StorybookConfigureSchema): Rule { if (schema.generateCypressSpecs && !schema.generateStories) { throw new Error( 'Cannot set generateCypressSpecs to true when generateStories is set to false.' @@ -19,9 +19,9 @@ export default function(schema: StorybookConfigureSchema): Rule { externalSchematic('@nrwl/storybook', 'configuration', { name: schema.name, uiFramework: '@storybook/angular', - configureCypress: schema.configureCypress + configureCypress: schema.configureCypress, }), - schema.generateStories ? generateStories(schema) : noop() + schema.generateStories ? generateStories(schema) : noop(), ]); } @@ -30,7 +30,7 @@ function generateStories(schema: StorybookConfigureSchema): Rule { return schematic('stories', { name: schema.name, generateCypressSpecs: - schema.configureCypress && schema.generateCypressSpecs + schema.configureCypress && schema.generateCypressSpecs, }); }; } diff --git a/packages/angular/src/schematics/upgrade-module/upgrade-module.spec.ts b/packages/angular/src/schematics/upgrade-module/upgrade-module.spec.ts index f31845d5e2de6..c92751913cbd9 100644 --- a/packages/angular/src/schematics/upgrade-module/upgrade-module.spec.ts +++ b/packages/angular/src/schematics/upgrade-module/upgrade-module.spec.ts @@ -17,7 +17,7 @@ describe('upgrade-module', () => { 'upgrade-module', { name: 'legacy', - project: 'myapp' + project: 'myapp', }, appTree ); @@ -39,8 +39,8 @@ describe('upgrade-module', () => { `/package.json`, JSON.stringify({ dependencies: { - '@angular/core': '4.4.4' - } + '@angular/core': '4.4.4', + }, }) ); @@ -48,7 +48,7 @@ describe('upgrade-module', () => { 'upgrade-module', { name: 'legacy', - project: 'myapp' + project: 'myapp', }, appTree ); @@ -63,8 +63,8 @@ describe('upgrade-module', () => { `/package.json`, JSON.stringify({ dependencies: { - '@angular/core': '4.4.4' - } + '@angular/core': '4.4.4', + }, }) ); @@ -73,7 +73,7 @@ describe('upgrade-module', () => { { name: 'legacy', skipPackageJson: true, - project: 'myapp' + project: 'myapp', }, appTree ); @@ -88,7 +88,7 @@ describe('upgrade-module', () => { { name: 'legacy', router: true, - project: 'myapp' + project: 'myapp', }, appTree ); @@ -103,7 +103,7 @@ describe('upgrade-module', () => { { name: 'legacy', angularJsImport: 'legacy-app', - project: 'myapp' + project: 'myapp', }, appTree ); diff --git a/packages/angular/src/schematics/upgrade-module/upgrade-module.ts b/packages/angular/src/schematics/upgrade-module/upgrade-module.ts index ea76a9b8ac024..f738e8551fbb9 100644 --- a/packages/angular/src/schematics/upgrade-module/upgrade-module.ts +++ b/packages/angular/src/schematics/upgrade-module/upgrade-module.ts @@ -9,7 +9,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { names, toClassName, toFileName } from '@nrwl/workspace'; @@ -24,7 +24,7 @@ import { addImportToModule, getBootstrapComponent, readBootstrapInfo, - removeFromNgModule + removeFromNgModule, } from '../../utils/ast-utils'; import { insertImport } from '@nrwl/workspace/src/utils/ast-utils'; @@ -58,7 +58,7 @@ function addImportsToModule(options: Schema): Rule { moduleSource, modulePath, getBootstrapComponent(moduleSource, moduleClassName) - ) + ), ]); return host; @@ -75,7 +75,7 @@ function addNgDoBootstrapToModule(options: Schema): Rule { insert(host, modulePath, [ ...addParameterToConstructor(moduleSource, modulePath, { className: moduleClassName, - param: 'private upgrade: UpgradeModule' + param: 'private upgrade: UpgradeModule', }), ...addMethod(moduleSource, modulePath, { className: moduleClassName, @@ -83,9 +83,9 @@ function addNgDoBootstrapToModule(options: Schema): Rule { body: ` configure${toClassName(options.name)}(this.upgrade.injector); this.upgrade.bootstrap(document.body, ['downgraded', '${options.name}']); - ` + `, }), - ...removeFromNgModule(moduleSource, modulePath, 'bootstrap') + ...removeFromNgModule(moduleSource, modulePath, 'bootstrap'), ]); return host; @@ -99,7 +99,7 @@ function createFiles(angularJsImport: string, options: Schema): Rule { mainPath, moduleSpec, bootstrapComponentClassName, - bootstrapComponentFileName + bootstrapComponentFileName, } = readBootstrapInfo(host, options.project); const dir = path.dirname(mainPath); @@ -113,16 +113,16 @@ function createFiles(angularJsImport: string, options: Schema): Rule { angularJsModule: options.name, bootstrapComponentClassName, bootstrapComponentFileName, - ...names(options.name) + ...names(options.name), }), - move(dir) + move(dir), ]); const r = branchAndMerge(chain([mergeWith(templateSource)])); return r(host, context); }; } -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { const angularJsImport = options.angularJsImport ? options.angularJsImport : options.name; @@ -132,6 +132,6 @@ export default function(options: Schema): Rule { addImportsToModule(options), addNgDoBootstrapToModule(options), options.skipPackageJson ? noop() : addUpgradeToPackageJson(), - formatFiles(options) + formatFiles(options), ]); } diff --git a/packages/angular/src/utils/ast-utils.spec.ts b/packages/angular/src/utils/ast-utils.spec.ts index 1ba479a187174..6b7e3746dad08 100644 --- a/packages/angular/src/utils/ast-utils.spec.ts +++ b/packages/angular/src/utils/ast-utils.spec.ts @@ -8,7 +8,7 @@ describe('ast-utils', () => { const fileName = 'app.module.ts'; const createTemplate = (content: string, close: string) => ({ start: content.length, - text: content + close + text: content + close, }); const createStockModule = (content: string) => createSourceFile(fileName, content, ScriptTarget.Latest, true); @@ -23,7 +23,7 @@ describe('ast-utils', () => { const source = createStockModule(text); const change = addProviderToModule(source, fileName, toAdd); const expectedChange = [ - new InsertChange(fileName, start, ` providers: [${toAdd}]\n`) + new InsertChange(fileName, start, ` providers: [${toAdd}]\n`), ]; expect(change).toEqual(expectedChange); @@ -53,7 +53,7 @@ describe('ast-utils', () => { let source = createStockModule(template.text); let change = addProviderToModule(source, fileName, toAdd); let expectedChange = [ - new InsertChange(fileName, template.start, `, ${toAdd}`) + new InsertChange(fileName, template.start, `, ${toAdd}`), ]; expect(change).toEqual(expectedChange); @@ -66,7 +66,7 @@ describe('ast-utils', () => { source = createStockModule(template.text); change = addProviderToModule(source, fileName, toAdd); expectedChange = [ - new InsertChange(fileName, template.start, `, ${toAdd}`) + new InsertChange(fileName, template.start, `, ${toAdd}`), ]; expect(change).toEqual(expectedChange); @@ -78,7 +78,7 @@ describe('ast-utils', () => { source = createStockModule(template.text); change = addProviderToModule(source, fileName, toAdd); expectedChange = [ - new InsertChange(fileName, template.start, `, ${toAdd}`) + new InsertChange(fileName, template.start, `, ${toAdd}`), ]; expect(change).toEqual(expectedChange); @@ -91,7 +91,7 @@ describe('ast-utils', () => { source = createStockModule(template.text); change = addProviderToModule(source, fileName, toAdd); expectedChange = [ - new InsertChange(fileName, template.start, `, ${toAdd}`) + new InsertChange(fileName, template.start, `, ${toAdd}`), ]; expect(change).toEqual(expectedChange); @@ -103,7 +103,7 @@ describe('ast-utils', () => { source = createStockModule(template.text); change = addProviderToModule(source, fileName, toAdd); expectedChange = [ - new InsertChange(fileName, template.start, `, ${toAdd}`) + new InsertChange(fileName, template.start, `, ${toAdd}`), ]; expect(change).toEqual(expectedChange); diff --git a/packages/angular/src/utils/ast-utils.ts b/packages/angular/src/utils/ast-utils.ts index 06415eb4d4380..df2b34c59ae8f 100644 --- a/packages/angular/src/utils/ast-utils.ts +++ b/packages/angular/src/utils/ast-utils.ts @@ -6,7 +6,7 @@ import { getProjectConfig, getSourceNodes, InsertChange, - RemoveChange + RemoveChange, } from '@nrwl/workspace/src/utils/ast-utils'; import { Tree, @@ -16,7 +16,7 @@ import { SchematicContext, mergeWith, apply, - forEach + forEach, } from '@angular-devkit/schematics'; import * as path from 'path'; import { toFileName } from '@nrwl/workspace/src/utils/name-utils'; @@ -48,7 +48,7 @@ function _angularImportsFromNode( if (nb.kind == ts.SyntaxKind.NamespaceImport) { // This is of the form `import * as name from 'path'`. Return `name.`. return { - [(nb as ts.NamespaceImport).name.text + '.']: modulePath + [(nb as ts.NamespaceImport).name.text + '.']: modulePath, }; } else { // This is of the form `import {a,b,c} from 'path'` @@ -98,14 +98,14 @@ export function getDecoratorMetadata( ); return getSourceNodes(source) - .filter(node => { + .filter((node) => { return ( node.kind == ts.SyntaxKind.Decorator && (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression ); }) - .map(node => (node as ts.Decorator).expression as ts.CallExpression) - .filter(expr => { + .map((node) => (node as ts.Decorator).expression as ts.CallExpression) + .filter((expr) => { if (expr.expression.kind == ts.SyntaxKind.Identifier) { const id = expr.expression as ts.Identifier; @@ -132,11 +132,11 @@ export function getDecoratorMetadata( return false; }) .filter( - expr => + (expr) => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression ) - .map(expr => expr.arguments[0] as ts.ObjectLiteralExpression); + .map((expr) => expr.arguments[0] as ts.ObjectLiteralExpression); } function _addSymbolToNgModuleMetadata( @@ -154,7 +154,7 @@ function _addSymbolToNgModuleMetadata( } // Get all the children property assignment of object literals. const matchingProperties: ts.ObjectLiteralElement[] = (node as ts.ObjectLiteralExpression).properties - .filter(prop => prop.kind == ts.SyntaxKind.PropertyAssignment) + .filter((prop) => prop.kind == ts.SyntaxKind.PropertyAssignment) // Filter out every fields that's not "metadataField". Also handles string literals // (but not expressions). .filter((prop: ts.PropertyAssignment) => { @@ -228,7 +228,7 @@ function _addSymbolToNgModuleMetadata( const isArray = Array.isArray(node); if (isArray) { const nodeArray = (node as {}) as Array; - const symbolsArray = nodeArray.map(node => node.getText()); + const symbolsArray = nodeArray.map((node) => node.getText()); if (symbolsArray.includes(expression)) { return []; } @@ -301,7 +301,7 @@ export function removeFromNgModule( modulePath, matchingProperty.getStart(source), matchingProperty.getFullText(source) - ) + ), ]; } else { return []; @@ -331,11 +331,11 @@ export function addImportToTestBed( ); const configureTestingModuleObjectLiterals = allCalls - .filter(c => c.expression.kind === ts.SyntaxKind.PropertyAccessExpression) + .filter((c) => c.expression.kind === ts.SyntaxKind.PropertyAccessExpression) .filter( (c: any) => c.expression.name.getText(source) === 'configureTestingModule' ) - .map(c => + .map((c) => c.arguments[0].kind === ts.SyntaxKind.ObjectLiteralExpression ? c.arguments[0] : null @@ -346,7 +346,7 @@ export function addImportToTestBed( .getFirstToken(source) .getEnd(); return [ - new InsertChange(specPath, startPosition, `imports: [${symbolName}], `) + new InsertChange(specPath, startPosition, `imports: [${symbolName}], `), ]; } else { return []; @@ -439,7 +439,7 @@ function getListOfRoutes( ts.SyntaxKind.VariableDeclaration ) as ts.VariableDeclaration[]; - const routesDeclaration = variableDeclarations.find(x => { + const routesDeclaration = variableDeclarations.find((x) => { return x.name.getText() === routes.getText(); }); @@ -534,7 +534,7 @@ export function readBootstrapInfo( throw new Error(`main.ts can only import a single module`); } const moduleImport = moduleImports[0]; - const moduleClassName = moduleImport.bindings.filter(b => + const moduleClassName = moduleImport.bindings.filter((b) => b.endsWith('Module') )[0]; @@ -575,7 +575,7 @@ export function readBootstrapInfo( moduleSource, moduleClassName, bootstrapComponentClassName, - bootstrapComponentFileName + bootstrapComponentFileName, }; } @@ -610,7 +610,7 @@ function getMatchingObjectLiteralElement( ) { return ( (node as ts.ObjectLiteralExpression).properties - .filter(prop => prop.kind == ts.SyntaxKind.PropertyAssignment) + .filter((prop) => prop.kind == ts.SyntaxKind.PropertyAssignment) // Filter out every fields that's not "metadataField". Also handles string literals // (but not expressions). .filter((prop: ts.PropertyAssignment) => { diff --git a/packages/angular/src/utils/test-runners.ts b/packages/angular/src/utils/test-runners.ts index e3ecaaa4f25b5..2304ac0a4f705 100644 --- a/packages/angular/src/utils/test-runners.ts +++ b/packages/angular/src/utils/test-runners.ts @@ -1,10 +1,10 @@ export const enum UnitTestRunner { Karma = 'karma', Jest = 'jest', - None = 'none' + None = 'none', } export const enum E2eTestRunner { Protractor = 'protractor', Cypress = 'cypress', - None = 'none' + None = 'none', } diff --git a/packages/angular/src/utils/testing.ts b/packages/angular/src/utils/testing.ts index 61de9e007a9bb..52a80408f3f38 100644 --- a/packages/angular/src/utils/testing.ts +++ b/packages/angular/src/utils/testing.ts @@ -4,7 +4,7 @@ import { Tree, Rule, externalSchematic } from '@angular-devkit/schematics'; import { names, toFileName } from '@nrwl/workspace/src/utils/name-utils'; import { createEmptyWorkspace, - MockBuilderContext + MockBuilderContext, } from '@nrwl/workspace/testing'; import { TestingArchitectHost } from '@angular-devkit/architect/testing'; import { schema } from '@angular-devkit/core'; @@ -82,7 +82,7 @@ export function createApp( // save for getAppDir() lookup by external *.spec.ts tests appConfig = { appName, - appModule: `/apps/${appName}/src/app/app.module.ts` + appModule: `/apps/${appName}/src/app/app.module.ts`, }; tree.create( @@ -121,13 +121,13 @@ export function createApp( tree.create( `/apps/${appName}/tsconfig.app.json`, JSON.stringify({ - include: ['**/*.ts'] + include: ['**/*.ts'], }) ); tree.create( `/apps/${appName}-e2e/tsconfig.e2e.json`, JSON.stringify({ - include: ['../**/*.ts'] + include: ['../**/*.ts'], }) ); tree.overwrite( @@ -142,15 +142,15 @@ export function createApp( architect: { build: { options: { - main: `apps/${appName}/src/main.ts` - } + main: `apps/${appName}/src/main.ts`, + }, }, serve: { - options: {} - } - } - } - } + options: {}, + }, + }, + }, + }, }) ); return tree; @@ -162,7 +162,7 @@ export function createLib(tree: Tree, libName: string): Tree { libConfig = { name, module: `/libs/${propertyName}/src/lib/${fileName}.module.ts`, - barrel: `/libs/${propertyName}/src/index.ts` + barrel: `/libs/${propertyName}/src/index.ts`, }; tree.create( diff --git a/packages/angular/src/utils/upgrade.ts b/packages/angular/src/utils/upgrade.ts index f66bebe24de8f..ac70cb80dac3c 100644 --- a/packages/angular/src/utils/upgrade.ts +++ b/packages/angular/src/utils/upgrade.ts @@ -3,7 +3,7 @@ import { angularJsVersion } from './versions'; import { updateJsonInTree } from '@nrwl/workspace'; export function addUpgradeToPackageJson(): Rule { - return updateJsonInTree('package.json', packageJson => { + return updateJsonInTree('package.json', (packageJson) => { if (!packageJson['dependencies']) { packageJson['dependencies'] = {}; } diff --git a/packages/bazel/src/schematics/init/init.ts b/packages/bazel/src/schematics/init/init.ts index f5ba076e858d9..ef909117d4ccd 100644 --- a/packages/bazel/src/schematics/init/init.ts +++ b/packages/bazel/src/schematics/init/init.ts @@ -4,7 +4,7 @@ import { mergeWith, Rule, template, - url + url, } from '@angular-devkit/schematics'; import { addDepsToPackageJson, readJsonInTree } from '@nrwl/workspace'; import ignore from 'ignore'; @@ -12,7 +12,7 @@ import { bazelVersion, iBazelVersion } from '../utils/versions'; import { noop } from 'rxjs'; function updateGitIgnore(): Rule { - return host => { + return (host) => { if (!host.exists('.gitignore')) { return; } @@ -34,33 +34,33 @@ const updateDependencies = addDepsToPackageJson( {}, { '@bazel/bazel': bazelVersion, - '@bazel/ibazel': iBazelVersion + '@bazel/ibazel': iBazelVersion, }, true ); function addFiles() { - return host => { + return (host) => { if (host.exists('/.bazelrc')) { return noop; } return mergeWith( apply(url('./files/root'), [ template({ - tmpl: '' - }) + tmpl: '', + }), ]) ); }; } export default (): Rule => { - return host => { + return (host) => { const packageJson = readJsonInTree(host, 'package.json'); return chain([ updateGitIgnore(), !packageJson.devDependencies['@bazel/bazel'] ? updateDependencies : noop, - addFiles() + addFiles(), ]); }; }; diff --git a/packages/bazel/src/schematics/sync/sync.spec.ts b/packages/bazel/src/schematics/sync/sync.spec.ts index b9012ec20618a..8a82c667d9ba2 100644 --- a/packages/bazel/src/schematics/sync/sync.spec.ts +++ b/packages/bazel/src/schematics/sync/sync.spec.ts @@ -102,7 +102,7 @@ describe('@nrwl/bazel:sync', () => { beforeEach(async () => { tree = await callRule( chain([ - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: 'proj', root: 'proj', @@ -111,21 +111,21 @@ describe('@nrwl/bazel:sync', () => { builder: '@nrwl/web:build', options: {}, configurations: { - production: {} - } + production: {}, + }, }, serve: { builder: '@nrwl/web:dev-server', options: {}, configurations: { - production: {} - } + production: {}, + }, }, test: { builder: '@nrwl/jest:jest', - options: {} - } - } + options: {}, + }, + }, }); workspace.projects.add({ name: 'proj2', @@ -135,28 +135,28 @@ describe('@nrwl/bazel:sync', () => { builder: '@angular-devkit/build-angular:browser', options: {}, configurations: { - production: {} - } + production: {}, + }, }, serve: { builder: '@angular-devkit/build-angular:dev-server', options: {}, configurations: { - production: {} - } + production: {}, + }, }, test: { builder: '@angular-devkit/build-angular:karma', - options: {} - } - } + options: {}, + }, + }, }); }), - updateJsonInTree('nx.json', json => { + updateJsonInTree('nx.json', (json) => { json.projects['proj'] = {}; json.projects['proj2'] = {}; return json; - }) + }), ]), tree ); diff --git a/packages/bazel/src/schematics/sync/sync.ts b/packages/bazel/src/schematics/sync/sync.ts index 911293e2ae63b..ad12788179907 100644 --- a/packages/bazel/src/schematics/sync/sync.ts +++ b/packages/bazel/src/schematics/sync/sync.ts @@ -9,18 +9,18 @@ import { Source, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { getProjectGraphFromHost, getWorkspace, readJsonInTree, - readWorkspace + readWorkspace, } from '@nrwl/workspace'; import { join, normalize } from '@angular-devkit/core'; import { ProjectGraph, - ProjectGraphNode + ProjectGraphNode, } from '@nrwl/workspace/src/core/project-graph'; import { rulesNodeJSSha, rulesNodeJSVersion } from '../utils/versions'; import { TargetDefinition } from '@angular-devkit/core/src/workspace'; @@ -30,7 +30,7 @@ const buildBuilders = { '@angular-devkit/build-angular:server': 'outputPath', '@angular-devkit/build-angular:ng-packagr': 'outputPath', '@angular-devkit/build-webpack:webpack': 'outputPath', - '@nrwl/web:build': 'outputPath' + '@nrwl/web:build': 'outputPath', }; const testBuilders = new Set([ @@ -39,7 +39,7 @@ const testBuilders = new Set([ '@angular-devkit/build-angular:tslint', '@nrwl/jest:jest', '@nrwl/cypress:cypress', - '@nrwl/linter:lint' + '@nrwl/linter:lint', ]); function createBuildFile( @@ -58,8 +58,8 @@ function createBuildFile( outputArgument: string; }[] = []; labelsMetadata - .map(metadata => - metadata.configurations.map(config => { + .map((metadata) => + metadata.configurations.map((config) => { const isTestTarget = testBuilders.has(metadata.target.builder); const isBuildTarget = !!buildBuilders[metadata.target.builder]; const outputArgument = buildBuilders[metadata.target.builder]; @@ -72,12 +72,12 @@ function createBuildFile( config === '__nx_default__' ? '' : `__${config}` }`, isBuildTarget, - outputArgument + outputArgument, }; }) ) - .forEach(arr => { - arr.forEach(label => labels.push(label)); + .forEach((arr) => { + arr.forEach((label) => labels.push(label)); }); return apply(url('./files/build-file'), [ @@ -87,14 +87,14 @@ function createBuildFile( projectGraph, dependencies: projectGraph.dependencies[project.name] ? projectGraph.dependencies[project.name].map( - dep => + (dep) => `//${normalize(projectGraph.nodes[dep.target].data.root)}:${ dep.target }` ) : [], - labels - }) + labels, + }), ]); } @@ -111,15 +111,15 @@ function updateBuildFile( target, configurations: [ '__nx_default__', - ...Object.keys(target.configurations || {}) - ] + ...Object.keys(target.configurations || {}), + ], })); const buildFile = createBuildFile(project, projectGraph, labelsMetadata); const buildFilePath = join(normalize(project.data.root), 'BUILD.bazel'); return mergeWith( apply(buildFile, [ - sourceHost => { + (sourceHost) => { if (host.exists(buildFilePath)) { const contents = sourceHost.read('BUILD.bazel').toString(); const customPart = host @@ -130,7 +130,7 @@ function updateBuildFile( sourceHost.overwrite('BUILD.bazel', customPart + contents); } }, - move(project.data.root) + move(project.data.root), ]), MergeStrategy.Overwrite ); @@ -138,20 +138,20 @@ function updateBuildFile( } function createWorkspaceFile() { - return host => { + return (host) => { return mergeWith( apply(url('./files/workspace-file'), [ template({ tmpl: '', name: readJsonInTree(host, '/package.json').name.replace('-', '_'), rulesNodeJSVersion, - rulesNodeJSSha + rulesNodeJSSha, }), () => { if (host.exists('WORKSPACE')) { host.delete('WORKSPACE'); } - } + }, ]), MergeStrategy.Overwrite ); @@ -161,20 +161,20 @@ function createWorkspaceFile() { const ignoredFromRootBuildFile = ['WORKSPACE', '.bazelrc', 'BUILD.bazel']; function createRootBuildFile() { - return host => { + return (host) => { return mergeWith( apply(url('./files/root-build-file'), [ template({ tmpl: '', rootFiles: host .getDir('/') - .subfiles.filter(f => !ignoredFromRootBuildFile.includes(f)) + .subfiles.filter((f) => !ignoredFromRootBuildFile.includes(f)), }), () => { if (host.exists('BUILD.bazel')) { host.delete('BUILD.bazel'); } - } + }, ]), MergeStrategy.Overwrite ); @@ -191,9 +191,9 @@ export default (): Rule => { runInit, createWorkspaceFile(), createRootBuildFile(), - ...Object.values(projectGraph.nodes).map(project => + ...Object.values(projectGraph.nodes).map((project) => updateBuildFile(project, projectGraph) - ) + ), ]); }; }; diff --git a/packages/cli/lib/init-global.ts b/packages/cli/lib/init-global.ts index cf0fc3c11cf87..97c564b8ab843 100644 --- a/packages/cli/lib/init-global.ts +++ b/packages/cli/lib/init-global.ts @@ -24,12 +24,12 @@ export function initGlobal() { title: `The current directory isn't part of an Nx workspace.`, bodyLines: [ `To create a workspace run:`, - chalk.bold.white(`npx create-nx-workspace@latest `) - ] + chalk.bold.white(`npx create-nx-workspace@latest `), + ], }); output.note({ - title: `For more information please visit https://nx.dev/` + title: `For more information please visit https://nx.dev/`, }); process.exit(0); } diff --git a/packages/cli/lib/output.ts b/packages/cli/lib/output.ts index 191fa8ccb0d05..1f894756eaac7 100644 --- a/packages/cli/lib/output.ts +++ b/packages/cli/lib/output.ts @@ -55,7 +55,7 @@ class CLIOutput { * implementation. */ colors = { - gray: chalk.gray + gray: chalk.gray, }; bold = chalk.bold; underline = chalk.underline; @@ -66,7 +66,7 @@ class CLIOutput { private writeOutputTitle({ label, - title + title, }: { label?: string; title: string; @@ -85,7 +85,7 @@ class CLIOutput { return; } this.addNewline(); - bodyLines.forEach(bodyLine => this.writeToStdOut(' ' + bodyLine + '\n')); + bodyLines.forEach((bodyLine) => this.writeToStdOut(' ' + bodyLine + '\n')); } addNewline() { @@ -101,7 +101,7 @@ class CLIOutput { this.writeOutputTitle({ label: chalk.reset.inverse.bold.red(' ERROR '), - title: chalk.bold.red(title) + title: chalk.bold.red(title), }); this.writeOptionalOutputBody(bodyLines); @@ -127,7 +127,7 @@ class CLIOutput { this.writeOutputTitle({ label: chalk.reset.inverse.bold.yellow(' WARNING '), - title: chalk.bold.yellow(title) + title: chalk.bold.yellow(title), }); this.writeOptionalOutputBody(bodyLines); @@ -153,7 +153,7 @@ class CLIOutput { this.writeOutputTitle({ label: chalk.reset.inverse.bold.keyword('orange')(' NOTE '), - title: chalk.bold.keyword('orange')(title) + title: chalk.bold.keyword('orange')(title), }); this.writeOptionalOutputBody(bodyLines); @@ -166,7 +166,7 @@ class CLIOutput { this.writeOutputTitle({ label: chalk.reset.inverse.bold.green(' SUCCESS '), - title: chalk.bold.green(title) + title: chalk.bold.green(title), }); this.addNewline(); @@ -176,7 +176,7 @@ class CLIOutput { this.addNewline(); this.writeOutputTitle({ - title: message + title: message, }); this.addNewline(); @@ -186,7 +186,7 @@ class CLIOutput { this.addNewline(); this.writeOutputTitle({ - title: chalk.white(title) + title: chalk.white(title), }); this.writeOptionalOutputBody(bodyLines); diff --git a/packages/cli/lib/parse-run-one-options.spec.ts b/packages/cli/lib/parse-run-one-options.spec.ts index d69c3b190918a..f5c0096e3fc97 100644 --- a/packages/cli/lib/parse-run-one-options.spec.ts +++ b/packages/cli/lib/parse-run-one-options.spec.ts @@ -10,7 +10,7 @@ describe('parseRunOneOptions', () => { project: 'myproj', target: 'build', configuration: 'production', - overrides: { flag: 'true' } + overrides: { flag: 'true' }, }); }); @@ -19,13 +19,13 @@ describe('parseRunOneOptions', () => { parseRunOneOptions(nxJson, workspaceJson, [ 'run', 'myproj:build:production', - '--flag=true' + '--flag=true', ]) ).toEqual({ project: 'myproj', target: 'build', configuration: 'production', - overrides: { flag: 'true' } + overrides: { flag: 'true' }, }); }); @@ -39,7 +39,7 @@ describe('parseRunOneOptions', () => { ).toEqual({ project: 'myproj', target: 'build', - overrides: { flag: 'true' } + overrides: { flag: 'true' }, }); }); diff --git a/packages/cli/lib/parse-run-one-options.ts b/packages/cli/lib/parse-run-one-options.ts index 3779fa44d72d3..8934e7a09634f 100644 --- a/packages/cli/lib/parse-run-one-options.ts +++ b/packages/cli/lib/parse-run-one-options.ts @@ -12,7 +12,7 @@ export function parseRunOneOptions( const parsedArgs = yargsParser(args, { boolean: ['prod', 'help'], - string: ['configuration', 'project'] + string: ['configuration', 'project'], }); if (parsedArgs['help']) { diff --git a/packages/cli/lib/run-cli.ts b/packages/cli/lib/run-cli.ts index 1fca6a1892616..035b0f33416a1 100644 --- a/packages/cli/lib/run-cli.ts +++ b/packages/cli/lib/run-cli.ts @@ -77,7 +77,7 @@ function setUpOutputWatching(captureStderr: boolean, forwardOutput: boolean) { } }; - process.on('exit', code => { + process.on('exit', (code) => { if (code === 0) { fs.writeFileSync( process.env.NX_TERMINAL_OUTPUT_PATH, diff --git a/packages/create-nx-plugin/bin/create-nx-plugin.ts b/packages/create-nx-plugin/bin/create-nx-plugin.ts index fb77ae765840a..3a073361ce62e 100644 --- a/packages/create-nx-plugin/bin/create-nx-plugin.ts +++ b/packages/create-nx-plugin/bin/create-nx-plugin.ts @@ -18,9 +18,9 @@ const prettierVersion = 'PRETTIER_VERSION'; const parsedArgs = yargsParser(process.argv, { string: ['pluginName'], alias: { - pluginName: 'plugin-name' + pluginName: 'plugin-name', }, - boolean: ['help'] + boolean: ['help'], }); if (parsedArgs.help) { @@ -29,8 +29,8 @@ if (parsedArgs.help) { } const packageManager = determinePackageManager(); -determineWorkspaceName(parsedArgs).then(workspaceName => { - return determinePluginName(parsedArgs).then(pluginName => { +determineWorkspaceName(parsedArgs).then((workspaceName) => { + return determinePluginName(parsedArgs).then((pluginName) => { const tmpDir = createSandbox(packageManager); createWorkspace(tmpDir, packageManager, parsedArgs, workspaceName); createNxPlugin(workspaceName, pluginName); @@ -49,15 +49,15 @@ function createSandbox(packageManager: string) { '@nrwl/workspace': nxVersion, '@nrwl/tao': cliVersion, typescript: tsVersion, - prettier: prettierVersion + prettier: prettierVersion, }, - license: 'MIT' + license: 'MIT', }) ); execSync(`${packageManager} install --silent`, { cwd: tmpDir, - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); return tmpDir; @@ -71,7 +71,7 @@ function createWorkspace( ) { const args = [ name, - ...process.argv.slice(parsedArgs._[2] ? 3 : 2).map(a => `"${a}"`) + ...process.argv.slice(parsedArgs._[2] ? 3 : 2).map((a) => `"${a}"`), ].join(' '); console.log(`new ${args} --preset=empty --collection=@nrwl/workspace`); @@ -83,12 +83,12 @@ function createWorkspace( 'tao' )}" new ${args} --preset=empty --collection=@nrwl/workspace`, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], } ); execSync(`${packageManager} add -D @nrwl/nx-plugin@${nxVersion}`, { cwd: name, - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); } @@ -98,7 +98,7 @@ function createNxPlugin(workspaceName, pluginName) { `node ./node_modules/@nrwl/cli/bin/nx.js generate @nrwl/nx-plugin:plugin ${pluginName}`, { cwd: workspaceName, - stdio: [0, 1, 2] + stdio: [0, 1, 2], } ); } @@ -106,11 +106,11 @@ function createNxPlugin(workspaceName, pluginName) { function commitChanges(workspaceName) { execSync('git add .', { cwd: workspaceName, - stdio: 'ignore' + stdio: 'ignore', }); execSync('git commit --amend --no-edit', { cwd: workspaceName, - stdio: 'ignore' + stdio: 'ignore', }); } @@ -126,14 +126,14 @@ function determineWorkspaceName(parsedArgs: any): Promise { { name: 'WorkspaceName', message: `Workspace name (e.g., org name) `, - type: 'string' - } + type: 'string', + }, ]) - .then(a => { + .then((a) => { if (!a.WorkspaceName) { output.error({ title: 'Invalid workspace name', - bodyLines: [`Workspace name cannot be empty`] + bodyLines: [`Workspace name cannot be empty`], }); process.exit(1); } @@ -151,14 +151,14 @@ function determinePluginName(parsedArgs) { { name: 'PluginName', message: `Plugin name `, - type: 'string' - } + type: 'string', + }, ]) - .then(a => { + .then((a) => { if (!a.PluginName) { output.error({ title: 'Invalid name', - bodyLines: [`Name cannot be empty`] + bodyLines: [`Name cannot be empty`], }); process.exit(1); } diff --git a/packages/create-nx-plugin/bin/shared.ts b/packages/create-nx-plugin/bin/shared.ts index 6dca29e76d722..35d417e66d43e 100644 --- a/packages/create-nx-plugin/bin/shared.ts +++ b/packages/create-nx-plugin/bin/shared.ts @@ -7,7 +7,7 @@ export function showNxWarning(workspaceName: string) { const pathToRunNxCommand = path.resolve(process.cwd(), workspaceName); execSync('nx --version', { cwd: pathToRunNxCommand, - stdio: ['ignore', 'ignore', 'ignore'] + stdio: ['ignore', 'ignore', 'ignore'], }); } catch (e) { // no nx found @@ -16,8 +16,8 @@ export function showNxWarning(workspaceName: string) { title: `Nx CLI is not installed globally.`, bodyLines: [ `This means that you might have to use "yarn nx" or "npm nx" to execute commands in the workspace.`, - `Run "yarn global add @nrwl/cli" or "npm install -g @nrwl/cli" to be able to execute command directly.` - ] + `Run "yarn global add @nrwl/cli" or "npm install -g @nrwl/cli" to be able to execute command directly.`, + ], }); } } @@ -45,7 +45,7 @@ function getPackageManagerFromAngularCLI(): string { try { return execSync('ng config -g cli.packageManager', { stdio: ['ignore', 'pipe', 'ignore'], - timeout: 500 + timeout: 500, }) .toString() .trim(); @@ -58,7 +58,7 @@ function isPackageManagerInstalled(packageManager: string) { let isInstalled = false; try { execSync(`${packageManager} --version`, { - stdio: ['ignore', 'ignore', 'ignore'] + stdio: ['ignore', 'ignore', 'ignore'], }); isInstalled = true; } catch (e) { diff --git a/packages/create-nx-workspace/bin/create-nx-workspace.ts b/packages/create-nx-workspace/bin/create-nx-workspace.ts index 160783e354a80..e4ceb1662addd 100644 --- a/packages/create-nx-workspace/bin/create-nx-workspace.ts +++ b/packages/create-nx-workspace/bin/create-nx-workspace.ts @@ -17,41 +17,41 @@ enum Preset { AngularWithNest = 'angular-nest', React = 'react', ReactWithExpress = 'react-express', - NextJs = 'next' + NextJs = 'next', } const presetOptions = [ { value: Preset.Empty, - name: 'empty [an empty workspace]' + name: 'empty [an empty workspace]', }, { value: 'web-components', name: - 'web components [a workspace with a single app built using web components]' + 'web components [a workspace with a single app built using web components]', }, { value: Preset.Angular, - name: 'angular [a workspace with a single Angular application]' + name: 'angular [a workspace with a single Angular application]', }, { value: Preset.AngularWithNest, name: - 'angular-nest [a workspace with a full stack application (Angular + Nest)]' + 'angular-nest [a workspace with a full stack application (Angular + Nest)]', }, { value: Preset.React, - name: 'react [a workspace with a single React application]' + name: 'react [a workspace with a single React application]', }, { value: Preset.ReactWithExpress, name: - 'react-express [a workspace with a full stack application (React + Express)]' + 'react-express [a workspace with a full stack application (React + Express)]', }, { value: Preset.NextJs, - name: 'next.js [a workspace with a single Next.js application]' - } + name: 'next.js [a workspace with a single Next.js application]', + }, ]; const tsVersion = 'TYPESCRIPT_VERSION'; @@ -63,9 +63,9 @@ const prettierVersion = 'PRETTIER_VERSION'; const parsedArgs = yargsParser(process.argv, { string: ['cli', 'preset', 'appName', 'style'], alias: { - appName: 'app-name' + appName: 'app-name', }, - boolean: ['help', 'interactive'] + boolean: ['help', 'interactive'], }); if (parsedArgs.help) { @@ -73,11 +73,11 @@ if (parsedArgs.help) { process.exit(0); } const packageManager = determinePackageManager(); -determineWorkspaceName(parsedArgs).then(name => { - determinePreset(parsedArgs).then(preset => { - return determineAppName(preset, parsedArgs).then(appName => { - return determineStyle(preset, parsedArgs).then(style => { - return determineCli(preset, parsedArgs).then(cli => { +determineWorkspaceName(parsedArgs).then((name) => { + determinePreset(parsedArgs).then((preset) => { + return determineAppName(preset, parsedArgs).then((appName) => { + return determineStyle(preset, parsedArgs).then((style) => { + return determineCli(preset, parsedArgs).then((cli) => { const tmpDir = createSandbox(packageManager, cli); createApp( tmpDir, @@ -100,7 +100,7 @@ determineWorkspaceName(parsedArgs).then(name => { function showHelp() { const options = Object.values(Preset) - .map(preset => '"' + preset + '"') + .map((preset) => '"' + preset + '"') .join(', '); console.log(` @@ -139,14 +139,14 @@ function determineWorkspaceName(parsedArgs: any): Promise { { name: 'WorkspaceName', message: `Workspace name (e.g., org name) `, - type: 'string' - } + type: 'string', + }, ]) - .then(a => { + .then((a) => { if (!a.WorkspaceName) { output.error({ title: 'Invalid workspace name', - bodyLines: [`Workspace name cannot be empty`] + bodyLines: [`Workspace name cannot be empty`], }); process.exit(1); } @@ -162,8 +162,8 @@ function determinePreset(parsedArgs: any): Promise { bodyLines: [ `It must be one of the following:`, '', - ...Object.values(Preset) - ] + ...Object.values(Preset), + ], }); process.exit(1); } else { @@ -178,8 +178,8 @@ function determinePreset(parsedArgs: any): Promise { message: `What to create in the new workspace`, default: 'empty', type: 'list', - choices: presetOptions - } + choices: presetOptions, + }, ]) .then((a: { Preset: Preset }) => a.Preset); } @@ -198,14 +198,14 @@ function determineAppName(preset: Preset, parsedArgs: any): Promise { { name: 'AppName', message: `Application name `, - type: 'string' - } + type: 'string', + }, ]) - .then(a => { + .then((a) => { if (!a.AppName) { output.error({ title: 'Invalid name', - bodyLines: [`Name cannot be empty`] + bodyLines: [`Name cannot be empty`], }); process.exit(1); } @@ -217,20 +217,20 @@ function determineCli(preset: Preset, parsedArgs: any) { const angular = { package: '@angular/cli', version: angularCliVersion, - command: 'ng' + command: 'ng', }; const nx = { package: '@nrwl/tao', version: cliVersion, - command: 'tao' + command: 'tao', }; if (parsedArgs.cli) { if (['nx', 'angular'].indexOf(parsedArgs.cli) === -1) { output.error({ title: 'Invalid cli', - bodyLines: [`It must be one of the following:`, '', 'nx', 'angular'] + bodyLines: [`It must be one of the following:`, '', 'nx', 'angular'], }); process.exit(1); } @@ -260,16 +260,16 @@ function determineCli(preset: Preset, parsedArgs: any) { { value: 'nx', name: - 'Nx [Extensible CLI for JavaScript and TypeScript applications]' + 'Nx [Extensible CLI for JavaScript and TypeScript applications]', }, { value: 'angular', name: - 'Angular CLI [Extensible CLI for Angular applications. Recommended for Angular projects.]' - } - ] - } + 'Angular CLI [Extensible CLI for Angular applications. Recommended for Angular projects.]', + }, + ], + }, ]) .then((a: { CLI: string }) => (a.CLI === 'angular' ? angular : nx)); } @@ -284,31 +284,31 @@ function determineStyle(preset: Preset, parsedArgs: any) { const choices = [ { value: 'css', - name: 'CSS' + name: 'CSS', }, { value: 'scss', - name: 'SASS(.scss) [ http://sass-lang.com ]' + name: 'SASS(.scss) [ http://sass-lang.com ]', }, { value: 'styl', - name: 'Stylus(.styl)[ http://stylus-lang.com ]' + name: 'Stylus(.styl)[ http://stylus-lang.com ]', }, { value: 'less', - name: 'LESS [ http://lesscss.org ]' - } + name: 'LESS [ http://lesscss.org ]', + }, ]; if ([Preset.ReactWithExpress, Preset.React, Preset.NextJs].includes(preset)) { choices.push( { value: 'styled-components', - name: 'styled-components [ https://styled-components.com ]' + name: 'styled-components [ https://styled-components.com ]', }, { value: '@emotion/styled', - name: 'emotion [ https://emotion.sh]' + name: 'emotion [ https://emotion.sh]', } ); } @@ -321,13 +321,15 @@ function determineStyle(preset: Preset, parsedArgs: any) { message: `Default stylesheet format `, default: 'css', type: 'list', - choices - } + choices, + }, ]) - .then(a => a.style); + .then((a) => a.style); } - const foundStyle = choices.find(choice => choice.value === parsedArgs.style); + const foundStyle = choices.find( + (choice) => choice.value === parsedArgs.style + ); if (foundStyle === undefined) { output.error({ @@ -335,8 +337,8 @@ function determineStyle(preset: Preset, parsedArgs: any) { bodyLines: [ `It must be one of the following:`, '', - ...choices.map(choice => choice.value) - ] + ...choices.map((choice) => choice.value), + ], }); process.exit(1); @@ -358,15 +360,15 @@ function createSandbox( '@nrwl/workspace': nxVersion, [cli.package]: cli.version, typescript: tsVersion, - prettier: prettierVersion + prettier: prettierVersion, }, - license: 'MIT' + license: 'MIT', }) ); execSync(`${packageManager} install --silent`, { cwd: tmpDir, - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); return tmpDir; @@ -388,7 +390,7 @@ function createApp( ...process.argv .slice(parsedArgs._[2] ? 3 : 2) .filter( - a => + (a) => !a.startsWith('--cli') && !a.startsWith('--preset') && !a.startsWith('--appName') && @@ -396,7 +398,7 @@ function createApp( !a.startsWith('--style') && !a.startsWith('--interactive') ) // not used by the new command - .map(a => `"${a}"`) + .map((a) => `"${a}"`), ].join(' '); const appNameArg = appName ? ` --appName="${appName}"` : ``; @@ -416,7 +418,7 @@ function createApp( cli.command )}" new ${args} --preset="${preset}"${appNameArg}${styleArg}${interactiveArg} --collection=@nrwl/workspace`, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], } ); } @@ -431,8 +433,8 @@ function showCliWarning(preset: Preset, parsedArgs: yargsParser.Arguments) { output.note({ title: `Because you selected an Angular-specific preset, we generated an Nx workspace powered by the Angular CLI.`, bodyLines: [ - `Run 'create-nx-workspace --help' to see how to select a different CLI.` - ] + `Run 'create-nx-workspace --help' to see how to select a different CLI.`, + ], }); } break; @@ -445,8 +447,8 @@ function showCliWarning(preset: Preset, parsedArgs: yargsParser.Arguments) { output.note({ title: `We generated an Nx workspace powered by the Nx CLI.`, bodyLines: [ - `Run 'create-nx-workspace --help' to see how to select a different CLI.` - ] + `Run 'create-nx-workspace --help' to see how to select a different CLI.`, + ], }); } break; @@ -465,8 +467,8 @@ function pointToTutorialAndCourse(preset: Preset) { title: title, bodyLines: [ `https://nx.dev/react/tutorial/01-create-application`, - ...pointToCourse() - ] + ...pointToCourse(), + ], }); break; case Preset.Angular: @@ -476,8 +478,8 @@ function pointToTutorialAndCourse(preset: Preset) { title: title, bodyLines: [ `https://nx.dev/angular/tutorial/01-create-application`, - ...pointToCourse() - ] + ...pointToCourse(), + ], }); break; case Preset.WebComponents: @@ -486,8 +488,8 @@ function pointToTutorialAndCourse(preset: Preset) { title: title, bodyLines: [ `https://nx.dev/web/tutorial/01-create-application`, - ...pointToCourse() - ] + ...pointToCourse(), + ], }); break; } @@ -497,6 +499,6 @@ function pointToCourse(): string[] { return [ ``, `Prefer watching videos? Check out this free Nx course on YouTube.`, - `https://www.youtube.com/watch?v=2mYLe9Kp9VM&list=PLakNactNC1dH38AfqmwabvOszDmKriGco` + `https://www.youtube.com/watch?v=2mYLe9Kp9VM&list=PLakNactNC1dH38AfqmwabvOszDmKriGco`, ]; } diff --git a/packages/create-nx-workspace/bin/shared.ts b/packages/create-nx-workspace/bin/shared.ts index 6dca29e76d722..35d417e66d43e 100644 --- a/packages/create-nx-workspace/bin/shared.ts +++ b/packages/create-nx-workspace/bin/shared.ts @@ -7,7 +7,7 @@ export function showNxWarning(workspaceName: string) { const pathToRunNxCommand = path.resolve(process.cwd(), workspaceName); execSync('nx --version', { cwd: pathToRunNxCommand, - stdio: ['ignore', 'ignore', 'ignore'] + stdio: ['ignore', 'ignore', 'ignore'], }); } catch (e) { // no nx found @@ -16,8 +16,8 @@ export function showNxWarning(workspaceName: string) { title: `Nx CLI is not installed globally.`, bodyLines: [ `This means that you might have to use "yarn nx" or "npm nx" to execute commands in the workspace.`, - `Run "yarn global add @nrwl/cli" or "npm install -g @nrwl/cli" to be able to execute command directly.` - ] + `Run "yarn global add @nrwl/cli" or "npm install -g @nrwl/cli" to be able to execute command directly.`, + ], }); } } @@ -45,7 +45,7 @@ function getPackageManagerFromAngularCLI(): string { try { return execSync('ng config -g cli.packageManager', { stdio: ['ignore', 'pipe', 'ignore'], - timeout: 500 + timeout: 500, }) .toString() .trim(); @@ -58,7 +58,7 @@ function isPackageManagerInstalled(packageManager: string) { let isInstalled = false; try { execSync(`${packageManager} --version`, { - stdio: ['ignore', 'ignore', 'ignore'] + stdio: ['ignore', 'ignore', 'ignore'], }); isInstalled = true; } catch (e) { diff --git a/packages/cypress/src/builders/cypress/cypress.impl.spec.ts b/packages/cypress/src/builders/cypress/cypress.impl.spec.ts index 079918b3325d5..2ca12922b210a 100644 --- a/packages/cypress/src/builders/cypress/cypress.impl.spec.ts +++ b/packages/cypress/src/builders/cypress/cypress.impl.spec.ts @@ -24,9 +24,9 @@ describe('Cypress builder', () => { let fork: jasmine.Spy; let cypressConfig: any; let mockedBuilderContext: MockBuilderContext; - let mockedInstalledCypressVersion: jest.Mock< - ReturnType - > = installedCypressVersion as any; + let mockedInstalledCypressVersion: jest.Mock> = installedCypressVersion as any; const cypressBuilderOptions: CypressBuilderOptions = { cypressConfig: 'apps/my-app-e2e/cypress.json', parallel: false, @@ -36,7 +36,7 @@ describe('Cypress builder', () => { exit: true, record: false, baseUrl: undefined, - watch: false + watch: false, }; beforeEach(async () => { @@ -56,7 +56,7 @@ describe('Cypress builder', () => { .mockReturnValue( of({ success: true, - baseUrl: 'http://localhost:4200' + baseUrl: 'http://localhost:4200', }) ); fakeEventEmitter = new EventEmitter(); @@ -65,14 +65,14 @@ describe('Cypress builder', () => { cypressOpen = spyOn(Cypress, 'open').and.returnValue(Promise.resolve({})); cypressConfig = { fixturesFolder: './src/fixtures', - integrationFolder: './src/integration' + integrationFolder: './src/integration', }; - spyOn(fsUtility, 'readJsonFile').and.callFake(path => { + spyOn(fsUtility, 'readJsonFile').and.callFake((path) => { return path.endsWith('tsconfig.json') ? { compilerOptions: { - outDir: '../../dist/out-tsc/apps/my-app-e2e/src' - } + outDir: '../../dist/out-tsc/apps/my-app-e2e/src', + }, } : cypressConfig; }); @@ -80,7 +80,7 @@ describe('Cypress builder', () => { spyOn(process, 'exit'); }); - it('should call `Cypress.run` if headless mode is `true`', async done => { + it('should call `Cypress.run` if headless mode is `true`', async (done) => { const run = await architect.scheduleBuilder( '@nrwl/cypress:cypress', cypressBuilderOptions @@ -90,7 +90,7 @@ describe('Cypress builder', () => { expect(cypressRun).toHaveBeenCalledWith( jasmine.objectContaining({ config: { baseUrl: 'http://localhost:4200' }, - project: path.dirname(cypressBuilderOptions.cypressConfig) + project: path.dirname(cypressBuilderOptions.cypressConfig), }) ); expect(cypressOpen).not.toHaveBeenCalled(); @@ -99,18 +99,18 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should call `Cypress.open` if headless mode is `false`', async done => { + it('should call `Cypress.open` if headless mode is `false`', async (done) => { const run = await architect.scheduleBuilder('@nrwl/cypress:cypress', { ...cypressBuilderOptions, headless: false, - watch: true + watch: true, }); run.result.then(async () => { await run.stop(); expect(cypressOpen).toHaveBeenCalledWith( jasmine.objectContaining({ config: { baseUrl: 'http://localhost:4200' }, - project: path.dirname(cypressBuilderOptions.cypressConfig) + project: path.dirname(cypressBuilderOptions.cypressConfig), }) ); expect(cypressRun).not.toHaveBeenCalled(); @@ -119,20 +119,20 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should call `Cypress.run` with provided baseUrl', async done => { + it('should call `Cypress.run` with provided baseUrl', async (done) => { const run = await architect.scheduleBuilder('@nrwl/cypress:cypress', { ...cypressBuilderOptions, devServerTarget: undefined, - baseUrl: 'http://my-distant-host.com' + baseUrl: 'http://my-distant-host.com', }); run.result.then(async () => { await run.stop(); expect(cypressRun).toHaveBeenCalledWith( jasmine.objectContaining({ config: { - baseUrl: 'http://my-distant-host.com' + baseUrl: 'http://my-distant-host.com', }, - project: path.dirname(cypressBuilderOptions.cypressConfig) + project: path.dirname(cypressBuilderOptions.cypressConfig), }) ); done(); @@ -142,17 +142,17 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should call `Cypress.run` with provided browser', async done => { + it('should call `Cypress.run` with provided browser', async (done) => { const run = await architect.scheduleBuilder('@nrwl/cypress:cypress', { ...cypressBuilderOptions, - browser: 'chrome' + browser: 'chrome', }); run.result.then(async () => { await run.stop(); expect(cypressRun).toHaveBeenCalledWith( jasmine.objectContaining({ browser: 'chrome', - project: path.dirname(cypressBuilderOptions.cypressConfig) + project: path.dirname(cypressBuilderOptions.cypressConfig), }) ); expect(cypressOpen).not.toHaveBeenCalled(); @@ -162,7 +162,7 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should call `Cypress.run` without baseUrl nor dev server target value', async done => { + it('should call `Cypress.run` without baseUrl nor dev server target value', async (done) => { const run = await architect.scheduleBuilder('@nrwl/cypress:cypress', { cypressConfig: 'apps/my-app-e2e/cypress.json', tsConfig: 'apps/my-app-e2e/tsconfig.json', @@ -172,13 +172,13 @@ describe('Cypress builder', () => { parallel: false, record: false, baseUrl: undefined, - watch: false + watch: false, }); run.result.then(async () => { await run.stop(); expect(cypressRun).toHaveBeenCalledWith( jasmine.objectContaining({ - project: path.dirname(cypressBuilderOptions.cypressConfig) + project: path.dirname(cypressBuilderOptions.cypressConfig), }) ); expect(cypressOpen).not.toHaveBeenCalled(); @@ -188,29 +188,29 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should fail early if application build fails', async done => { + it('should fail early if application build fails', async (done) => { (devkitArchitect as any).scheduleTargetAndForget = jest .fn() .mockReturnValue( of({ - success: false + success: false, }) ); const run = await architect.scheduleBuilder( '@nrwl/cypress:cypress', cypressBuilderOptions ); - run.result.then(async res => { + run.result.then(async (res) => { await run.stop(); expect(res.success).toBe(false); done(); }); }); - it('should call `Cypress.run` with provided cypressConfig as project and configFile', async done => { + it('should call `Cypress.run` with provided cypressConfig as project and configFile', async (done) => { const cfg = { ...cypressBuilderOptions, - cypressConfig: 'some/project/my-cypress.json' + cypressConfig: 'some/project/my-cypress.json', }; const run = await architect.scheduleBuilder('@nrwl/cypress:cypress', cfg); @@ -219,7 +219,7 @@ describe('Cypress builder', () => { expect(cypressRun).toHaveBeenCalledWith( jasmine.objectContaining({ project: path.dirname(cfg.cypressConfig), - configFile: path.basename(cfg.cypressConfig) + configFile: path.basename(cfg.cypressConfig), }) ); expect(cypressOpen).not.toHaveBeenCalled(); @@ -229,7 +229,7 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should show warnings if using unsupported browsers v3', async done => { + it('should show warnings if using unsupported browsers v3', async (done) => { mockedInstalledCypressVersion.mockReturnValue(3); const result = await cypressBuilderRunner( { ...cypressBuilderOptions, browser: 'edge' }, @@ -244,7 +244,7 @@ describe('Cypress builder', () => { done(); }); - it('should show warnings if using unsupported browsers v4', async done => { + it('should show warnings if using unsupported browsers v4', async (done) => { mockedInstalledCypressVersion.mockReturnValue(4); const result = await cypressBuilderRunner( @@ -264,7 +264,7 @@ describe('Cypress builder', () => { beforeEach(() => { cypressConfig = { fixturesFolder: '../../dist/out-tsc/apps/my-app-e2e/src/fixtures', - integrationFolder: '../../dist/out-tsc/apps/my-app-e2e/src/integration' + integrationFolder: '../../dist/out-tsc/apps/my-app-e2e/src/integration', }; }); @@ -283,14 +283,16 @@ describe('Cypress builder', () => { ); }); - it('should copy fixtures folder to out-dir', async done => { + it('should copy fixtures folder to out-dir', async (done) => { const run = await architect.scheduleBuilder( '@nrwl/cypress:cypress', cypressBuilderOptions ); run.result.then(async () => { await run.stop(); - expect(fsExtras.copySync).toHaveBeenCalledWith( + expect( + fsExtras.copySync + ).toHaveBeenCalledWith( '/root/apps/my-app-e2e/src/fixtures', '/root/dist/out-tsc/apps/my-app-e2e/src/fixtures', { overwrite: true } @@ -301,7 +303,7 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should not copy fixtures folder if they are not defined in the cypress config', async done => { + it('should not copy fixtures folder if they are not defined in the cypress config', async (done) => { delete cypressConfig.fixturesFolder; const run = await architect.scheduleBuilder( '@nrwl/cypress:cypress', @@ -316,16 +318,18 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should copy regex files to out-dir', async done => { + it('should copy regex files to out-dir', async (done) => { const regex: string = '^.+\\.feature$'; const run = await architect.scheduleBuilder('@nrwl/cypress:cypress', { ...cypressBuilderOptions, - copyFiles: regex + copyFiles: regex, }); run.result.then(async () => { await run.stop(); - expect(fsExtras.copySync).toHaveBeenCalledWith( + expect( + fsExtras.copySync + ).toHaveBeenCalledWith( '/root/apps/my-app-e2e/src/integration', '/root/dist/out-tsc/apps/my-app-e2e/src/integration', { filter: jasmine.any(Function) } @@ -336,16 +340,18 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should not copy regex files if the regex is not defined', async done => { + it('should not copy regex files if the regex is not defined', async (done) => { const regex: string = undefined; const run = await architect.scheduleBuilder('@nrwl/cypress:cypress', { ...cypressBuilderOptions, - copyFiles: regex + copyFiles: regex, }); run.result.then(async () => { await run.stop(); - expect(fsExtras.copySync).not.toHaveBeenCalledWith( + expect( + fsExtras.copySync + ).not.toHaveBeenCalledWith( '/root/apps/my-app-e2e/src/integration', '/root/dist/out-tsc/apps/my-app-e2e/src/integration', { filter: jasmine.any(Function) } @@ -356,14 +362,14 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should not copy regex files if the integration files are not defined in the cypress config', async done => { + it('should not copy regex files if the integration files are not defined in the cypress config', async (done) => { delete cypressConfig.integrationFolder; const regex: string = '^.+\\.feature$'; const run = await architect.scheduleBuilder('@nrwl/cypress:cypress', { ...cypressBuilderOptions, - copyFiles: regex + copyFiles: regex, }); run.result .then(async () => { @@ -378,12 +384,12 @@ describe('Cypress builder', () => { fakeEventEmitter.emit('exit', 0); // Passing tsc command }); - it('should fail early if integration files fail to compile', async done => { + it('should fail early if integration files fail to compile', async (done) => { const run = await architect.scheduleBuilder( '@nrwl/cypress:cypress', cypressBuilderOptions ); - run.result.then(async res => { + run.result.then(async (res) => { await run.stop(); expect(res.success).toBe(false); done(); diff --git a/packages/cypress/src/builders/cypress/cypress.impl.ts b/packages/cypress/src/builders/cypress/cypress.impl.ts index 0f2815d0c9acb..23d6eea1bddd5 100644 --- a/packages/cypress/src/builders/cypress/cypress.impl.ts +++ b/packages/cypress/src/builders/cypress/cypress.impl.ts @@ -3,7 +3,7 @@ import { createBuilder, BuilderOutput, scheduleTargetAndForget, - targetFromTargetString + targetFromTargetString, } from '@angular-devkit/architect'; import { Observable, of, noop } from 'rxjs'; import { catchError, concatMap, tap, map, take } from 'rxjs/operators'; @@ -86,11 +86,11 @@ export function cypressBuilderRunner( ) ), options.watch ? tap(noop) : take(1), - catchError(error => { + catchError((error) => { context.reportStatus(`Error: ${error.message}`); context.logger.error(error.message); return of({ - success: false + success: false, }); }) ); @@ -135,7 +135,7 @@ function initCypress( const projectFolderPath = dirname(cypressConfig); const options: any = { project: projectFolderPath, - configFile: basename(cypressConfig) + configFile: basename(cypressConfig), }; // If not, will use the `baseUrl` normally from `cypress.json` @@ -167,13 +167,13 @@ function initCypress( !isWatching || headless ? Cypress.run(options) : Cypress.open(options) ).pipe( // tap(() => (isWatching && !headless ? process.exit() : null)), // Forcing `cypress.open` to give back the terminal - map(result => ({ + map((result) => ({ /** * `cypress.open` is returning `0` and is not of the same type as `cypress.run`. * `cypress.open` is the graphical UI, so it will be obvious to know what wasn't * working. Forcing the build to success when `cypress.open` is used. */ - success: !result.totalFailed && !result.failures + success: !result.totalFailed && !result.failures, })) ); } @@ -192,14 +192,14 @@ export function startDevServer( ): Observable { // Overrides dev server watch setting. const overrides = { - watch: isWatching + watch: isWatching, }; return scheduleTargetAndForget( context, targetFromTargetString(devServerTarget), overrides ).pipe( - map(output => { + map((output) => { if (!output.success && !isWatching) { throw new Error('Could not compile application files'); } diff --git a/packages/cypress/src/builders/cypress/legacy.ts b/packages/cypress/src/builders/cypress/legacy.ts index 2ee466cf137a4..e75876211fca9 100644 --- a/packages/cypress/src/builders/cypress/legacy.ts +++ b/packages/cypress/src/builders/cypress/legacy.ts @@ -67,7 +67,7 @@ function compileTypescriptFiles( subscriber.next({ success: true }); } else { tscProcess = fork(tscPath, args, { stdio: [0, 1, 2, 'ipc'] }); - tscProcess.on('exit', code => { + tscProcess.on('exit', (code) => { code === 0 ? subscriber.next({ success: true }) : subscriber.error('Could not compile Typescript files'); @@ -134,12 +134,12 @@ function copyIntegrationFilesByRegex( dirname(join(context.workspaceRoot, cypressConfigPath)), cypressConfig.integrationFolder ), - { filter: file => regExp.test(file) } + { filter: (file) => regExp.test(file) } ); } function killProcess(context: BuilderContext): void { - return treeKill(tscProcess.pid, 'SIGTERM', error => { + return treeKill(tscProcess.pid, 'SIGTERM', (error) => { tscProcess = null; if (error) { if (Array.isArray(error) && error[0] && error[2]) { diff --git a/packages/cypress/src/migrations/update-8-1-0/update-8-1-0.spec.ts b/packages/cypress/src/migrations/update-8-1-0/update-8-1-0.spec.ts index f000e030e4bfe..8c1e561015545 100644 --- a/packages/cypress/src/migrations/update-8-1-0/update-8-1-0.spec.ts +++ b/packages/cypress/src/migrations/update-8-1-0/update-8-1-0.spec.ts @@ -13,7 +13,7 @@ describe('Update 8.1.0', () => { initialTree.create( 'package.json', serializeJson({ - scripts: {} + scripts: {}, }) ); schematicRunner = new SchematicTestRunner( diff --git a/packages/cypress/src/migrations/update-8-1-0/update-8-1-0.ts b/packages/cypress/src/migrations/update-8-1-0/update-8-1-0.ts index f22e68e17450c..48e0529fd603f 100644 --- a/packages/cypress/src/migrations/update-8-1-0/update-8-1-0.ts +++ b/packages/cypress/src/migrations/update-8-1-0/update-8-1-0.ts @@ -2,7 +2,7 @@ import { Rule, chain, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { formatFiles, updateJsonInTree } from '@nrwl/workspace'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; @@ -16,19 +16,19 @@ function displayInformation(host: Tree, context: SchematicContext) { ); } -export default function(): Rule { +export default function (): Rule { return chain([ - updateJsonInTree('package.json', json => { + updateJsonInTree('package.json', (json) => { json.devDependencies = json.devDependencies || {}; json.devDependencies = { ...json.devDependencies, - cypress: '~3.3.1' + cypress: '~3.3.1', }; return json; }), displayInformation, - formatFiles() + formatFiles(), ]); } diff --git a/packages/cypress/src/migrations/update-8-10-0/update-8-10-0.ts b/packages/cypress/src/migrations/update-8-10-0/update-8-10-0.ts index 16bb5a7c9515e..2257c756503e3 100644 --- a/packages/cypress/src/migrations/update-8-10-0/update-8-10-0.ts +++ b/packages/cypress/src/migrations/update-8-10-0/update-8-10-0.ts @@ -9,6 +9,6 @@ export default () => { join(__dirname, '../../../migrations.json'), '8.10.0' ), - formatFiles() + formatFiles(), ]); }; diff --git a/packages/cypress/src/migrations/update-8-12-0/update-8-12-0.ts b/packages/cypress/src/migrations/update-8-12-0/update-8-12-0.ts index fecdec6f48b18..6d526136aedc8 100644 --- a/packages/cypress/src/migrations/update-8-12-0/update-8-12-0.ts +++ b/packages/cypress/src/migrations/update-8-12-0/update-8-12-0.ts @@ -9,6 +9,6 @@ export default () => { join(__dirname, '../../../migrations.json'), '8.12.0' ), - formatFiles() + formatFiles(), ]); }; diff --git a/packages/cypress/src/migrations/update-8-2-0/update-8-2-0.spec.ts b/packages/cypress/src/migrations/update-8-2-0/update-8-2-0.spec.ts index 88384c1ac14ed..7b3718317e236 100644 --- a/packages/cypress/src/migrations/update-8-2-0/update-8-2-0.spec.ts +++ b/packages/cypress/src/migrations/update-8-2-0/update-8-2-0.spec.ts @@ -5,7 +5,7 @@ import { callRule, runMigration } from '../../utils/testing'; import { updateWorkspace, readJsonInTree, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; describe('Update 8.2.0', () => { @@ -15,7 +15,7 @@ describe('Update 8.2.0', () => { initialTree = createEmptyWorkspace(Tree.empty()); initialTree = await callRule( chain([ - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ root: 'project', name: 'proejct', @@ -25,17 +25,17 @@ describe('Update 8.2.0', () => { options: { cypressConfig: 'project/cypress.json', tsConfig: 'project/tsconfig.e2e.json', - devServerTarget: 'project:serve' + devServerTarget: 'project:serve', }, configurations: { production: { cypressConfig: 'project/cypress.prod.json', tsConfig: 'project/tsconfig.e2e.json', - devServerTarget: 'project:serve:production' - } - } - } - } + devServerTarget: 'project:serve:production', + }, + }, + }, + }, }); }), updateJsonInTree('project/cypress.json', () => ({ @@ -46,7 +46,7 @@ describe('Update 8.2.0', () => { supportFile: false, video: true, videosFolder: '../dist/out-tsc/project/videos', - screenshotsFolder: '../dist/out-tsc/project/screenshots' + screenshotsFolder: '../dist/out-tsc/project/screenshots', })), updateJsonInTree('project/cypress.prod.json', () => ({ fileServerFolder: '../dist/out-tsc/project', @@ -57,21 +57,21 @@ describe('Update 8.2.0', () => { video: true, videosFolder: '../dist/out-tsc/project/videos', screenshotsFolder: '../dist/out-tsc/project/screenshots', - baseUrl: 'https://www.example.com' + baseUrl: 'https://www.example.com', })), updateJsonInTree('project/tsconfig.e2e.json', () => ({ extends: '../tsconfig.json', compilerOptions: { - outDir: '../dist/out-tsc' + outDir: '../dist/out-tsc', }, - include: ['**/*'] + include: ['**/*'], })), updateJsonInTree('tsconfig.json', () => ({ compilerOptions: { - rootDir: '.' - } + rootDir: '.', + }, })), - host => { + (host) => { host.create( 'project/src/plugins/index.ts', ` @@ -98,7 +98,7 @@ describe('Update 8.2.0', () => { ` ); - } + }, ]), initialTree ); @@ -114,7 +114,7 @@ describe('Update 8.2.0', () => { supportFile: false, video: true, videosFolder: '../dist/out-tsc/project/videos', - screenshotsFolder: '../dist/out-tsc/project/screenshots' + screenshotsFolder: '../dist/out-tsc/project/screenshots', }); expect(readJsonInTree(result, 'project/cypress.prod.json')).toEqual({ fileServerFolder: './', @@ -125,14 +125,16 @@ describe('Update 8.2.0', () => { video: true, videosFolder: '../dist/out-tsc/project/videos', screenshotsFolder: '../dist/out-tsc/project/screenshots', - baseUrl: 'https://www.example.com' + baseUrl: 'https://www.example.com', }); }); it('should transpile plugin files', async () => { const result = await runMigration('update-8.2.0', {}, initialTree); const newPluginsFile = result.readContent('project/src/plugins/index.js'); - expect(newPluginsFile).toContain('module.exports = function(on, config) {'); + expect(newPluginsFile).toContain( + 'module.exports = function (on, config) {' + ); expect(newPluginsFile).toContain( `const { preprocessTypescript } = require('@nrwl/cypress/plugins/preprocessor');` ); diff --git a/packages/cypress/src/migrations/update-8-2-0/update-8-2-0.ts b/packages/cypress/src/migrations/update-8-2-0/update-8-2-0.ts index f8aaf273ae834..8d7278afca1df 100644 --- a/packages/cypress/src/migrations/update-8-2-0/update-8-2-0.ts +++ b/packages/cypress/src/migrations/update-8-2-0/update-8-2-0.ts @@ -2,13 +2,13 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { formatFiles, getWorkspace, readJsonInTree, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { @@ -25,7 +25,7 @@ import { isFunctionExpression, isArrowFunction, isBlock, - ScriptTarget + ScriptTarget, } from 'typescript'; import { dirname, join, relative } from 'path'; import { normalize } from '@angular-devkit/core'; @@ -34,24 +34,24 @@ async function updateCypressJson(host: Tree, context: SchematicContext) { const rules: Rule[] = []; const workspace = await getWorkspace(host); - workspace.projects.forEach(project => { - project.targets.forEach(target => { + workspace.projects.forEach((project) => { + project.targets.forEach((target) => { if (target.builder !== '@nrwl/cypress:cypress') { return; } const parseConfigHost: ParseConfigHost = { useCaseSensitiveFileNames: true, - fileExists: path => host.exists(path), - readDirectory: dir => host.getDir(dir).subfiles, - readFile: path => host.read(path).toString() + fileExists: (path) => host.exists(path), + readDirectory: (dir) => host.getDir(dir).subfiles, + readFile: (path) => host.read(path).toString(), }; const updatedCypressJsons = new Set(); updatedCypressJsons.add(target.options.cypressConfig as string); rules.push( - updateJsonInTree(target.options.cypressConfig as string, json => { + updateJsonInTree(target.options.cypressConfig as string, (json) => { function getUpdatedPath(path: string) { if (typeof path !== 'string') { return path; @@ -88,13 +88,13 @@ async function updateCypressJson(host: Tree, context: SchematicContext) { }) ); - Object.values(target.configurations).forEach(config => { + Object.values(target.configurations).forEach((config) => { if ( config.cypressConfig && !updatedCypressJsons.has(config.cypressConfig) ) { rules.push( - updateJsonInTree(config.cypressConfig as string, json => { + updateJsonInTree(config.cypressConfig as string, (json) => { function getUpdatedPath(path: string) { if (typeof path !== 'string') { return path; @@ -143,14 +143,14 @@ async function updateCypressJson(host: Tree, context: SchematicContext) { async function updatePlugins(host: Tree, context: SchematicContext) { const workspace = await getWorkspace(host); - workspace.projects.forEach(project => { - project.targets.forEach(target => { + workspace.projects.forEach((project) => { + project.targets.forEach((target) => { if (target.builder !== '@nrwl/cypress:cypress') { return; } [target.options, ...Object.values(target.configurations)].forEach( - config => { + (config) => { if (!config.cypressConfig) { return; } @@ -176,8 +176,8 @@ async function updatePlugins(host: Tree, context: SchematicContext) { const result = transpileModule(host.read(pluginFile).toString(), { compilerOptions: { - module: ModuleKind.CommonJS - } + module: ModuleKind.CommonJS, + }, }); host.create(newPluginFile, result.outputText); host.delete(pluginFile); @@ -194,7 +194,7 @@ async function updatePlugins(host: Tree, context: SchematicContext) { 0, `const { preprocessTypescript } = require('@nrwl/cypress/plugins/preprocessor');` ); - sourceFile.statements.forEach(statement => { + sourceFile.statements.forEach((statement) => { if ( isExpressionStatement(statement) && isBinaryExpression(statement.expression) && @@ -236,6 +236,6 @@ async function updatePlugins(host: Tree, context: SchematicContext) { }); } -export default function(): Rule { +export default function (): Rule { return chain([updateCypressJson, updatePlugins, formatFiles()]); } diff --git a/packages/cypress/src/plugins/preprocessor.spec.ts b/packages/cypress/src/plugins/preprocessor.spec.ts index f83e27df59a99..04043d82d6bd8 100644 --- a/packages/cypress/src/plugins/preprocessor.spec.ts +++ b/packages/cypress/src/plugins/preprocessor.spec.ts @@ -8,15 +8,15 @@ import TsConfigPathsPlugin from 'tsconfig-paths-webpack-plugin'; describe('getWebpackConfig', () => { beforeEach(() => { - (TsConfigPathsPlugin).mockImplementation( - function MockPathsPlugin() {} - ); + (( + TsConfigPathsPlugin + )).mockImplementation(function MockPathsPlugin() {}); }); it('should load typescript', () => { const config = getWebpackConfig({ env: { - tsConfig: './tsconfig.json' - } + tsConfig: './tsconfig.json', + }, }); expect(config.module.rules).toContainEqual({ test: /\.(j|t)sx?$/, @@ -26,20 +26,20 @@ describe('getWebpackConfig', () => { configFile: './tsconfig.json', // https://github.com/TypeStrong/ts-loader/pull/685 experimentalWatchApi: true, - transpileOnly: true - } + transpileOnly: true, + }, }); }); it('should resolve tsconfig paths', () => { const config = getWebpackConfig({ env: { - tsConfig: './tsconfig.json' - } + tsConfig: './tsconfig.json', + }, }); expect( config.resolve.plugins.some( - plugin => plugin instanceof TsConfigPathsPlugin + (plugin) => plugin instanceof TsConfigPathsPlugin ) ).toEqual(true); }); @@ -47,23 +47,23 @@ describe('getWebpackConfig', () => { it('should resolve relevant extensions', () => { const config = getWebpackConfig({ env: { - tsConfig: './tsconfig.json' - } + tsConfig: './tsconfig.json', + }, }); expect(config.resolve.extensions).toEqual([ '.ts', '.tsx', '.mjs', '.js', - '.jsx' + '.jsx', ]); }); it('should keep node_modules external', () => { const config = getWebpackConfig({ env: { - tsConfig: './tsconfig.json' - } + tsConfig: './tsconfig.json', + }, }); const callback = jest.fn(); config.externals[0](null, '@nestjs/core', callback); @@ -75,8 +75,8 @@ describe('preprocessTypescript', () => { it('should work if no customizer is passed', async () => { const preprocessor = preprocessTypescript({ env: { - tsConfig: './tsconfig.json' - } + tsConfig: './tsconfig.json', + }, }); await preprocessor('arg0', 'arg1'); expect(wp).toBeCalled(); @@ -90,10 +90,10 @@ describe('preprocessTypescript', () => { const preprocessor = preprocessTypescript( { env: { - tsConfig: './tsconfig.json' - } + tsConfig: './tsconfig.json', + }, }, - webpackConfig => { + (webpackConfig) => { webpackConfig.resolve.extensions.push('.mdx'); return webpackConfig; } diff --git a/packages/cypress/src/plugins/preprocessor.ts b/packages/cypress/src/plugins/preprocessor.ts index 1983bf322526f..02123d7e152d5 100644 --- a/packages/cypress/src/plugins/preprocessor.ts +++ b/packages/cypress/src/plugins/preprocessor.ts @@ -29,9 +29,9 @@ export function getWebpackConfig(config: any) { plugins: [ new TsconfigPathsPlugin({ configFile: config.env.tsConfig, - extensions - }) - ] + extensions, + }), + ], }, module: { rules: [ @@ -43,17 +43,17 @@ export function getWebpackConfig(config: any) { configFile: config.env.tsConfig, // https://github.com/TypeStrong/ts-loader/pull/685 experimentalWatchApi: true, - transpileOnly: true - } - } - ] + transpileOnly: true, + }, + }, + ], }, plugins: [ new ForkTsCheckerWebpackPlugin({ tsconfig: config.env.tsConfig, - useTypescriptIncrementalApi: false - }) + useTypescriptIncrementalApi: false, + }), ], - externals: [nodeExternals()] + externals: [nodeExternals()], }; } diff --git a/packages/cypress/src/schematics/cypress-project/cypress-project.spec.ts b/packages/cypress/src/schematics/cypress-project/cypress-project.spec.ts index 9700b23d0a885..4082c0c68e0ad 100644 --- a/packages/cypress/src/schematics/cypress-project/cypress-project.spec.ts +++ b/packages/cypress/src/schematics/cypress-project/cypress-project.spec.ts @@ -51,21 +51,21 @@ describe('schematic:cypress-project', () => { builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: ['apps/my-app-e2e/tsconfig.e2e.json'], - exclude: ['**/node_modules/**', '!apps/my-app-e2e/**'] - } + exclude: ['**/node_modules/**', '!apps/my-app-e2e/**'], + }, }); expect(project.architect.e2e).toEqual({ builder: '@nrwl/cypress:cypress', options: { cypressConfig: 'apps/my-app-e2e/cypress.json', devServerTarget: 'my-app:serve', - tsConfig: 'apps/my-app-e2e/tsconfig.e2e.json' + tsConfig: 'apps/my-app-e2e/tsconfig.e2e.json', }, configurations: { production: { - devServerTarget: 'my-app:serve:production' - } - } + devServerTarget: 'my-app:serve:production', + }, + }, }); }); @@ -84,8 +84,8 @@ describe('schematic:cypress-project', () => { linter: 'eslint', config: 'apps/my-app-e2e/.eslintrc', tsConfig: ['apps/my-app-e2e/tsconfig.e2e.json'], - exclude: ['**/node_modules/**', '!apps/my-app-e2e/**'] - } + exclude: ['**/node_modules/**', '!apps/my-app-e2e/**'], + }, }); }); @@ -99,7 +99,7 @@ describe('schematic:cypress-project', () => { const nxJson = readJsonInTree(tree, 'nx.json'); expect(nxJson.projects['my-app-e2e']).toEqual({ tags: [], - implicitDependencies: ['my-app'] + implicitDependencies: ['my-app'], }); }); @@ -121,7 +121,7 @@ describe('schematic:cypress-project', () => { video: true, videosFolder: '../../dist/cypress/apps/my-app-e2e/videos', screenshotsFolder: '../../dist/cypress/apps/my-app-e2e/screenshots', - chromeWebSecurity: false + chromeWebSecurity: false, }); }); @@ -148,7 +148,7 @@ describe('schematic:cypress-project', () => { name: 'my-app-e2e', project: 'my-dir-my-app', directory: 'my-dir', - linter: Linter.TsLint + linter: Linter.TsLint, }, appTree ); @@ -161,8 +161,8 @@ describe('schematic:cypress-project', () => { builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: ['apps/my-dir/my-app-e2e/tsconfig.e2e.json'], - exclude: ['**/node_modules/**', '!apps/my-dir/my-app-e2e/**'] - } + exclude: ['**/node_modules/**', '!apps/my-dir/my-app-e2e/**'], + }, }); expect(projectConfig.architect.e2e).toEqual({ @@ -170,13 +170,13 @@ describe('schematic:cypress-project', () => { options: { cypressConfig: 'apps/my-dir/my-app-e2e/cypress.json', devServerTarget: 'my-dir-my-app:serve', - tsConfig: 'apps/my-dir/my-app-e2e/tsconfig.e2e.json' + tsConfig: 'apps/my-dir/my-app-e2e/tsconfig.e2e.json', }, configurations: { production: { - devServerTarget: 'my-dir-my-app:serve:production' - } - } + devServerTarget: 'my-dir-my-app:serve:production', + }, + }, }); }); @@ -202,7 +202,7 @@ describe('schematic:cypress-project', () => { videosFolder: '../../../dist/cypress/apps/my-dir/my-app-e2e/videos', screenshotsFolder: '../../../dist/cypress/apps/my-dir/my-app-e2e/screenshots', - chromeWebSecurity: false + chromeWebSecurity: false, }); }); diff --git a/packages/cypress/src/schematics/cypress-project/cypress-project.ts b/packages/cypress/src/schematics/cypress-project/cypress-project.ts index cb46b47cb3af3..6e3d0c97cbcca 100644 --- a/packages/cypress/src/schematics/cypress-project/cypress-project.ts +++ b/packages/cypress/src/schematics/cypress-project/cypress-project.ts @@ -6,7 +6,7 @@ import { noop, Rule, template, - url + url, } from '@angular-devkit/schematics'; import { join, normalize } from '@angular-devkit/core'; // app @@ -15,7 +15,7 @@ import { NxJson, updateWorkspaceInTree, generateProjectLint, - addLintFiles + addLintFiles, } from '@nrwl/workspace'; import { offsetFromRoot } from '@nrwl/workspace'; import { toFileName } from '@nrwl/workspace'; @@ -36,27 +36,27 @@ function generateFiles(options: CypressProjectSchema): Rule { tmpl: '', ...options, ext: options.js ? 'js' : 'ts', - offsetFromRoot: offsetFromRoot(options.projectRoot) + offsetFromRoot: offsetFromRoot(options.projectRoot), }), move(options.projectRoot), - options.js ? toJS() : noop() + options.js ? toJS() : noop(), ]) ); }; } function updateNxJson(options: CypressProjectSchema): Rule { - return updateJsonInTree('nx.json', json => { + return updateJsonInTree('nx.json', (json) => { json.projects[options.projectName] = { tags: [], - implicitDependencies: [options.project] + implicitDependencies: [options.project], }; return json; }); } function updateWorkspaceJson(options: CypressProjectSchema): Rule { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const architect: any = {}; architect.e2e = { @@ -64,13 +64,13 @@ function updateWorkspaceJson(options: CypressProjectSchema): Rule { options: { cypressConfig: join(normalize(options.projectRoot), 'cypress.json'), tsConfig: join(normalize(options.projectRoot), 'tsconfig.e2e.json'), - devServerTarget: `${options.project}:serve` + devServerTarget: `${options.project}:serve`, }, configurations: { production: { - devServerTarget: `${options.project}:serve:production` - } - } + devServerTarget: `${options.project}:serve:production`, + }, + }, }; architect.lint = generateProjectLint( @@ -83,13 +83,13 @@ function updateWorkspaceJson(options: CypressProjectSchema): Rule { root: options.projectRoot, sourceRoot: join(normalize(options.projectRoot), 'src'), projectType: 'application', - architect + architect, }; return json; }); } -export default function(options: CypressProjectSchema): Rule { +export default function (options: CypressProjectSchema): Rule { options = normalizeOptions(options); return chain([ addLintFiles(options.projectRoot, options.linter, { @@ -103,15 +103,15 @@ export default function(options: CypressProjectSchema): Rule { files: ['src/plugins/index.js'], rules: { '@typescript-eslint/no-var-requires': 'off', - 'no-undef': 'off' - } - } - ] - } + 'no-undef': 'off', + }, + }, + ], + }, }), generateFiles(options), updateWorkspaceJson(options), - updateNxJson(options) + updateNxJson(options), ]); } @@ -125,6 +125,6 @@ function normalizeOptions(options: CypressProjectSchema): CypressProjectSchema { return { ...options, projectName, - projectRoot + projectRoot, }; } diff --git a/packages/cypress/src/schematics/init/init.ts b/packages/cypress/src/schematics/init/init.ts index f846aea7ab889..b3e1edec17fd2 100644 --- a/packages/cypress/src/schematics/init/init.ts +++ b/packages/cypress/src/schematics/init/init.ts @@ -19,7 +19,7 @@ function updateDependencies(): Rule { delete dependencies['@nrwl/cypress']; } - return updateJsonInTree('package.json', json => { + return updateJsonInTree('package.json', (json) => { json.dependencies = dependencies; json.devDependencies = devDependencies; return json; @@ -27,6 +27,6 @@ function updateDependencies(): Rule { }; } -export default function(schema: Schema) { +export default function (schema: Schema) { return updateDependencies(); } diff --git a/packages/eslint-plugin-nx/src/index.ts b/packages/eslint-plugin-nx/src/index.ts index 9aec075818fe8..8d0d8d155cf69 100644 --- a/packages/eslint-plugin-nx/src/index.ts +++ b/packages/eslint-plugin-nx/src/index.ts @@ -1,9 +1,9 @@ import enforceModuleBoundaries, { - RULE_NAME as enforceModuleBoundariesRuleName + RULE_NAME as enforceModuleBoundariesRuleName, } from './rules/enforce-module-boundaries'; module.exports = { rules: { - [enforceModuleBoundariesRuleName]: enforceModuleBoundaries - } + [enforceModuleBoundariesRuleName]: enforceModuleBoundaries, + }, }; diff --git a/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts b/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts index 59a11c19ae01b..4c9fae68fd58e 100644 --- a/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts +++ b/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts @@ -11,7 +11,7 @@ import { isRelativeImportIntoAnotherProject, matchImportWithWildcard, onlyLoadChildren, - hasArchitectBuildBuilder + hasArchitectBuildBuilder, } from '@nrwl/workspace/src/utils/runtime-lint-utils'; import { TSESTree } from '@typescript-eslint/experimental-utils'; import { createESLintRule } from '../utils/create-eslint-rule'; @@ -19,12 +19,12 @@ import { normalize } from '@angular-devkit/core'; import { createProjectGraph, ProjectGraph, - ProjectType + ProjectType, } from '@nrwl/workspace/src/core/project-graph'; import { normalizedProjectRoot, readNxJson, - readWorkspaceJson + readWorkspaceJson, } from '@nrwl/workspace/src/core/file-utils'; import { TargetProjectLocator } from '@nrwl/workspace/src/core/target-project-locator'; @@ -53,7 +53,7 @@ export default createESLintRule({ docs: { description: `Ensure that module boundaries are respected within the monorepo`, category: 'Best Practices', - recommended: 'error' + recommended: 'error', }, fixable: 'code', schema: [ @@ -67,14 +67,14 @@ export default createESLintRule({ type: 'object', properties: { sourceTag: { type: 'string' }, - onlyDependOnLibsWithTags: [{ type: 'string' }] + onlyDependOnLibsWithTags: [{ type: 'string' }], }, - additionalProperties: false - } - ] + additionalProperties: false, + }, + ], }, - additionalProperties: false - } + additionalProperties: false, + }, ], messages: { noRelativeOrAbsoluteImportsAcrossLibraries: `Library imports must start with @{{npmScope}}/`, @@ -85,15 +85,15 @@ export default createESLintRule({ 'Buildable libs cannot import non-buildable libs', noImportsOfLazyLoadedLibraries: `Imports of lazy-loaded libraries are forbidden`, projectWithoutTagsCannotHaveDependencies: `A project without tags cannot depend on any libraries`, - tagConstraintViolation: `A project tagged with "{{sourceTag}}" can only depend on libs tagged with {{allowedTags}}` - } + tagConstraintViolation: `A project tagged with "{{sourceTag}}" can only depend on libs tagged with {{allowedTags}}`, + }, }, defaultOptions: [ { allow: [], depConstraints: [], - enforceBuildableLibDependency: false - } + enforceBuildableLibDependency: false, + }, ], create(context, [{ allow, depConstraints, enforceBuildableLibDependency }]) { /** @@ -127,7 +127,7 @@ export default createESLintRule({ ); // whitelisted import - if (allow.some(a => matchImportWithWildcard(a, imp))) { + if (allow.some((a) => matchImportWithWildcard(a, imp))) { return; } @@ -145,8 +145,8 @@ export default createESLintRule({ node, messageId: 'noRelativeOrAbsoluteImportsAcrossLibraries', data: { - npmScope - } + npmScope, + }, }); return; } @@ -176,8 +176,8 @@ export default createESLintRule({ messageId: 'noCircularDependencies', data: { sourceProjectName: sourceProject.name, - targetProjectName: targetProject.name - } + targetProjectName: targetProject.name, + }, }); return; } @@ -191,7 +191,7 @@ export default createESLintRule({ if (targetProject.type !== ProjectType.lib) { context.report({ node, - messageId: 'noImportsOfApps' + messageId: 'noImportsOfApps', }); return; } @@ -208,7 +208,7 @@ export default createESLintRule({ ) { context.report({ node, - messageId: 'noImportOfNonBuildableLibraries' + messageId: 'noImportOfNonBuildableLibraries', }); return; } @@ -218,7 +218,7 @@ export default createESLintRule({ if (imp !== `@${npmScope}/${normalizedProjectRoot(targetProject)}`) { context.report({ node, - messageId: 'noDeepImportsIntoLibraries' + messageId: 'noDeepImportsIntoLibraries', }); return; } @@ -234,7 +234,7 @@ export default createESLintRule({ ) { context.report({ node, - messageId: 'noImportsOfLazyLoadedLibraries' + messageId: 'noImportsOfLazyLoadedLibraries', }); return; } @@ -249,7 +249,7 @@ export default createESLintRule({ if (constraints.length === 0) { context.report({ node, - messageId: 'projectWithoutTagsCannotHaveDependencies' + messageId: 'projectWithoutTagsCannotHaveDependencies', }); return; } @@ -262,22 +262,22 @@ export default createESLintRule({ ) ) { const allowedTags = constraint.onlyDependOnLibsWithTags - .map(s => `"${s}"`) + .map((s) => `"${s}"`) .join(', '); context.report({ node, messageId: 'tagConstraintViolation', data: { sourceTag: constraint.sourceTag, - allowedTags - } + allowedTags, + }, }); return; } } } } - } + }, }; - } + }, }); diff --git a/packages/eslint-plugin-nx/tests/rules/enforce-module-boundaries.spec.ts b/packages/eslint-plugin-nx/tests/rules/enforce-module-boundaries.spec.ts index 4dd0cfceb9a60..671ba88c83f08 100644 --- a/packages/eslint-plugin-nx/tests/rules/enforce-module-boundaries.spec.ts +++ b/packages/eslint-plugin-nx/tests/rules/enforce-module-boundaries.spec.ts @@ -1,19 +1,19 @@ import { DependencyType, ProjectGraph, - ProjectType + ProjectType, } from '@nrwl/workspace/src/core/project-graph'; import { TSESLint } from '@typescript-eslint/experimental-utils'; import * as parser from '@typescript-eslint/parser'; import { vol } from 'memfs'; import { extname } from 'path'; import enforceModuleBoundaries, { - RULE_NAME as enforceModuleBoundariesRuleName + RULE_NAME as enforceModuleBoundariesRuleName, } from '../../src/rules/enforce-module-boundaries'; import { TargetProjectLocator } from '@nrwl/workspace/src/core/target-project-locator'; jest.mock('fs', () => require('memfs').fs); jest.mock('@nrwl/workspace/src/utils/app-root', () => ({ - appRootPath: '/root' + appRootPath: '/root', })); const tsconfig = { @@ -36,12 +36,12 @@ const tsconfig = { '@mycompany/anotherlibName': ['libs/anotherlibName/src/index.ts'], '@mycompany/badcirclelib': ['libs/badcirclelib/src/index.ts'], '@mycompany/domain1': ['libs/domain1/src/index.ts'], - '@mycompany/domain2': ['libs/domain2/src/index.ts'] + '@mycompany/domain2': ['libs/domain2/src/index.ts'], }, - types: ['node'] + types: ['node'], }, exclude: ['**/*.spec.ts'], - include: ['**/*.ts'] + include: ['**/*.ts'], }; const fileSys = { @@ -62,7 +62,7 @@ const fileSys = { './libs/badcirclelib/src/index.ts': '', './libs/domain1/src/index.ts': '', './libs/domain2/src/index.ts': '', - './tsconfig.json': JSON.stringify(tsconfig) + './tsconfig.json': JSON.stringify(tsconfig), }; describe('Enforce Module Boundaries', () => { @@ -92,9 +92,9 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`apps/myapp/src/main.ts`), - createFile(`apps/myapp/blah.ts`) - ] - } + createFile(`apps/myapp/blah.ts`), + ], + }, }, mylibName: { name: 'mylibName', @@ -106,12 +106,12 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`libs/mylib/src/index.ts`), - createFile(`libs/mylib/src/deep.ts`) - ] - } - } + createFile(`libs/mylib/src/deep.ts`), + ], + }, + }, }, - dependencies: {} + dependencies: {}, } ); @@ -137,9 +137,9 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`apps/myapp/src/main.ts`), - createFile(`apps/myapp/src/blah.ts`) - ] - } + createFile(`apps/myapp/src/blah.ts`), + ], + }, }, myapp2Name: { name: 'myapp2Name', @@ -149,8 +149,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [] - } + files: [], + }, }, 'myapp2-mylib': { name: 'myapp2-mylib', @@ -160,11 +160,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/myapp2/mylib/src/index.ts')] - } - } + files: [createFile('libs/myapp2/mylib/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, } ); @@ -182,8 +182,8 @@ describe('Enforce Module Boundaries', () => { tags: ['api', 'domain1'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/api/src/index.ts`)] - } + files: [createFile(`libs/api/src/index.ts`)], + }, }, 'impl-both-domainsName': { name: 'impl-both-domainsName', @@ -193,8 +193,8 @@ describe('Enforce Module Boundaries', () => { tags: ['impl', 'domain1', 'domain2'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/impl-both-domains/src/index.ts`)] - } + files: [createFile(`libs/impl-both-domains/src/index.ts`)], + }, }, 'impl-domain2Name': { name: 'impl-domain2Name', @@ -204,8 +204,8 @@ describe('Enforce Module Boundaries', () => { tags: ['impl', 'domain2'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/impl-domain2/src/index.ts`)] - } + files: [createFile(`libs/impl-domain2/src/index.ts`)], + }, }, impl2Name: { name: 'impl2Name', @@ -215,8 +215,8 @@ describe('Enforce Module Boundaries', () => { tags: ['impl', 'domain1'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/impl2/src/index.ts`)] - } + files: [createFile(`libs/impl2/src/index.ts`)], + }, }, implName: { name: 'implName', @@ -226,8 +226,8 @@ describe('Enforce Module Boundaries', () => { tags: ['impl', 'domain1'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/impl/src/index.ts`)] - } + files: [createFile(`libs/impl/src/index.ts`)], + }, }, untaggedName: { name: 'untaggedName', @@ -237,11 +237,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/untagged/src/index.ts`)] - } - } + files: [createFile(`libs/untagged/src/index.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, }; const depConstraints = { @@ -249,8 +249,8 @@ describe('Enforce Module Boundaries', () => { { sourceTag: 'api', onlyDependOnLibsWithTags: ['api'] }, { sourceTag: 'impl', onlyDependOnLibsWithTags: ['api', 'impl'] }, { sourceTag: 'domain1', onlyDependOnLibsWithTags: ['domain1'] }, - { sourceTag: 'domain2', onlyDependOnLibsWithTags: ['domain2'] } - ] + { sourceTag: 'domain2', onlyDependOnLibsWithTags: ['domain2'] }, + ], }; beforeEach(() => { @@ -359,7 +359,7 @@ describe('Enforce Module Boundaries', () => { it('should support wild cards', () => { const failures = runRule( { - depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }] + depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }], }, `${process.cwd()}/proj/libs/api/src/index.ts`, ` @@ -390,12 +390,12 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`libs/mylib/src/main.ts`), - createFile(`libs/mylib/other.ts`) - ] - } - } + createFile(`libs/mylib/other.ts`), + ], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toEqual(0); @@ -418,12 +418,12 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`libs/mylib/src/main.ts`), - createFile(`libs/mylib/other/index.ts`) - ] - } - } + createFile(`libs/mylib/other/index.ts`), + ], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toEqual(0); @@ -444,8 +444,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, otherName: { name: 'otherName', @@ -455,11 +455,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/other/src/index.ts')] - } - } + files: [createFile('libs/other/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures[0].message).toEqual( @@ -482,8 +482,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, otherName: { name: 'otherName', @@ -493,11 +493,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/other/src/index.ts')] - } - } + files: [createFile('libs/other/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures[0].message).toEqual( @@ -523,12 +523,12 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`libs/mylib/src/main.ts`), - createFile(`libs/mylib/src/other.ts`) - ] - } - } + createFile(`libs/mylib/src/other.ts`), + ], + }, + }, }, - dependencies: {} + dependencies: {}, } ); @@ -555,8 +555,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, utils: { name: 'utils', @@ -566,11 +566,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/utils/a.ts`)] - } - } + files: [createFile(`libs/utils/a.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toEqual(0); @@ -591,8 +591,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, otherName: { name: 'otherName', @@ -602,19 +602,19 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/other/index.ts`)] - } - } + files: [createFile(`libs/other/index.ts`)], + }, + }, }, dependencies: { mylibName: [ { source: 'mylibName', target: 'otherName', - type: DependencyType.dynamic - } - ] - } + type: DependencyType.dynamic, + }, + ], + }, } ); expect(failures[0].message).toEqual( @@ -637,8 +637,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, myappName: { name: 'myappName', @@ -648,11 +648,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`apps/myapp/src/index.ts`)] - } - } + files: [createFile(`apps/myapp/src/index.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures[0].message).toEqual('Imports of apps are forbidden'); @@ -673,8 +673,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, anotherlibName: { name: 'anotherlibName', @@ -684,8 +684,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/anotherlib/src/main.ts`)] - } + files: [createFile(`libs/anotherlib/src/main.ts`)], + }, }, myappName: { name: 'myappName', @@ -695,19 +695,19 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`apps/myapp/src/index.ts`)] - } - } + files: [createFile(`apps/myapp/src/index.ts`)], + }, + }, }, dependencies: { mylibName: [ { source: 'mylibName', target: 'anotherlibName', - type: DependencyType.static - } - ] - } + type: DependencyType.static, + }, + ], + }, } ); expect(failures[0].message).toEqual( @@ -730,8 +730,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, anotherlibName: { name: 'anotherlibName', @@ -741,8 +741,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/anotherlib/src/main.ts`)] - } + files: [createFile(`libs/anotherlib/src/main.ts`)], + }, }, badcirclelibName: { name: 'badcirclelibName', @@ -752,8 +752,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/badcirclelib/src/main.ts`)] - } + files: [createFile(`libs/badcirclelib/src/main.ts`)], + }, }, myappName: { name: 'myappName', @@ -763,33 +763,33 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`apps/myapp/index.ts`)] - } - } + files: [createFile(`apps/myapp/index.ts`)], + }, + }, }, dependencies: { mylibName: [ { source: 'mylibName', target: 'badcirclelibName', - type: DependencyType.static - } + type: DependencyType.static, + }, ], badcirclelibName: [ { source: 'badcirclelibName', target: 'anotherlibName', - type: DependencyType.static - } + type: DependencyType.static, + }, ], anotherlibName: [ { source: 'anotherlibName', target: 'mylibName', - type: DependencyType.static - } - ] - } + type: DependencyType.static, + }, + ], + }, } ); expect(failures[0].message).toEqual( @@ -801,7 +801,7 @@ describe('Enforce Module Boundaries', () => { it('should ignore the buildable library verification if the enforceBuildableLibDependency is set to false', () => { const failures = runRule( { - enforceBuildableLibDependency: false + enforceBuildableLibDependency: false, }, `${process.cwd()}/proj/libs/buildableLib/src/main.ts`, 'import "@mycompany/nonBuildableLib"', @@ -817,11 +817,11 @@ describe('Enforce Module Boundaries', () => { architect: { build: { // defines a buildable lib - builder: '@angular-devkit/build-ng-packagr:build' - } + builder: '@angular-devkit/build-ng-packagr:build', + }, }, - files: [createFile(`libs/buildableLib/src/main.ts`)] - } + files: [createFile(`libs/buildableLib/src/main.ts`)], + }, }, nonBuildableLib: { name: 'nonBuildableLib', @@ -831,11 +831,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/nonBuildableLib/src/main.ts`)] - } - } + files: [createFile(`libs/nonBuildableLib/src/main.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toBe(0); @@ -844,7 +844,7 @@ describe('Enforce Module Boundaries', () => { it('should error when buildable libraries import non-buildable libraries', () => { const failures = runRule( { - enforceBuildableLibDependency: true + enforceBuildableLibDependency: true, }, `${process.cwd()}/proj/libs/buildableLib/src/main.ts`, 'import "@mycompany/nonBuildableLib"', @@ -860,11 +860,11 @@ describe('Enforce Module Boundaries', () => { architect: { build: { // defines a buildable lib - builder: '@angular-devkit/build-ng-packagr:build' - } + builder: '@angular-devkit/build-ng-packagr:build', + }, }, - files: [createFile(`libs/buildableLib/src/main.ts`)] - } + files: [createFile(`libs/buildableLib/src/main.ts`)], + }, }, nonBuildableLib: { name: 'nonBuildableLib', @@ -874,11 +874,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/nonBuildableLib/src/main.ts`)] - } - } + files: [createFile(`libs/nonBuildableLib/src/main.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures[0].message).toEqual( @@ -889,7 +889,7 @@ describe('Enforce Module Boundaries', () => { it('should not error when buildable libraries import another buildable libraries', () => { const failures = runRule( { - enforceBuildableLibDependency: true + enforceBuildableLibDependency: true, }, `${process.cwd()}/proj/libs/buildableLib/src/main.ts`, 'import "@mycompany/nonBuildableLib"', @@ -905,11 +905,11 @@ describe('Enforce Module Boundaries', () => { architect: { build: { // defines a buildable lib - builder: '@angular-devkit/build-ng-packagr:build' - } + builder: '@angular-devkit/build-ng-packagr:build', + }, }, - files: [createFile(`libs/buildableLib/src/main.ts`)] - } + files: [createFile(`libs/buildableLib/src/main.ts`)], + }, }, nonBuildableLib: { name: 'nonBuildableLib', @@ -921,14 +921,14 @@ describe('Enforce Module Boundaries', () => { architect: { build: { // defines a buildable lib - builder: '@angular-devkit/build-ng-packagr:build' - } + builder: '@angular-devkit/build-ng-packagr:build', + }, }, - files: [createFile(`libs/nonBuildableLib/src/main.ts`)] - } - } + files: [createFile(`libs/nonBuildableLib/src/main.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toBe(0); @@ -937,7 +937,7 @@ describe('Enforce Module Boundaries', () => { it('should ignore the buildable library verification if no architect is specified', () => { const failures = runRule( { - enforceBuildableLibDependency: true + enforceBuildableLibDependency: true, }, `${process.cwd()}/proj/libs/buildableLib/src/main.ts`, 'import "@mycompany/nonBuildableLib"', @@ -950,8 +950,8 @@ describe('Enforce Module Boundaries', () => { root: 'libs/buildableLib', tags: [], implicitDependencies: [], - files: [createFile(`libs/buildableLib/src/main.ts`)] - } + files: [createFile(`libs/buildableLib/src/main.ts`)], + }, }, nonBuildableLib: { name: 'nonBuildableLib', @@ -960,11 +960,11 @@ describe('Enforce Module Boundaries', () => { root: 'libs/nonBuildableLib', tags: [], implicitDependencies: [], - files: [createFile(`libs/nonBuildableLib/src/main.ts`)] - } - } + files: [createFile(`libs/nonBuildableLib/src/main.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toBe(0); @@ -977,11 +977,11 @@ const baseConfig = { parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2018 as const, - sourceType: 'module' as const + sourceType: 'module' as const, }, rules: { - [enforceModuleBoundariesRuleName]: 'error' - } + [enforceModuleBoundariesRuleName]: 'error', + }, }; linter.defineParser('@typescript-eslint/parser', parser); linter.defineRule(enforceModuleBoundariesRuleName, enforceModuleBoundaries); @@ -1006,8 +1006,8 @@ function runRule( const config = { ...baseConfig, rules: { - [enforceModuleBoundariesRuleName]: ['error', ruleArguments] - } + [enforceModuleBoundariesRuleName]: ['error', ruleArguments], + }, }; return linter.verifyAndFix(content, config as any, contentPath).messages; diff --git a/packages/eslint-plugin-nx/tests/test-helper.ts b/packages/eslint-plugin-nx/tests/test-helper.ts index d4d5644669ea8..cd5cd229b8fe3 100644 --- a/packages/eslint-plugin-nx/tests/test-helper.ts +++ b/packages/eslint-plugin-nx/tests/test-helper.ts @@ -16,7 +16,7 @@ export class RuleTester extends TSESLint.RuleTester { constructor(options: RuleTesterConfig) { super({ ...options, - parser: require.resolve(options.parser) + parser: require.resolve(options.parser), }); if (options.parserOptions && options.parserOptions.project) { @@ -35,18 +35,18 @@ export class RuleTester extends TSESLint.RuleTester { const errorMessage = `Do not set the parser at the test level unless you want to use a parser other than ${parser}`; if (this.filename) { - tests.valid = tests.valid.map(test => { + tests.valid = tests.valid.map((test) => { if (typeof test === 'string') { return { code: test, - filename: this.filename + filename: this.filename, }; } return test; }); } - tests.valid.forEach(test => { + tests.valid.forEach((test) => { if (typeof test !== 'string') { if (test.parser === parser) { throw new Error(errorMessage); @@ -56,7 +56,7 @@ export class RuleTester extends TSESLint.RuleTester { } } }); - tests.invalid.forEach(test => { + tests.invalid.forEach((test) => { if (test.parser === parser) { throw new Error(errorMessage); } diff --git a/packages/express/src/schematics/application/application.ts b/packages/express/src/schematics/application/application.ts index 0472a80b37e71..a4e3c1a4c4990 100644 --- a/packages/express/src/schematics/application/application.ts +++ b/packages/express/src/schematics/application/application.ts @@ -3,7 +3,7 @@ import { externalSchematic, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { join, normalize, Path } from '@angular-devkit/core'; import { Schema } from './schema'; @@ -17,7 +17,7 @@ interface NormalizedSchema extends Schema { function addTypes(options: NormalizedSchema): Rule { const tsConfigPath = join(options.appProjectRoot, 'tsconfig.json'); - return updateJsonInTree(tsConfigPath, json => { + return updateJsonInTree(tsConfigPath, (json) => { json.compilerOptions.types = [...json.compilerOptions.types, 'express']; return json; }); @@ -50,7 +50,7 @@ server.on('error', console.error); }; } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(schema); return chain([ @@ -58,7 +58,7 @@ export default function(schema: Schema): Rule { externalSchematic('@nrwl/node', 'application', schema), addMainFile(options), addTypes(options), - formatFiles(options) + formatFiles(options), ])(host, context); }; } @@ -71,6 +71,6 @@ function normalizeOptions(options: Schema): NormalizedSchema { return { ...options, - appProjectRoot + appProjectRoot, }; } diff --git a/packages/express/src/schematics/init/init.spec.ts b/packages/express/src/schematics/init/init.spec.ts index 609ac237e34ae..8a984c584bbdd 100644 --- a/packages/express/src/schematics/init/init.spec.ts +++ b/packages/express/src/schematics/init/init.spec.ts @@ -46,7 +46,7 @@ describe('init', () => { const result = await runSchematic( 'init', { - unitTestRunner: 'none' + unitTestRunner: 'none', }, tree ); diff --git a/packages/express/src/schematics/init/init.ts b/packages/express/src/schematics/init/init.ts index 44dcd17fa12b2..6ed3c9c9789f9 100644 --- a/packages/express/src/schematics/init/init.ts +++ b/packages/express/src/schematics/init/init.ts @@ -2,30 +2,30 @@ import { chain, noop, Rule } from '@angular-devkit/schematics'; import { addPackageWithInit, formatFiles, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import { expressTypingsVersion, expressVersion, - nxVersion + nxVersion, } from '../../utils/versions'; import { Schema } from './schema'; import { setDefaultCollection } from '@nrwl/workspace/src/utils/rules/workspace'; function updateDependencies(): Rule { - return updateJsonInTree('package.json', json => { + return updateJsonInTree('package.json', (json) => { delete json.dependencies['@nrwl/express']; json.dependencies['express'] = expressVersion; json.devDependencies = { ...json.devDependencies, '@types/express': expressTypingsVersion, - '@nrwl/express': nxVersion + '@nrwl/express': nxVersion, }; return json; }); } -export default function(schema: Schema) { +export default function (schema: Schema) { return chain([ setDefaultCollection('@nrwl/express'), addPackageWithInit('@nrwl/node', schema), @@ -33,6 +33,6 @@ export default function(schema: Schema) { ? addPackageWithInit('@nrwl/jest') : noop(), updateDependencies(), - formatFiles(schema) + formatFiles(schema), ]); } diff --git a/packages/jest/plugins/resolver.ts b/packages/jest/plugins/resolver.ts index 9904b8ba629d5..d7145c7bfc880 100644 --- a/packages/jest/plugins/resolver.ts +++ b/packages/jest/plugins/resolver.ts @@ -37,7 +37,7 @@ function getCompilerSetup(rootDir: string) { let compilerSetup; -module.exports = function(path: string, options: ResolveOptions) { +module.exports = function (path: string, options: ResolveOptions) { const ext = extname(path); if ( ext === '.css' || diff --git a/packages/jest/src/builders/jest/jest.impl.spec.ts b/packages/jest/src/builders/jest/jest.impl.spec.ts index 990555f927d4a..4baf8af96496a 100644 --- a/packages/jest/src/builders/jest/jest.impl.spec.ts +++ b/packages/jest/src/builders/jest/jest.impl.spec.ts @@ -13,7 +13,7 @@ describe('Jest Builder', () => { runCLI = jest.fn(); jest.doMock('jest', () => ({ - runCLI + runCLI, })); const registry = new schema.CoreSchemaRegistry(); @@ -28,8 +28,8 @@ describe('Jest Builder', () => { runCLI.mockReturnValue( Promise.resolve({ results: { - success: true - } + success: true, + }, }) ); }); @@ -40,8 +40,8 @@ describe('Jest Builder', () => { '/root/jest.config.js', () => ({ transform: { - '^.+\\.[tj]sx?$': 'ts-jest' - } + '^.+\\.[tj]sx?$': 'ts-jest', + }, }), { virtual: true } ); @@ -51,11 +51,11 @@ describe('Jest Builder', () => { const run = await architect.scheduleBuilder('@nrwl/jest:jest', { jestConfig: './jest.config.js', tsConfig: './tsconfig.test.json', - watch: false + watch: false, }); expect(await run.result).toEqual( jasmine.objectContaining({ - success: true + success: true, }) ); expect(runCLI).toHaveBeenCalledWith( @@ -67,12 +67,12 @@ describe('Jest Builder', () => { stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: [ 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer' - ] - } + 'jest-preset-angular/build/StripStylesTransformer', + ], + }, }), testPathPattern: [], - watch: false + watch: false, }, ['/root/jest.config.js'] ); @@ -92,11 +92,11 @@ describe('Jest Builder', () => { verbose: false, coverageReporters: 'test', coverageDirectory: '/test/path', - watch: false + watch: false, }); expect(await run.result).toEqual( jasmine.objectContaining({ - success: true + success: true, }) ); @@ -109,9 +109,9 @@ describe('Jest Builder', () => { stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: [ 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer' - ] - } + 'jest-preset-angular/build/StripStylesTransformer', + ], + }, }), coverage: false, runInBand: true, @@ -122,7 +122,7 @@ describe('Jest Builder', () => { verbose: false, coverageReporters: 'test', coverageDirectory: '/test/path', - watch: false + watch: false, }, ['/root/jest.config.js'] ); @@ -136,11 +136,11 @@ describe('Jest Builder', () => { codeCoverage: false, runInBand: true, testNamePattern: 'should load', - watch: false + watch: false, }); expect(await run.result).toEqual( jasmine.objectContaining({ - success: true + success: true, }) ); @@ -153,16 +153,16 @@ describe('Jest Builder', () => { stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: [ 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer' - ] - } + 'jest-preset-angular/build/StripStylesTransformer', + ], + }, }), coverage: false, findRelatedTests: true, runInBand: true, testNamePattern: 'should load', testPathPattern: [], - watch: false + watch: false, }, ['/root/jest.config.js'] ); @@ -194,11 +194,11 @@ describe('Jest Builder', () => { useStderr: true, watch: false, watchAll: false, - testLocationInResults: true + testLocationInResults: true, }); expect(await run.result).toEqual( jasmine.objectContaining({ - success: true + success: true, }) ); expect(runCLI).toHaveBeenCalledWith( @@ -210,9 +210,9 @@ describe('Jest Builder', () => { stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: [ 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer' - ] - } + 'jest-preset-angular/build/StripStylesTransformer', + ], + }, }), coverage: true, bail: 1, @@ -236,7 +236,7 @@ describe('Jest Builder', () => { useStderr: true, watch: false, watchAll: false, - testLocationInResults: true + testLocationInResults: true, }, ['/root/jest.config.js'] ); @@ -247,11 +247,11 @@ describe('Jest Builder', () => { jestConfig: './jest.config.js', tsConfig: './tsconfig.test.json', setupFile: './test-setup.ts', - watch: false + watch: false, }); expect(await run.result).toEqual( jasmine.objectContaining({ - success: true + success: true, }) ); expect(runCLI).toHaveBeenCalledWith( @@ -263,27 +263,27 @@ describe('Jest Builder', () => { stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: [ 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer' - ] - } + 'jest-preset-angular/build/StripStylesTransformer', + ], + }, }), setupFilesAfterEnv: ['/root/test-setup.ts'], testPathPattern: [], - watch: false + watch: false, }, ['/root/jest.config.js'] ); }); - it('should return the proper result', async done => { + it('should return the proper result', async (done) => { const run = await architect.scheduleBuilder('@nrwl/jest:jest', { jestConfig: './jest.config.js', tsConfig: './tsconfig.test.json', - watch: false + watch: false, }); expect(await run.result).toEqual( jasmine.objectContaining({ - success: true + success: true, }) ); done(); @@ -296,9 +296,9 @@ describe('Jest Builder', () => { '/root/jest.config.js', () => ({ transform: { - '^.+\\.[tj]sx?$': 'ts-jest' + '^.+\\.[tj]sx?$': 'ts-jest', }, - globals: { hereToStay: true, 'ts-jest': { diagnostics: false } } + globals: { hereToStay: true, 'ts-jest': { diagnostics: false } }, }), { virtual: true } ); @@ -309,7 +309,7 @@ describe('Jest Builder', () => { jestConfig: './jest.config.js', tsConfig: './tsconfig.test.json', setupFile: './test-setup.ts', - watch: false + watch: false, }); expect(runCLI).toHaveBeenCalledWith( @@ -323,13 +323,13 @@ describe('Jest Builder', () => { stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: [ 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer' - ] - } + 'jest-preset-angular/build/StripStylesTransformer', + ], + }, }), setupFilesAfterEnv: ['/root/test-setup.ts'], testPathPattern: [], - watch: false + watch: false, }, ['/root/jest.config.js'] ); @@ -342,8 +342,8 @@ describe('Jest Builder', () => { '/root/jest.config.js', () => ({ transform: { - '^.+\\.[tj]sx?$': 'babel-jest' - } + '^.+\\.[tj]sx?$': 'babel-jest', + }, }), { virtual: true } ); @@ -353,13 +353,13 @@ describe('Jest Builder', () => { const options: JestBuilderOptions = { jestConfig: './jest.config.js', tsConfig: './tsconfig.test.json', - watch: false + watch: false, }; const run = await architect.scheduleBuilder('@nrwl/jest:jest', options); expect(await run.result).toEqual( jasmine.objectContaining({ - success: true + success: true, }) ); expect(runCLI).toHaveBeenCalledWith( @@ -367,7 +367,7 @@ describe('Jest Builder', () => { _: [], globals: '{}', testPathPattern: [], - watch: false + watch: false, }, ['/root/jest.config.js'] ); @@ -381,8 +381,8 @@ describe('Jest Builder', () => { () => ({ transform: { '^.+\\.tsx?$': 'ts-jest', - '^.+\\.jsx?$': 'babel-jest' - } + '^.+\\.jsx?$': 'babel-jest', + }, }), { virtual: true } ); @@ -392,7 +392,7 @@ describe('Jest Builder', () => { const options: JestBuilderOptions = { jestConfig: './jest.config.js', tsConfig: './tsconfig.test.json', - watch: false + watch: false, }; const run = await architect.scheduleBuilder('@nrwl/jest:jest', options); diff --git a/packages/jest/src/builders/jest/jest.impl.ts b/packages/jest/src/builders/jest/jest.impl.ts index 585e7c35eb871..3ebeceada75e2 100644 --- a/packages/jest/src/builders/jest/jest.impl.ts +++ b/packages/jest/src/builders/jest/jest.impl.ts @@ -1,7 +1,7 @@ import { BuilderContext, BuilderOutput, - createBuilder + createBuilder, } from '@angular-devkit/architect'; import { runCLI } from 'jest'; import * as path from 'path'; @@ -42,7 +42,7 @@ function run( const globals = jestConfig.globals || {}; if (!transformers.includes('babel-jest')) { const tsJestConfig = { - tsConfig: path.resolve(context.workspaceRoot, options.tsConfig) + tsConfig: path.resolve(context.workspaceRoot, options.tsConfig), }; // TODO: This is hacky, We should probably just configure it in the user's workspace @@ -53,8 +53,8 @@ function run( stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: [ 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer' - ] + 'jest-preset-angular/build/StripStylesTransformer', + ], }); } catch (e) {} @@ -62,8 +62,8 @@ function run( Object.assign(globals, { 'ts-jest': { ...(globals['ts-jest'] || {}), - ...tsJestConfig - } + ...tsJestConfig, + }, }); } @@ -93,12 +93,12 @@ function run( useStderr: options.useStderr, watch: options.watch, watchAll: options.watchAll, - globals: JSON.stringify(globals) + globals: JSON.stringify(globals), }; if (options.setupFile) { config.setupFilesAfterEnv = [ - path.resolve(context.workspaceRoot, options.setupFile) + path.resolve(context.workspaceRoot, options.setupFile), ]; } @@ -107,7 +107,9 @@ function run( } if (options.findRelatedTests) { - const parsedTests = options.findRelatedTests.split(',').map(s => s.trim()); + const parsedTests = options.findRelatedTests + .split(',') + .map((s) => s.trim()); config._.push(...parsedTests); config.findRelatedTests = true; } @@ -121,9 +123,9 @@ function run( } return from(runCLI(config, [options.jestConfig])).pipe( - map(results => { + map((results) => { return { - success: results.results.success + success: results.results.success, }; }) ); diff --git a/packages/jest/src/migrations/update-8-3-0/test-files/jest.config.js b/packages/jest/src/migrations/update-8-3-0/test-files/jest.config.js index caba6c4f7ce52..9b08aea993436 100644 --- a/packages/jest/src/migrations/update-8-3-0/test-files/jest.config.js +++ b/packages/jest/src/migrations/update-8-3-0/test-files/jest.config.js @@ -1,10 +1,10 @@ module.exports = { testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'], transform: { - '^.+\\.(ts|js|html)$': 'ts-jest' + '^.+\\.(ts|js|html)$': 'ts-jest', }, resolver: '@nrwl/jest/plugins/resolver', moduleFileExtensions: ['ts', 'js', 'html'], collectCoverage: true, - coverageReporters: ['html'] + coverageReporters: ['html'], }; diff --git a/packages/jest/src/migrations/update-8-3-0/update-8-3-0.spec.ts b/packages/jest/src/migrations/update-8-3-0/update-8-3-0.spec.ts index db0c7fe1a8a2f..87a651cd020d3 100644 --- a/packages/jest/src/migrations/update-8-3-0/update-8-3-0.spec.ts +++ b/packages/jest/src/migrations/update-8-3-0/update-8-3-0.spec.ts @@ -33,7 +33,7 @@ describe('Update 8.3.0', () => { expect(updatedJestConfigFile).not.toContain('collectCoverage: true'); //check if the file is still valid - expect(updatedJestConfigFile.match(/,/g) || []).toHaveLength(6); + expect(updatedJestConfigFile.match(/,/g) || []).toHaveLength(8); expect(updatedJestConfigFile).toContain('}'); expect(updatedJestConfigFile).toContain('{'); }); diff --git a/packages/jest/src/migrations/update-8-3-0/update-8-3-0.ts b/packages/jest/src/migrations/update-8-3-0/update-8-3-0.ts index 70bf76c4f8d66..4775f1820aded 100644 --- a/packages/jest/src/migrations/update-8-3-0/update-8-3-0.ts +++ b/packages/jest/src/migrations/update-8-3-0/update-8-3-0.ts @@ -3,7 +3,7 @@ import { insert, formatFiles } from '@nrwl/workspace'; import * as ts from 'typescript'; import { getSourceNodes, - RemoveChange + RemoveChange, } from '@nrwl/workspace/src/utils/ast-utils'; function updateJestConfig(host: Tree) { @@ -40,6 +40,6 @@ function updateJestConfig(host: Tree) { } } -export default function(): Rule { +export default function (): Rule { return chain([updateJestConfig, formatFiles()]); } diff --git a/packages/jest/src/migrations/update-8-7-0/update-8-7-0.spec.ts b/packages/jest/src/migrations/update-8-7-0/update-8-7-0.spec.ts index 93b5634e66c50..659d95f1f0b0f 100644 --- a/packages/jest/src/migrations/update-8-7-0/update-8-7-0.spec.ts +++ b/packages/jest/src/migrations/update-8-7-0/update-8-7-0.spec.ts @@ -26,21 +26,21 @@ describe('Update 8.7.0', () => { jest1: { builder: '@nrwl/jest:jest', options: { - testPathPattern: 'some/test/path' - } + testPathPattern: 'some/test/path', + }, }, jest2: { builder: '@nrwl/jest:jest', options: { - foo: 'bar' - } + foo: 'bar', + }, }, jest3: { - builder: '@nrwl/jest:jest' - } - } - } - } + builder: '@nrwl/jest:jest', + }, + }, + }, + }, }) ); diff --git a/packages/jest/src/migrations/update-8-7-0/update-8-7-0.ts b/packages/jest/src/migrations/update-8-7-0/update-8-7-0.ts index e01989f03a192..b7dcd893099f6 100644 --- a/packages/jest/src/migrations/update-8-7-0/update-8-7-0.ts +++ b/packages/jest/src/migrations/update-8-7-0/update-8-7-0.ts @@ -2,9 +2,9 @@ import { chain, Rule } from '@angular-devkit/schematics'; import { updateWorkspace } from '@nrwl/workspace/src/utils/workspace'; import { formatFiles } from '@nrwl/workspace'; -const convertToArray = updateWorkspace(workspace => { - workspace.projects.forEach(project => { - project.targets.forEach(target => { +const convertToArray = updateWorkspace((workspace) => { + workspace.projects.forEach((project) => { + project.targets.forEach((target) => { if ( target.builder === '@nrwl/jest:jest' && target.options && @@ -16,6 +16,6 @@ const convertToArray = updateWorkspace(workspace => { }); }); -export default function(): Rule { +export default function (): Rule { return chain([convertToArray, formatFiles()]); } diff --git a/packages/jest/src/migrations/update-9-0-0/update-9-0-0.spec.ts b/packages/jest/src/migrations/update-9-0-0/update-9-0-0.spec.ts index ce1707e879354..d25c5d6e4d98b 100644 --- a/packages/jest/src/migrations/update-9-0-0/update-9-0-0.spec.ts +++ b/packages/jest/src/migrations/update-9-0-0/update-9-0-0.spec.ts @@ -32,10 +32,10 @@ describe('Update 9.0.0', () => { test: { builder: '@nrwl/jest:jest', options: { - jestConfig: 'apps/angular-one/jest.config.js' - } - } - } + jestConfig: 'apps/angular-one/jest.config.js', + }, + }, + }, }, 'angular-two': { root: 'apps/angular-two/', @@ -43,10 +43,10 @@ describe('Update 9.0.0', () => { test: { builder: '@nrwl/jest:jest', options: { - jestConfig: 'apps/angular-two/jest.config.js' - } - } - } + jestConfig: 'apps/angular-two/jest.config.js', + }, + }, + }, }, 'non-angular-one': { root: 'apps/non-angular-one/', @@ -54,12 +54,12 @@ describe('Update 9.0.0', () => { test: { builder: '@nrwl/jest:jest', options: { - jestConfig: 'apps/non-angular-one/jest.config.js' - } - } - } - } - } + jestConfig: 'apps/non-angular-one/jest.config.js', + }, + }, + }, + }, + }, }) ); diff --git a/packages/jest/src/migrations/update-9-0-0/update-9-0-0.ts b/packages/jest/src/migrations/update-9-0-0/update-9-0-0.ts index 3099fc8f7b65e..245aae9f9f938 100644 --- a/packages/jest/src/migrations/update-9-0-0/update-9-0-0.ts +++ b/packages/jest/src/migrations/update-9-0-0/update-9-0-0.ts @@ -2,13 +2,13 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { formatFiles, insert, readWorkspace, - updatePackagesInPackageJson + updatePackagesInPackageJson, } from '@nrwl/workspace'; import * as ts from 'typescript'; import * as path from 'path'; @@ -17,7 +17,7 @@ import { getSourceNodes, InsertChange, readJsonInTree, - ReplaceChange + ReplaceChange, } from '@nrwl/workspace/src/utils/ast-utils'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; @@ -29,7 +29,7 @@ export default function update(): Rule { '9.0.0' ), updateJestConfigs, - formatFiles() + formatFiles(), ]); } @@ -54,12 +54,12 @@ function updateJestConfigs(host: Tree) { const workspaceConfig = readWorkspace(host); const jestConfigsToUpdate = []; - Object.values(workspaceConfig.projects).forEach(project => { + Object.values(workspaceConfig.projects).forEach((project) => { if (!project.architect) { return; } - Object.values(project.architect).forEach(target => { + Object.values(project.architect).forEach((target) => { if (target.builder !== '@nrwl/jest:jest') { return; } @@ -69,7 +69,7 @@ function updateJestConfigs(host: Tree) { } if (target.configurations) { - Object.values(target.configurations).forEach(config => { + Object.values(target.configurations).forEach((config) => { if (config.jestConfig) { jestConfigsToUpdate.push(config.jestConfig); } @@ -78,7 +78,7 @@ function updateJestConfigs(host: Tree) { }); }); - jestConfigsToUpdate.forEach(configPath => { + jestConfigsToUpdate.forEach((configPath) => { if (host.exists(configPath)) { const contents = host.read(configPath).toString(); const sourceFile = ts.createSourceFile( @@ -89,7 +89,7 @@ function updateJestConfigs(host: Tree) { const changes: Change[] = []; - getSourceNodes(sourceFile).forEach(node => { + getSourceNodes(sourceFile).forEach((node) => { if (node && ts.isStringLiteral(node)) { const nodeText = node.text; diff --git a/packages/jest/src/migrations/update-9-0-1/test-files/jest.config.js b/packages/jest/src/migrations/update-9-0-1/test-files/jest.config.js index ffd5ba20bfbc4..e4ee1a2b33936 100644 --- a/packages/jest/src/migrations/update-9-0-1/test-files/jest.config.js +++ b/packages/jest/src/migrations/update-9-0-1/test-files/jest.config.js @@ -1,10 +1,10 @@ module.exports = { testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'], transform: { - '^.+\\.(ts|js|html)$': 'ts-jest' + '^.+\\.(ts|js|html)$': 'ts-jest', }, resolver: '@nrwl/jest/plugins/resolver', moduleFileExtensions: ['ts', 'js', 'html'], coverageReporters: ['html'], - passWithNoTests: true + passWithNoTests: true, }; diff --git a/packages/jest/src/migrations/update-9-0-1/update-9-0-1.spec.ts b/packages/jest/src/migrations/update-9-0-1/update-9-0-1.spec.ts index 1d2f85f080d2c..30fa56ce0747e 100644 --- a/packages/jest/src/migrations/update-9-0-1/update-9-0-1.spec.ts +++ b/packages/jest/src/migrations/update-9-0-1/update-9-0-1.spec.ts @@ -36,7 +36,7 @@ describe('Update 9.0.1', () => { expect(updatedJestConfigFile).not.toContain('passWithNoTests: true'); //check if the file is still valid - expect(updatedJestConfigFile.match(/,/g) || []).toHaveLength(6); + expect(updatedJestConfigFile.match(/,/g) || []).toHaveLength(8); expect(updatedJestConfigFile).toContain('}'); expect(updatedJestConfigFile).toContain('{'); }); @@ -52,36 +52,36 @@ describe('Update 9.0.1', () => { test: { builder: '@nrwl/jest:jest', options: { - jestConfig: 'apps/angular-one/jest.config.js' - } - } - } + jestConfig: 'apps/angular-one/jest.config.js', + }, + }, + }, }, 'angular-two': { architect: { test: { builder: '@nrwl/jest:jest', options: { - passWithNoTests: false - } - } - } + passWithNoTests: false, + }, + }, + }, }, other1: { architect: { 'other-architect': { builder: 'other', options: { - foo: 'bar' - } + foo: 'bar', + }, }, test: { builder: '@nrwl/jest:jest', - options: {} - } - } - } - } + options: {}, + }, + }, + }, + }, }) ); @@ -118,24 +118,24 @@ describe('Update 9.0.1', () => { jest1: { builder: '@nrwl/jest:jest', options: { - foo: 'bar' - } + foo: 'bar', + }, }, jest2: { builder: '@nrwl/jest:jest', options: { foo: 'bar', - passWithNoTests: false - } + passWithNoTests: false, + }, }, other1: { options: { - foo: 'bar' - } - } - } - } - } + foo: 'bar', + }, + }, + }, + }, + }, }) ); diff --git a/packages/jest/src/migrations/update-9-0-1/update-9-0-1.ts b/packages/jest/src/migrations/update-9-0-1/update-9-0-1.ts index 95aab67707e18..2c6b466fee13c 100644 --- a/packages/jest/src/migrations/update-9-0-1/update-9-0-1.ts +++ b/packages/jest/src/migrations/update-9-0-1/update-9-0-1.ts @@ -3,7 +3,7 @@ import { formatFiles, insert } from '@nrwl/workspace'; import * as ts from 'typescript'; import { getSourceNodes, - RemoveChange + RemoveChange, } from '@nrwl/workspace/src/utils/ast-utils'; import { updateWorkspace } from '@nrwl/workspace/src/utils/workspace'; @@ -11,13 +11,13 @@ export default function update(): Rule { return chain([ addPassWithNoTestsToWorkspace, removePassWithNoTestsFromJestConfig, - formatFiles() + formatFiles(), ]); } -const addPassWithNoTestsToWorkspace = updateWorkspace(workspace => { - workspace.projects.forEach(project => { - project.targets.forEach(target => { +const addPassWithNoTestsToWorkspace = updateWorkspace((workspace) => { + workspace.projects.forEach((project) => { + project.targets.forEach((target) => { if ( target.builder === '@nrwl/jest:jest' && target.options && diff --git a/packages/jest/src/migrations/update-9-2-0/update-9-2-0.ts b/packages/jest/src/migrations/update-9-2-0/update-9-2-0.ts index 3d7650b88474a..4c6be6484ebd9 100644 --- a/packages/jest/src/migrations/update-9-2-0/update-9-2-0.ts +++ b/packages/jest/src/migrations/update-9-2-0/update-9-2-0.ts @@ -8,6 +8,6 @@ export default function update(): Rule { path.join(__dirname, '../../../', 'migrations.json'), '9.2.0' ), - formatFiles() + formatFiles(), ]); } diff --git a/packages/jest/src/schematics/init/init.ts b/packages/jest/src/schematics/init/init.ts index 6da1a194b12e1..1fd4250ad23c4 100644 --- a/packages/jest/src/schematics/init/init.ts +++ b/packages/jest/src/schematics/init/init.ts @@ -3,7 +3,7 @@ import { chain, Rule, Tree } from '@angular-devkit/schematics'; import { addDepsToPackageJson, readJsonInTree, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import { noop } from 'rxjs'; import { @@ -15,7 +15,7 @@ import { jestTypesVersion, jestVersion, nxVersion, - tsJestVersion + tsJestVersion, } from '../../utils/versions'; import { JestInitOptions } from './schema'; @@ -27,7 +27,7 @@ const removeNrwlJestFromDeps = (host: Tree) => { currentPackageJson.dependencies && currentPackageJson.dependencies['@nrwl/jest'] ) { - return updateJsonInTree('package.json', json => { + return updateJsonInTree('package.json', (json) => { json.dependencies = json.dependencies || {}; delete json.dependencies['@nrwl/jest']; return json; @@ -60,7 +60,7 @@ function updateDependencies(options: JestInitOptions): Rule { '@nrwl/jest': nxVersion, jest: jestVersion, '@types/jest': jestTypesVersion, - 'ts-jest': tsJestVersion + 'ts-jest': tsJestVersion, }; if (options.babelJest) { @@ -74,10 +74,10 @@ function updateDependencies(options: JestInitOptions): Rule { return addDepsToPackageJson({}, devDeps); } -export default function(options: JestInitOptions): Rule { +export default function (options: JestInitOptions): Rule { return chain([ createJestConfig, updateDependencies(options), - removeNrwlJestFromDeps + removeNrwlJestFromDeps, ]); } diff --git a/packages/jest/src/schematics/jest-project/jest-project.spec.ts b/packages/jest/src/schematics/jest-project/jest-project.spec.ts index 7aa5185b59036..5f8bfd25c4e3f 100644 --- a/packages/jest/src/schematics/jest-project/jest-project.spec.ts +++ b/packages/jest/src/schematics/jest-project/jest-project.spec.ts @@ -10,28 +10,28 @@ describe('jestProject', () => { appTree = Tree.empty(); appTree = createEmptyWorkspace(appTree); appTree = await callRule( - updateJsonInTree('workspace.json', json => { + updateJsonInTree('workspace.json', (json) => { json.projects.lib1 = { root: 'libs/lib1', architect: { lint: { builder: '@angular-devkit/build-angular:tslint', options: { - tsConfig: [] - } - } - } + tsConfig: [], + }, + }, + }, }; return json; }), appTree ); appTree = await callRule( - updateJsonInTree('libs/lib1/tsconfig.json', json => { + updateJsonInTree('libs/lib1/tsconfig.json', (json) => { return { compilerOptions: { - types: [] - } + types: [], + }, }; }), appTree @@ -43,7 +43,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - setupFile: 'angular' + setupFile: 'angular', }, appTree ); @@ -57,7 +57,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - setupFile: 'angular' + setupFile: 'angular', }, appTree ); @@ -68,8 +68,8 @@ describe('jestProject', () => { jestConfig: 'libs/lib1/jest.config.js', setupFile: 'libs/lib1/src/test-setup.ts', tsConfig: 'libs/lib1/tsconfig.spec.json', - passWithNoTests: true - } + passWithNoTests: true, + }, }); expect( workspaceJson.projects.lib1.architect.lint.options.tsConfig @@ -80,7 +80,7 @@ describe('jestProject', () => { const resultTree = await runSchematic( 'jest-project', { - project: 'lib1' + project: 'lib1', }, appTree ); @@ -102,7 +102,7 @@ describe('jestProject', () => { const resultTree = await runSchematic( 'jest-project', { - project: 'lib1' + project: 'lib1', }, appTree ); @@ -116,7 +116,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - setupFile: 'angular' + setupFile: 'angular', }, appTree ); @@ -126,10 +126,10 @@ describe('jestProject', () => { compilerOptions: { module: 'commonjs', outDir: '../../dist/out-tsc', - types: ['jest', 'node'] + types: ['jest', 'node'], }, files: ['src/test-setup.ts'], - include: ['**/*.spec.ts', '**/*.d.ts'] + include: ['**/*.spec.ts', '**/*.d.ts'], }); }); @@ -140,7 +140,7 @@ describe('jestProject', () => { { project: 'lib1', setupFile: 'none', - babelJest: true + babelJest: true, }, appTree ); @@ -155,7 +155,7 @@ describe('jestProject', () => { { project: 'lib1', setupFile: 'none', - babelJest: false + babelJest: false, }, appTree ); @@ -171,7 +171,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - setupFile: 'none' + setupFile: 'none', }, appTree ); @@ -183,7 +183,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - setupFile: 'none' + setupFile: 'none', }, appTree ); @@ -198,7 +198,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - setupFile: 'none' + setupFile: 'none', }, appTree ); @@ -216,7 +216,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - skipSetupFile: true + skipSetupFile: true, }, appTree ); @@ -228,7 +228,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - skipSetupFile: true + skipSetupFile: true, }, appTree ); @@ -243,7 +243,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - skipSetupFile: true + skipSetupFile: true, }, appTree ); @@ -261,7 +261,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - skipSerializers: true + skipSerializers: true, }, appTree ); @@ -282,7 +282,7 @@ describe('jestProject', () => { 'jest-project', { project: 'lib1', - supportTsx: true + supportTsx: true, }, appTree ); diff --git a/packages/jest/src/schematics/jest-project/jest-project.ts b/packages/jest/src/schematics/jest-project/jest-project.ts index 99ef393b09605..2fa04ec0c85be 100644 --- a/packages/jest/src/schematics/jest-project/jest-project.ts +++ b/packages/jest/src/schematics/jest-project/jest-project.ts @@ -17,17 +17,17 @@ function normalizeOptions(options: JestProjectSchema): JestProjectSchema { return { ...options, - setupFile: 'none' + setupFile: 'none', }; } -export default function(options: JestProjectSchema): Rule { +export default function (options: JestProjectSchema): Rule { options = normalizeOptions(options); return chain([ init(options), checkForTestTarget(options), generateFiles(options), updateTsConfig(options), - updateWorkspace(options) + updateWorkspace(options), ]); } diff --git a/packages/jest/src/schematics/jest-project/lib/generate-files.ts b/packages/jest/src/schematics/jest-project/lib/generate-files.ts index 80e6a7c63e475..bed2bf5aea212 100644 --- a/packages/jest/src/schematics/jest-project/lib/generate-files.ts +++ b/packages/jest/src/schematics/jest-project/lib/generate-files.ts @@ -8,7 +8,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { getProjectConfig, offsetFromRoot } from '@nrwl/workspace'; import { JestProjectSchema } from '../schema'; @@ -24,15 +24,15 @@ export function generateFiles(options: JestProjectSchema): Rule { ...options, transformer: options.babelJest ? 'babel-jest' : 'ts-jest', projectRoot: projectConfig.root, - offsetFromRoot: offsetFromRoot(projectConfig.root) + offsetFromRoot: offsetFromRoot(projectConfig.root), }), options.setupFile === 'none' - ? filter(file => file !== '/src/test-setup.ts') + ? filter((file) => file !== '/src/test-setup.ts') : noop(), options.babelJest ? noop() - : filter(file => file != '/babel-jest.config.json'), - move(projectConfig.root) + : filter((file) => file != '/babel-jest.config.json'), + move(projectConfig.root), ]) ); }; diff --git a/packages/jest/src/schematics/jest-project/lib/update-tsconfig.ts b/packages/jest/src/schematics/jest-project/lib/update-tsconfig.ts index f35d67176dc81..feb308917cbde 100644 --- a/packages/jest/src/schematics/jest-project/lib/update-tsconfig.ts +++ b/packages/jest/src/schematics/jest-project/lib/update-tsconfig.ts @@ -14,16 +14,19 @@ export function updateTsConfig(options: JestProjectSchema): Rule { )} to exist. Please create one.` ); } - return updateJsonInTree(join(projectConfig.root, 'tsconfig.json'), json => { - return { - ...json, - compilerOptions: { - ...json.compilerOptions, - types: Array.from( - new Set([...(json.compilerOptions.types || []), 'node', 'jest']) - ) - } - }; - }); + return updateJsonInTree( + join(projectConfig.root, 'tsconfig.json'), + (json) => { + return { + ...json, + compilerOptions: { + ...json.compilerOptions, + types: Array.from( + new Set([...(json.compilerOptions.types || []), 'node', 'jest']) + ), + }, + }; + } + ); }; } diff --git a/packages/jest/src/schematics/jest-project/lib/update-workspace.ts b/packages/jest/src/schematics/jest-project/lib/update-workspace.ts index ddf608717b4c4..b39eb4ca7a753 100644 --- a/packages/jest/src/schematics/jest-project/lib/update-workspace.ts +++ b/packages/jest/src/schematics/jest-project/lib/update-workspace.ts @@ -4,15 +4,15 @@ import { updateWorkspaceInTree } from '@nrwl/workspace'; import { JestProjectSchema } from '../schema'; export function updateWorkspace(options: JestProjectSchema): Rule { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const projectConfig = json.projects[options.project]; projectConfig.architect.test = { builder: '@nrwl/jest:jest', options: { jestConfig: join(normalize(projectConfig.root), 'jest.config.js'), tsConfig: join(normalize(projectConfig.root), 'tsconfig.spec.json'), - passWithNoTests: true - } + passWithNoTests: true, + }, }; if (options.setupFile !== 'none') { projectConfig.architect.test.options.setupFile = join( @@ -23,7 +23,7 @@ export function updateWorkspace(options: JestProjectSchema): Rule { if (projectConfig.architect.lint) { projectConfig.architect.lint.options.tsConfig = [ ...projectConfig.architect.lint.options.tsConfig, - join(normalize(projectConfig.root), 'tsconfig.spec.json') + join(normalize(projectConfig.root), 'tsconfig.spec.json'), ]; } return json; diff --git a/packages/linter/src/builders/lint/lint.impl.spec.ts b/packages/linter/src/builders/lint/lint.impl.spec.ts index 59c9306085683..67af86ab9e43f 100644 --- a/packages/linter/src/builders/lint/lint.impl.spec.ts +++ b/packages/linter/src/builders/lint/lint.impl.spec.ts @@ -25,15 +25,15 @@ function mockEslint() { loadESLint: () => ({ CLIEngine: MockCliEngine, Linter: { - version: mockEslintVersion - } - }) + version: mockEslintVersion, + }, + }), })); } function mockCreateProgram() { jest.doMock('./utility/ts-utils', () => ({ - createProgram: jest.fn().mockImplementation(path => path + '-program') + createProgram: jest.fn().mockImplementation((path) => path + '-program'), })); } @@ -56,7 +56,7 @@ async function runBuilder(options: JsonObject) { const logger = new logging.Logger(''); logger.subscribe(loggerSpy); const run = await architect.scheduleBuilder('@nrwl/linter:lint', options, { - logger + logger, }); return run.result; @@ -76,7 +76,7 @@ describe('Linter Builder', () => { const result = runBuilder({ linter: 'eslint', config: './.eslintrc', - files: [] + files: [], }); await expect(result).rejects.toThrow( /ESLint must be version 6.1 or higher/ @@ -89,7 +89,7 @@ describe('Linter Builder', () => { const result = runBuilder({ linter: 'eslint', config: './.eslintrc', - files: [] + files: [], }); await expect(result).resolves.not.toThrow(); }); @@ -98,7 +98,7 @@ describe('Linter Builder', () => { const result = runBuilder({ linter: 'tslint', config: './.eslintrc', - files: [] + files: [], }); await expect(result).rejects.toThrow( /'tslint' option is no longer supported/ @@ -113,7 +113,7 @@ describe('Linter Builder', () => { await runBuilder({ linter: 'eslint', config: './.eslintrc', - tsConfig: './tsconfig.json' + tsConfig: './tsconfig.json', }); expect(createProgram).toHaveBeenCalledTimes(1); expect(createProgram).toHaveBeenCalledWith('/root/tsconfig.json'); @@ -134,7 +134,7 @@ describe('Linter Builder', () => { await runBuilder({ linter: 'eslint', config: './.eslintrc', - tsConfig: ['./tsconfig.json', './tsconfig2.json'] + tsConfig: ['./tsconfig.json', './tsconfig2.json'], }); expect(createProgram).toHaveBeenCalledTimes(2); expect(createProgram).toHaveBeenNthCalledWith(1, '/root/tsconfig.json'); @@ -166,7 +166,7 @@ describe('Linter Builder', () => { await runBuilder({ linter: 'eslint', config: './.eslintrc', - files: [] + files: [], }); expect(createProgram).not.toHaveBeenCalled(); expect(lint).toHaveBeenCalledTimes(1); @@ -189,7 +189,7 @@ describe('Linter Builder', () => { exclude: ['excludedFile1'], fix: true, cache: true, - cacheLocation: 'cacheLocation1' + cacheLocation: 'cacheLocation1', }); expect(lint).toHaveBeenCalledWith( expect.anything(), @@ -206,7 +206,7 @@ describe('Linter Builder', () => { linter: 'eslint', outputFile: undefined, silent: false, - tsConfig: undefined + tsConfig: undefined, }, expect.any(Set) ); @@ -217,7 +217,7 @@ describe('Linter Builder', () => { const result = runBuilder({ linter: 'eslint', config: './.eslintrc', - files: ['includedFile1'] + files: ['includedFile1'], }); await expect(result).rejects.toThrow( /Invalid lint configuration. Nothing to lint./ @@ -229,14 +229,14 @@ describe('Linter Builder', () => { linter: 'eslint', config: './.eslintrc', files: ['includedFile1'], - format: 'json' + format: 'json', }); expect(mockGetFormatter).toHaveBeenCalledWith('json'); await runBuilder({ linter: 'eslint', config: './.eslintrc', files: ['includedFile1'], - format: 'html' + format: 'html', }); expect(mockGetFormatter).toHaveBeenCalledWith('html'); }); @@ -247,7 +247,7 @@ describe('Linter Builder', () => { config: './.eslintrc', files: ['includedFile1'], format: 'json', - fix: false + fix: false, }); expect(mockOutputFixes).toHaveBeenCalled(); }); @@ -259,14 +259,14 @@ describe('Linter Builder', () => { errorCount: 1, warningCount: 4, results: [], - usedDeprecatedRules: [] + usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], - usedDeprecatedRules: [] - } + usedDeprecatedRules: [], + }, ]; setupMocks(); await runBuilder({ @@ -274,7 +274,7 @@ describe('Linter Builder', () => { config: './.eslintrc', files: ['includedFile1'], format: 'json', - silent: false + silent: false, }); const flattenedCalls = loggerSpy.mock.calls.reduce((logs, call) => { return [...logs, call[0]]; @@ -283,14 +283,14 @@ describe('Linter Builder', () => { expect.objectContaining({ message: expect.stringContaining( 'Lint errors found in the listed files.' - ) + ), }) ); expect(flattenedCalls).toContainEqual( expect.objectContaining({ message: expect.stringContaining( 'Lint warnings found in the listed files.' - ) + ), }) ); }); @@ -300,14 +300,14 @@ describe('Linter Builder', () => { errorCount: 0, warningCount: 0, results: [], - usedDeprecatedRules: [] + usedDeprecatedRules: [], }, { errorCount: 0, warningCount: 0, results: [], - usedDeprecatedRules: [] - } + usedDeprecatedRules: [], + }, ]; setupMocks(); const output = await runBuilder({ @@ -315,7 +315,7 @@ describe('Linter Builder', () => { config: './.eslintrc', files: ['includedFile1'], format: 'json', - silent: false + silent: false, }); const flattenedCalls = loggerSpy.mock.calls.reduce((logs, call) => { return [...logs, call[0]]; @@ -324,19 +324,19 @@ describe('Linter Builder', () => { expect.objectContaining({ message: expect.stringContaining( 'Lint errors found in the listed files.' - ) + ), }) ); expect(flattenedCalls).not.toContainEqual( expect.objectContaining({ message: expect.stringContaining( 'Lint warnings found in the listed files.' - ) + ), }) ); expect(flattenedCalls).toContainEqual( expect.objectContaining({ - message: expect.stringContaining('All files pass linting.') + message: expect.stringContaining('All files pass linting.'), }) ); }); @@ -345,14 +345,14 @@ describe('Linter Builder', () => { setupMocks(); jest.spyOn(fs, 'writeFileSync').mockImplementation(); jest.mock('@nrwl/workspace', () => ({ - createDirectory: jest.fn() + createDirectory: jest.fn(), })); const { createDirectory } = require('@nrwl/workspace'); await runBuilder({ linter: 'eslint', config: './.eslintrc', files: ['includedFile1'], - outputFile: 'a/b/c/outputFile1' + outputFile: 'a/b/c/outputFile1', }); expect(createDirectory).toHaveBeenCalledWith('/root/a/b/c'); expect(fs.writeFileSync).toHaveBeenCalledWith( @@ -366,7 +366,7 @@ describe('Linter Builder', () => { await runBuilder({ linter: 'eslint', config: './.eslintrc', - files: ['includedFile1'] + files: ['includedFile1'], }); expect(fs.writeFileSync).not.toHaveBeenCalled(); }); @@ -376,14 +376,14 @@ describe('Linter Builder', () => { errorCount: 1, warningCount: 4, results: [], - usedDeprecatedRules: [] + usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], - usedDeprecatedRules: [] - } + usedDeprecatedRules: [], + }, ]; setupMocks(); const output = await runBuilder({ @@ -391,7 +391,7 @@ describe('Linter Builder', () => { config: './.eslintrc', files: ['includedFile1'], format: 'json', - silent: true + silent: true, }); const flattenedCalls = loggerSpy.mock.calls.reduce((logs, call) => { return [...logs, call[0]]; @@ -400,14 +400,14 @@ describe('Linter Builder', () => { expect.objectContaining({ message: expect.stringContaining( 'Lint errors found in the listed files.' - ) + ), }) ); expect(flattenedCalls).not.toContainEqual( expect.objectContaining({ message: expect.stringContaining( 'Lint warnings found in the listed files.' - ) + ), }) ); }); @@ -419,14 +419,14 @@ describe('Linter Builder', () => { errorCount: 0, warningCount: 4, results: [], - usedDeprecatedRules: [] + usedDeprecatedRules: [], }, { errorCount: 0, warningCount: 6, results: [], - usedDeprecatedRules: [] - } + usedDeprecatedRules: [], + }, ]; setupMocks(); const output = await runBuilder({ @@ -434,7 +434,7 @@ describe('Linter Builder', () => { config: './.eslintrc', files: ['includedFile1'], format: 'json', - silent: true + silent: true, }); expect(output.success).toBeTruthy(); }); @@ -444,14 +444,14 @@ describe('Linter Builder', () => { errorCount: 2, warningCount: 4, results: [], - usedDeprecatedRules: [] + usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], - usedDeprecatedRules: [] - } + usedDeprecatedRules: [], + }, ]; setupMocks(); const output = await runBuilder({ @@ -460,7 +460,7 @@ describe('Linter Builder', () => { files: ['includedFile1'], format: 'json', silent: true, - force: true + force: true, }); expect(output.success).toBeTruthy(); }); @@ -470,14 +470,14 @@ describe('Linter Builder', () => { errorCount: 2, warningCount: 4, results: [], - usedDeprecatedRules: [] + usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], - usedDeprecatedRules: [] - } + usedDeprecatedRules: [], + }, ]; setupMocks(); const output = await runBuilder({ @@ -486,7 +486,7 @@ describe('Linter Builder', () => { files: ['includedFile1'], format: 'json', silent: true, - force: false + force: false, }); expect(output.success).toBeFalsy(); }); diff --git a/packages/linter/src/builders/lint/lint.impl.ts b/packages/linter/src/builders/lint/lint.impl.ts index c14e988cd583e..48eed9fc44e58 100644 --- a/packages/linter/src/builders/lint/lint.impl.ts +++ b/packages/linter/src/builders/lint/lint.impl.ts @@ -66,14 +66,14 @@ async function run(options: Schema, context: BuilderContext): Promise { lintedFiles, program, allPrograms - )) + )), ]; context.reportProgress(++i, allPrograms.length); } } else { lintReports = [ ...lintReports, - ...(await lint(systemRoot, eslintConfigPath, options, lintedFiles)) + ...(await lint(systemRoot, eslintConfigPath, options, lintedFiles)), ]; } @@ -91,7 +91,7 @@ async function run(options: Schema, context: BuilderContext): Promise { fixableWarningCount: 0, warningCount: 0, results: [], - usedDeprecatedRules: [] + usedDeprecatedRules: [], }; for (const report of lintReports) { // output fixes to disk @@ -132,7 +132,7 @@ async function run(options: Schema, context: BuilderContext): Promise { } return { - success: options.force || bundledReport.errorCount === 0 + success: options.force || bundledReport.errorCount === 0, }; } diff --git a/packages/linter/src/builders/lint/utility/eslint-utils.spec.ts b/packages/linter/src/builders/lint/utility/eslint-utils.spec.ts index 5d2c84e1889df..4617a20a0332c 100644 --- a/packages/linter/src/builders/lint/utility/eslint-utils.spec.ts +++ b/packages/linter/src/builders/lint/utility/eslint-utils.spec.ts @@ -1,21 +1,21 @@ jest.mock('./file-utils', () => ({ - getFilesToLint: jest.fn() + getFilesToLint: jest.fn(), })); jest.mock('eslint', () => ({ - CLIEngine: jest.fn() + CLIEngine: jest.fn(), })); const { CLIEngine } = require('eslint'); (CLIEngine).mockImplementation(() => ({ - executeOnFiles: (args: string[]) => args + executeOnFiles: (args: string[]) => args, })); const { lint } = require('./eslint-utils'); function prog(sourceFile: string) { return { - getSourceFile: (file: string) => (sourceFile === file ? true : undefined) + getSourceFile: (file: string) => (sourceFile === file ? true : undefined), }; } @@ -53,7 +53,7 @@ describe('eslint-util', () => { useEslintrc: false, fix: true, cache: true, - cacheLocation: '/root/cache' + cacheLocation: '/root/cache', }); }); it('should not lint the same files twice', async () => { @@ -63,7 +63,7 @@ describe('eslint-util', () => { 'file2', 'file1', 'file3', - 'file4' + 'file4', ]); const lintedFiles = new Set(); lintedFiles.add('file4'); @@ -81,7 +81,7 @@ describe('eslint-util', () => { 'file1', 'file2', 'file1', - 'file3' + 'file3', ]); const program = prog('file8'); const allPrograms = [prog('file1'), prog('file2')]; @@ -104,7 +104,7 @@ describe('eslint-util', () => { 'file1', 'file2', 'file1', - 'file3' + 'file3', ]); const program = prog('file2'); const allPrograms = [prog('file1'), prog('file2'), prog('file3')]; diff --git a/packages/linter/src/builders/lint/utility/eslint-utils.ts b/packages/linter/src/builders/lint/utility/eslint-utils.ts index 6bb75f5c7fdd5..fe177efc31da8 100644 --- a/packages/linter/src/builders/lint/utility/eslint-utils.ts +++ b/packages/linter/src/builders/lint/utility/eslint-utils.ts @@ -36,7 +36,7 @@ export async function lint( useEslintrc: false, fix: !!options.fix, cache: !!options.cache, - cacheLocation: options.cacheLocation + cacheLocation: options.cacheLocation, }); const lintReports: CLIEngine.LintReport[] = []; @@ -44,7 +44,7 @@ export async function lint( for (const file of files) { if (program && allPrograms) { // If it cannot be found in ANY program, then this is an error. - if (allPrograms.every(p => p.getSourceFile(file) === undefined)) { + if (allPrograms.every((p) => p.getSourceFile(file) === undefined)) { throw new Error( `File ${JSON.stringify(file)} is not part of a TypeScript project '${ options.tsConfig diff --git a/packages/linter/src/builders/lint/utility/file-utils.spec.ts b/packages/linter/src/builders/lint/utility/file-utils.spec.ts index df31af964b737..528c1a6e4b40a 100644 --- a/packages/linter/src/builders/lint/utility/file-utils.spec.ts +++ b/packages/linter/src/builders/lint/utility/file-utils.spec.ts @@ -1,11 +1,11 @@ jest.mock('glob', () => ({ - sync: jest.fn().mockImplementation(file => file) + sync: jest.fn().mockImplementation((file) => file), })); jest.mock('path', () => ({ join: (...paths) => paths.join('/'), - normalize: path => path, - relative: (...paths) => paths[1] + normalize: (path) => path, + relative: (...paths) => paths[1], })); const { sync } = require('glob'); @@ -18,12 +18,12 @@ describe('file-utility', () => { expect(sync).toHaveBeenNthCalledWith(1, 'file1', { cwd: '/root', ignore: ['file2'], - nodir: true + nodir: true, }); expect(sync).toHaveBeenNthCalledWith(2, 'file2', { cwd: '/root', ignore: ['file2'], - nodir: true + nodir: true, }); expect(toLint).toEqual(['/root/file1', '/root/file2']); }); @@ -38,11 +38,11 @@ describe('file-utility', () => { { fileName: 'foo.d.ts', isFromExternalLib: false }, { fileName: 'foo.json', isFromExternalLib: false }, { fileName: 'bar.ts', isFromExternalLib: true }, - { fileName: 'bar.ts', isFromExternalLib: false } + { fileName: 'bar.ts', isFromExternalLib: false }, ]; const program = { getSourceFiles: () => sourceFiles, - isSourceFileFromExternalLibrary: (file: any) => file.isFromExternalLib + isSourceFileFromExternalLibrary: (file: any) => file.isFromExternalLib, }; const toLint = getFilesToLint('/root', {}, program); expect(toLint).toEqual(['foo.ts', 'bar.ts']); @@ -51,12 +51,12 @@ describe('file-utility', () => { const sourceFiles = [ { fileName: 'foo.ts' }, { fileName: 'bar.spec.ts' }, - { fileName: 'bar.ts' } + { fileName: 'bar.ts' }, ]; const exclude = ['*.spec.ts']; const program = { getSourceFiles: () => sourceFiles, - isSourceFileFromExternalLibrary: () => false + isSourceFileFromExternalLibrary: () => false, }; const toLint = getFilesToLint('/root', { exclude }, program); expect(toLint).toEqual(['foo.ts', 'bar.ts']); diff --git a/packages/linter/src/builders/lint/utility/file-utils.ts b/packages/linter/src/builders/lint/utility/file-utils.ts index 4f0c7cea1fac4..1b37c79afe3bd 100644 --- a/packages/linter/src/builders/lint/utility/file-utils.ts +++ b/packages/linter/src/builders/lint/utility/file-utils.ts @@ -30,7 +30,7 @@ function mapDefined( * `resolveJsonModule`. */ function getFileNamesFromProgram(program: ts.Program): string[] { - return mapDefined(program.getSourceFiles(), file => + return mapDefined(program.getSourceFiles(), (file) => file.fileName.endsWith('.d.ts') || file.fileName.endsWith('.json') || program.isSourceFileFromExternalLibrary(file) @@ -49,9 +49,9 @@ export function getFilesToLint( if (files.length > 0) { return files - .map(file => glob.sync(file, { cwd: root, ignore, nodir: true })) + .map((file) => glob.sync(file, { cwd: root, ignore, nodir: true })) .reduce((prev, curr) => prev.concat(curr), []) - .map(file => path.join(root, file)); + .map((file) => path.join(root, file)); } if (!program) { diff --git a/packages/linter/src/builders/lint/utility/ts-utils.spec.ts b/packages/linter/src/builders/lint/utility/ts-utils.spec.ts index c7347a0e12e90..9c32a7bf8c8d9 100644 --- a/packages/linter/src/builders/lint/utility/ts-utils.spec.ts +++ b/packages/linter/src/builders/lint/utility/ts-utils.spec.ts @@ -8,17 +8,17 @@ jest.mock('typescript', () => ({ parseJsonConfigFileContent: mockParseJsonConfigFileContent, formatDiagnostics: jest.fn().mockReturnValue('error details'), createCompilerHost: jest.fn(), - createProgram: jest.fn() + createProgram: jest.fn(), })); jest.mock('path', () => ({ dirname: jest.fn(), - resolve: jest.fn().mockReturnValue('proj-dir') + resolve: jest.fn().mockReturnValue('proj-dir'), })); jest.mock('fs', () => ({ readFileSync: jest.fn().mockReturnValue('fs-read-file'), - existsSync: () => {} + existsSync: () => {}, })); const ts = require('typescript'); @@ -28,7 +28,7 @@ describe('ts-utility', () => { beforeEach(() => { jest.clearAllMocks(); mockReadConfigFile.mockReturnValue({ - config: 'read-config-file' + config: 'read-config-file', }); }); it('should read and parse config file', () => { @@ -40,7 +40,7 @@ describe('ts-utility', () => { fileExists: expect.any(Function), readDirectory: 'sys-dir', readFile: expect.any(Function), - useCaseSensitiveFileNames: true + useCaseSensitiveFileNames: true, }), 'proj-dir', { noEmit: true } @@ -59,8 +59,8 @@ describe('ts-utility', () => { errors: [ { category: 'diag-categ-error', code: 1 }, { category: 'unexpected-category', code: 1 }, - { category: 'diag-categ-error', code: 18003 } - ] + { category: 'diag-categ-error', code: 18003 }, + ], }); try { createProgram('tsconfig-1'); @@ -79,8 +79,8 @@ describe('ts-utility', () => { errors: [ { category: 'diag-categ-error', code: 18003 }, { category: 'unexpected-category', code: 1 }, - { category: 'diag-categ-error', code: 18003 } - ] + { category: 'diag-categ-error', code: 18003 }, + ], }); expect(() => createProgram('tsconfig-1')).not.toThrow(); }); diff --git a/packages/linter/src/builders/lint/utility/ts-utils.ts b/packages/linter/src/builders/lint/utility/ts-utils.ts index 6c752af8cee79..7ac3f7cabb6f0 100644 --- a/packages/linter/src/builders/lint/utility/ts-utils.ts +++ b/packages/linter/src/builders/lint/utility/ts-utils.ts @@ -45,17 +45,17 @@ export function createProgram( if (config.error !== undefined) { throw new FatalError( ts.formatDiagnostics([config.error], { - getCanonicalFileName: f => f, + getCanonicalFileName: (f) => f, getCurrentDirectory: process.cwd, - getNewLine: () => '\n' + getNewLine: () => '\n', }) ); } const parseConfigHost: ts.ParseConfigHost = { fileExists: existsSync, readDirectory: ts.sys.readDirectory, - readFile: file => readFileSync(file, 'utf8'), - useCaseSensitiveFileNames: true + readFile: (file) => readFileSync(file, 'utf8'), + useCaseSensitiveFileNames: true, }; const parsed = ts.parseJsonConfigFileContent( config.config, @@ -66,14 +66,14 @@ export function createProgram( if (parsed.errors !== undefined) { // ignore warnings and 'TS18003: No inputs were found in config file ...' const errors = parsed.errors.filter( - d => d.category === ts.DiagnosticCategory.Error && d.code !== 18003 + (d) => d.category === ts.DiagnosticCategory.Error && d.code !== 18003 ); if (errors.length !== 0) { throw new FatalError( ts.formatDiagnostics(errors, { - getCanonicalFileName: f => f, + getCanonicalFileName: (f) => f, getCurrentDirectory: process.cwd, - getNewLine: () => '\n' + getNewLine: () => '\n', }) ); } diff --git a/packages/nest/src/migrations/update-8-7-0/update-8-7-0.ts b/packages/nest/src/migrations/update-8-7-0/update-8-7-0.ts index c9185ce473868..2238636f91a66 100644 --- a/packages/nest/src/migrations/update-8-7-0/update-8-7-0.ts +++ b/packages/nest/src/migrations/update-8-7-0/update-8-7-0.ts @@ -8,6 +8,6 @@ export default function update(): Rule { path.join(__dirname, '../../../', 'migrations.json'), '8.7.0' ), - formatFiles() + formatFiles(), ]); } diff --git a/packages/nest/src/schematics/application/application.ts b/packages/nest/src/schematics/application/application.ts index 5063fb8523fb8..45f0c9e73f37b 100644 --- a/packages/nest/src/schematics/application/application.ts +++ b/packages/nest/src/schematics/application/application.ts @@ -8,7 +8,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { join, normalize, Path } from '@angular-devkit/core'; import { Schema } from './schema'; @@ -55,30 +55,33 @@ function addAppFiles(options: NormalizedSchema): Rule { template({ tmpl: '', name: options.name, - root: options.appProjectRoot + root: options.appProjectRoot, }), - move(join(options.appProjectRoot, 'src')) + move(join(options.appProjectRoot, 'src')), ]) ); } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(schema); return chain([ init({ ...options, - skipFormat: true + skipFormat: true, }), externalSchematic('@nrwl/node', 'application', schema), addMainFile(options), addAppFiles(options), - updateJsonInTree(join(options.appProjectRoot, 'tsconfig.json'), json => { - json.compilerOptions.emitDecoratorMetadata = true; - json.compilerOptions.target = 'es2015'; - return json; - }), - formatFiles(options) + updateJsonInTree( + join(options.appProjectRoot, 'tsconfig.json'), + (json) => { + json.compilerOptions.emitDecoratorMetadata = true; + json.compilerOptions.target = 'es2015'; + return json; + } + ), + formatFiles(options), ])(host, context); }; } @@ -91,6 +94,6 @@ function normalizeOptions(options: Schema): NormalizedSchema { return { ...options, - appProjectRoot + appProjectRoot, }; } diff --git a/packages/nest/src/schematics/init/init.spec.ts b/packages/nest/src/schematics/init/init.spec.ts index 25171cbd1cd4a..e337ebeb775e4 100644 --- a/packages/nest/src/schematics/init/init.spec.ts +++ b/packages/nest/src/schematics/init/init.spec.ts @@ -32,7 +32,7 @@ describe('init', () => { const result = await runSchematic( 'init', { - unitTestRunner: 'none' + unitTestRunner: 'none', }, tree ); diff --git a/packages/nest/src/schematics/init/init.ts b/packages/nest/src/schematics/init/init.ts index f43572357d53f..88eb2d200a36f 100644 --- a/packages/nest/src/schematics/init/init.ts +++ b/packages/nest/src/schematics/init/init.ts @@ -3,14 +3,14 @@ import { addDepsToPackageJson, addPackageWithInit, formatFiles, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import { Schema } from './schema'; import { nestJsSchematicsVersion, nestJsVersion, nxVersion, - reflectMetadataVersion + reflectMetadataVersion, } from '../../utils/versions'; import { setDefaultCollection } from '@nrwl/workspace/src/utils/rules/workspace'; @@ -19,17 +19,17 @@ export const updateDependencies = addDepsToPackageJson( '@nestjs/common': nestJsVersion, '@nestjs/core': nestJsVersion, '@nestjs/platform-express': nestJsVersion, - 'reflect-metadata': reflectMetadataVersion + 'reflect-metadata': reflectMetadataVersion, }, { '@nestjs/schematics': nestJsSchematicsVersion, '@nestjs/testing': nestJsVersion, - '@nrwl/nest': nxVersion + '@nrwl/nest': nxVersion, } ); function moveDependency(): Rule { - return updateJsonInTree('package.json', json => { + return updateJsonInTree('package.json', (json) => { json.dependencies = json.dependencies || {}; delete json.dependencies['@nrwl/nest']; @@ -37,7 +37,7 @@ function moveDependency(): Rule { }); } -export default function(schema: Schema) { +export default function (schema: Schema) { return chain([ setDefaultCollection('@nrwl/nest'), addPackageWithInit('@nrwl/node', schema), @@ -46,6 +46,6 @@ export default function(schema: Schema) { : noop(), updateDependencies, moveDependency(), - formatFiles(schema) + formatFiles(schema), ]); } diff --git a/packages/nest/src/schematics/library/library.spec.ts b/packages/nest/src/schematics/library/library.spec.ts index dde0f19cb8b30..25a6e3ca23749 100644 --- a/packages/nest/src/schematics/library/library.spec.ts +++ b/packages/nest/src/schematics/library/library.spec.ts @@ -24,17 +24,17 @@ describe('lib', () => { exclude: ['**/node_modules/**', '!libs/my-lib/**'], tsConfig: [ 'libs/my-lib/tsconfig.lib.json', - 'libs/my-lib/tsconfig.spec.json' - ] - } + 'libs/my-lib/tsconfig.spec.json', + ], + }, }); expect(workspaceJson.projects['my-lib'].architect.test).toEqual({ builder: '@nrwl/jest:jest', options: { jestConfig: 'libs/my-lib/jest.config.js', tsConfig: 'libs/my-lib/tsconfig.spec.json', - passWithNoTests: true - } + passWithNoTests: true, + }, }); }); @@ -81,7 +81,7 @@ describe('lib', () => { @Module({ controllers: [], providers: [], - exports: [] + exports: [], }) export class MyLibModule {}` ); @@ -105,7 +105,7 @@ describe('lib', () => { @Module({ controllers: [MyLibController], providers: [MyLibService], - exports: [MyLibService] + exports: [MyLibService], }) export class MyLibModule {}` ); @@ -141,8 +141,8 @@ describe('lib', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-lib': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -150,7 +150,7 @@ describe('lib', () => { const tree = await runSchematic('lib', { name: 'myLib' }, appTree); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ - 'libs/my-lib/src/index.ts' + 'libs/my-lib/src/index.ts', ]); }); @@ -161,9 +161,9 @@ describe('lib', () => { extends: '../../tsconfig.json', compilerOptions: { types: ['node', 'jest'], - target: 'es6' + target: 'es6', }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); }); @@ -200,15 +200,15 @@ describe('lib', () => { { name: 'myLib', directory: 'myDir', - tags: 'one' + tags: 'one', }, appTree ); const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] - } + tags: ['one'], + }, }); const tree2 = await runSchematic( @@ -216,18 +216,18 @@ describe('lib', () => { { name: 'myLib2', directory: 'myDir', - tags: 'one,two' + tags: 'one,two', }, tree ); const nxJson2 = readJsonInTree(tree2, '/nx.json'); expect(nxJson2.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] + tags: ['one'], }, 'my-dir-my-lib2': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -261,9 +261,9 @@ describe('lib', () => { exclude: ['**/node_modules/**', '!libs/my-dir/my-lib/**'], tsConfig: [ 'libs/my-dir/my-lib/tsconfig.lib.json', - 'libs/my-dir/my-lib/tsconfig.spec.json' - ] - } + 'libs/my-dir/my-lib/tsconfig.spec.json', + ], + }, }); }); @@ -274,9 +274,9 @@ describe('lib', () => { appTree ); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); - expect(tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib']).toEqual( - ['libs/my-dir/my-lib/src/index.ts'] - ); + expect( + tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib'] + ).toEqual(['libs/my-dir/my-lib/src/index.ts']); expect( tsconfigJson.compilerOptions.paths['my-dir-my-lib/*'] ).toBeUndefined(); @@ -297,9 +297,9 @@ describe('lib', () => { extends: '../../../tsconfig.json', compilerOptions: { types: ['node', 'jest'], - target: 'es6' + target: 'es6', }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); }); }); @@ -324,9 +324,9 @@ describe('lib', () => { extends: '../../tsconfig.json', compilerOptions: { types: ['node'], - target: 'es6' + target: 'es6', }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); expect( workspaceJson.projects['my-lib'].architect.lint.options.tsConfig @@ -390,10 +390,10 @@ describe('lib', () => { preset: '../../jest.config.js', testEnvironment: 'node', transform: { - '^.+\\.[tj]sx?$': 'ts-jest' + '^.+\\.[tj]sx?$': 'ts-jest', }, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'html'], - coverageDirectory: '../../coverage/libs/my-lib' + coverageDirectory: '../../coverage/libs/my-lib', };`); }); }); diff --git a/packages/nest/src/schematics/library/library.ts b/packages/nest/src/schematics/library/library.ts index e27df27f4da47..b036937279711 100644 --- a/packages/nest/src/schematics/library/library.ts +++ b/packages/nest/src/schematics/library/library.ts @@ -12,7 +12,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { addGlobal, @@ -25,7 +25,7 @@ import { offsetFromRoot, toFileName, updateJsonInTree, - updateWorkspaceInTree + updateWorkspaceInTree, } from '@nrwl/workspace'; import { Schema } from './schema'; import * as ts from 'typescript'; @@ -40,7 +40,7 @@ export interface NormalizedSchema extends Schema { parsedTags: string[]; } -export default function(schema: NormalizedSchema): Rule { +export default function (schema: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); @@ -51,7 +51,7 @@ export default function(schema: NormalizedSchema): Rule { updateTsConfig(options), addProject(options), formatFiles(options), - deleteFile(`/${options.projectRoot}/src/lib/${options.fileName}.spec.ts`) + deleteFile(`/${options.projectRoot}/src/lib/${options.fileName}.spec.ts`), ]); }; } @@ -68,7 +68,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { const projectRoot = normalize(`libs/${projectDirectory}`); const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const normalized: NormalizedSchema = { @@ -78,7 +78,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { name: projectName, projectRoot, projectDirectory, - parsedTags + parsedTags, }; return normalized; @@ -121,7 +121,7 @@ function addExportsToBarrelFile(options: NormalizedSchema): Rule { indexFilePath, `export * from './lib/${options.fileName}.controller';` ) - : []) + : []), ]); } }; @@ -134,25 +134,27 @@ function createFiles(options: NormalizedSchema): Rule { ...options, ...names(options.name), tmpl: '', - offsetFromRoot: offsetFromRoot(options.projectRoot) + offsetFromRoot: offsetFromRoot(options.projectRoot), }), move(options.projectRoot), options.unitTestRunner === 'none' - ? filter(file => !file.endsWith('spec.ts')) + ? filter((file) => !file.endsWith('spec.ts')) : noop(), options.publishable ? noop() - : filter(file => !file.endsWith('package.json')), - options.service ? noop() : filter(file => !file.endsWith('.service.ts')), + : filter((file) => !file.endsWith('package.json')), + options.service + ? noop() + : filter((file) => !file.endsWith('.service.ts')), options.controller ? noop() - : filter(file => !file.endsWith('.controller.ts')), + : filter((file) => !file.endsWith('.controller.ts')), !options.controller || options.unitTestRunner === 'none' - ? filter(file => !file.endsWith('.controller.spec.ts')) + ? filter((file) => !file.endsWith('.controller.spec.ts')) : noop(), !options.service || options.unitTestRunner === 'none' - ? filter(file => !file.endsWith('.service.spec.ts')) - : noop() + ? filter((file) => !file.endsWith('.service.spec.ts')) + : noop(), ]), MergeStrategy.Overwrite ); @@ -161,7 +163,7 @@ function createFiles(options: NormalizedSchema): Rule { function updateTsConfig(options: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const projectConfig = getProjectConfig(host, options.name); - return updateJsonInTree(`${projectConfig.root}/tsconfig.json`, json => { + return updateJsonInTree(`${projectConfig.root}/tsconfig.json`, (json) => { json.compilerOptions.target = options.target; return json; }); @@ -173,7 +175,7 @@ function addProject(options: NormalizedSchema): Rule { return noop(); } - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const architect = json.projects[options.name].architect; if (architect) { architect.build = { @@ -183,8 +185,8 @@ function addProject(options: NormalizedSchema): Rule { tsConfig: `${options.projectRoot}/tsconfig.lib.json`, packageJson: `${options.projectRoot}/package.json`, main: `${options.projectRoot}/src/index.ts`, - assets: [`${options.projectRoot}/*.md`] - } + assets: [`${options.projectRoot}/*.md`], + }, }; } return json; diff --git a/packages/next/src/builders/build/build.impl.spec.ts b/packages/next/src/builders/build/build.impl.spec.ts index fd7e5f635853d..0e37b55ca0b71 100644 --- a/packages/next/src/builders/build/build.impl.spec.ts +++ b/packages/next/src/builders/build/build.impl.spec.ts @@ -7,7 +7,7 @@ import { run } from './build.impl'; jest.mock('next/dist/build'); jest.mock('./lib/create-package-json', () => { return { - createPackageJson: () => Promise.resolve({}) + createPackageJson: () => Promise.resolve({}), }; }); @@ -24,9 +24,9 @@ describe('Next.js Builder', () => { fileReplacements: [ { replace: 'apps/wibble/src/environment.ts', - with: 'apps/wibble/src/environment.prod.ts' - } - ] + with: 'apps/wibble/src/environment.prod.ts', + }, + ], }; jest.spyOn(build, 'default').mockReturnValue(Promise.resolve()); @@ -39,7 +39,7 @@ describe('Next.js Builder', () => { '/root/apps/wibble', expect.objectContaining({ distDir: '../../dist/apps/wibble/.next', - outdir: '../../dist/apps/wibble' + outdir: '../../dist/apps/wibble', }) ); }); diff --git a/packages/next/src/builders/build/build.impl.ts b/packages/next/src/builders/build/build.impl.ts index e1c1dbe8a0c03..4bd799b475c11 100644 --- a/packages/next/src/builders/build/build.impl.ts +++ b/packages/next/src/builders/build/build.impl.ts @@ -1,7 +1,7 @@ import { BuilderContext, BuilderOutput, - createBuilder + createBuilder, } from '@angular-devkit/architect'; import build from 'next/dist/build'; import { PHASE_PRODUCTION_BUILD } from 'next/dist/next-server/lib/constants'; diff --git a/packages/next/src/builders/build/lib/create-package-json.ts b/packages/next/src/builders/build/lib/create-package-json.ts index 320487bdcb9b8..67c3d42a56e73 100644 --- a/packages/next/src/builders/build/lib/create-package-json.ts +++ b/packages/next/src/builders/build/lib/create-package-json.ts @@ -15,21 +15,21 @@ export async function createPackageJson( const allWorkspaceDeps = { ...rootPackageJson.dependencies, - ...rootPackageJson.devDependencies + ...rootPackageJson.devDependencies, }; const outPackageJson = { name: context.target.project, version: '0.0.1', scripts: { - start: 'next start' + start: 'next start', }, dependencies: { next: allWorkspaceDeps.next, react: allWorkspaceDeps.react || reactVersion, - 'react-dom': allWorkspaceDeps['react-dom'] || reactDomVersion + 'react-dom': allWorkspaceDeps['react-dom'] || reactDomVersion, }, - devDependencies: {} + devDependencies: {}, }; writeFileSync( diff --git a/packages/next/src/builders/export/export.impl.ts b/packages/next/src/builders/export/export.impl.ts index f172a719600b7..de85450b0b3f5 100644 --- a/packages/next/src/builders/export/export.impl.ts +++ b/packages/next/src/builders/export/export.impl.ts @@ -3,7 +3,7 @@ import { BuilderOutput, createBuilder, scheduleTargetAndForget, - targetFromTargetString + targetFromTargetString, } from '@angular-devkit/architect'; import exportApp from 'next/dist/export'; import { PHASE_EXPORT } from 'next/dist/next-server/lib/constants'; @@ -13,7 +13,7 @@ import { concatMap, map } from 'rxjs/operators'; import { prepareConfig } from '../../utils/config'; import { NextBuildBuilderOptions, - NextExportBuilderOptions + NextExportBuilderOptions, } from '../../utils/types'; try { @@ -30,7 +30,7 @@ function run( const build$ = scheduleTargetAndForget(context, buildTarget); return build$.pipe( - concatMap(r => { + concatMap((r) => { if (!r.success) return of(r); return from(context.getTargetOptions(buildTarget)).pipe( concatMap((buildOptions: NextBuildBuilderOptions) => { @@ -42,7 +42,7 @@ function run( { silent: options.silent, threads: options.threads, - outdir: `${buildOptions.outputPath}/exported` + outdir: `${buildOptions.outputPath}/exported`, } as any, config ) diff --git a/packages/next/src/builders/server/lib/default-server.ts b/packages/next/src/builders/server/lib/default-server.ts index f045189b95efd..31df70998af18 100644 --- a/packages/next/src/builders/server/lib/default-server.ts +++ b/packages/next/src/builders/server/lib/default-server.ts @@ -20,7 +20,7 @@ export async function defaultServer( // Set up the proxy. if (proxyConfig) { const proxyMiddleware = require('http-proxy-middleware'); - Object.keys(proxyConfig).forEach(context => { + Object.keys(proxyConfig).forEach((context) => { server.use(proxyMiddleware(context, proxyConfig[context])); }); } diff --git a/packages/next/src/builders/server/server.impl.ts b/packages/next/src/builders/server/server.impl.ts index 333821bcf88e8..973306e870096 100644 --- a/packages/next/src/builders/server/server.impl.ts +++ b/packages/next/src/builders/server/server.impl.ts @@ -3,13 +3,13 @@ import { BuilderOutput, createBuilder, scheduleTargetAndForget, - targetFromTargetString + targetFromTargetString, } from '@angular-devkit/architect'; import { terminal } from '@angular-devkit/core'; import * as fs from 'fs'; import { PHASE_DEVELOPMENT_SERVER, - PHASE_PRODUCTION_SERVER + PHASE_PRODUCTION_SERVER, } from 'next/dist/next-server/lib/constants'; import * as path from 'path'; import { from, Observable, of, throwError } from 'rxjs'; @@ -20,7 +20,7 @@ import { NextServeBuilderOptions, NextServer, NextServerOptions, - ProxyConfig + ProxyConfig, } from '../../utils/types'; import { customServer } from './lib/custom-server'; import { defaultServer } from './lib/default-server'; @@ -59,7 +59,7 @@ export function run( conf: config, port: options.port, path: options.customServerPath, - hostname: options.hostname + hostname: options.hostname, }; const server: NextServer = options.customServerPath @@ -79,7 +79,7 @@ export function run( } return from(server(settings, proxyConfig)).pipe( - catchError(err => { + catchError((err) => { if (options.dev) { throw err; } else { @@ -92,11 +92,11 @@ export function run( context.logger.info(`${readyPrefix} on ${baseUrl}`); }), switchMap( - e => - new Observable(obs => { + (e) => + new Observable((obs) => { obs.next({ baseUrl, - success: true + success: true, }); }) ) diff --git a/packages/next/src/migrations/update-8-10-0/update-8-10-0.ts b/packages/next/src/migrations/update-8-10-0/update-8-10-0.ts index b83572d1885a9..44354a45ff6fa 100644 --- a/packages/next/src/migrations/update-8-10-0/update-8-10-0.ts +++ b/packages/next/src/migrations/update-8-10-0/update-8-10-0.ts @@ -8,6 +8,6 @@ export default function update(): Rule { path.join(__dirname, '../../../', 'migrations.json'), '8.10.0' ), - formatFiles() + formatFiles(), ]); } diff --git a/packages/next/src/migrations/update-9-2-0/create-next-config.spec.ts b/packages/next/src/migrations/update-9-2-0/create-next-config.spec.ts index f0dffdb887772..e7531a62e5b5b 100644 --- a/packages/next/src/migrations/update-9-2-0/create-next-config.spec.ts +++ b/packages/next/src/migrations/update-9-2-0/create-next-config.spec.ts @@ -28,9 +28,9 @@ describe('create-next-config-9.2.0', () => { architect: { build: { builder: '@nrwl/next:build', - options: {} - } - } + options: {}, + }, + }, }, demo2: { root: 'apps/demo2', @@ -38,9 +38,9 @@ describe('create-next-config-9.2.0', () => { architect: { build: { builder: '@nrwl/react:build', - options: {} - } - } + options: {}, + }, + }, }, demo3: { root: 'apps/demo3', @@ -48,12 +48,12 @@ describe('create-next-config-9.2.0', () => { architect: { build: { builder: '@nrwl/next:build', - options: {} - } - } - } + options: {}, + }, + }, + }, }, - newProjectRoot: '' + newProjectRoot: '', }) ); @@ -84,12 +84,12 @@ describe('create-next-config-9.2.0', () => { architect: { build: { builder: '@nrwl/next:build', - options: {} - } - } - } + options: {}, + }, + }, + }, }, - newProjectRoot: '' + newProjectRoot: '', }) ); diff --git a/packages/next/src/migrations/update-9-2-0/create-next-config.ts b/packages/next/src/migrations/update-9-2-0/create-next-config.ts index dbc537446942b..4d2fb3a2f7956 100644 --- a/packages/next/src/migrations/update-9-2-0/create-next-config.ts +++ b/packages/next/src/migrations/update-9-2-0/create-next-config.ts @@ -27,7 +27,7 @@ export default function update(): Rule { (host: Tree) => { const workspaceJson = readWorkspace(host); const nextProjects = Object.keys(workspaceJson.projects) - .map(name => { + .map((name) => { const p = workspaceJson.projects[name]; const buildBuilder = p.architect && p.architect.build && p.architect.build.builder; @@ -35,13 +35,13 @@ export default function update(): Rule { }) .filter(Boolean); - nextProjects.forEach(p => { + nextProjects.forEach((p) => { const configPath = join(p.root, CONFIG_FILE); if (!host.exists(configPath)) { host.create(configPath, defaultConfig); } }); }, - formatFiles() + formatFiles(), ]); } diff --git a/packages/next/src/schematics/application/application.spec.ts b/packages/next/src/schematics/application/application.spec.ts index 17cc3f6a09c97..4b917bbe7bddc 100644 --- a/packages/next/src/schematics/application/application.spec.ts +++ b/packages/next/src/schematics/application/application.spec.ts @@ -32,12 +32,12 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-app': { - tags: ['one', 'two'] + tags: ['one', 'two'], }, 'my-app-e2e': { tags: [], - implicitDependencies: ['my-app'] - } + implicitDependencies: ['my-app'], + }, }); }); @@ -64,7 +64,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -78,7 +78,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -92,7 +92,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -101,7 +101,7 @@ describe('app', () => { expect(architectConfig.build.builder).toEqual('@nrwl/next:build'); expect(architectConfig.build.options).toEqual({ root: 'apps/my-app', - outputPath: 'dist/apps/my-app' + outputPath: 'dist/apps/my-app', }); }); @@ -109,7 +109,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -118,10 +118,10 @@ describe('app', () => { expect(architectConfig.serve.builder).toEqual('@nrwl/next:server'); expect(architectConfig.serve.options).toEqual({ buildTarget: 'my-app:build', - dev: true + dev: true, }); expect(architectConfig.serve.configurations).toEqual({ - production: { dev: false, buildTarget: 'my-app:build:production' } + production: { dev: false, buildTarget: 'my-app:build:production' }, }); }); @@ -129,7 +129,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -137,7 +137,7 @@ describe('app', () => { const architectConfig = workspaceJson.projects['my-app'].architect; expect(architectConfig.export.builder).toEqual('@nrwl/next:export'); expect(architectConfig.export.options).toEqual({ - buildTarget: 'my-app:build:production' + buildTarget: 'my-app:build:production', }); }); @@ -191,8 +191,8 @@ describe('app', () => { expect(packageJson).toMatchObject({ devDependencies: { 'eslint-plugin-react': expect.anything(), - 'eslint-plugin-react-hooks': expect.anything() - } + 'eslint-plugin-react-hooks': expect.anything(), + }, }); }); }); diff --git a/packages/next/src/schematics/application/application.ts b/packages/next/src/schematics/application/application.ts index fc5b640e30627..5e1143dacc47b 100644 --- a/packages/next/src/schematics/application/application.ts +++ b/packages/next/src/schematics/application/application.ts @@ -2,7 +2,7 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { extraEslintDependencies, reactEslintJson } from '@nrwl/react'; import { addLintFiles, formatFiles } from '@nrwl/workspace'; @@ -19,18 +19,18 @@ import { updateNxJson } from './lib/update-nx-json'; import { Schema } from './schema'; import { addStyleDependencies } from '../../utils/styles'; -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, _context: SchematicContext) => { const options = normalizeOptions(host, schema); return chain([ init({ ...options, - skipFormat: true + skipFormat: true, }), addLintFiles(options.appProjectRoot, options.linter, { localConfig: reactEslintJson, - extraPackageDeps: extraEslintDependencies + extraPackageDeps: extraEslintDependencies, }), createApplicationFiles(options), createNextServerFiles(options), @@ -41,7 +41,7 @@ export default function(schema: Schema): Rule { updateJestConfig(options), addStyleDependencies(options.style), setDefaults(options), - formatFiles(options) + formatFiles(options), ]); }; } diff --git a/packages/next/src/schematics/application/lib/add-cypress.ts b/packages/next/src/schematics/application/lib/add-cypress.ts index 6d7ce588048fe..baa15ad088d3d 100644 --- a/packages/next/src/schematics/application/lib/add-cypress.ts +++ b/packages/next/src/schematics/application/lib/add-cypress.ts @@ -7,7 +7,7 @@ export function addCypress(options: NormalizedSchema): Rule { ...options, name: options.name + '-e2e', directory: options.directory, - project: options.projectName + project: options.projectName, }) : noop(); } diff --git a/packages/next/src/schematics/application/lib/add-jest.ts b/packages/next/src/schematics/application/lib/add-jest.ts index ee947a451d3de..0803cdecd639e 100644 --- a/packages/next/src/schematics/application/lib/add-jest.ts +++ b/packages/next/src/schematics/application/lib/add-jest.ts @@ -2,7 +2,7 @@ import { chain, externalSchematic, noop, - Rule + Rule, } from '@angular-devkit/schematics'; import { updateJsonInTree } from '@nrwl/workspace'; import { NormalizedSchema } from './normalize-options'; @@ -14,16 +14,16 @@ export function addJest(options: NormalizedSchema): Rule { project: options.projectName, supportTsx: true, skipSerializers: true, - setupFile: 'none' + setupFile: 'none', }), updateJsonInTree( `${options.appProjectRoot}/tsconfig.spec.json`, - json => { + (json) => { json.compilerOptions.jsx = 'react'; return json; } - ) + ), ]) : noop(); } diff --git a/packages/next/src/schematics/application/lib/add-project.spec.ts b/packages/next/src/schematics/application/lib/add-project.spec.ts index 79ac0f6f82417..571bc066cae7b 100644 --- a/packages/next/src/schematics/application/lib/add-project.spec.ts +++ b/packages/next/src/schematics/application/lib/add-project.spec.ts @@ -26,7 +26,7 @@ describe('addProject Rule', () => { e2eProjectRoot: normalize('/apps/todos-e2e'), parsedTags: [], fileName: 'index', - styledModule: null + styledModule: null, }; }); @@ -39,12 +39,12 @@ describe('addProject Rule', () => { expect(project.architect.build).toEqual({ builder: '@nrwl/next:build', configurations: { - production: {} + production: {}, }, options: { outputPath: 'dist/apps/todos', - root: '/apps/todos' - } + root: '/apps/todos', + }, }); }); }); diff --git a/packages/next/src/schematics/application/lib/add-project.ts b/packages/next/src/schematics/application/lib/add-project.ts index 1d4d9bca7827d..181bfa7025bd0 100644 --- a/packages/next/src/schematics/application/lib/add-project.ts +++ b/packages/next/src/schematics/application/lib/add-project.ts @@ -5,7 +5,7 @@ import { updateWorkspaceInTree } from '@nrwl/workspace/src/utils/ast-utils'; import { NormalizedSchema } from './normalize-options'; export function addProject(options: NormalizedSchema): Rule { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const architect: { [key: string]: any } = {}; const { server } = options; @@ -13,41 +13,41 @@ export function addProject(options: NormalizedSchema): Rule { builder: '@nrwl/next:build', options: { root: options.appProjectRoot, - outputPath: join(normalize('dist'), options.appProjectRoot) + outputPath: join(normalize('dist'), options.appProjectRoot), }, // This has to be here so `nx serve [app] --prod` will work. Otherwise // a missing configuration error will be thrown. configurations: { - production: {} - } + production: {}, + }, }; architect.serve = { builder: '@nrwl/next:server', options: { buildTarget: `${options.projectName}:build`, - dev: true + dev: true, }, configurations: { production: { buildTarget: `${options.projectName}:build:production`, - dev: false - } - } + dev: false, + }, + }, }; if (server) { architect.serve.options = { ...architect.serve.options, - customServerPath: options.server + customServerPath: options.server, }; } architect.export = { builder: '@nrwl/next:export', options: { - buildTarget: `${options.projectName}:build:production` - } + buildTarget: `${options.projectName}:build:production`, + }, }; architect.lint = generateProjectLint( @@ -61,7 +61,7 @@ export function addProject(options: NormalizedSchema): Rule { sourceRoot: options.appProjectRoot, projectType: 'application', schematics: {}, - architect + architect, }; json.defaultProject = json.defaultProject || options.projectName; diff --git a/packages/next/src/schematics/application/lib/create-application-files.ts b/packages/next/src/schematics/application/lib/create-application-files.ts index 9b14902425473..d5ec0c87a3d79 100644 --- a/packages/next/src/schematics/application/lib/create-application-files.ts +++ b/packages/next/src/schematics/application/lib/create-application-files.ts @@ -6,7 +6,7 @@ import { noop, Rule, template, - url + url, } from '@angular-devkit/schematics'; import { names, offsetFromRoot } from '@nrwl/workspace'; import { NormalizedSchema } from './normalize-options'; @@ -18,19 +18,19 @@ export function createApplicationFiles(options: NormalizedSchema): Rule { ...names(options.name), ...options, tmpl: '', - offsetFromRoot: offsetFromRoot(options.appProjectRoot) + offsetFromRoot: offsetFromRoot(options.appProjectRoot), }), options.styledModule - ? filter(file => !file.endsWith(`.${options.style}`)) + ? filter((file) => !file.endsWith(`.${options.style}`)) : noop(), // Custom document is used for styled-components SSR in Next.js options.style === 'styled-components' ? noop() - : filter(file => file.indexOf('_document.tsx') === -1), + : filter((file) => file.indexOf('_document.tsx') === -1), options.unitTestRunner === 'none' - ? filter(file => file !== `/specs/index.spec.tsx`) + ? filter((file) => file !== `/specs/index.spec.tsx`) : noop(), - move(options.appProjectRoot) + move(options.appProjectRoot), ]) ); } diff --git a/packages/next/src/schematics/application/lib/normalize-options.ts b/packages/next/src/schematics/application/lib/normalize-options.ts index e15293ad4230e..2bb5e8e6c2bec 100644 --- a/packages/next/src/schematics/application/lib/normalize-options.ts +++ b/packages/next/src/schematics/application/lib/normalize-options.ts @@ -29,7 +29,7 @@ export function normalizeOptions( const e2eProjectRoot = normalize(`apps/${appDirectory}-e2e`); const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const fileName = 'index'; @@ -49,6 +49,6 @@ export function normalizeOptions( e2eProjectName, parsedTags, fileName, - styledModule + styledModule, }; } diff --git a/packages/next/src/schematics/application/lib/set-defaults.ts b/packages/next/src/schematics/application/lib/set-defaults.ts index e3a3fdff5fb7c..184c9087317aa 100644 --- a/packages/next/src/schematics/application/lib/set-defaults.ts +++ b/packages/next/src/schematics/application/lib/set-defaults.ts @@ -6,7 +6,7 @@ import { NormalizedSchema } from './normalize-options'; export function setDefaults(options: NormalizedSchema): Rule { return options.skipWorkspaceJson ? noop() - : updateWorkspace(workspace => { + : updateWorkspace((workspace) => { workspace.extensions.schematics = jsonIdentity( workspace.extensions.schematics || {} ); @@ -23,9 +23,9 @@ export function setDefaults(options: NormalizedSchema): Rule { application: { style: options.style, linter: options.linter, - ...jsonIdentity(prev.application) - } - } + ...jsonIdentity(prev.application), + }, + }, }; }); } diff --git a/packages/next/src/schematics/application/lib/update-jest-config.ts b/packages/next/src/schematics/application/lib/update-jest-config.ts index 4c840179dca0d..ad9c63801d33c 100644 --- a/packages/next/src/schematics/application/lib/update-jest-config.ts +++ b/packages/next/src/schematics/application/lib/update-jest-config.ts @@ -4,7 +4,7 @@ import { NormalizedSchema } from './normalize-options'; export function updateJestConfig(options: NormalizedSchema): Rule { return options.unitTestRunner === 'none' ? noop() - : host => { + : (host) => { const configPath = `${options.appProjectRoot}/jest.config.js`; const originalContent = host.read(configPath).toString(); const content = originalContent.replace( diff --git a/packages/next/src/schematics/application/lib/update-nx-json.ts b/packages/next/src/schematics/application/lib/update-nx-json.ts index 6c20b17cb9913..ac507f4567cd4 100644 --- a/packages/next/src/schematics/application/lib/update-nx-json.ts +++ b/packages/next/src/schematics/application/lib/update-nx-json.ts @@ -3,7 +3,7 @@ import { NxJson, updateJsonInTree } from '@nrwl/workspace'; import { NormalizedSchema } from './normalize-options'; export function updateNxJson(options: NormalizedSchema): Rule { - return updateJsonInTree('nx.json', json => { + return updateJsonInTree('nx.json', (json) => { json.projects[options.projectName] = { tags: options.parsedTags }; return json; }); diff --git a/packages/next/src/schematics/component/component.ts b/packages/next/src/schematics/component/component.ts index ff1773be46445..37d71d7cbc642 100644 --- a/packages/next/src/schematics/component/component.ts +++ b/packages/next/src/schematics/component/component.ts @@ -13,7 +13,7 @@ interface Schema { * This schematic is basically the React one, but for Next we need * extra dependencies for css, sass, less, styl style options. */ -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { return chain([ externalSchematic('@nrwl/react', 'component', { ...options, @@ -21,8 +21,8 @@ export default function(options: Schema): Rule { pascalCaseFiles: false, export: false, classComponent: false, - routing: false + routing: false, }), - addStyleDependencies(options.style) + addStyleDependencies(options.style), ]); } diff --git a/packages/next/src/schematics/init/init.spec.ts b/packages/next/src/schematics/init/init.spec.ts index ff30e830f9059..1693df631259c 100644 --- a/packages/next/src/schematics/init/init.spec.ts +++ b/packages/next/src/schematics/init/init.spec.ts @@ -31,7 +31,7 @@ describe('init', () => { const result = await runSchematic( 'init', { - unitTestRunner: 'none' + unitTestRunner: 'none', }, tree ); diff --git a/packages/next/src/schematics/init/init.ts b/packages/next/src/schematics/init/init.ts index df5871b3888ea..a6b9db40ce2bf 100644 --- a/packages/next/src/schematics/init/init.ts +++ b/packages/next/src/schematics/init/init.ts @@ -5,19 +5,19 @@ import { Schema } from './schema'; import { setDefaultCollection } from '@nrwl/workspace/src/utils/rules/workspace'; import { reactDomVersion, - reactVersion + reactVersion, } from '../../../../react/src/utils/versions'; const updateDependencies = addDepsToPackageJson( { next: nextVersion, react: reactVersion, - 'react-dom': reactDomVersion + 'react-dom': reactDomVersion, }, {} ); -export default function(schema: Schema) { +export default function (schema: Schema) { return chain([ setDefaultCollection('@nrwl/next'), schema.unitTestRunner === 'jest' @@ -28,6 +28,6 @@ export default function(schema: Schema) { : noop(), addPackageWithInit('@nrwl/web', schema), addPackageWithInit('@nrwl/react', schema), - updateDependencies + updateDependencies, ]); } diff --git a/packages/next/src/schematics/page/page.ts b/packages/next/src/schematics/page/page.ts index 4b05504363d36..e6b364fb248ed 100644 --- a/packages/next/src/schematics/page/page.ts +++ b/packages/next/src/schematics/page/page.ts @@ -13,7 +13,7 @@ interface Schema { * extra dependencies for css, sass, less, styl style options, and make sure * it is under `pages` folder. */ -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { return chain([ externalSchematic('@nrwl/react', 'component', { ...options, @@ -23,8 +23,8 @@ export default function(options: Schema): Rule { classComponent: false, routing: false, skipTests: !options.withTests, - flat: false + flat: false, }), - addStyleDependencies(options.style) + addStyleDependencies(options.style), ]); } diff --git a/packages/next/src/utils/config.spec.ts b/packages/next/src/utils/config.spec.ts index b7330f1e95beb..ed09308670ac8 100644 --- a/packages/next/src/utils/config.spec.ts +++ b/packages/next/src/utils/config.spec.ts @@ -6,8 +6,8 @@ jest.mock('tsconfig-paths-webpack-plugin'); jest.mock('next/dist/next-server/server/config', () => ({ __esModule: true, default: () => ({ - webpack: () => ({}) - }) + webpack: () => ({}), + }), })); describe('Next.js webpack config builder', () => { @@ -27,7 +27,7 @@ describe('Next.js webpack config builder', () => { expect(TsconfigPathsPlugin).toHaveBeenCalledWith({ configFile: '/root/apps/wibble/tsconfig.json', extensions: ['.ts', '.tsx', '.mjs', '.js', '.jsx'], - mainFields: ['es2015', 'module', 'main'] + mainFields: ['es2015', 'module', 'main'], }); }); @@ -35,8 +35,8 @@ describe('Next.js webpack config builder', () => { const webpackConfig = createWebpackConfig('/root', 'apps/wibble', [ { replace: 'apps/wibble/src/environment.ts', - with: 'apps/wibble/src/environment.prod.ts' - } + with: 'apps/wibble/src/environment.prod.ts', + }, ]); const config = webpackConfig( @@ -46,7 +46,7 @@ describe('Next.js webpack config builder', () => { expect(config.resolve.alias).toEqual({ '/root/apps/wibble/src/environment.ts': - '/root/apps/wibble/src/environment.prod.ts' + '/root/apps/wibble/src/environment.prod.ts', }); }); @@ -71,7 +71,7 @@ describe('Next.js webpack config builder', () => { { root: 'apps/wibble', outputPath: 'dist/apps/wibble', - fileReplacements: [] + fileReplacements: [], }, { workspaceRoot: '/root' } as any ); @@ -79,7 +79,7 @@ describe('Next.js webpack config builder', () => { expect(config).toEqual( expect.objectContaining({ distDir: '../../dist/apps/wibble/.next', - outdir: '../../dist/apps/wibble' + outdir: '../../dist/apps/wibble', }) ); }); diff --git a/packages/next/src/utils/config.ts b/packages/next/src/utils/config.ts index 0b84223b61689..8c822d276d12e 100644 --- a/packages/next/src/utils/config.ts +++ b/packages/next/src/utils/config.ts @@ -3,7 +3,7 @@ import { PHASE_DEVELOPMENT_SERVER, PHASE_EXPORT, PHASE_PRODUCTION_BUILD, - PHASE_PRODUCTION_SERVER + PHASE_PRODUCTION_SERVER, } from 'next/dist/next-server/lib/constants'; import loadConfig from 'next/dist/next-server/server/config'; import { join, resolve } from 'path'; @@ -12,7 +12,7 @@ import { Configuration } from 'webpack'; import { FileReplacement, NextBuildBuilderOptions, - NextServeBuilderOptions + NextServeBuilderOptions, } from './types'; import { BuilderContext } from '@angular-devkit/architect'; @@ -31,14 +31,14 @@ export function createWebpackConfig( new TsconfigPathsPlugin({ configFile: resolve(workspaceRoot, projectRoot, 'tsconfig.json'), extensions, - mainFields - }) + mainFields, + }), ]; fileReplacements - .map(fileReplacement => ({ + .map((fileReplacement) => ({ replace: resolve(workspaceRoot, fileReplacement.replace), - with: resolve(workspaceRoot, fileReplacement.with) + with: resolve(workspaceRoot, fileReplacement.with), })) .reduce((alias, replacement) => { alias[replacement.replace] = replacement.with; @@ -48,7 +48,7 @@ export function createWebpackConfig( config.module.rules.push( { test: /\.tsx?$/, - use: [defaultLoaders.babel] + use: [defaultLoaders.babel], }, { test: /\.svg$/, @@ -56,7 +56,7 @@ export function createWebpackConfig( // If coming from JS/TS file, then transform into React component using SVGR. { issuer: { - test: /\.[jt]sx?$/ + test: /\.[jt]sx?$/, }, use: [ '@svgr/webpack?-svgo,+titleProp,+ref![path]', @@ -64,10 +64,10 @@ export function createWebpackConfig( loader: 'url-loader', options: { limit: 10000, // 10kB - name: '[name].[hash:7].[ext]' - } - } - ] + name: '[name].[hash:7].[ext]', + }, + }, + ], }, // Fallback to plain URL loader. { @@ -76,12 +76,12 @@ export function createWebpackConfig( loader: 'url-loader', options: { limit: 10000, // 10kB - name: '[name].[hash:7].[ext]' - } - } - ] - } - ] + name: '[name].[hash:7].[ext]', + }, + }, + ], + }, + ], } ); return config; diff --git a/packages/next/src/utils/styles.ts b/packages/next/src/utils/styles.ts index b0639ab6d3412..15c4abdc918ac 100644 --- a/packages/next/src/utils/styles.ts +++ b/packages/next/src/utils/styles.ts @@ -8,7 +8,7 @@ import { zeitNextLess, zeitNextSass, zeitNextStylus, - nodeSass + nodeSass, } from './versions'; export const NEXT_SPECIFIC_STYLE_DEPENDENCIES = { @@ -16,42 +16,42 @@ export const NEXT_SPECIFIC_STYLE_DEPENDENCIES = { dependencies: CSS_IN_JS_DEPENDENCIES['styled-components'].dependencies, devDependencies: { ...CSS_IN_JS_DEPENDENCIES['styled-components'].devDependencies, - 'babel-plugin-styled-components': babelPluginStyledComponentsVersion - } + 'babel-plugin-styled-components': babelPluginStyledComponentsVersion, + }, }, '@emotion/styled': { dependencies: { ...CSS_IN_JS_DEPENDENCIES['@emotion/styled'].dependencies, - 'emotion-server': emotionServerVersion + 'emotion-server': emotionServerVersion, }, - devDependencies: CSS_IN_JS_DEPENDENCIES['@emotion/styled'].devDependencies + devDependencies: CSS_IN_JS_DEPENDENCIES['@emotion/styled'].devDependencies, }, css: { dependencies: { - '@zeit/next-css': zeitNextCss + '@zeit/next-css': zeitNextCss, }, - devDependencies: {} + devDependencies: {}, }, scss: { dependencies: { - '@zeit/next-sass': zeitNextSass + '@zeit/next-sass': zeitNextSass, }, devDependencies: { - 'node-sass': nodeSass - } + 'node-sass': nodeSass, + }, }, less: { dependencies: { - '@zeit/next-less': zeitNextLess + '@zeit/next-less': zeitNextLess, }, - devDependencies: {} + devDependencies: {}, }, styl: { dependencies: { - '@zeit/next-stylus': zeitNextStylus + '@zeit/next-stylus': zeitNextStylus, }, - devDependencies: {} - } + devDependencies: {}, + }, }; export function addStyleDependencies(style: string): Rule { diff --git a/packages/next/src/utils/testing.ts b/packages/next/src/utils/testing.ts index a8add45df20d1..75e7b67725941 100644 --- a/packages/next/src/utils/testing.ts +++ b/packages/next/src/utils/testing.ts @@ -25,13 +25,13 @@ export function createApp(tree: Tree, appName: string): Promise { const { fileName } = names(appName); return callRule( - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: fileName, root: `apps/${fileName}`, projectType: 'application', sourceRoot: `apps/${fileName}/src`, - targets: {} + targets: {}, }); }), tree diff --git a/packages/node/src/builders/build/build.impl.ts b/packages/node/src/builders/build/build.impl.ts index d1401ab1119b5..db50f5fff0c33 100644 --- a/packages/node/src/builders/build/build.impl.ts +++ b/packages/node/src/builders/build/build.impl.ts @@ -13,7 +13,7 @@ import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { createProjectGraph } from '@nrwl/workspace/src/core/project-graph'; import { calculateProjectDependencies, - createTmpTsConfig + createTmpTsConfig, } from '@nrwl/workspace/src/utils/buildable-libs-utils'; try { @@ -52,25 +52,25 @@ function run( } return from(getSourceRoot(context)).pipe( - map(sourceRoot => + map((sourceRoot) => normalizeBuildOptions(options, context.workspaceRoot, sourceRoot) ), - map(options => { + map((options) => { let config = getNodeWebpackConfig(options); if (options.webpackConfig) { config = require(options.webpackConfig)(config, { options, - configuration: context.target.configuration + configuration: context.target.configuration, }); } return config; }), - concatMap(config => + concatMap((config) => runWebpack(config, context, { - logging: stats => { + logging: (stats) => { context.logger.info(stats.toString(config.stats)); }, - webpackFactory: require('webpack') + webpackFactory: require('webpack'), }) ), map((buildEvent: BuildResult) => { diff --git a/packages/node/src/builders/execute/execute.impl.spec.ts b/packages/node/src/builders/execute/execute.impl.spec.ts index ec647708cfbd2..943527c3c8891 100644 --- a/packages/node/src/builders/execute/execute.impl.spec.ts +++ b/packages/node/src/builders/execute/execute.impl.spec.ts @@ -1,7 +1,7 @@ import { InspectType, NodeExecuteBuilderOptions, - nodeExecuteBuilderHandler + nodeExecuteBuilderHandler, } from './execute.impl'; import { of, from } from 'rxjs'; import * as devkitArchitect from '@angular-devkit/architect'; @@ -22,7 +22,7 @@ describe('NodeExecuteBuilder', () => { beforeEach(async () => { fork.mockReturnValue({ - pid: 123 + pid: 123, }); treeKill.mockImplementation((pid, signal, callback) => { callback(); @@ -31,7 +31,7 @@ describe('NodeExecuteBuilder', () => { context.addTarget( { project: 'nodeapp', - target: 'build' + target: 'build', }, '@nrwl/node:build' ); @@ -43,7 +43,7 @@ describe('NodeExecuteBuilder', () => { port: 9229, waitUntilTargets: [], host: 'localhost', - watch: true + watch: true, }; scheduleTargetAndForget = spyOn( devkitArchitect, @@ -58,18 +58,18 @@ describe('NodeExecuteBuilder', () => { context, { project: 'nodeapp', - target: 'build' + target: 'build', }, { - watch: true + watch: true, } ); expect(fork).toHaveBeenCalledWith('outfile.js', [], { execArgv: [ '-r', 'source-map-support/register', - '--inspect=localhost:9229' - ] + '--inspect=localhost:9229', + ], }); expect(treeKill).toHaveBeenCalledTimes(0); expect(fork).toHaveBeenCalledTimes(1); @@ -81,7 +81,7 @@ describe('NodeExecuteBuilder', () => { await nodeExecuteBuilderHandler( { ...testOptions, - inspect: InspectType.Inspect + inspect: InspectType.Inspect, }, context ).toPromise(); @@ -89,8 +89,8 @@ describe('NodeExecuteBuilder', () => { execArgv: [ '-r', 'source-map-support/register', - '--inspect=localhost:9229' - ] + '--inspect=localhost:9229', + ], }); }); }); @@ -100,7 +100,7 @@ describe('NodeExecuteBuilder', () => { await nodeExecuteBuilderHandler( { ...testOptions, - inspect: InspectType.InspectBrk + inspect: InspectType.InspectBrk, }, context ).toPromise(); @@ -108,8 +108,8 @@ describe('NodeExecuteBuilder', () => { execArgv: [ '-r', 'source-map-support/register', - '--inspect=localhost:9229' - ] + '--inspect=localhost:9229', + ], }); }); }); @@ -121,7 +121,7 @@ describe('NodeExecuteBuilder', () => { await nodeExecuteBuilderHandler( { ...testOptions, - host: '0.0.0.0' + host: '0.0.0.0', }, context ).toPromise(); @@ -129,8 +129,8 @@ describe('NodeExecuteBuilder', () => { execArgv: [ '-r', 'source-map-support/register', - '--inspect=localhost:9229' - ] + '--inspect=localhost:9229', + ], }); }); }); @@ -142,7 +142,7 @@ describe('NodeExecuteBuilder', () => { await nodeExecuteBuilderHandler( { ...testOptions, - port: 1234 + port: 1234, }, context ).toPromise(); @@ -150,8 +150,8 @@ describe('NodeExecuteBuilder', () => { execArgv: [ '-r', 'source-map-support/register', - '--inspect=localhost:1234' - ] + '--inspect=localhost:1234', + ], }); }); }); @@ -162,7 +162,7 @@ describe('NodeExecuteBuilder', () => { await nodeExecuteBuilderHandler( { ...testOptions, - runtimeArgs: ['-r', 'node-register'] + runtimeArgs: ['-r', 'node-register'], }, context ).toPromise(); @@ -172,13 +172,13 @@ describe('NodeExecuteBuilder', () => { 'source-map-support/register', '-r', 'node-register', - '--inspect=localhost:9229' - ] + '--inspect=localhost:9229', + ], }); }); }); - it('should log errors from killing the process', async done => { + it('should log errors from killing the process', async (done) => { treeKill.mockImplementation((pid, signal, callback) => { callback(new Error('Error Message')); }); @@ -186,14 +186,14 @@ describe('NodeExecuteBuilder', () => { scheduleTargetAndForget = scheduleTargetAndForget.and.returnValue( from([ { success: true, outfile: 'outfile.js' }, - { success: true, outfile: 'outfile.js' } + { success: true, outfile: 'outfile.js' }, ]) ); nodeExecuteBuilderHandler(testOptions, context).subscribe({ complete: () => { expect(loggerError.calls.argsFor(1)).toEqual(['Error Message']); done(); - } + }, }); }); @@ -205,7 +205,7 @@ describe('NodeExecuteBuilder', () => { scheduleTargetAndForget = scheduleTargetAndForget.and.returnValue( from([ { success: true, outfile: 'outfile.js' }, - { success: true, outfile: 'outfile.js' } + { success: true, outfile: 'outfile.js' }, ]) ); await nodeExecuteBuilderHandler(testOptions, context).toPromise(); @@ -217,19 +217,19 @@ describe('NodeExecuteBuilder', () => { { ...testOptions, inspect: false, - args: ['arg1', 'arg2'] + args: ['arg1', 'arg2'], }, context ).toPromise(); expect(fork).toHaveBeenCalledWith('outfile.js', ['arg1', 'arg2'], { - execArgv: ['-r', 'source-map-support/register'] + execArgv: ['-r', 'source-map-support/register'], }); }); it('should warn users who try to use it in production', async () => { spyOn(context, 'validateOptions').and.returnValue( Promise.resolve({ - optimization: true + optimization: true, }) ); spyOn(context.logger, 'warn'); @@ -245,7 +245,7 @@ describe('NodeExecuteBuilder', () => { await nodeExecuteBuilderHandler( { ...testOptions, - waitUntilTargets: ['project1:target1', 'project2:target2'] + waitUntilTargets: ['project1:target1', 'project2:target2'], }, context ).toPromise(); @@ -253,16 +253,16 @@ describe('NodeExecuteBuilder', () => { expect(scheduleTargetAndForget).toHaveBeenCalledTimes(3); expect(scheduleTargetAndForget).toHaveBeenCalledWith(context, { project: 'project1', - target: 'target1' + target: 'target1', }); expect(scheduleTargetAndForget).toHaveBeenCalledWith(context, { project: 'project2', - target: 'target2' + target: 'target2', }); }); it('should not run the build if any of the tasks fail', async () => { - scheduleTargetAndForget = scheduleTargetAndForget.and.callFake(target => + scheduleTargetAndForget = scheduleTargetAndForget.and.callFake((target) => of({ success: target.target === 'project1' }) ); const loggerError = spyOn(context.logger, 'error'); @@ -270,13 +270,13 @@ describe('NodeExecuteBuilder', () => { const output = await nodeExecuteBuilderHandler( { ...testOptions, - waitUntilTargets: ['project1:target1', 'project2:target2'] + waitUntilTargets: ['project1:target1', 'project2:target2'], }, context ).toPromise(); expect(output).toEqual( jasmine.objectContaining({ - success: false + success: false, }) ); expect(loggerError).toHaveBeenCalled(); diff --git a/packages/node/src/builders/execute/execute.impl.ts b/packages/node/src/builders/execute/execute.impl.ts index a40f66af6ca14..eb4dd8ce50910 100644 --- a/packages/node/src/builders/execute/execute.impl.ts +++ b/packages/node/src/builders/execute/execute.impl.ts @@ -3,7 +3,7 @@ import { createBuilder, BuilderOutput, targetFromTargetString, - scheduleTargetAndForget + scheduleTargetAndForget, } from '@angular-devkit/architect'; import { ChildProcess, fork } from 'child_process'; import * as treeKill from 'tree-kill'; @@ -21,7 +21,7 @@ try { export const enum InspectType { Inspect = 'inspect', - InspectBrk = 'inspect-brk' + InspectBrk = 'inspect-brk', } export interface NodeExecuteBuilderOptions extends JsonObject { @@ -46,7 +46,7 @@ export function nodeExecuteBuilderHandler( context: BuilderContext ): Observable { return runWaitUntilTargets(options, context).pipe( - concatMap(v => { + concatMap((v) => { if (!v.success) { context.logger.error( `One of the tasks specified in waitUntilTargets failed` @@ -73,7 +73,7 @@ function runProcess(event: NodeBuildEvent, options: NodeExecuteBuilderOptions) { if (subProcess || !event.success) return; subProcess = fork(event.outfile, options.args, { - execArgv: getExecArgv(options) + execArgv: getExecArgv(options), }); } @@ -110,7 +110,7 @@ function killProcess(context: BuilderContext): Observable { const observableTreeKill = bindCallback(treeKill); return observableTreeKill(subProcess.pid, 'SIGTERM').pipe( - tap(err => { + tap((err) => { subProcess = null; if (err) { if (Array.isArray(err) && err[0] && err[2]) { @@ -132,12 +132,12 @@ function startBuild( return from( Promise.all([ context.getTargetOptions(target), - context.getBuilderNameForTarget(target) + context.getBuilderNameForTarget(target), ]).then(([options, builderName]) => context.validateOptions(options, builderName) ) ).pipe( - tap(options => { + tap((options) => { if (options.optimization) { context.logger.warn(stripIndents` ************************************************ @@ -150,10 +150,10 @@ function startBuild( } }), concatMap( - options => + (options) => scheduleTargetAndForget(context, target, { ...options, - watch: true + watch: true, }) as Observable ) ); @@ -167,15 +167,15 @@ function runWaitUntilTargets( return of({ success: true }); return zip( - ...options.waitUntilTargets.map(b => { + ...options.waitUntilTargets.map((b) => { return scheduleTargetAndForget(context, targetFromTargetString(b)).pipe( - filter(e => e.success !== undefined), + filter((e) => e.success !== undefined), first() ); }) ).pipe( - map(results => { - return { success: !results.some(r => !r.success) }; + map((results) => { + return { success: !results.some((r) => !r.success) }; }) ); } diff --git a/packages/node/src/builders/package/package.impl.spec.ts b/packages/node/src/builders/package/package.impl.spec.ts index 991f17b5c2e54..2e3d2af43b919 100644 --- a/packages/node/src/builders/package/package.impl.spec.ts +++ b/packages/node/src/builders/package/package.impl.spec.ts @@ -5,12 +5,12 @@ import { MockBuilderContext } from '@nrwl/workspace/testing'; import * as projectGraphUtils from '@nrwl/workspace/src/core/project-graph'; import { ProjectGraph, - ProjectType + ProjectType, } from '@nrwl/workspace/src/core/project-graph'; import { NodePackageBuilderOptions, - runNodePackageBuilder + runNodePackageBuilder, } from './package.impl'; import * as fsMock from 'fs'; @@ -46,14 +46,14 @@ describe('NodeCompileBuilder', () => { outDir: '../../dist/out-tsc', declaration: true, rootDir: './src', - types: ['node'] + types: ['node'], }, exclude: ['**/*.spec.ts'], - include: ['**/*.ts'] + include: ['**/*.ts'], }; } else { return { - name: 'nodelib' + name: 'nodelib', }; } }); @@ -68,7 +68,7 @@ describe('NodeCompileBuilder', () => { packageJson: 'libs/nodelib/package.json', tsConfig: 'libs/nodelib/tsconfig.lib.json', watch: false, - sourceMap: false + sourceMap: false, }; }); @@ -78,32 +78,34 @@ describe('NodeCompileBuilder', () => { spyOn(projectGraphUtils, 'createProjectGraph').and.callFake(() => { return { nodes: {}, - dependencies: {} + dependencies: {}, } as ProjectGraph; }); }); - it('should call tsc to compile', done => { + it('should call tsc to compile', (done) => { runNodePackageBuilder(testOptions, context).subscribe({ complete: () => { - expect(fork).toHaveBeenCalledWith( + expect( + fork + ).toHaveBeenCalledWith( `${context.workspaceRoot}/node_modules/typescript/bin/tsc`, [ '-p', join(context.workspaceRoot, testOptions.tsConfig), '--outDir', - join(context.workspaceRoot, testOptions.outputPath) + join(context.workspaceRoot, testOptions.outputPath), ], { stdio: [0, 1, 2, 'ipc'] } ); done(); - } + }, }); fakeEventEmitter.emit('exit', 0); }); - it('should update the package.json after compiling typescript', done => { + it('should update the package.json after compiling typescript', (done) => { runNodePackageBuilder(testOptions, context).subscribe({ complete: () => { expect(fork).toHaveBeenCalled(); @@ -112,24 +114,24 @@ describe('NodeCompileBuilder', () => { { name: 'nodelib', main: 'index.js', - typings: 'index.d.ts' + typings: 'index.d.ts', } ); done(); - } + }, }); fakeEventEmitter.emit('exit', 0); }); - it('should have the output path in the BuilderOutput', done => { + it('should have the output path in the BuilderOutput', (done) => { runNodePackageBuilder(testOptions, context).subscribe({ - next: value => { + next: (value) => { expect(value.outputPath).toEqual(testOptions.outputPath); }, complete: () => { done(); - } + }, }); fakeEventEmitter.emit('exit', 0); }); @@ -139,7 +141,7 @@ describe('NodeCompileBuilder', () => { jest.clearAllMocks(); }); - it('should be able to copy assets using the glob object', done => { + it('should be able to copy assets using the glob object', (done) => { glob.sync.mockReturnValue(['logo.png']); runNodePackageBuilder( { @@ -149,9 +151,9 @@ describe('NodeCompileBuilder', () => { glob: '**.*', input: 'lib/nodelib/src/assets', output: './newfolder', - ignore: [] - } - ] + ignore: [], + }, + ], }, context ).subscribe({ @@ -163,17 +165,17 @@ describe('NodeCompileBuilder', () => { ); done(); - } + }, }); fakeEventEmitter.emit('exit', 0); }); - it('should be able to copy assets with a regular string', done => { + it('should be able to copy assets with a regular string', (done) => { glob.sync.mockReturnValue(['lib/nodelib/src/LICENSE']); runNodePackageBuilder( { ...testOptions, - assets: ['lib/nodelib/src/LICENSE'] + assets: ['lib/nodelib/src/LICENSE'], }, context ).subscribe({ @@ -184,20 +186,20 @@ describe('NodeCompileBuilder', () => { `${context.workspaceRoot}/${testOptions.outputPath}/LICENSE` ); done(); - } + }, }); fakeEventEmitter.emit('exit', 0); }); - it('should be able to copy assets with a glob string', done => { + it('should be able to copy assets with a glob string', (done) => { glob.sync.mockReturnValue([ 'lib/nodelib/src/README.md', - 'lib/nodelib/src/CONTRIBUTING.md' + 'lib/nodelib/src/CONTRIBUTING.md', ]); runNodePackageBuilder( { ...testOptions, - assets: ['lib/nodelib/src/*.MD'] + assets: ['lib/nodelib/src/*.MD'], }, context ).subscribe({ @@ -212,7 +214,7 @@ describe('NodeCompileBuilder', () => { `${context.workspaceRoot}/${testOptions.outputPath}/CONTRIBUTING.md` ); done(); - } + }, }); fakeEventEmitter.emit('exit', 0); }); @@ -230,8 +232,8 @@ describe('NodeCompileBuilder', () => { data: { files: [], root: 'libs/nodelib', - architect: { build: { builder: 'any builder' } } - } + architect: { build: { builder: 'any builder' } }, + }, }, 'nodelib-child': { type: ProjectType.lib, @@ -248,23 +250,23 @@ describe('NodeCompileBuilder', () => { main: 'libs/nodelib-child/src/index.ts', outputPath: 'dist/libs/nodelib-child', packageJson: 'libs/nodelib-child/package.json', - tsConfig: 'libs/nodelib-child/tsconfig.lib.json' - } - } - } - } - } + tsConfig: 'libs/nodelib-child/tsconfig.lib.json', + }, + }, + }, + }, + }, }, dependencies: { nodelib: [ { type: ProjectType.lib, target: 'nodelib-child', - source: null - } + source: null, + }, ], - 'nodelib-child': [] - } + 'nodelib-child': [], + }, } as ProjectGraph; }); @@ -283,7 +285,7 @@ describe('NodeCompileBuilder', () => { spyOn(fsMock, 'unlinkSync'); }); - it('should call the tsc compiler with the modified tsconfig.json', done => { + it('should call the tsc compiler with the modified tsconfig.json', (done) => { let tmpTsConfigPath = join( '/root', 'tmp', @@ -300,13 +302,13 @@ describe('NodeCompileBuilder', () => { tmpTsConfigPath, // join(context.workspaceRoot, testOptions.tsConfig), '--outDir', - join(context.workspaceRoot, testOptions.outputPath) + join(context.workspaceRoot, testOptions.outputPath), ], { stdio: [0, 1, 2, 'ipc'] } ); done(); - } + }, }); fakeEventEmitter.emit('exit', 0); }); diff --git a/packages/node/src/builders/package/package.impl.ts b/packages/node/src/builders/package/package.impl.ts index 84e884c6e5d13..bc4389d3eb706 100644 --- a/packages/node/src/builders/package/package.impl.ts +++ b/packages/node/src/builders/package/package.impl.ts @@ -1,7 +1,7 @@ import { BuilderContext, BuilderOutput, - createBuilder + createBuilder, } from '@angular-devkit/architect'; import { JsonObject } from '@angular-devkit/core'; import { readJsonFile } from '@nrwl/workspace'; @@ -15,14 +15,14 @@ import { map, switchMap, tap } from 'rxjs/operators'; import * as treeKill from 'tree-kill'; import { createProjectGraph, - ProjectGraph + ProjectGraph, } from '@nrwl/workspace/src/core/project-graph'; import { calculateProjectDependencies, checkDependentProjectsHaveBeenBuilt, createTmpTsConfig, DependentBuildableProjectNode, - updateBuildableProjectPackageJsonDependencies + updateBuildableProjectPackageJsonDependencies, } from '@nrwl/workspace/src/utils/buildable-libs-utils'; export interface NodePackageBuilderOptions extends JsonObject { @@ -68,7 +68,7 @@ export function runNodePackageBuilder( ); return of(checkDependentProjectsHaveBeenBuilt(context, dependencies)).pipe( - switchMap(result => { + switchMap((result) => { if (result) { return compileTypeScriptFiles( normalizedOptions, @@ -94,10 +94,10 @@ export function runNodePackageBuilder( return of({ success: false }); } }), - map(value => { + map((value) => { return { ...value, - outputPath: normalizedOptions.outputPath + outputPath: normalizedOptions.outputPath, }; }) ); @@ -118,16 +118,16 @@ function normalizeOptions( return glob.sync(pattern, { cwd: input, nodir: true, - ignore + ignore, }); }; - options.assets.forEach(asset => { + options.assets.forEach((asset) => { if (typeof asset === 'string') { - globbedFiles(asset, context.workspaceRoot).forEach(globbedFile => { + globbedFiles(asset, context.workspaceRoot).forEach((globbedFile) => { files.push({ input: join(context.workspaceRoot, globbedFile), - output: join(context.workspaceRoot, outDir, basename(globbedFile)) + output: join(context.workspaceRoot, outDir, basename(globbedFile)), }); }); } else { @@ -135,10 +135,15 @@ function normalizeOptions( asset.glob, join(context.workspaceRoot, asset.input), asset.ignore - ).forEach(globbedFile => { + ).forEach((globbedFile) => { files.push({ input: join(context.workspaceRoot, asset.input, globbedFile), - output: join(context.workspaceRoot, outDir, asset.output, globbedFile) + output: join( + context.workspaceRoot, + outDir, + asset.output, + globbedFile + ), }); }); } @@ -159,7 +164,7 @@ function normalizeOptions( ...options, files, relativeMainFileOutput, - normalizedOutputPath: join(context.workspaceRoot, options.outputPath) + normalizedOutputPath: join(context.workspaceRoot, options.outputPath), }; } @@ -209,7 +214,7 @@ function compileTypeScriptFiles( `Compiling TypeScript files for library ${context.target.project}...` ); tscProcess = fork(tscPath, args, { stdio: [0, 1, 2, 'ipc'] }); - tscProcess.on('exit', code => { + tscProcess.on('exit', (code) => { if (code === 0) { context.logger.info( `Done compiling TypeScript files for library ${context.target.project}` @@ -233,7 +238,7 @@ function compileTypeScriptFiles( } function killProcess(context: BuilderContext): void { - return treeKill(tscProcess.pid, 'SIGTERM', error => { + return treeKill(tscProcess.pid, 'SIGTERM', (error) => { tscProcess = null; if (error) { if (Array.isArray(error) && error[0] && error[2]) { @@ -272,17 +277,17 @@ function copyAssetFiles( context: BuilderContext ): Promise { context.logger.info('Copying asset files...'); - return Promise.all(options.files.map(file => copy(file.input, file.output))) + return Promise.all(options.files.map((file) => copy(file.input, file.output))) .then(() => { context.logger.info('Done copying asset files.'); return { - success: true + success: true, }; }) .catch((err: Error) => { return { error: err.message, - success: false + success: false, }; }); } diff --git a/packages/node/src/migrations/update-9-2-0/set-build-libs-from-source.spec.ts b/packages/node/src/migrations/update-9-2-0/set-build-libs-from-source.spec.ts index 5a88f62636097..ed9fe96e9e002 100644 --- a/packages/node/src/migrations/update-9-2-0/set-build-libs-from-source.spec.ts +++ b/packages/node/src/migrations/update-9-2-0/set-build-libs-from-source.spec.ts @@ -27,11 +27,11 @@ describe('set buildLibsFromSource to true', () => { architect: { build: { builder: '@nrwl/node:build', - options: {} - } - } - } - } + options: {}, + }, + }, + }, + }, }) ); @@ -41,7 +41,7 @@ describe('set buildLibsFromSource to true', () => { const config = readWorkspace(tree); expect(config.projects.demo.architect.build.options).toEqual({ - buildLibsFromSource: true + buildLibsFromSource: true, }); }); }); diff --git a/packages/node/src/migrations/update-9-2-0/set-build-libs-from-source.ts b/packages/node/src/migrations/update-9-2-0/set-build-libs-from-source.ts index 9e3969dbb314e..9e9a3216d9745 100644 --- a/packages/node/src/migrations/update-9-2-0/set-build-libs-from-source.ts +++ b/packages/node/src/migrations/update-9-2-0/set-build-libs-from-source.ts @@ -3,7 +3,7 @@ import { formatFiles, updateWorkspaceInTree } from '@nrwl/workspace'; export default function update(): Rule { return chain([ - updateWorkspaceInTree(workspaceJson => { + updateWorkspaceInTree((workspaceJson) => { Object.entries(workspaceJson.projects).forEach( ([projectName, project]) => { if (!project.architect) { @@ -25,6 +25,6 @@ export default function update(): Rule { ); return workspaceJson; }), - formatFiles() + formatFiles(), ]); } diff --git a/packages/node/src/schematics/application/application.spec.ts b/packages/node/src/schematics/application/application.spec.ts index 86e1ac1a07e4b..dfcd2374f7fca 100644 --- a/packages/node/src/schematics/application/application.spec.ts +++ b/packages/node/src/schematics/application/application.spec.ts @@ -27,7 +27,7 @@ describe('app', () => { outputPath: 'dist/apps/my-node-app', main: 'apps/my-node-app/src/main.ts', tsConfig: 'apps/my-node-app/tsconfig.app.json', - assets: ['apps/my-node-app/src/assets'] + assets: ['apps/my-node-app/src/assets'], }, configurations: { production: { @@ -38,18 +38,18 @@ describe('app', () => { { replace: 'apps/my-node-app/src/environments/environment.ts', with: - 'apps/my-node-app/src/environments/environment.prod.ts' - } - ] - } - } + 'apps/my-node-app/src/environments/environment.prod.ts', + }, + ], + }, + }, }, serve: { builder: '@nrwl/node:execute', options: { - buildTarget: 'my-node-app:build' - } - } + buildTarget: 'my-node-app:build', + }, + }, }) ); expect(workspaceJson.projects['my-node-app'].architect.lint).toEqual({ @@ -57,10 +57,10 @@ describe('app', () => { options: { tsConfig: [ 'apps/my-node-app/tsconfig.app.json', - 'apps/my-node-app/tsconfig.spec.json' + 'apps/my-node-app/tsconfig.spec.json', ], - exclude: ['**/node_modules/**', '!apps/my-node-app/**'] - } + exclude: ['**/node_modules/**', '!apps/my-node-app/**'], + }, }); expect(workspaceJson.projects['my-node-app-e2e']).toBeUndefined(); expect(workspaceJson.defaultProject).toEqual('my-node-app'); @@ -75,8 +75,8 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-node-app': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -125,10 +125,10 @@ describe('app', () => { options: { tsConfig: [ 'apps/my-dir/my-node-app/tsconfig.app.json', - 'apps/my-dir/my-node-app/tsconfig.spec.json' + 'apps/my-dir/my-node-app/tsconfig.spec.json', ], - exclude: ['**/node_modules/**', '!apps/my-dir/my-node-app/**'] - } + exclude: ['**/node_modules/**', '!apps/my-dir/my-node-app/**'], + }, }); expect(workspaceJson.projects['my-dir-my-node-app-e2e']).toBeUndefined(); @@ -144,8 +144,8 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-node-app': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -165,8 +165,8 @@ describe('app', () => { // Make sure these exist [ `apps/my-dir/my-node-app/jest.config.js`, - 'apps/my-dir/my-node-app/src/main.ts' - ].forEach(path => { + 'apps/my-dir/my-node-app/src/main.ts', + ].forEach((path) => { expect(tree.exists(path)).toBeTruthy(); }); @@ -174,24 +174,24 @@ describe('app', () => { [ { path: 'apps/my-dir/my-node-app/tsconfig.json', - lookupFn: json => json.extends, - expectedValue: '../../../tsconfig.json' + lookupFn: (json) => json.extends, + expectedValue: '../../../tsconfig.json', }, { path: 'apps/my-dir/my-node-app/tsconfig.app.json', - lookupFn: json => json.compilerOptions.outDir, - expectedValue: '../../../dist/out-tsc' + lookupFn: (json) => json.compilerOptions.outDir, + expectedValue: '../../../dist/out-tsc', }, { path: 'apps/my-dir/my-node-app/tsconfig.app.json', - lookupFn: json => json.compilerOptions.types, - expectedValue: ['node'] + lookupFn: (json) => json.compilerOptions.types, + expectedValue: ['node'], }, { path: 'apps/my-dir/my-node-app/tslint.json', - lookupFn: json => json.extends, - expectedValue: '../../../tslint.json' - } + lookupFn: (json) => json.extends, + expectedValue: '../../../tslint.json', + }, ].forEach(hasJsonValue); }); }); diff --git a/packages/node/src/schematics/application/application.ts b/packages/node/src/schematics/application/application.ts index 9498023c6367b..f160d1cafdc28 100644 --- a/packages/node/src/schematics/application/application.ts +++ b/packages/node/src/schematics/application/application.ts @@ -9,7 +9,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { join, normalize, Path } from '@angular-devkit/core'; import { Schema } from './schema'; @@ -17,7 +17,7 @@ import { updateJsonInTree, updateWorkspaceInTree, generateProjectLint, - addLintFiles + addLintFiles, } from '@nrwl/workspace'; import { toFileName } from '@nrwl/workspace'; import { getProjectConfig } from '@nrwl/workspace'; @@ -30,13 +30,13 @@ interface NormalizedSchema extends Schema { } function updateNxJson(options: NormalizedSchema): Rule { - return updateJsonInTree(`/nx.json`, json => { + return updateJsonInTree(`/nx.json`, (json) => { return { ...json, projects: { ...json.projects, - [options.name]: { tags: options.parsedTags } - } + [options.name]: { tags: options.parsedTags }, + }, }; }); } @@ -48,7 +48,7 @@ function getBuildConfig(project: any, options: NormalizedSchema) { outputPath: join(normalize('dist'), options.appProjectRoot), main: join(project.sourceRoot, 'main.ts'), tsConfig: join(options.appProjectRoot, 'tsconfig.app.json'), - assets: [join(project.sourceRoot, 'assets')] + assets: [join(project.sourceRoot, 'assets')], }, configurations: { production: { @@ -58,11 +58,11 @@ function getBuildConfig(project: any, options: NormalizedSchema) { fileReplacements: [ { replace: join(project.sourceRoot, 'environments/environment.ts'), - with: join(project.sourceRoot, 'environments/environment.prod.ts') - } - ] - } - } + with: join(project.sourceRoot, 'environments/environment.prod.ts'), + }, + ], + }, + }, }; } @@ -70,20 +70,20 @@ function getServeConfig(options: NormalizedSchema) { return { builder: '@nrwl/node:execute', options: { - buildTarget: `${options.name}:build` - } + buildTarget: `${options.name}:build`, + }, }; } function updateWorkspaceJson(options: NormalizedSchema): Rule { - return updateWorkspaceInTree(workspaceJson => { + return updateWorkspaceInTree((workspaceJson) => { const project = { root: options.appProjectRoot, sourceRoot: join(options.appProjectRoot, 'src'), projectType: 'application', prefix: options.name, schematics: {}, - architect: {} + architect: {}, }; project.architect.build = getBuildConfig(project, options); @@ -109,9 +109,9 @@ function addAppFiles(options: NormalizedSchema): Rule { tmpl: '', name: options.name, root: options.appProjectRoot, - offset: offsetFromRoot(options.appProjectRoot) + offset: offsetFromRoot(options.appProjectRoot), }), - move(options.appProjectRoot) + move(options.appProjectRoot), ]) ); } @@ -127,15 +127,15 @@ function addProxy(options: NormalizedSchema): Rule { { '/api': { target: 'http://localhost:3333', - secure: false - } + secure: false, + }, }, null, 2 ) ); - updateWorkspaceInTree(json => { + updateWorkspaceInTree((json) => { projectConfig.architect.serve.options.proxyConfig = pathToProxyFile; json.projects[options.frontendProject] = projectConfig; return json; @@ -144,13 +144,13 @@ function addProxy(options: NormalizedSchema): Rule { }; } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(schema); return chain([ init({ ...options, - skipFormat: true + skipFormat: true, }), addLintFiles(options.appProjectRoot, options.linter), addAppFiles(options), @@ -160,10 +160,10 @@ export default function(schema: Schema): Rule { ? externalSchematic('@nrwl/jest', 'jest-project', { project: options.name, setupFile: 'none', - skipSerializers: true + skipSerializers: true, }) : noop(), - options.frontendProject ? addProxy(options) : noop() + options.frontendProject ? addProxy(options) : noop(), ])(host, context); }; } @@ -178,7 +178,7 @@ function normalizeOptions(options: Schema): NormalizedSchema { const appProjectRoot = join(normalize('apps'), appDirectory); const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; return { @@ -188,6 +188,6 @@ function normalizeOptions(options: Schema): NormalizedSchema { ? toFileName(options.frontendProject) : undefined, appProjectRoot, - parsedTags + parsedTags, }; } diff --git a/packages/node/src/schematics/init/init.spec.ts b/packages/node/src/schematics/init/init.spec.ts index 431247adb2b2c..caa390e863239 100644 --- a/packages/node/src/schematics/init/init.spec.ts +++ b/packages/node/src/schematics/init/init.spec.ts @@ -43,7 +43,7 @@ describe('init', () => { const result = await runSchematic( 'init', { - unitTestRunner: 'none' + unitTestRunner: 'none', }, tree ); diff --git a/packages/node/src/schematics/init/init.ts b/packages/node/src/schematics/init/init.ts index f68c36b20f7e4..6460ff287fc83 100644 --- a/packages/node/src/schematics/init/init.ts +++ b/packages/node/src/schematics/init/init.ts @@ -2,27 +2,27 @@ import { chain, noop, Rule } from '@angular-devkit/schematics'; import { addPackageWithInit, formatFiles, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import { nxVersion } from '../../utils/versions'; import { Schema } from './schema'; import { setDefaultCollection } from '@nrwl/workspace/src/utils/rules/workspace'; function updateDependencies(): Rule { - return updateJsonInTree('package.json', json => { + return updateJsonInTree('package.json', (json) => { delete json.dependencies['@nrwl/node']; json.devDependencies['@nrwl/node'] = nxVersion; return json; }); } -export default function(schema: Schema) { +export default function (schema: Schema) { return chain([ setDefaultCollection('@nrwl/node'), schema.unitTestRunner === 'jest' ? addPackageWithInit('@nrwl/jest') : noop(), updateDependencies(), - formatFiles(schema) + formatFiles(schema), ]); } diff --git a/packages/node/src/schematics/library/library.spec.ts b/packages/node/src/schematics/library/library.spec.ts index f76f89a5bc877..5ca6d826736d3 100644 --- a/packages/node/src/schematics/library/library.spec.ts +++ b/packages/node/src/schematics/library/library.spec.ts @@ -24,17 +24,17 @@ describe('lib', () => { exclude: ['**/node_modules/**', '!libs/my-lib/**'], tsConfig: [ 'libs/my-lib/tsconfig.lib.json', - 'libs/my-lib/tsconfig.spec.json' - ] - } + 'libs/my-lib/tsconfig.spec.json', + ], + }, }); expect(workspaceJson.projects['my-lib'].architect.test).toEqual({ builder: '@nrwl/jest:jest', options: { jestConfig: 'libs/my-lib/jest.config.js', tsConfig: 'libs/my-lib/tsconfig.spec.json', - passWithNoTests: true - } + passWithNoTests: true, + }, }); }); @@ -47,8 +47,8 @@ describe('lib', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-lib': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -56,7 +56,7 @@ describe('lib', () => { const tree = await runSchematic('lib', { name: 'myLib' }, appTree); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ - 'libs/my-lib/src/index.ts' + 'libs/my-lib/src/index.ts', ]); }); @@ -66,9 +66,9 @@ describe('lib', () => { expect(tsconfigJson).toEqual({ extends: '../../tsconfig.json', compilerOptions: { - types: ['node', 'jest'] + types: ['node', 'jest'], }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); }); @@ -104,15 +104,15 @@ describe('lib', () => { { name: 'myLib', directory: 'myDir', - tags: 'one' + tags: 'one', }, appTree ); const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] - } + tags: ['one'], + }, }); const tree2 = await runSchematic( @@ -120,18 +120,18 @@ describe('lib', () => { { name: 'myLib2', directory: 'myDir', - tags: 'one,two' + tags: 'one,two', }, tree ); const nxJson2 = readJsonInTree(tree2, '/nx.json'); expect(nxJson2.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] + tags: ['one'], }, 'my-dir-my-lib2': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -162,9 +162,9 @@ describe('lib', () => { exclude: ['**/node_modules/**', '!libs/my-dir/my-lib/**'], tsConfig: [ 'libs/my-dir/my-lib/tsconfig.lib.json', - 'libs/my-dir/my-lib/tsconfig.spec.json' - ] - } + 'libs/my-dir/my-lib/tsconfig.spec.json', + ], + }, }); }); @@ -175,9 +175,9 @@ describe('lib', () => { appTree ); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); - expect(tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib']).toEqual( - ['libs/my-dir/my-lib/src/index.ts'] - ); + expect( + tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib'] + ).toEqual(['libs/my-dir/my-lib/src/index.ts']); expect( tsconfigJson.compilerOptions.paths['my-dir-my-lib/*'] ).toBeUndefined(); @@ -197,9 +197,9 @@ describe('lib', () => { expect(tsconfigJson).toEqual({ extends: '../../../tsconfig.json', compilerOptions: { - types: ['node', 'jest'] + types: ['node', 'jest'], }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); }); }); @@ -223,9 +223,9 @@ describe('lib', () => { expect(tsconfigJson).toEqual({ extends: '../../tsconfig.json', compilerOptions: { - types: ['node'] + types: ['node'], }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); expect( workspaceJson.projects['my-lib'].architect.lint.options.tsConfig diff --git a/packages/node/src/schematics/library/library.ts b/packages/node/src/schematics/library/library.ts index 7aa1b0d330c99..0b80d1f1c9f52 100644 --- a/packages/node/src/schematics/library/library.ts +++ b/packages/node/src/schematics/library/library.ts @@ -12,7 +12,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { formatFiles, @@ -22,7 +22,7 @@ import { toFileName, updateJsonInTree, updateWorkspaceInTree, - getNpmScope + getNpmScope, } from '@nrwl/workspace'; import { Schema } from './schema'; @@ -35,7 +35,7 @@ export interface NormalizedSchema extends Schema { parsedTags: string[]; } -export default function(schema: NormalizedSchema): Rule { +export default function (schema: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); @@ -44,7 +44,7 @@ export default function(schema: NormalizedSchema): Rule { createFiles(options), updateTsConfig(options), addProject(options), - formatFiles(options) + formatFiles(options), ]); }; } @@ -61,7 +61,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { const projectRoot = normalize(`libs/${projectDirectory}`); const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const normalized: NormalizedSchema = { @@ -71,7 +71,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { name: projectName, projectRoot, projectDirectory, - parsedTags + parsedTags, }; return normalized; @@ -84,15 +84,15 @@ function createFiles(options: NormalizedSchema): Rule { ...options, ...names(options.name), tmpl: '', - offsetFromRoot: offsetFromRoot(options.projectRoot) + offsetFromRoot: offsetFromRoot(options.projectRoot), }), move(options.projectRoot), options.unitTestRunner === 'none' - ? filter(file => !file.endsWith('spec.ts')) + ? filter((file) => !file.endsWith('spec.ts')) : noop(), options.publishable ? noop() - : filter(file => !file.endsWith('package.json')) + : filter((file) => !file.endsWith('package.json')), ]), MergeStrategy.Overwrite ); @@ -105,7 +105,7 @@ function updateTsConfig(options: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const projectConfig = getProjectConfig(host, options.name); - return updateJsonInTree(`${projectConfig.root}/tsconfig.json`, json => { + return updateJsonInTree(`${projectConfig.root}/tsconfig.json`, (json) => { json.compilerOptions.types.push('jest'); return json; }); @@ -117,7 +117,7 @@ function addProject(options: NormalizedSchema): Rule { return noop(); } - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const architect = json.projects[options.name].architect; if (architect) { architect.build = { @@ -127,8 +127,8 @@ function addProject(options: NormalizedSchema): Rule { tsConfig: `${options.projectRoot}/tsconfig.lib.json`, packageJson: `${options.projectRoot}/package.json`, main: `${options.projectRoot}/src/index.ts`, - assets: [`${options.projectRoot}/*.md`] - } + assets: [`${options.projectRoot}/*.md`], + }, }; } return json; diff --git a/packages/node/src/utils/config.spec.ts b/packages/node/src/utils/config.spec.ts index e57aff0f2f097..de5e49c631c04 100644 --- a/packages/node/src/utils/config.spec.ts +++ b/packages/node/src/utils/config.spec.ts @@ -19,11 +19,11 @@ describe('getBaseWebpackPartial', () => { tsConfig: 'tsconfig.json', fileReplacements: [], root: getSystemPath(normalize('/root')), - statsJson: false + statsJson: false, }; - (TsConfigPathsPlugin).mockImplementation( - function MockPathsPlugin() {} - ); + (( + TsConfigPathsPlugin + )).mockImplementation(function MockPathsPlugin() {}); }); describe('unconditional options', () => { @@ -42,7 +42,7 @@ describe('getBaseWebpackPartial', () => { it('should have a rule for typescript', () => { const result = getBaseWebpackPartial(input); - const typescriptRule = result.module.rules.find(rule => + const typescriptRule = result.module.rules.find((rule) => (rule.test as RegExp).test('app/main.ts') ); expect(typescriptRule).toBeTruthy(); @@ -54,7 +54,7 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin).toBeTruthy(); }); @@ -63,7 +63,7 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); expect(result.performance).toEqual({ - hints: false + hints: false, }); }); @@ -75,15 +75,15 @@ describe('getBaseWebpackPartial', () => { '.tsx', '.mjs', '.js', - '.jsx' + '.jsx', ]); }); it('should include module and main in mainFields', () => { spyOn(ts, 'parseJsonConfigFileContent').and.returnValue({ options: { - target: 'es5' - } + target: 'es5', + }, }); const result = getBaseWebpackPartial(input); @@ -102,7 +102,7 @@ describe('getBaseWebpackPartial', () => { cachedAssets: false, modules: false, warnings: true, - errors: true + errors: true, }) ); }); @@ -113,7 +113,7 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); expect(result.entry).toEqual({ - main: ['main.ts'] + main: ['main.ts'], }); }); }); @@ -131,11 +131,11 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); expect( - result.module.rules.find(rule => rule.loader === 'ts-loader').options + result.module.rules.find((rule) => rule.loader === 'ts-loader').options ).toEqual({ configFile: 'tsconfig.json', transpileOnly: true, - experimentalWatchApi: true + experimentalWatchApi: true, }); }); @@ -143,7 +143,7 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin.options.tsconfig).toBe('tsconfig.json'); }); @@ -152,14 +152,14 @@ describe('getBaseWebpackPartial', () => { spyOn(ts, 'parseJsonConfigFileContent').and.returnValue({ options: { paths: { - '@npmScope/libraryName': ['libs/libraryName/src/index.ts'] - } - } + '@npmScope/libraryName': ['libs/libraryName/src/index.ts'], + }, + }, }); const result = getBaseWebpackPartial(input); expect( result.resolve.plugins.some( - plugin => plugin instanceof TsConfigPathsPlugin + (plugin) => plugin instanceof TsConfigPathsPlugin ) ).toEqual(true); }); @@ -167,8 +167,8 @@ describe('getBaseWebpackPartial', () => { it('should include es2015 in mainFields if typescript is set es2015', () => { spyOn(ts, 'parseJsonConfigFileContent').and.returnValue({ options: { - target: 'es2015' - } + target: 'es2015', + }, }); const result = getBaseWebpackPartial(input); @@ -179,7 +179,7 @@ describe('getBaseWebpackPartial', () => { describe('the file replacements option', () => { it('should set aliases', () => { spyOn(ts, 'parseJsonConfigFileContent').and.returnValue({ - options: {} + options: {}, }); const result = getBaseWebpackPartial({ @@ -187,13 +187,13 @@ describe('getBaseWebpackPartial', () => { fileReplacements: [ { replace: 'environments/environment.ts', - with: 'environments/environment.prod.ts' - } - ] + with: 'environments/environment.prod.ts', + }, + ], }); expect(result.resolve.alias).toEqual({ - 'environments/environment.ts': 'environments/environment.prod.ts' + 'environments/environment.ts': 'environments/environment.prod.ts', }); }); }); @@ -202,7 +202,7 @@ describe('getBaseWebpackPartial', () => { it('should enable file watching', () => { const result = getBaseWebpackPartial({ ...input, - watch: true + watch: true, }); expect(result.watch).toEqual(true); @@ -213,7 +213,7 @@ describe('getBaseWebpackPartial', () => { it('should determine the polling rate', () => { const result = getBaseWebpackPartial({ ...input, - poll: 1000 + poll: 1000, }); expect(result.watchOptions.poll).toEqual(1000); @@ -224,7 +224,7 @@ describe('getBaseWebpackPartial', () => { it('should enable source-map devtool', () => { const result = getBaseWebpackPartial({ ...input, - sourceMap: true + sourceMap: true, }); expect(result.devtool).toEqual('source-map'); @@ -233,7 +233,7 @@ describe('getBaseWebpackPartial', () => { it('should disable source-map devtool', () => { const result = getBaseWebpackPartial({ ...input, - sourceMap: false + sourceMap: false, }); expect(result.devtool).toEqual(false); @@ -253,7 +253,7 @@ describe('getBaseWebpackPartial', () => { it('should set the mode to production', () => { const result = getBaseWebpackPartial({ ...input, - optimization: true + optimization: true, }); expect(result.mode).toEqual('production'); @@ -265,11 +265,11 @@ describe('getBaseWebpackPartial', () => { it('should set the maximum workers for the type checker', () => { const result = getBaseWebpackPartial({ ...input, - maxWorkers: 1 + maxWorkers: 1, }); const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin.options.workers).toEqual(1); }); @@ -279,11 +279,11 @@ describe('getBaseWebpackPartial', () => { it('should set the memory limit for the type checker', () => { const result = getBaseWebpackPartial({ ...input, - memoryLimit: 512 + memoryLimit: 512, }); const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin.options.memoryLimit).toEqual(512); }); @@ -297,20 +297,20 @@ describe('getBaseWebpackPartial', () => { { input: 'assets', glob: '**/*', - output: 'assets' + output: 'assets', }, { input: '', glob: 'file.txt', - output: '' - } - ] + output: '', + }, + ], }); // This test isn't great because it's hard to find CopyWebpackPlugin expect( result.plugins.some( - plugin => !(plugin instanceof ForkTsCheckerWebpackPlugin) + (plugin) => !(plugin instanceof ForkTsCheckerWebpackPlugin) ) ).toBeTruthy(); }); @@ -320,12 +320,12 @@ describe('getBaseWebpackPartial', () => { it('should show warnings for circular dependencies', () => { const result = getBaseWebpackPartial({ ...input, - showCircularDependencies: true + showCircularDependencies: true, }); expect( result.plugins.find( - plugin => plugin instanceof CircularDependencyPlugin + (plugin) => plugin instanceof CircularDependencyPlugin ) ).toBeTruthy(); }); @@ -333,11 +333,11 @@ describe('getBaseWebpackPartial', () => { it('should exclude node modules', () => { const result = getBaseWebpackPartial({ ...input, - showCircularDependencies: true + showCircularDependencies: true, }); const circularDependencyPlugin: CircularDependencyPlugin = result.plugins.find( - plugin => plugin instanceof CircularDependencyPlugin + (plugin) => plugin instanceof CircularDependencyPlugin ); expect(circularDependencyPlugin.options.exclude).toEqual( /[\\\/]node_modules[\\\/]/ @@ -349,11 +349,11 @@ describe('getBaseWebpackPartial', () => { it('should extract licenses to a separate file', () => { const result = getBaseWebpackPartial({ ...input, - extractLicenses: true + extractLicenses: true, }); const licensePlugin = result.plugins.find( - plugin => plugin instanceof LicenseWebpackPlugin + (plugin) => plugin instanceof LicenseWebpackPlugin ); expect(licensePlugin).toBeTruthy(); @@ -364,11 +364,11 @@ describe('getBaseWebpackPartial', () => { it('should show build progress', () => { const result = getBaseWebpackPartial({ ...input, - progress: true + progress: true, }); expect( - result.plugins.find(plugin => plugin instanceof ProgressPlugin) + result.plugins.find((plugin) => plugin instanceof ProgressPlugin) ).toBeTruthy(); }); }); @@ -390,7 +390,7 @@ describe('getBaseWebpackPartial', () => { version: false, errorDetails: false, moduleTrace: false, - usedExports: false + usedExports: false, }) ); }); @@ -413,7 +413,7 @@ describe('getBaseWebpackPartial', () => { version: true, errorDetails: true, moduleTrace: true, - usedExports: true + usedExports: true, }) ); }); diff --git a/packages/node/src/utils/config.ts b/packages/node/src/utils/config.ts index c374847532b13..5434228f93812 100644 --- a/packages/node/src/utils/config.ts +++ b/packages/node/src/utils/config.ts @@ -24,13 +24,13 @@ export function getBaseWebpackPartial( const extensions = ['.ts', '.tsx', '.mjs', '.js', '.jsx']; const webpackConfig: Configuration = { entry: { - main: [options.main] + main: [options.main], }, devtool: options.sourceMap ? 'source-map' : false, mode: options.optimization ? 'production' : 'development', output: { path: options.outputPath, - filename: OUT_FILENAME + filename: OUT_FILENAME, }, module: { rules: [ @@ -42,10 +42,10 @@ export function getBaseWebpackPartial( configFile: options.tsConfig, transpileOnly: true, // https://github.com/TypeStrong/ts-loader/pull/685 - experimentalWatchApi: true - } - } - ] + experimentalWatchApi: true, + }, + }, + ], }, resolve: { extensions, @@ -54,13 +54,13 @@ export function getBaseWebpackPartial( new TsConfigPathsPlugin({ configFile: options.tsConfig, extensions, - mainFields - }) + mainFields, + }), ], - mainFields + mainFields, }, performance: { - hints: false + hints: false, }, plugins: [ new ForkTsCheckerWebpackPlugin({ @@ -69,14 +69,14 @@ export function getBaseWebpackPartial( options.memoryLimit || ForkTsCheckerWebpackPlugin.DEFAULT_MEMORY_LIMIT, workers: options.maxWorkers || ForkTsCheckerWebpackPlugin.TWO_CPUS_FREE, - useTypescriptIncrementalApi: false - }) + useTypescriptIncrementalApi: false, + }), ], watch: options.watch, watchOptions: { - poll: options.poll + poll: options.poll, }, - stats: getStatsConfig(options) + stats: getStatsConfig(options), }; const extraPlugins: webpack.Plugin[] = []; @@ -86,13 +86,15 @@ export function getBaseWebpackPartial( } if (options.extractLicenses) { - extraPlugins.push((new LicenseWebpackPlugin({ - stats: { - errors: false - }, - perChunkOutput: false, - outputFilename: `3rdpartylicenses.txt` - }) as unknown) as webpack.Plugin); + extraPlugins.push( + (new LicenseWebpackPlugin({ + stats: { + errors: false, + }, + perChunkOutput: false, + outputFilename: `3rdpartylicenses.txt`, + }) as unknown) as webpack.Plugin + ); } // process asset entries @@ -105,13 +107,13 @@ export function getBaseWebpackPartial( ignore: asset.ignore, from: { glob: asset.glob, - dot: true - } + dot: true, + }, }; }); const copyWebpackPluginOptions = { - ignore: ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'] + ignore: ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'], }; const copyWebpackPluginInstance = new CopyWebpackPlugin( @@ -124,7 +126,7 @@ export function getBaseWebpackPartial( if (options.showCircularDependencies) { extraPlugins.push( new CircularDependencyPlugin({ - exclude: /[\\\/]node_modules[\\\/]/ + exclude: /[\\\/]node_modules[\\\/]/, }) ); } @@ -138,7 +140,7 @@ function getAliases(options: BuildBuilderOptions): { [key: string]: string } { return options.fileReplacements.reduce( (aliases, replacement) => ({ ...aliases, - [replacement.replace]: replacement.with + [replacement.replace]: replacement.with, }), {} ); @@ -163,6 +165,6 @@ function getStatsConfig(options: BuildBuilderOptions): Stats.ToStringOptions { version: !!options.verbose, errorDetails: !!options.verbose, moduleTrace: !!options.verbose, - usedExports: !!options.verbose + usedExports: !!options.verbose, }; } diff --git a/packages/node/src/utils/node.config.spec.ts b/packages/node/src/utils/node.config.spec.ts index c5fb2ed02fb94..7f9bd701d6a78 100644 --- a/packages/node/src/utils/node.config.spec.ts +++ b/packages/node/src/utils/node.config.spec.ts @@ -13,11 +13,11 @@ describe('getNodePartial', () => { tsConfig: 'tsconfig.json', externalDependencies: 'all', fileReplacements: [], - statsJson: false + statsJson: false, }; - (TsConfigPathsPlugin).mockImplementation( - function MockPathsPlugin() {} - ); + (( + TsConfigPathsPlugin + )).mockImplementation(function MockPathsPlugin() {}); }); describe('unconditionally', () => { @@ -43,7 +43,7 @@ describe('getNodePartial', () => { it('should not minify', () => { const result = getNodeWebpackConfig({ ...input, - optimization: true + optimization: true, }); expect(result.optimization.minimize).toEqual(false); @@ -52,7 +52,7 @@ describe('getNodePartial', () => { it('should not concatenate modules', () => { const result = getNodeWebpackConfig({ ...input, - optimization: true + optimization: true, }); expect(result.optimization.concatenateModules).toEqual(false); @@ -70,7 +70,7 @@ describe('getNodePartial', () => { it('should change given module names to commonjs imports but not others', () => { const result = getNodeWebpackConfig({ ...input, - externalDependencies: ['module1'] + externalDependencies: ['module1'], }); const callback = jest.fn(); result.externals[0](null, 'module1', callback); @@ -82,7 +82,7 @@ describe('getNodePartial', () => { it('should not change any modules to commonjs imports', () => { const result = getNodeWebpackConfig({ ...input, - externalDependencies: 'none' + externalDependencies: 'none', }); expect(result.externals).not.toBeDefined(); diff --git a/packages/node/src/utils/node.config.ts b/packages/node/src/utils/node.config.ts index 550a8efc0539f..4e24f49dea3a1 100644 --- a/packages/node/src/utils/node.config.ts +++ b/packages/node/src/utils/node.config.ts @@ -8,16 +8,16 @@ import { getBaseWebpackPartial } from './config'; function getNodePartial(options: BuildNodeBuilderOptions) { const webpackConfig: Configuration = { output: { - libraryTarget: 'commonjs' + libraryTarget: 'commonjs', }, target: 'node', - node: false + node: false, }; if (options.optimization) { webpackConfig.optimization = { minimize: false, - concatenateModules: false + concatenateModules: false, }; } @@ -25,14 +25,14 @@ function getNodePartial(options: BuildNodeBuilderOptions) { webpackConfig.externals = [nodeExternals()]; } else if (Array.isArray(options.externalDependencies)) { webpackConfig.externals = [ - function(context, request, callback: Function) { + function (context, request, callback: Function) { if (options.externalDependencies.includes(request)) { // not bundled return callback(null, 'commonjs ' + request); } // bundled callback(); - } + }, ]; } return webpackConfig; @@ -41,6 +41,6 @@ function getNodePartial(options: BuildNodeBuilderOptions) { export function getNodeWebpackConfig(options: BuildNodeBuilderOptions) { return mergeWebpack([ getBaseWebpackPartial(options), - getNodePartial(options) + getNodePartial(options), ]); } diff --git a/packages/node/src/utils/normalize.spec.ts b/packages/node/src/utils/normalize.spec.ts index 215132af4ce58..0deab2f693d3a 100644 --- a/packages/node/src/utils/normalize.spec.ts +++ b/packages/node/src/utils/normalize.spec.ts @@ -17,15 +17,15 @@ describe('normalizeBuildOptions', () => { fileReplacements: [ { replace: 'apps/environment/environment.ts', - with: 'apps/environment/environment.prod.ts' + with: 'apps/environment/environment.prod.ts', }, { replace: 'module1.ts', - with: 'module2.ts' - } + with: 'module2.ts', + }, ], assets: [], - statsJson: false + statsJson: false, }; root = '/root'; sourceRoot = normalize('apps/nodeapp/src'); @@ -52,7 +52,7 @@ describe('normalizeBuildOptions', () => { it('should normalize asset patterns', () => { spyOn(fs, 'statSync').and.returnValue({ - isDirectory: () => true + isDirectory: () => true, }); const result = normalizeBuildOptions( { @@ -64,9 +64,9 @@ describe('normalizeBuildOptions', () => { input: 'outsideproj', output: 'output', glob: '**/*', - ignore: ['**/*.json'] - } - ] + ignore: ['**/*.json'], + }, + ], }, root, sourceRoot @@ -75,14 +75,14 @@ describe('normalizeBuildOptions', () => { { input: '/root/apps/nodeapp/src/assets', output: 'assets', - glob: '**/*' + glob: '**/*', }, { input: '/root/outsideproj', output: 'output', glob: '**/*', - ignore: ['**/*.json'] - } + ignore: ['**/*.json'], + }, ]); }); @@ -91,12 +91,12 @@ describe('normalizeBuildOptions', () => { expect(result.fileReplacements).toEqual([ { replace: '/root/apps/environment/environment.ts', - with: '/root/apps/environment/environment.prod.ts' + with: '/root/apps/environment/environment.prod.ts', }, { replace: '/root/module1.ts', - with: '/root/module2.ts' - } + with: '/root/module2.ts', + }, ]); }); }); diff --git a/packages/node/src/utils/normalize.ts b/packages/node/src/utils/normalize.ts index a0a74da9c5d8c..7c1a153944dcd 100644 --- a/packages/node/src/utils/normalize.ts +++ b/packages/node/src/utils/normalize.ts @@ -24,7 +24,7 @@ export function normalizeBuildOptions( assets: normalizeAssets(options.assets, root, sourceRoot), webpackConfig: options.webpackConfig ? resolve(root, options.webpackConfig) - : options.webpackConfig + : options.webpackConfig, }; } @@ -33,7 +33,7 @@ function normalizeAssets( root: string, sourceRoot: string ): any[] { - return assets.map(asset => { + return assets.map((asset) => { if (typeof asset === 'string') { const assetPath = normalize(asset); const resolvedAssetPath = resolve(root, assetPath); @@ -54,7 +54,7 @@ function normalizeAssets( return { input, output, - glob + glob, }; } else { if (asset.output.startsWith('..')) { @@ -69,7 +69,7 @@ function normalizeAssets( ...asset, input: resolvedAssetPath, // Now we remove starting slash to make Webpack place it from the output root. - output: asset.output.replace(/^\//, '') + output: asset.output.replace(/^\//, ''), }; } }); @@ -79,8 +79,8 @@ function normalizeFileReplacements( root: string, fileReplacements: FileReplacement[] ): FileReplacement[] { - return fileReplacements.map(fileReplacement => ({ + return fileReplacements.map((fileReplacement) => ({ replace: resolve(root, fileReplacement.replace), - with: resolve(root, fileReplacement.with) + with: resolve(root, fileReplacement.with), })); } diff --git a/packages/nx-plugin/src/builders/e2e/e2e.impl.spec.ts b/packages/nx-plugin/src/builders/e2e/e2e.impl.spec.ts index 55309b4ea1597..3e93016983637 100644 --- a/packages/nx-plugin/src/builders/e2e/e2e.impl.spec.ts +++ b/packages/nx-plugin/src/builders/e2e/e2e.impl.spec.ts @@ -18,7 +18,7 @@ describe('NxPluginE2EBuilder', () => { testOptions = { jestConfig: 'apps/plugin-e2e/jest.config.js', tsSpecConfig: 'apps/plugin-e2e/tsconfig.spec.js', - target: 'plugin:build' + target: 'plugin:build', }; scheduleTargetAndForgetSpy = jest @@ -38,11 +38,11 @@ describe('NxPluginE2EBuilder', () => { info: { builderName: 'builder', description: '', - optionSchema: {} + optionSchema: {}, }, output: of({ success: true }), progress: of({} as any), - stop: jest.fn() + stop: jest.fn(), }); }); }); @@ -52,12 +52,12 @@ describe('NxPluginE2EBuilder', () => { await runNxPluginE2EBuilder(testOptions, context).toPromise(); expect(scheduleTargetAndForgetSpy).toHaveBeenCalledWith(context, { project: 'plugin', - target: 'build' + target: 'build', }); expect(contextBuilderSpy).toHaveBeenCalledWith('@nrwl/jest:jest', { tsConfig: testOptions.tsSpecConfig, jestConfig: testOptions.jestConfig, - watch: false + watch: false, }); }); }); diff --git a/packages/nx-plugin/src/builders/e2e/e2e.impl.ts b/packages/nx-plugin/src/builders/e2e/e2e.impl.ts index 4d1ea0f1c83ad..fb9328836b415 100644 --- a/packages/nx-plugin/src/builders/e2e/e2e.impl.ts +++ b/packages/nx-plugin/src/builders/e2e/e2e.impl.ts @@ -2,7 +2,7 @@ import { BuilderContext, createBuilder, scheduleTargetAndForget, - targetFromTargetString + targetFromTargetString, } from '@angular-devkit/architect'; import { switchMap, concatMap } from 'rxjs/operators'; import { Schema } from './schema'; @@ -25,9 +25,9 @@ export function runNxPluginE2EBuilder( context.scheduleBuilder('@nrwl/jest:jest', { tsConfig: options.tsSpecConfig, jestConfig: options.jestConfig, - watch: false + watch: false, }) - ).pipe(concatMap(run => run.output)); + ).pipe(concatMap((run) => run.output)); }) ); } diff --git a/packages/nx-plugin/src/schematics/builder/builder.spec.ts b/packages/nx-plugin/src/schematics/builder/builder.spec.ts index 350d976076d5c..6ce4f45ce480b 100644 --- a/packages/nx-plugin/src/schematics/builder/builder.spec.ts +++ b/packages/nx-plugin/src/schematics/builder/builder.spec.ts @@ -19,7 +19,7 @@ describe('NxPlugin builder', () => { 'builder', { project: projectName, - name: 'my-builder' + name: 'my-builder', }, appTree ); @@ -44,7 +44,7 @@ describe('NxPlugin builder', () => { { project: projectName, name: 'my-builder', - description: 'my-builder description' + description: 'my-builder description', }, appTree ); @@ -67,7 +67,7 @@ describe('NxPlugin builder', () => { 'builder', { project: projectName, - name: 'my-builder' + name: 'my-builder', }, appTree ); @@ -85,7 +85,7 @@ describe('NxPlugin builder', () => { { project: projectName, name: 'my-builder', - description: 'my-builder custom description' + description: 'my-builder custom description', }, appTree ); @@ -105,7 +105,7 @@ describe('NxPlugin builder', () => { { project: projectName, name: 'my-builder', - unitTestRunner: 'none' + unitTestRunner: 'none', }, appTree ); diff --git a/packages/nx-plugin/src/schematics/builder/builder.ts b/packages/nx-plugin/src/schematics/builder/builder.ts index 271f96a28df2d..e3416cafef053 100644 --- a/packages/nx-plugin/src/schematics/builder/builder.ts +++ b/packages/nx-plugin/src/schematics/builder/builder.ts @@ -9,14 +9,14 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { getProjectConfig, names, readNxJsonInTree, toFileName, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import * as path from 'path'; import { Schema } from './schema'; @@ -28,7 +28,7 @@ export interface NormalizedSchema extends Schema { npmScope: string; } -export default function(schema: NormalizedSchema): Rule { +export default function (schema: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); @@ -59,7 +59,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { description, projectRoot, projectSourceRoot, - npmScope + npmScope, }; return normalized; @@ -71,12 +71,12 @@ function addFiles(options: NormalizedSchema): Rule { template({ ...options, ...names(options.name), - tmpl: '' + tmpl: '', }), options.unitTestRunner === 'none' - ? filter(file => !file.endsWith('.spec.ts')) + ? filter((file) => !file.endsWith('.spec.ts')) : noop(), - move(`${options.projectSourceRoot}/builders`) + move(`${options.projectSourceRoot}/builders`), ]) ); } @@ -84,12 +84,12 @@ function addFiles(options: NormalizedSchema): Rule { function updateBuildersJson(options: NormalizedSchema): Rule { return updateJsonInTree( path.join(options.projectRoot, 'builders.json'), - json => { + (json) => { const builders = json.builders ? json.builders : {}; builders[options.name] = { implementation: `./src/builders/${options.name}/builder`, schema: `./src/builders/${options.name}/schema.json`, - description: options.description + description: options.description, }; json.builders = builders; diff --git a/packages/nx-plugin/src/schematics/e2e-project/e2e.spec.ts b/packages/nx-plugin/src/schematics/e2e-project/e2e.spec.ts index b92fcf538a17f..28411bb481f0f 100644 --- a/packages/nx-plugin/src/schematics/e2e-project/e2e.spec.ts +++ b/packages/nx-plugin/src/schematics/e2e-project/e2e.spec.ts @@ -4,7 +4,7 @@ import { updateWorkspace, readJsonInTree, readWorkspace, - getWorkspace + getWorkspace, } from '@nrwl/workspace'; import { runSchematic } from '../../utils/testing'; @@ -13,7 +13,7 @@ describe('NxPlugin e2e-project', () => { beforeEach(() => { appTree = createEmptyWorkspace(Tree.empty()); // add a plugin project to the workspace for validations - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: 'my-plugin', root: 'libs/my-plugin' }); })(appTree, null); }); @@ -25,7 +25,7 @@ describe('NxPlugin e2e-project', () => { { pluginName: 'my-plugin', pluginOutputPath: `dist/libs/my-plugin`, - npmPackageName: '@proj/my-plugin' + npmPackageName: '@proj/my-plugin', }, appTree ) @@ -37,7 +37,7 @@ describe('NxPlugin e2e-project', () => { { pluginName: 'my-nonexistentplugin', pluginOutputPath: `dist/libs/my-nonexistentplugin`, - npmPackageName: '@proj/my-nonexistentplugin' + npmPackageName: '@proj/my-nonexistentplugin', }, appTree ) @@ -50,7 +50,7 @@ describe('NxPlugin e2e-project', () => { { pluginName: 'my-plugin', pluginOutputPath: `dist/libs/my-plugin`, - npmPackageName: '@proj/my-plugin' + npmPackageName: '@proj/my-plugin', }, appTree ); @@ -66,7 +66,7 @@ describe('NxPlugin e2e-project', () => { { pluginName: 'my-plugin', pluginOutputPath: `dist/libs/my-plugin`, - npmPackageName: '@proj/my-plugin' + npmPackageName: '@proj/my-plugin', }, appTree ); @@ -74,9 +74,9 @@ describe('NxPlugin e2e-project', () => { projects: { 'my-plugin-e2e': { tags: [], - implicitDependencies: ['my-plugin'] - } - } + implicitDependencies: ['my-plugin'], + }, + }, }); }); @@ -86,7 +86,7 @@ describe('NxPlugin e2e-project', () => { { pluginName: 'my-plugin', pluginOutputPath: `dist/libs/my-plugin`, - npmPackageName: '@proj/my-plugin' + npmPackageName: '@proj/my-plugin', }, appTree ); @@ -100,8 +100,8 @@ describe('NxPlugin e2e-project', () => { options: expect.objectContaining({ target: 'my-plugin:build', npmPackageName: '@proj/my-plugin', - pluginOutputPath: 'dist/libs/my-plugin' - }) + pluginOutputPath: 'dist/libs/my-plugin', + }), }); }); @@ -111,7 +111,7 @@ describe('NxPlugin e2e-project', () => { { pluginName: 'my-plugin', pluginOutputPath: `dist/libs/my-plugin`, - npmPackageName: '@proj/my-plugin' + npmPackageName: '@proj/my-plugin', }, appTree ); @@ -120,8 +120,8 @@ describe('NxPlugin e2e-project', () => { expect(project.targets.get('e2e')).toMatchObject({ options: expect.objectContaining({ tsSpecConfig: 'apps/my-plugin-e2e/tsconfig.spec.json', - jestConfig: 'apps/my-plugin-e2e/jest.config.js' - }) + jestConfig: 'apps/my-plugin-e2e/jest.config.js', + }), }); expect(tree.exists('apps/my-plugin-e2e/tsconfig.spec.json')).toBeTruthy(); diff --git a/packages/nx-plugin/src/schematics/e2e-project/e2e.ts b/packages/nx-plugin/src/schematics/e2e-project/e2e.ts index de55164003a9c..6cfec491428b0 100644 --- a/packages/nx-plugin/src/schematics/e2e-project/e2e.ts +++ b/packages/nx-plugin/src/schematics/e2e-project/e2e.ts @@ -11,7 +11,7 @@ import { SchematicsException, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { addProjectToNxJsonInTree, @@ -19,7 +19,7 @@ import { offsetFromRoot, readNxJsonInTree, toPropertyName, - updateWorkspace + updateWorkspace, } from '@nrwl/workspace'; import { join } from 'path'; import { Schema } from './schema'; @@ -31,7 +31,7 @@ export interface NxPluginE2ESchema extends Schema { npmScope: string; } -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { return async (host: Tree, context: SchematicContext) => { const workspace = await getWorkspace(host); validatePlugin(workspace, options.pluginName); @@ -40,7 +40,7 @@ export default function(options: Schema): Rule { updateFiles(normalizedOptions), updateNxJson(normalizedOptions), updateWorkspaceJson(normalizedOptions), - addJest(normalizedOptions) + addJest(normalizedOptions), ]); }; } @@ -64,14 +64,14 @@ function normalizeOptions(host: Tree, options: Schema): NxPluginE2ESchema { projectName, pluginPropertyName, projectRoot, - npmScope + npmScope, }; } function updateNxJson(options: NxPluginE2ESchema): Rule { return addProjectToNxJsonInTree(options.projectName, { tags: [], - implicitDependencies: [options.pluginName] + implicitDependencies: [options.pluginName], }); } @@ -90,13 +90,13 @@ function updateWorkspaceJson(options: NxPluginE2ESchema): Rule { options: { target: `${options.pluginName}:build`, npmPackageName: options.npmPackageName, - pluginOutputPath: options.pluginOutputPath - } - } - } + pluginOutputPath: options.pluginOutputPath, + }, + }, + }, }); return updateWorkspace(workspace); - } + }, ]); } @@ -106,9 +106,9 @@ function updateFiles(options: NxPluginE2ESchema): Rule { template({ tmpl: '', ...options, - offsetFromRoot: offsetFromRoot(options.projectRoot) + offsetFromRoot: offsetFromRoot(options.projectRoot), }), - move(options.projectRoot) + move(options.projectRoot), ]) ); } @@ -119,7 +119,7 @@ function addJest(options: NxPluginE2ESchema): Rule { project: options.projectName, setupFile: 'none', supportTsx: false, - skipSerializers: true + skipSerializers: true, }), async (host, context) => { const workspace = await getWorkspace(host); @@ -130,14 +130,14 @@ function addJest(options: NxPluginE2ESchema): Rule { ...e2eOptions, ...{ jestConfig: testOptions.jestConfig, - tsSpecConfig: testOptions.tsConfig - } + tsSpecConfig: testOptions.tsConfig, + }, }; // remove the jest build target project.targets.delete('test'); return updateWorkspace(workspace); - } + }, ]); } diff --git a/packages/nx-plugin/src/schematics/migration/migration.spec.ts b/packages/nx-plugin/src/schematics/migration/migration.spec.ts index 5832afde0b422..a99c2f988c715 100644 --- a/packages/nx-plugin/src/schematics/migration/migration.spec.ts +++ b/packages/nx-plugin/src/schematics/migration/migration.spec.ts @@ -19,7 +19,7 @@ describe('NxPlugin migration', () => { 'migration', { project: projectName, - version: '1.0.0' + version: '1.0.0', }, appTree ); @@ -29,7 +29,7 @@ describe('NxPlugin migration', () => { expect(project.architect.build.options.assets).toContainEqual({ input: './libs/my-plugin', glob: 'migrations.json', - output: '.' + output: '.', }); }); @@ -40,7 +40,7 @@ describe('NxPlugin migration', () => { project: projectName, name: 'my-migration', description: 'my-migration description', - version: '1.0.0' + version: '1.0.0', }, appTree ); @@ -78,7 +78,7 @@ describe('NxPlugin migration', () => { { project: projectName, description: 'my-migration description', - version: '1.0.0' + version: '1.0.0', }, appTree ); @@ -103,7 +103,7 @@ describe('NxPlugin migration', () => { { project: projectName, name: 'my-migration', - version: '1.0.0' + version: '1.0.0', }, appTree ); @@ -125,7 +125,7 @@ describe('NxPlugin migration', () => { project: projectName, name: 'my-migration', version: '1.0.0', - packageJsonUpdates: true + packageJsonUpdates: true, }, appTree ); @@ -138,8 +138,8 @@ describe('NxPlugin migration', () => { expect(migrationsJson.packageJsonUpdates).toEqual({ ['1.0.0']: { version: '1.0.0', - packages: {} - } + packages: {}, + }, }); }); @@ -152,7 +152,7 @@ describe('NxPlugin migration', () => { project: projectName, name: 'my-migration', version: '1.0.0', - unitTestRunner: 'none' + unitTestRunner: 'none', }, appTree ); diff --git a/packages/nx-plugin/src/schematics/migration/migration.ts b/packages/nx-plugin/src/schematics/migration/migration.ts index 57805f1ab36d6..7a8da93b2ed5d 100644 --- a/packages/nx-plugin/src/schematics/migration/migration.ts +++ b/packages/nx-plugin/src/schematics/migration/migration.ts @@ -10,13 +10,13 @@ import { Tree, url, filter, - noop + noop, } from '@angular-devkit/schematics'; import { getProjectConfig, toFileName, updateJsonInTree, - updateWorkspace + updateWorkspace, } from '@nrwl/workspace'; import * as path from 'path'; import { Schema } from './schema'; @@ -26,7 +26,7 @@ export interface NormalizedSchema extends Schema { projectSourceRoot: string; } -export default function(schema: NormalizedSchema): Rule { +export default function (schema: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); @@ -34,7 +34,7 @@ export default function(schema: NormalizedSchema): Rule { addFiles(options), updateMigrationsJson(options), updateWorkspaceJson(options), - updatePackageJson(options) + updatePackageJson(options), ]); }; } @@ -64,7 +64,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { name, description, projectRoot, - projectSourceRoot + projectSourceRoot, }; return normalized; @@ -75,18 +75,18 @@ function addFiles(options: NormalizedSchema): Rule { apply(url(`./files/migration`), [ template({ ...options, - tmpl: '' + tmpl: '', }), options.unitTestRunner === 'none' - ? filter(file => !file.endsWith('.spec.ts')) + ? filter((file) => !file.endsWith('.spec.ts')) : noop(), - move(`${options.projectSourceRoot}/migrations`) + move(`${options.projectSourceRoot}/migrations`), ]) ); } function updateWorkspaceJson(options: NormalizedSchema): Rule { - return updateWorkspace(workspace => { + return updateWorkspace((workspace) => { const targets = workspace.projects.get(options.project).targets; const build = targets.get('build'); if (build) { @@ -95,8 +95,8 @@ function updateWorkspaceJson(options: NormalizedSchema): Rule { { input: `./${options.projectRoot}`, glob: 'migrations.json', - output: '.' - } + output: '.', + }, ] ); } @@ -106,12 +106,12 @@ function updateWorkspaceJson(options: NormalizedSchema): Rule { function updateMigrationsJson(options: NormalizedSchema): Rule { return updateJsonInTree( path.join(options.projectRoot, 'migrations.json'), - json => { + (json) => { const schematics = json.schematics ? json.schematics : {}; schematics[options.name] = { version: options.version, description: options.description, - factory: `./src/migrations/${options.name}/${options.name}` + factory: `./src/migrations/${options.name}/${options.name}`, }; json.schematics = schematics; @@ -122,7 +122,7 @@ function updateMigrationsJson(options: NormalizedSchema): Rule { if (!packageJsonUpdatesObj[options.version]) { packageJsonUpdatesObj[options.version] = { version: options.version, - packages: {} + packages: {}, }; } json.packageJsonUpdates = packageJsonUpdatesObj; @@ -136,13 +136,13 @@ function updateMigrationsJson(options: NormalizedSchema): Rule { function updatePackageJson(options: NormalizedSchema): Rule { return updateJsonInTree( path.join(options.projectRoot, 'package.json'), - json => { + (json) => { if (!json['ng-update'] || !json['ng-update'].migrations) { if (json['ng-update']) { json['ng-update'].migrations = './migrations.json'; } else { json['ng-update'] = { - migrations: './migrations.json' + migrations: './migrations.json', }; } } diff --git a/packages/nx-plugin/src/schematics/plugin/plugin.spec.ts b/packages/nx-plugin/src/schematics/plugin/plugin.spec.ts index 1d324374766eb..604bcc15f3dd6 100644 --- a/packages/nx-plugin/src/schematics/plugin/plugin.spec.ts +++ b/packages/nx-plugin/src/schematics/plugin/plugin.spec.ts @@ -26,20 +26,20 @@ describe('NxPlugin plugin', () => { { input: './libs/my-plugin/src', glob: '**/*.!(ts)', - output: './src' + output: './src', }, { input: './libs/my-plugin', glob: 'collection.json', - output: '.' + output: '.', }, { input: './libs/my-plugin', glob: 'builders.json', - output: '.' - } - ] - } + output: '.', + }, + ], + }, }); expect(project.architect.lint).toEqual({ builder: '@angular-devkit/build-angular:tslint', @@ -47,17 +47,17 @@ describe('NxPlugin plugin', () => { exclude: ['**/node_modules/**', '!libs/my-plugin/**'], tsConfig: [ 'libs/my-plugin/tsconfig.lib.json', - 'libs/my-plugin/tsconfig.spec.json' - ] - } + 'libs/my-plugin/tsconfig.spec.json', + ], + }, }); expect(project.architect.test).toEqual({ builder: '@nrwl/jest:jest', options: { jestConfig: 'libs/my-plugin/jest.config.js', tsConfig: 'libs/my-plugin/tsconfig.spec.json', - passWithNoTests: true - } + passWithNoTests: true, + }, }); }); @@ -120,7 +120,7 @@ describe('NxPlugin plugin', () => { '@nrwl/node', 'lib', expect.objectContaining({ - publishable: true + publishable: true, }) ); }); @@ -133,7 +133,7 @@ describe('NxPlugin plugin', () => { expect.objectContaining({ pluginName: 'my-plugin', pluginOutputPath: `dist/libs/my-plugin`, - npmPackageName: '@proj/my-plugin' + npmPackageName: '@proj/my-plugin', }) ); }); @@ -145,7 +145,7 @@ describe('NxPlugin plugin', () => { 'schematic', expect.objectContaining({ project: 'my-plugin', - name: `my-plugin` + name: `my-plugin`, }) ); }); @@ -157,7 +157,7 @@ describe('NxPlugin plugin', () => { 'builder', expect.objectContaining({ project: 'my-plugin', - name: `build` + name: `build`, }) ); }); @@ -179,7 +179,7 @@ describe('NxPlugin plugin', () => { '@nrwl/node', 'lib', expect.objectContaining({ - unitTestRunner: 'none' + unitTestRunner: 'none', }) ); diff --git a/packages/nx-plugin/src/schematics/plugin/plugin.ts b/packages/nx-plugin/src/schematics/plugin/plugin.ts index dccee95aa4f8a..1ef83233dd14a 100644 --- a/packages/nx-plugin/src/schematics/plugin/plugin.ts +++ b/packages/nx-plugin/src/schematics/plugin/plugin.ts @@ -14,7 +14,7 @@ import { Tree, url, filter, - noop + noop, } from '@angular-devkit/schematics'; import { formatFiles, @@ -24,7 +24,7 @@ import { readNxJsonInTree, toFileName, updateJsonInTree, - updateWorkspace + updateWorkspace, } from '@nrwl/workspace'; import { allFilesInDirInHost } from '@nrwl/workspace/src/utils/ast-utils'; import { Schema } from './schema'; @@ -39,7 +39,7 @@ export interface NormalizedSchema extends Schema { fileTemplate: string; } -export default function(schema: NormalizedSchema): Rule { +export default function (schema: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); @@ -47,7 +47,7 @@ export default function(schema: NormalizedSchema): Rule { externalSchematic('@nrwl/node', 'lib', { ...schema, publishable: true, - unitTestRunner: options.unitTestRunner + unitTestRunner: options.unitTestRunner, }), addFiles(options), updateWorkspaceJson(options), @@ -55,9 +55,9 @@ export default function(schema: NormalizedSchema): Rule { schematic('e2e-project', { pluginName: options.name, pluginOutputPath: `dist/libs/${options.projectDirectory}`, - npmPackageName: options.npmPackageName + npmPackageName: options.npmPackageName, }), - formatFiles(options) + formatFiles(options), ]); }; } @@ -75,7 +75,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { const projectRoot = normalize(`libs/${projectDirectory}`); const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const npmPackageName = `@${npmScope}/${name}`; @@ -90,7 +90,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { projectDirectory, parsedTags, npmPackageName, - fileTemplate + fileTemplate, }; return normalized; @@ -98,11 +98,11 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { function addFiles(options: NormalizedSchema): Rule { return chain([ - host => { + (host) => { allFilesInDirInHost( host, normalize(`${options.projectRoot}/src/lib`) - ).forEach(file => { + ).forEach((file) => { host.delete(file); }); @@ -114,27 +114,27 @@ function addFiles(options: NormalizedSchema): Rule { ...options, ...names(options.name), tmpl: '', - offsetFromRoot: offsetFromRoot(options.projectRoot) + offsetFromRoot: offsetFromRoot(options.projectRoot), }), - move(options.projectRoot) + move(options.projectRoot), ]), MergeStrategy.Overwrite ), schematic('schematic', { project: options.name, name: options.name, - unitTestRunner: options.unitTestRunner + unitTestRunner: options.unitTestRunner, }), schematic('builder', { project: options.name, name: 'build', - unitTestRunner: options.unitTestRunner - }) + unitTestRunner: options.unitTestRunner, + }), ]); } function updateWorkspaceJson(options: NormalizedSchema): Rule { - return updateWorkspace(workspace => { + return updateWorkspace((workspace) => { const targets = workspace.projects.get(options.name).targets; const build = targets.get('build'); if (build) { @@ -143,18 +143,18 @@ function updateWorkspaceJson(options: NormalizedSchema): Rule { { input: `./${options.projectRoot}/src`, glob: '**/*.!(ts)', - output: './src' + output: './src', }, { input: `./${options.projectRoot}`, glob: 'collection.json', - output: '.' + output: '.', }, { input: `./${options.projectRoot}`, glob: 'builders.json', - output: '.' - } + output: '.', + }, ] ); } @@ -164,10 +164,13 @@ function updateWorkspaceJson(options: NormalizedSchema): Rule { function updateTsConfig(options: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const projectConfig = getProjectConfig(host, options.name); - return updateJsonInTree(`${projectConfig.root}/tsconfig.lib.json`, json => { - json.compilerOptions.rootDir = '.'; - return json; - }); + return updateJsonInTree( + `${projectConfig.root}/tsconfig.lib.json`, + (json) => { + json.compilerOptions.rootDir = '.'; + return json; + } + ); }; } diff --git a/packages/nx-plugin/src/schematics/schematic/schematic.spec.ts b/packages/nx-plugin/src/schematics/schematic/schematic.spec.ts index 82f6da70f47f9..48799a43d6342 100644 --- a/packages/nx-plugin/src/schematics/schematic/schematic.spec.ts +++ b/packages/nx-plugin/src/schematics/schematic/schematic.spec.ts @@ -19,7 +19,7 @@ describe('NxPlugin schematic', () => { 'schematic', { project: projectName, - name: 'my-schematic' + name: 'my-schematic', }, appTree ); @@ -46,7 +46,7 @@ describe('NxPlugin schematic', () => { { project: projectName, name: 'my-schematic', - description: 'my-schematic description' + description: 'my-schematic description', }, appTree ); @@ -72,7 +72,7 @@ describe('NxPlugin schematic', () => { 'schematic', { project: projectName, - name: 'my-schematic' + name: 'my-schematic', }, appTree ); @@ -93,7 +93,7 @@ describe('NxPlugin schematic', () => { { project: projectName, name: 'my-schematic', - description: 'my-schematic custom description' + description: 'my-schematic custom description', }, appTree ); @@ -116,7 +116,7 @@ describe('NxPlugin schematic', () => { { project: projectName, name: 'my-schematic', - unitTestRunner: 'none' + unitTestRunner: 'none', }, appTree ); diff --git a/packages/nx-plugin/src/schematics/schematic/schematic.ts b/packages/nx-plugin/src/schematics/schematic/schematic.ts index 35fdfbc44adf6..e66a03c7642b8 100644 --- a/packages/nx-plugin/src/schematics/schematic/schematic.ts +++ b/packages/nx-plugin/src/schematics/schematic/schematic.ts @@ -10,14 +10,14 @@ import { Tree, url, filter, - noop + noop, } from '@angular-devkit/schematics'; import { getProjectConfig, names, readNxJsonInTree, toFileName, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import * as path from 'path'; import { Schema } from './schema'; @@ -31,7 +31,7 @@ export interface NormalizedSchema extends Schema { fileTemplate: string; } -export default function(schema: NormalizedSchema): Rule { +export default function (schema: NormalizedSchema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); @@ -68,7 +68,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { projectSourceRoot, npmScope, npmPackageName, - fileTemplate + fileTemplate, }; return normalized; @@ -80,12 +80,12 @@ function addFiles(options: NormalizedSchema): Rule { template({ ...options, ...names(options.name), - tmpl: '' + tmpl: '', }), options.unitTestRunner === 'none' - ? filter(file => !file.endsWith('.spec.ts')) + ? filter((file) => !file.endsWith('.spec.ts')) : noop(), - move(`${options.projectSourceRoot}/schematics`) + move(`${options.projectSourceRoot}/schematics`), ]) ); } @@ -93,12 +93,12 @@ function addFiles(options: NormalizedSchema): Rule { function updateCollectionJson(options: NormalizedSchema): Rule { return updateJsonInTree( path.join(options.projectRoot, 'collection.json'), - json => { + (json) => { const schematics = json.schematics ? json.schematics : {}; schematics[options.name] = { factory: `./src/schematics/${options.name}/schematic`, schema: `./src/schematics/${options.name}/schema.json`, - description: options.description + description: options.description, }; json.schematics = schematics; diff --git a/packages/nx-plugin/src/utils/testing-utils/async-commands.ts b/packages/nx-plugin/src/utils/testing-utils/async-commands.ts index 4c00522f2af58..5152f1a52203b 100644 --- a/packages/nx-plugin/src/utils/testing-utils/async-commands.ts +++ b/packages/nx-plugin/src/utils/testing-utils/async-commands.ts @@ -10,14 +10,14 @@ import { tmpProjPath } from './paths'; export function runCommandAsync( command: string, opts = { - silenceError: false + silenceError: false, } ): Promise<{ stdout: string; stderr: string }> { return new Promise((resolve, reject) => { exec( command, { - cwd: tmpProjPath() + cwd: tmpProjPath(), }, (err, stdout, stderr) => { if (!opts.silenceError && err) { @@ -37,7 +37,7 @@ export function runCommandAsync( export function runNxCommandAsync( command: string, opts = { - silenceError: false + silenceError: false, } ): Promise<{ stdout: string; stderr: string }> { return runCommandAsync( diff --git a/packages/nx-plugin/src/utils/testing-utils/commands.ts b/packages/nx-plugin/src/utils/testing-utils/commands.ts index deacebeef6724..308db0a533978 100644 --- a/packages/nx-plugin/src/utils/testing-utils/commands.ts +++ b/packages/nx-plugin/src/utils/testing-utils/commands.ts @@ -11,12 +11,12 @@ import { tmpProjPath } from './paths'; export function runNxCommand( command?: string, opts = { - silenceError: false + silenceError: false, } ): string { try { return execSync(`node ./node_modules/@nrwl/cli/bin/nx.js ${command}`, { - cwd: tmpProjPath() + cwd: tmpProjPath(), }) .toString() .replace( @@ -37,7 +37,7 @@ export function runCommand(command: string): string { try { return execSync(command, { cwd: tmpProjPath(), - stdio: ['pipe', 'pipe', 'pipe'] + stdio: ['pipe', 'pipe', 'pipe'], }).toString(); } catch (e) { return e.stdout.toString() + e.stderr.toString(); diff --git a/packages/nx-plugin/src/utils/testing-utils/nx-project.ts b/packages/nx-plugin/src/utils/testing-utils/nx-project.ts index 481c5b6978322..7d7d713162987 100644 --- a/packages/nx-plugin/src/utils/testing-utils/nx-project.ts +++ b/packages/nx-plugin/src/utils/testing-utils/nx-project.ts @@ -10,11 +10,12 @@ function runNxNewCommand(args?: string, silent?: boolean) { return execSync( `node ${require.resolve( '@nrwl/tao' - )} new proj --no-interactive --skip-install --collection=@nrwl/workspace --npmScope=proj ${args || - ''}`, + )} new proj --no-interactive --skip-install --collection=@nrwl/workspace --npmScope=proj ${ + args || '' + }`, { cwd: localTmpDir, - ...(silent && false ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) + ...(silent && false ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}), } ); } @@ -42,7 +43,7 @@ export function uniq(prefix: string) { export function runYarnInstall(silent: boolean = true) { const install = execSync('yarn install', { cwd: tmpProjPath(), - ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) + ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}), }); return install ? install.toString() : ''; } diff --git a/packages/nx-plugin/src/utils/testing-utils/utils.ts b/packages/nx-plugin/src/utils/testing-utils/utils.ts index 0f8ade4fc0dd7..e6d75c3e23824 100644 --- a/packages/nx-plugin/src/utils/testing-utils/utils.ts +++ b/packages/nx-plugin/src/utils/testing-utils/utils.ts @@ -6,7 +6,7 @@ import { removeSync, renameSync, statSync, - writeFileSync + writeFileSync, } from 'fs-extra'; import { dirname, isAbsolute } from 'path'; import { tmpProjPath } from './paths'; @@ -16,7 +16,7 @@ import { tmpProjPath } from './paths'; * @param modules a list of module names or scopes to copy */ export function copyNodeModules(modules: string[]) { - modules.forEach(module => { + modules.forEach((module) => { removeSync(`${tmpProjPath()}/node_modules/${module}`); copySync( `./node_modules/${module}`, @@ -79,7 +79,7 @@ export function renameFile(path: string, newPath: string): void { * @usage `checkFileExists('file1', 'file2', '/var/user/file')` */ export function checkFilesExist(...expectedPaths: string[]) { - expectedPaths.forEach(path => { + expectedPaths.forEach((path) => { const filePath = isAbsolute(path) ? path : tmpProjPath(path); if (!exists(filePath)) { throw new Error(`'${filePath}' does not exist`); diff --git a/packages/react/ast-utils.ts b/packages/react/ast-utils.ts index 0f84c3d3e6d22..1b96d3f6e2bf2 100644 --- a/packages/react/ast-utils.ts +++ b/packages/react/ast-utils.ts @@ -5,5 +5,5 @@ export { findElements, findDefaultExport, findClosestOpening, - isTag + isTag, } from './src/utils/ast-utils'; diff --git a/packages/react/plugins/bundle-rollup.ts b/packages/react/plugins/bundle-rollup.ts index 6411c1e152fd9..74d2248cf9039 100644 --- a/packages/react/plugins/bundle-rollup.ts +++ b/packages/react/plugins/bundle-rollup.ts @@ -6,16 +6,16 @@ function getRollupOptions(options: rollup.RollupOptions) { 'react-dom': 'ReactDOM', 'styled-components': 'styled', '@emotion/core': 'emotionCore', - '@emotion/styled': 'emotionStyled' + '@emotion/styled': 'emotionStyled', }; if (Array.isArray(options.output)) { - options.output.forEach(o => { + options.output.forEach((o) => { o.globals = { ...o.globals, ...extraGlobals }; }); } else { options.output = { ...options.output, - ...extraGlobals + ...extraGlobals, }; } return options; diff --git a/packages/react/plugins/jest.ts b/packages/react/plugins/jest.ts index ede4ce5fda691..ccf2fad967fd2 100644 --- a/packages/react/plugins/jest.ts +++ b/packages/react/plugins/jest.ts @@ -29,5 +29,5 @@ module.exports = { } return `module.exports = ${assetFilename};`; - } + }, }; diff --git a/packages/react/plugins/webpack.ts b/packages/react/plugins/webpack.ts index f96b1c7e51d60..4761b1034ff6c 100644 --- a/packages/react/plugins/webpack.ts +++ b/packages/react/plugins/webpack.ts @@ -3,7 +3,7 @@ import { updateBabelOptions } from '../src/utils/babel-utils'; // Add React-specific configuration function getWebpackConfig(config: Configuration) { - const idx = config.module.rules.findIndex(r => r.loader === 'babel-loader'); + const idx = config.module.rules.findIndex((r) => r.loader === 'babel-loader'); const babelRuleOptions = config.module.rules[idx].options as any; updateBabelOptions(babelRuleOptions); @@ -13,8 +13,8 @@ function getWebpackConfig(config: Configuration) { loader: 'url-loader', options: { limit: 10000, // 10kB - name: '[name].[hash:7].[ext]' - } + name: '[name].[hash:7].[ext]', + }, }, { test: /\.svg$/, @@ -22,7 +22,7 @@ function getWebpackConfig(config: Configuration) { // If coming from JS/TS file, then transform into React component using SVGR. { issuer: { - test: /\.[jt]sx?$/ + test: /\.[jt]sx?$/, }, use: [ '@svgr/webpack?-svgo,+titleProp,+ref![path]', @@ -30,10 +30,10 @@ function getWebpackConfig(config: Configuration) { loader: 'url-loader', options: { limit: 10000, // 10kB - name: '[name].[hash:7].[ext]' - } - } - ] + name: '[name].[hash:7].[ext]', + }, + }, + ], }, // Fallback to plain URL loader. { @@ -42,12 +42,12 @@ function getWebpackConfig(config: Configuration) { loader: 'url-loader', options: { limit: 10000, // 10kB - name: '[name].[hash:7].[ext]' - } - } - ] - } - ] + name: '[name].[hash:7].[ext]', + }, + }, + ], + }, + ], } ); diff --git a/packages/react/src/migrations/update-8-10-0/update-8-10-0.spec.ts b/packages/react/src/migrations/update-8-10-0/update-8-10-0.spec.ts index 3385a118cefa3..84e91a3a10fda 100644 --- a/packages/react/src/migrations/update-8-10-0/update-8-10-0.spec.ts +++ b/packages/react/src/migrations/update-8-10-0/update-8-10-0.spec.ts @@ -23,11 +23,11 @@ describe('Update 8-10-0', () => { JSON.stringify({ dependencies: { '@emotion/core': '10.0.23', - '@emotion/styled': '10.0.23' + '@emotion/styled': '10.0.23', }, devDependencies: { - '@types/react': '16.9.13' - } + '@types/react': '16.9.13', + }, }) ); @@ -39,11 +39,11 @@ describe('Update 8-10-0', () => { expect(packageJson).toMatchObject({ dependencies: { '@emotion/core': '10.0.27', - '@emotion/styled': '10.0.27' + '@emotion/styled': '10.0.27', }, devDependencies: { - '@types/react': '16.9.17' - } + '@types/react': '16.9.17', + }, }); }); @@ -90,11 +90,11 @@ describe('Update 8-10-0', () => { build: { builder: '@nrwl/web:build', options: { - webpackConfig: '@nrwl/react/plugins/babel' - } - } - } - } + webpackConfig: '@nrwl/react/plugins/babel', + }, + }, + }, + }, }; tree.overwrite('/workspace.json', JSON.stringify(workspaceJson)); @@ -111,11 +111,11 @@ describe('Update 8-10-0', () => { build: { builder: '@nrwl/web:build', options: { - webpackConfig: '@nrwl/react/plugins/webpack' - } - } - } - } + webpackConfig: '@nrwl/react/plugins/webpack', + }, + }, + }, + }, }); }); }); diff --git a/packages/react/src/migrations/update-8-10-0/update-8-10-0.ts b/packages/react/src/migrations/update-8-10-0/update-8-10-0.ts index cb87ae053b967..dc8599469a499 100644 --- a/packages/react/src/migrations/update-8-10-0/update-8-10-0.ts +++ b/packages/react/src/migrations/update-8-10-0/update-8-10-0.ts @@ -3,7 +3,7 @@ import { noop, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { formatFiles, @@ -11,7 +11,7 @@ import { readWorkspace, updateJsonInTree, updatePackagesInPackageJson, - updateWorkspaceInTree + updateWorkspaceInTree, } from '@nrwl/workspace'; import * as path from 'path'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; @@ -26,7 +26,7 @@ export default function update(): Rule { updatePackagesInPackageJson( path.join(__dirname, '../../../', 'migrations.json'), '8.10.0' - ) + ), ]); } @@ -47,13 +47,13 @@ function displayInformation(host: Tree, context: SchematicContext) { function addCustomTypings(host: Tree) { const workspace = readWorkspace(host); return chain([ - ...Object.keys(workspace.projects).map(k => { + ...Object.keys(workspace.projects).map((k) => { const p = workspace.projects[k]; if (p.projectType !== 'application') { return noop(); } if (isReactProject(p)) { - return updateJsonInTree(path.join(p.root, 'tsconfig.json'), json => { + return updateJsonInTree(path.join(p.root, 'tsconfig.json'), (json) => { const files = json.files || []; files.push( `${offsetFromRoot( @@ -70,12 +70,12 @@ function addCustomTypings(host: Tree) { return noop(); } }), - formatFiles() + formatFiles(), ]); } function updateBuilderWebpackOption(json) { - Object.keys(json.projects).map(k => { + Object.keys(json.projects).map((k) => { const p = json.projects[k]; if (isReactProject(p)) { p.architect.build.options.webpackConfig = '@nrwl/react/plugins/webpack'; diff --git a/packages/react/src/migrations/update-8-10-1/fix-react-tsconfig-8-10-1.spec.ts b/packages/react/src/migrations/update-8-10-1/fix-react-tsconfig-8-10-1.spec.ts index 08d4e1283005d..9a1aaf3fdcc15 100644 --- a/packages/react/src/migrations/update-8-10-1/fix-react-tsconfig-8-10-1.spec.ts +++ b/packages/react/src/migrations/update-8-10-1/fix-react-tsconfig-8-10-1.spec.ts @@ -34,8 +34,8 @@ describe('Update 8-10-0', () => { files: [ '../../node_modules/@nrwl/react/typings/cssmodule.d.ts', '../../node_modules/@nrwl/react/typings/image.d.ts', - '../../node_modules/@nrwl/react/typings/svg.d.ts' - ] + '../../node_modules/@nrwl/react/typings/svg.d.ts', + ], }) ); @@ -47,7 +47,7 @@ describe('Update 8-10-0', () => { expect(tsConfig.files).toEqual([ '../../node_modules/@nrwl/react/typings/cssmodule.d.ts', - '../../node_modules/@nrwl/react/typings/image.d.ts' + '../../node_modules/@nrwl/react/typings/image.d.ts', ]); }); }); diff --git a/packages/react/src/migrations/update-8-10-1/fix-react-tsconfig-8-10-1.ts b/packages/react/src/migrations/update-8-10-1/fix-react-tsconfig-8-10-1.ts index ae17697ee7fda..b0c0b6f4c32b5 100644 --- a/packages/react/src/migrations/update-8-10-1/fix-react-tsconfig-8-10-1.ts +++ b/packages/react/src/migrations/update-8-10-1/fix-react-tsconfig-8-10-1.ts @@ -8,23 +8,26 @@ export default function update(): Rule { return (host: Tree) => { const workspace = readWorkspace(host); return chain([ - ...Object.keys(workspace.projects).map(k => { + ...Object.keys(workspace.projects).map((k) => { const p = workspace.projects[k]; if (p.projectType !== 'application') { return noop(); } if (isReactProject(p)) { - return updateJsonInTree(path.join(p.root, 'tsconfig.json'), json => { - json.files = json.files.filter( - f => f.indexOf('@nrwl/react/typings/svg.d.ts') === -1 - ); - return json; - }); + return updateJsonInTree( + path.join(p.root, 'tsconfig.json'), + (json) => { + json.files = json.files.filter( + (f) => f.indexOf('@nrwl/react/typings/svg.d.ts') === -1 + ); + return json; + } + ); } else { return noop(); } }), - formatFiles() + formatFiles(), ]); }; } diff --git a/packages/react/src/migrations/update-8-12-0/fix-react-files-8-12-0.spec.ts b/packages/react/src/migrations/update-8-12-0/fix-react-files-8-12-0.spec.ts index d3cec363a4de9..7c47b699b2aaf 100644 --- a/packages/react/src/migrations/update-8-12-0/fix-react-files-8-12-0.spec.ts +++ b/packages/react/src/migrations/update-8-12-0/fix-react-files-8-12-0.spec.ts @@ -22,7 +22,7 @@ describe('Update 8-12-0', () => { 'package.json', JSON.stringify({ dependencies: {}, - devDependencies: {} + devDependencies: {}, }) ); @@ -35,12 +35,12 @@ describe('Update 8-12-0', () => { build: { builder: '@nrwl/web:build', options: { - main: 'apps/demo/src/main.tsx' - } - } - } - } - } + main: 'apps/demo/src/main.tsx', + }, + }, + }, + }, + }, }) ); @@ -58,18 +58,18 @@ describe('Update 8-12-0', () => { builder: '@nrwl/web:build', options: { main: 'apps/demo/src/main.tsx', - webpackConfig: '@nrwl/react/plugins/webpack' - } - } - } - } - } + webpackConfig: '@nrwl/react/plugins/webpack', + }, + }, + }, + }, + }, }); expect(packageJson).toMatchObject({ dependencies: {}, devDependencies: { - '@babel/preset-react': '7.8.3' - } + '@babel/preset-react': '7.8.3', + }, }); }); }); diff --git a/packages/react/src/migrations/update-8-12-0/fix-react-files-8-12-0.ts b/packages/react/src/migrations/update-8-12-0/fix-react-files-8-12-0.ts index 7509915f2edf2..98a591a4895f0 100644 --- a/packages/react/src/migrations/update-8-12-0/fix-react-files-8-12-0.ts +++ b/packages/react/src/migrations/update-8-12-0/fix-react-files-8-12-0.ts @@ -2,7 +2,7 @@ import { chain, Rule } from '@angular-devkit/schematics'; import { addDepsToPackageJson, formatFiles, - updateWorkspaceInTree + updateWorkspaceInTree, } from '@nrwl/workspace'; const ignore = require('ignore'); @@ -11,12 +11,12 @@ export default function update(): Rule { return chain([ updateWorkspaceInTree(updateBuilderWebpackOption), addDepsToPackageJson({}, { '@babel/preset-react': '7.8.3' }), - formatFiles() + formatFiles(), ]); } function updateBuilderWebpackOption(json) { - Object.keys(json.projects).map(k => { + Object.keys(json.projects).map((k) => { const p = json.projects[k]; if (isReactProject(p) && !p.architect.build.options.webpackConfig) { p.architect.build.options.webpackConfig = '@nrwl/react/plugins/webpack'; diff --git a/packages/react/src/migrations/update-8-12-0/update-8-12-0.spec.ts b/packages/react/src/migrations/update-8-12-0/update-8-12-0.spec.ts index d0deb3efbc81b..419d4f3e5a04a 100644 --- a/packages/react/src/migrations/update-8-12-0/update-8-12-0.spec.ts +++ b/packages/react/src/migrations/update-8-12-0/update-8-12-0.spec.ts @@ -22,11 +22,11 @@ describe('Update 8-10-0', () => { 'package.json', JSON.stringify({ dependencies: { - 'styled-components': '4.3.2' + 'styled-components': '4.3.2', }, devDependencies: { - '@types/styled-components': '4.4.1' - } + '@types/styled-components': '4.4.1', + }, }) ); @@ -37,11 +37,11 @@ describe('Update 8-10-0', () => { const packageJson = readJsonInTree(tree, '/package.json'); expect(packageJson).toMatchObject({ dependencies: { - 'styled-components': '5.0.0' + 'styled-components': '5.0.0', }, devDependencies: { - '@types/styled-components': '4.4.2' - } + '@types/styled-components': '4.4.2', + }, }); }); }); diff --git a/packages/react/src/migrations/update-8-12-0/update-8-12-0.ts b/packages/react/src/migrations/update-8-12-0/update-8-12-0.ts index 49d2f2e425907..4071ca6694d08 100644 --- a/packages/react/src/migrations/update-8-12-0/update-8-12-0.ts +++ b/packages/react/src/migrations/update-8-12-0/update-8-12-0.ts @@ -8,6 +8,6 @@ export default function update(): Rule { path.join(__dirname, '../../../', 'migrations.json'), '8.12.0' ), - formatFiles() + formatFiles(), ]); } diff --git a/packages/react/src/migrations/update-8-3-0/update-8-3-0.spec.ts b/packages/react/src/migrations/update-8-3-0/update-8-3-0.spec.ts index fb3606584f1e6..3d9663c9b2bca 100644 --- a/packages/react/src/migrations/update-8-3-0/update-8-3-0.spec.ts +++ b/packages/react/src/migrations/update-8-3-0/update-8-3-0.spec.ts @@ -22,14 +22,14 @@ describe('Update 8-0-0', () => { react: '16.8.1', 'react-dom': '16.8.1', 'react-router-dom': '5.0.0', - 'styled-components': '4.0.0' + 'styled-components': '4.0.0', }, devDependencies: { '@types/styled-components': '4.0.0', 'react-testing-library': '5.0.0', '@types/react': '16.8.0', - '@types/react-dom': '16.8.0' - } + '@types/react-dom': '16.8.0', + }, })), tree ) diff --git a/packages/react/src/migrations/update-8-3-0/update-8-3-0.ts b/packages/react/src/migrations/update-8-3-0/update-8-3-0.ts index 7067dfff45584..8741536a6889b 100644 --- a/packages/react/src/migrations/update-8-3-0/update-8-3-0.ts +++ b/packages/react/src/migrations/update-8-3-0/update-8-3-0.ts @@ -2,7 +2,7 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { @@ -10,13 +10,13 @@ import { insert, readJsonInTree, updateJsonInTree, - updatePackageJsonDependencies + updatePackageJsonDependencies, } from '@nrwl/workspace'; import { createSourceFile, isImportDeclaration, isStringLiteral, - ScriptTarget + ScriptTarget, } from 'typescript'; import { ReplaceChange } from '@nrwl/workspace/src/utils/ast-utils'; import { relative } from 'path'; @@ -29,7 +29,7 @@ export default function update(): Rule { displayInformation, updateDependencies, updateImports, - formatFiles() + formatFiles(), ]); } @@ -67,7 +67,7 @@ function updateDependencies(tree: Tree) { '@types/react-dom': '16.8.5', 'styled-components': '4.3.2', '@types/styled-components': '4.1.18', - '@emotion/styled': '10.0.14' + '@emotion/styled': '10.0.14', }; const updated = Object.entries(candidates).reduce( @@ -82,8 +82,8 @@ function updateDependencies(tree: Tree) { { dependencies: {}, devDependencies: { - '@testing-library/react': testingLibraryReactVersion - } + '@testing-library/react': testingLibraryReactVersion, + }, } ); @@ -102,7 +102,7 @@ function updateImports(host: Tree) { ig = ig.add(host.read('.gitignore').toString()); } - host.visit(path => { + host.visit((path) => { if (ig.ignores(relative('/', path)) || !/\.tsx?$/.test(path)) { return; } @@ -114,7 +114,7 @@ function updateImports(host: Tree) { true ); const changes = []; - sourceFile.statements.forEach(statement => { + sourceFile.statements.forEach((statement) => { if ( isImportDeclaration(statement) && isStringLiteral(statement.moduleSpecifier) diff --git a/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.spec.ts b/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.spec.ts index 25020ab97339d..7f58e4b138320 100644 --- a/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.spec.ts +++ b/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.spec.ts @@ -5,7 +5,7 @@ import { readJsonInTree, updateWorkspaceInTree, readWorkspace, - getWorkspacePath + getWorkspacePath, } from '@nrwl/workspace'; import * as path from 'path'; @@ -30,13 +30,13 @@ describe('Update 8-5-0', () => { schematics: { '@nrwl/react': { application: { - babel: true - } + babel: true, + }, }, '@nrwl/react:application': { - babel: true - } - } + babel: true, + }, + }, }) ); @@ -48,10 +48,10 @@ describe('Update 8-5-0', () => { expect(config).toEqual({ schematics: { '@nrwl/react': { - application: {} + application: {}, }, - '@nrwl/react:application': {} - } + '@nrwl/react:application': {}, + }, }); }); }); diff --git a/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.ts b/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.ts index e759bfdba0a9e..32955c853f05b 100644 --- a/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.ts +++ b/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.ts @@ -3,10 +3,10 @@ import { formatFiles, updateWorkspaceInTree } from '@nrwl/workspace'; export default function update(): Rule { return chain([ - updateWorkspaceInTree(config => { + updateWorkspaceInTree((config) => { const a = []; const b = []; - Object.keys(config.schematics).forEach(name => { + Object.keys(config.schematics).forEach((name) => { if (name === '@nrwl/react' && config.schematics[name].application) { a.push(config.schematics[name]); } @@ -14,14 +14,14 @@ export default function update(): Rule { b.push(config.schematics[name]); } }); - a.forEach(x => { + a.forEach((x) => { delete x.application.babel; }); - b.forEach(x => { + b.forEach((x) => { delete x.babel; }); return config; }), - formatFiles() + formatFiles(), ]); } diff --git a/packages/react/src/migrations/update-8-7-0/update-8-7-0.ts b/packages/react/src/migrations/update-8-7-0/update-8-7-0.ts index 78a8c56e429b3..9b33feabfc27f 100644 --- a/packages/react/src/migrations/update-8-7-0/update-8-7-0.ts +++ b/packages/react/src/migrations/update-8-7-0/update-8-7-0.ts @@ -2,12 +2,12 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { formatFiles, readJsonInTree, - updatePackagesInPackageJson + updatePackagesInPackageJson, } from '@nrwl/workspace'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import * as path from 'path'; @@ -19,7 +19,7 @@ export default function update(): Rule { path.join(__dirname, '../../../', 'migrations.json'), '8.7.0' ), - formatFiles() + formatFiles(), ]); } diff --git a/packages/react/src/migrations/update-8-9-0/update-8-9-0.spec.ts b/packages/react/src/migrations/update-8-9-0/update-8-9-0.spec.ts index 08745b60e65df..390ad0fb5f2ab 100644 --- a/packages/react/src/migrations/update-8-9-0/update-8-9-0.spec.ts +++ b/packages/react/src/migrations/update-8-9-0/update-8-9-0.spec.ts @@ -5,7 +5,7 @@ import { readJsonInTree, updateWorkspaceInTree, readWorkspace, - getWorkspacePath + getWorkspacePath, } from '@nrwl/workspace'; import * as path from 'path'; @@ -28,8 +28,8 @@ describe('Update 8-9-0', () => { 'package.json', JSON.stringify({ dependencies: { - react: '16.0.0' - } + react: '16.0.0', + }, }) ); @@ -39,7 +39,7 @@ describe('Update 8-9-0', () => { const packageJson = readJsonInTree(tree, '/package.json'); expect(packageJson.dependencies).toEqual({ - react: '16.12.0' + react: '16.12.0', }); }); @@ -48,8 +48,8 @@ describe('Update 8-9-0', () => { 'package.json', JSON.stringify({ dependencies: { - 'redux-starter-kit': '0.8.0' - } + 'redux-starter-kit': '0.8.0', + }, }) ); @@ -65,7 +65,7 @@ describe('Update 8-9-0', () => { const packageJson = readJsonInTree(tree, '/package.json'); expect(packageJson.dependencies).toEqual({ - '@reduxjs/toolkit': '1.0.4' + '@reduxjs/toolkit': '1.0.4', }); const sourceCode = tree.read('apps/demo/src/main.tsx').toString(); diff --git a/packages/react/src/migrations/update-8-9-0/update-8-9-0.ts b/packages/react/src/migrations/update-8-9-0/update-8-9-0.ts index 65bbe147c1766..526e9fac8292c 100644 --- a/packages/react/src/migrations/update-8-9-0/update-8-9-0.ts +++ b/packages/react/src/migrations/update-8-9-0/update-8-9-0.ts @@ -4,7 +4,7 @@ import { noop, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { formatFiles, @@ -12,7 +12,7 @@ import { readJsonInTree, updateJsonInTree, updatePackageJsonDependencies, - updatePackagesInPackageJson + updatePackagesInPackageJson, } from '@nrwl/workspace'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import * as path from 'path'; @@ -30,7 +30,7 @@ export default function update(): Rule { path.join(__dirname, '../../../', 'migrations.json'), '8.9.0' ), - formatFiles() + formatFiles(), ]); } @@ -78,7 +78,7 @@ function updateImports(host: Tree) { ig = ig.add(host.read('.gitignore').toString()); } - host.visit(path => { + host.visit((path) => { if (ig.ignores(relative('/', path)) || !/\.tsx?$/.test(path)) { return; } @@ -90,7 +90,7 @@ function updateImports(host: Tree) { true ); const changes = []; - sourceFile.statements.forEach(statement => { + sourceFile.statements.forEach((statement) => { if ( ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) diff --git a/packages/react/src/schematics/application/application.spec.ts b/packages/react/src/schematics/application/application.spec.ts index 5ac2bddfc9fe4..82ff7aa40c411 100644 --- a/packages/react/src/schematics/application/application.spec.ts +++ b/packages/react/src/schematics/application/application.spec.ts @@ -33,12 +33,12 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-app': { - tags: ['one', 'two'] + tags: ['one', 'two'], }, 'my-app-e2e': { tags: [], - implicitDependencies: ['my-app'] - } + implicitDependencies: ['my-app'], + }, }); }); @@ -102,12 +102,12 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-app': { - tags: ['one', 'two'] + tags: ['one', 'two'], }, 'my-dir-my-app-e2e': { tags: [], - implicitDependencies: ['my-dir-my-app'] - } + implicitDependencies: ['my-dir-my-app'], + }, }); }); @@ -129,8 +129,8 @@ describe('app', () => { 'apps/my-dir/my-app/src/main.tsx', 'apps/my-dir/my-app/src/app/app.tsx', 'apps/my-dir/my-app/src/app/app.spec.tsx', - 'apps/my-dir/my-app/src/app/app.css' - ].forEach(path => { + 'apps/my-dir/my-app/src/app/app.css', + ].forEach((path) => { expect(tree.exists(path)).toBeTruthy(); }); @@ -138,29 +138,29 @@ describe('app', () => { [ { path: 'apps/my-dir/my-app/tsconfig.json', - lookupFn: json => json.extends, - expectedValue: '../../../tsconfig.json' + lookupFn: (json) => json.extends, + expectedValue: '../../../tsconfig.json', }, { path: 'apps/my-dir/my-app/tsconfig.app.json', - lookupFn: json => json.compilerOptions.outDir, - expectedValue: '../../../dist/out-tsc' + lookupFn: (json) => json.compilerOptions.outDir, + expectedValue: '../../../dist/out-tsc', }, { path: 'apps/my-dir/my-app-e2e/tsconfig.json', - lookupFn: json => json.extends, - expectedValue: '../../../tsconfig.json' + lookupFn: (json) => json.extends, + expectedValue: '../../../tsconfig.json', }, { path: 'apps/my-dir/my-app-e2e/tsconfig.e2e.json', - lookupFn: json => json.compilerOptions.outDir, - expectedValue: '../../../dist/out-tsc' + lookupFn: (json) => json.compilerOptions.outDir, + expectedValue: '../../../dist/out-tsc', }, { path: 'apps/my-dir/my-app/tslint.json', - lookupFn: json => json.extends, - expectedValue: '../../../tslint.json' - } + lookupFn: (json) => json.extends, + expectedValue: '../../../tslint.json', + }, ].forEach(hasJsonValue); }); }); @@ -192,7 +192,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -206,7 +206,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -220,7 +220,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -236,7 +236,7 @@ describe('app', () => { scripts: [], styles: ['apps/my-app/src/styles.css'], tsConfig: 'apps/my-app/tsconfig.app.json', - webpackConfig: '@nrwl/react/plugins/webpack' + webpackConfig: '@nrwl/react/plugins/webpack', }); expect(architectConfig.build.configurations.production).toEqual({ optimization: true, @@ -244,21 +244,21 @@ describe('app', () => { { maximumError: '5mb', maximumWarning: '2mb', - type: 'initial' - } + type: 'initial', + }, ], extractCss: true, extractLicenses: true, fileReplacements: [ { replace: 'apps/my-app/src/environments/environment.ts', - with: 'apps/my-app/src/environments/environment.prod.ts' - } + with: 'apps/my-app/src/environments/environment.prod.ts', + }, ], namedChunks: false, outputHashing: 'all', sourceMap: false, - vendorChunk: false + vendorChunk: false, }); }); @@ -266,7 +266,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -274,10 +274,10 @@ describe('app', () => { const architectConfig = workspaceJson.projects['my-app'].architect; expect(architectConfig.serve.builder).toEqual('@nrwl/web:dev-server'); expect(architectConfig.serve.options).toEqual({ - buildTarget: 'my-app:build' + buildTarget: 'my-app:build', }); expect(architectConfig.serve.configurations.production).toEqual({ - buildTarget: 'my-app:build:production' + buildTarget: 'my-app:build:production', }); }); @@ -285,7 +285,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-app' + name: 'my-app', }, appTree ); @@ -296,9 +296,9 @@ describe('app', () => { exclude: ['**/node_modules/**', '!apps/my-app/**'], tsConfig: [ 'apps/my-app/tsconfig.app.json', - 'apps/my-app/tsconfig.spec.json' - ] - } + 'apps/my-app/tsconfig.spec.json', + ], + }, }); }); @@ -372,8 +372,8 @@ describe('app', () => { expect(packageJson).toMatchObject({ devDependencies: { 'eslint-plugin-react': expect.anything(), - 'eslint-plugin-react-hooks': expect.anything() - } + 'eslint-plugin-react-hooks': expect.anything(), + }, }); }); @@ -422,7 +422,7 @@ describe('app', () => { 'app', { name: 'myApp', - style: 'none' + style: 'none', }, appTree ); @@ -430,14 +430,14 @@ describe('app', () => { const workspaceJson = readJsonInTree(tree, '/workspace.json'); expect(workspaceJson.schematics['@nrwl/react']).toMatchObject({ application: { - style: 'none' + style: 'none', }, component: { - style: 'none' + style: 'none', }, library: { - style: 'none' - } + style: 'none', + }, }); }); @@ -589,7 +589,7 @@ describe('app', () => { name: 'myApp', babel: true, style: 'styled-components', - skipWorkspaceJson: false + skipWorkspaceJson: false, }, appTree ); @@ -598,14 +598,14 @@ describe('app', () => { expect(workspaceJson.schematics['@nrwl/react']).toMatchObject({ application: { babel: true, - style: 'styled-components' + style: 'styled-components', }, component: { - style: 'styled-components' + style: 'styled-components', }, library: { - style: 'styled-components' - } + style: 'styled-components', + }, }); }); }); diff --git a/packages/react/src/schematics/application/application.ts b/packages/react/src/schematics/application/application.ts index e8cce54984a43..0922630ed72ab 100644 --- a/packages/react/src/schematics/application/application.ts +++ b/packages/react/src/schematics/application/application.ts @@ -11,7 +11,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { addLintFiles, @@ -23,11 +23,11 @@ import { offsetFromRoot, toFileName, updateJsonInTree, - updateWorkspace + updateWorkspace, } from '@nrwl/workspace'; import { addDepsToPackageJson, - updateWorkspaceInTree + updateWorkspaceInTree, } from '@nrwl/workspace/src/utils/ast-utils'; import { toJS } from '@nrwl/workspace/src/utils/rules/to-js'; import * as ts from 'typescript'; @@ -38,7 +38,7 @@ import { extraEslintDependencies, reactEslintJson } from '../../utils/lint'; import { CSS_IN_JS_DEPENDENCIES } from '../../utils/styled'; import { reactRouterDomVersion, - typesReactRouterDomVersion + typesReactRouterDomVersion, } from '../../utils/versions'; import init from '../init/init'; import { Schema } from './schema'; @@ -54,18 +54,18 @@ interface NormalizedSchema extends Schema { hasStyles: boolean; } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); return chain([ init({ ...options, - skipFormat: true + skipFormat: true, }), addLintFiles(options.appProjectRoot, options.linter, { localConfig: reactEslintJson, - extraPackageDeps: extraEslintDependencies + extraPackageDeps: extraEslintDependencies, }), createApplicationFiles(options), updateNxJson(options), @@ -76,7 +76,7 @@ export default function(schema: Schema): Rule { addStyledModuleDependencies(options), addRouting(options, context), setDefaults(options), - formatFiles(options) + formatFiles(options), ]); }; } @@ -88,16 +88,16 @@ function createApplicationFiles(options: NormalizedSchema): Rule { ...names(options.name), ...options, tmpl: '', - offsetFromRoot: offsetFromRoot(options.appProjectRoot) + offsetFromRoot: offsetFromRoot(options.appProjectRoot), }), options.styledModule || !options.hasStyles - ? filter(file => !file.endsWith(`.${options.style}`)) + ? filter((file) => !file.endsWith(`.${options.style}`)) : noop(), options.unitTestRunner === 'none' - ? filter(file => file !== `/src/app/${options.fileName}.spec.tsx`) + ? filter((file) => file !== `/src/app/${options.fileName}.spec.tsx`) : noop(), move(options.appProjectRoot), - options.js ? toJS() : noop() + options.js ? toJS() : noop(), ]) ); } @@ -105,7 +105,7 @@ function createApplicationFiles(options: NormalizedSchema): Rule { function updateJestConfig(options: NormalizedSchema): Rule { return options.unitTestRunner === 'none' ? noop() - : host => { + : (host) => { const configPath = `${options.appProjectRoot}/jest.config.js`; const originalContent = host.read(configPath).toString(); const content = updateJestConfigContent(originalContent); @@ -114,14 +114,14 @@ function updateJestConfig(options: NormalizedSchema): Rule { } function updateNxJson(options: NormalizedSchema): Rule { - return updateJsonInTree('nx.json', json => { + return updateJsonInTree('nx.json', (json) => { json.projects[options.projectName] = { tags: options.parsedTags }; return json; }); } function addProject(options: NormalizedSchema): Rule { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const architect: { [key: string]: any } = {}; architect.build = { @@ -137,14 +137,14 @@ function addProject(options: NormalizedSchema): Rule { tsConfig: join(options.appProjectRoot, 'tsconfig.app.json'), assets: [ join(options.appProjectRoot, 'src/favicon.ico'), - join(options.appProjectRoot, 'src/assets') + join(options.appProjectRoot, 'src/assets'), ], styles: options.styledModule || !options.hasStyles ? [] : [join(options.appProjectRoot, `src/styles.${options.style}`)], scripts: [], - webpackConfig: '@nrwl/react/plugins/webpack' + webpackConfig: '@nrwl/react/plugins/webpack', }, configurations: { production: { @@ -157,8 +157,8 @@ function addProject(options: NormalizedSchema): Rule { with: join( options.appProjectRoot, maybeJs(options, `src/environments/environment.prod.ts`) - ) - } + ), + }, ], optimization: true, outputHashing: 'all', @@ -171,23 +171,23 @@ function addProject(options: NormalizedSchema): Rule { { type: 'initial', maximumWarning: '2mb', - maximumError: '5mb' - } - ] - } - } + maximumError: '5mb', + }, + ], + }, + }, }; architect.serve = { builder: '@nrwl/web:dev-server', options: { - buildTarget: `${options.projectName}:build` + buildTarget: `${options.projectName}:build`, }, configurations: { production: { - buildTarget: `${options.projectName}:build:production` - } - } + buildTarget: `${options.projectName}:build:production`, + }, + }, }; architect.lint = generateProjectLint( @@ -201,7 +201,7 @@ function addProject(options: NormalizedSchema): Rule { sourceRoot: join(options.appProjectRoot, 'src'), projectType: 'application', schematics: {}, - architect + architect, }; json.defaultProject = json.defaultProject || options.projectName; @@ -216,7 +216,7 @@ function addCypress(options: NormalizedSchema): Rule { ...options, name: options.name + '-e2e', directory: options.directory, - project: options.projectName + project: options.projectName, }) : noop(); } @@ -228,7 +228,7 @@ function addJest(options: NormalizedSchema): Rule { supportTsx: true, skipSerializers: true, setupFile: 'none', - babelJest: options.babelJest + babelJest: options.babelJest, }) : noop(); } @@ -268,7 +268,7 @@ function addRouting( addDepsToPackageJson( { 'react-router-dom': reactRouterDomVersion }, { '@types/react-router-dom': typesReactRouterDomVersion } - ) + ), ]) : noop(); } @@ -276,7 +276,7 @@ function addRouting( function setDefaults(options: NormalizedSchema): Rule { return options.skipWorkspaceJson ? noop() - : updateWorkspace(workspace => { + : updateWorkspace((workspace) => { workspace.extensions.schematics = jsonIdentity( workspace.extensions.schematics || {} ); @@ -293,18 +293,18 @@ function setDefaults(options: NormalizedSchema): Rule { application: { style: options.style, linter: options.linter, - ...jsonIdentity(prev.application) + ...jsonIdentity(prev.application), }, component: { style: options.style, - ...jsonIdentity(prev.component) + ...jsonIdentity(prev.component), }, library: { style: options.style, linter: options.linter, - ...jsonIdentity(prev.library) - } - } + ...jsonIdentity(prev.library), + }, + }, }; }); } @@ -325,7 +325,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { const e2eProjectRoot = normalize(`apps/${appDirectory}-e2e`); const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const fileName = options.pascalCaseFiles ? 'App' : 'app'; @@ -346,7 +346,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { parsedTags, fileName, styledModule, - hasStyles: options.style !== 'none' + hasStyles: options.style !== 'none', }; } diff --git a/packages/react/src/schematics/component-cypress-spec/component-cypress-spec.spec.ts b/packages/react/src/schematics/component-cypress-spec/component-cypress-spec.spec.ts index 183d228d12a87..9a7384ddb367a 100644 --- a/packages/react/src/schematics/component-cypress-spec/component-cypress-spec.spec.ts +++ b/packages/react/src/schematics/component-cypress-spec/component-cypress-spec.spec.ts @@ -44,7 +44,7 @@ describe('react:component-cypress-spec', () => { }; export default Test; - ` + `, }, { plainJS: true, @@ -72,9 +72,9 @@ describe('react:component-cypress-spec', () => { }; export default Test; - ` - } - ].forEach(testConfig => { + `, + }, + ].forEach((testConfig) => { let fileCmpExt = testConfig.plainJS ? 'js' : 'tsx'; let fileExt = testConfig.plainJS ? 'js' : 'ts'; @@ -98,7 +98,7 @@ describe('react:component-cypress-spec', () => { { componentPath: `lib/test-ui-lib.${fileCmpExt}`, project: 'test-ui-lib', - js: testConfig.plainJS + js: testConfig.plainJS, }, appTree ); @@ -129,7 +129,7 @@ describe('react:component-cypress-spec', () => { { componentPath: `lib/test-ui-lib.${fileCmpExt}`, project: 'test-ui-lib', - js: testConfig.plainJS + js: testConfig.plainJS, }, appTree ); @@ -160,7 +160,7 @@ export async function createTestUILib( appTree = await callRule( externalSchematic('@nrwl/react', 'library', { name: libName, - js: plainJS + js: plainJS, }), appTree ); @@ -170,7 +170,7 @@ export async function createTestUILib( appTree = await callRule( externalSchematic('@nrwl/react', 'application', { name: `${libName}-e2e`, - js: plainJS + js: plainJS, }), appTree ); diff --git a/packages/react/src/schematics/component-cypress-spec/component-cypress-spec.ts b/packages/react/src/schematics/component-cypress-spec/component-cypress-spec.ts index d735cfe14e43c..98d0a94db1cb3 100644 --- a/packages/react/src/schematics/component-cypress-spec/component-cypress-spec.ts +++ b/packages/react/src/schematics/component-cypress-spec/component-cypress-spec.ts @@ -7,7 +7,7 @@ import { SchematicsException, applyTemplates, Tree, - url + url, } from '@angular-devkit/schematics'; import { findNodes, getProjectConfig } from '@nrwl/workspace'; import { applyWithSkipExisting } from '@nrwl/workspace/src/utils/ast-utils'; @@ -15,7 +15,7 @@ import { join } from 'path'; import ts = require('typescript'); import { getComponentName, - getComponentPropsInterface + getComponentPropsInterface, } from '../../utils/ast-utils'; export interface CreateComponentSpecFileSchema { @@ -24,7 +24,7 @@ export interface CreateComponentSpecFileSchema { js?: boolean; } -export default function(schema: CreateComponentSpecFileSchema): Rule { +export default function (schema: CreateComponentSpecFileSchema): Rule { return chain([createComponentSpecFile(schema)]); } @@ -33,7 +33,7 @@ export function getKnobDefaultValue(property: ts.SyntaxKind): string { const typeNameToDefault: Record = { [ts.SyntaxKind.StringKeyword]: '', [ts.SyntaxKind.NumberKeyword]: 0, - [ts.SyntaxKind.BooleanKeyword]: false + [ts.SyntaxKind.BooleanKeyword]: false, }; const resolvedValue = typeNameToDefault[property]; @@ -47,7 +47,7 @@ export function getKnobDefaultValue(property: ts.SyntaxKind): string { export function createComponentSpecFile({ project, componentPath, - js + js, }: CreateComponentSpecFileSchema): Rule { return (tree: Tree, context: SchematicContext): Rule => { const e2eLibIntegrationFolderPath = @@ -91,7 +91,7 @@ export function createComponentSpecFile({ props = propsInterface.members.map((member: ts.PropertySignature) => { return { name: (member.name as ts.Identifier).text, - defaultValue: getKnobDefaultValue(member.type.kind) + defaultValue: getKnobDefaultValue(member.type.kind), }; }); } @@ -102,9 +102,9 @@ export function createComponentSpecFile({ componentName, componentSelector: (cmpDeclaration as any).name.text, props, - fileExt: js ? 'js' : 'ts' + fileExt: js ? 'js' : 'ts', }), - move(e2eLibIntegrationFolderPath + '/' + componentName) + move(e2eLibIntegrationFolderPath + '/' + componentName), ]); }; } diff --git a/packages/react/src/schematics/component-story/component-story.spec.ts b/packages/react/src/schematics/component-story/component-story.spec.ts index 5c1574701d239..6ff50d03ccdee 100644 --- a/packages/react/src/schematics/component-story/component-story.spec.ts +++ b/packages/react/src/schematics/component-story/component-story.spec.ts @@ -4,7 +4,6 @@ import { createEmptyWorkspace } from '@nrwl/workspace/testing'; import { callRule, runSchematic } from '../../utils/testing'; import { CreateComponentStoriesFileSchema } from './component-story'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; -import { updateWorkspaceInTree } from '@nrwl/workspace'; describe('react:component-story', () => { let appTree: Tree; @@ -25,13 +24,13 @@ describe('react:component-story', () => { ); }); - it('should fail with a descriptive error message', async done => { + it('should fail with a descriptive error message', async (done) => { try { tree = await runSchematic( 'component-story', { componentPath: 'lib/test-ui-lib.tsx', - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); @@ -50,7 +49,7 @@ describe('react:component-story', () => { 'component-story', { componentPath: 'lib/test-ui-lib.tsx', - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); @@ -61,21 +60,23 @@ describe('react:component-story', () => { }); it('should properly set up the story', () => { - expect(tree.readContent(storyFilePath)) - .toContain(`import React from 'react'; -import { TestUiLib, TestUiLibProps } from './test-ui-lib'; - -export default { - component: TestUiLib, - title: 'TestUiLib' -}; - -export const primary = () => { - /* eslint-disable-next-line */ - const props: TestUiLibProps = {}; - - return ; -};`); + expect(stripIndents`${tree.readContent(storyFilePath)}`) + .toContain(stripIndents` + import React from 'react'; + import { TestUiLib, TestUiLibProps } from './test-ui-lib'; + + export default { + component: TestUiLib, + title: 'TestUiLib', + }; + + export const primary = () => { + /* eslint-disable-next-line */ + const props: TestUiLibProps = {}; + + return ; + }; + `); }); }); @@ -106,7 +107,7 @@ export const primary = () => { 'component-story', { componentPath: 'lib/test-ui-libplain.jsx', - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); @@ -117,21 +118,23 @@ export const primary = () => { }); it('should properly set up the story', () => { - expect(tree.readContent(storyFilePathPlain)) - .toContain(`import React from 'react'; -import { Test } from './test-ui-libplain'; - -export default { - component: Test, - title: 'Test' -}; - -export const primary = () => { - /* eslint-disable-next-line */ - const props = {}; - - return ; -};`); + expect(stripIndents`${tree.readContent(storyFilePathPlain)}`) + .toContain(stripIndents` + import React from 'react'; + import { Test } from './test-ui-libplain'; + + export default { + component: Test, + title: 'Test', + }; + + export const primary = () => { + /* eslint-disable-next-line */ + const props = {}; + + return ; + }; + `); }); }); @@ -159,26 +162,27 @@ export const primary = () => { 'component-story', { componentPath: 'lib/test-ui-lib.tsx', - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); }); it('should create a story without knobs', () => { - expect(tree.readContent(storyFilePath)) - .toContain(`import React from 'react'; -import { Test } from './test-ui-lib'; - -export default { - component: Test, - title: 'Test' -}; - -export const primary = () => { - return ; -}; -`); + expect(stripIndents`${tree.readContent(storyFilePath)}`) + .toContain(stripIndents` + import React from 'react'; + import { Test } from './test-ui-lib'; + + export default { + component: Test, + title: 'Test', + }; + + export const primary = () => { + return ; + }; + `); }); }); @@ -211,32 +215,33 @@ export const primary = () => { 'component-story', { componentPath: 'lib/test-ui-lib.tsx', - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); }); it('should setup knobs based on the component props', () => { - expect(tree.readContent(storyFilePath)) - .toContain(`import { text, boolean } from '@storybook/addon-knobs'; -import React from 'react'; -import { Test, TestProps } from './test-ui-lib'; - -export default { - component: Test, - title: 'Test' -}; - -export const primary = () => { - const props: TestProps = { - name: text('name', ''), - displayAge: boolean('displayAge', false) - }; - - return ; -}; -`); + expect(stripIndents`${tree.readContent(storyFilePath)}`) + .toContain(stripIndents` + import { text, boolean } from '@storybook/addon-knobs'; + import React from 'react'; + import { Test, TestProps } from './test-ui-lib'; + + export default { + component: Test, + title: 'Test', + }; + + export const primary = () => { + const props: TestProps = { + name: text('name', ''), + displayAge: boolean('displayAge', false), + }; + + return ; + }; + `); }); }); @@ -250,7 +255,7 @@ export const primary = () => { ); }; - ` + `, }, { name: 'function and then export', @@ -263,7 +268,7 @@ export const primary = () => { ); }; export default Test; - ` + `, }, { name: 'arrow function', @@ -276,14 +281,14 @@ export const primary = () => { ); }; export default Test; - ` + `, }, { name: 'arrow function without {..}', src: ` const Test = (props: TestProps) =>

Welcome to test component, {props.name}

; export default Test - ` + `, }, { name: 'direct export of component class', @@ -293,7 +298,7 @@ export const primary = () => { return

Welcome to test component, {this.props.name}

; } } - ` + `, }, { name: 'component class & then default export', @@ -304,7 +309,7 @@ export const primary = () => { } } export default Test - ` + `, }, { name: 'PureComponent class & then default export', @@ -315,9 +320,9 @@ export const primary = () => { } } export default Test - ` - } - ].forEach(config => { + `, + }, + ].forEach((config) => { describe(`React component defined as:${config.name}`, () => { beforeEach(async () => { appTree.overwrite( @@ -339,31 +344,33 @@ export const primary = () => { 'component-story', { componentPath: 'lib/test-ui-lib.tsx', - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); }); it('should properly setup the knobs based on the component props', () => { - expect(tree.readContent(storyFilePath)) - .toContain(`import { text, boolean } from '@storybook/addon-knobs'; -import React from 'react'; -import { Test, TestProps } from './test-ui-lib'; - -export default { - component: Test, - title: 'Test' -}; - -export const primary = () => { - const props: TestProps = { - name: text('name', ''), - displayAge: boolean('displayAge', false) - }; - - return ; -};`); + expect(stripIndents`${tree.readContent(storyFilePath)}`) + .toContain(stripIndents` + import { text, boolean } from '@storybook/addon-knobs'; + import React from 'react'; + import { Test, TestProps } from './test-ui-lib'; + + export default { + component: Test, + title: 'Test', + }; + + export const primary = () => { + const props: TestProps = { + name: text('name', ''), + displayAge: boolean('displayAge', false), + }; + + return ; + }; + `); }); }); }); @@ -376,28 +383,30 @@ export const primary = () => { 'component-story', { componentPath: 'lib/test-ui-lib.tsx', - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); }); it('should properly set up the story', () => { - expect(tree.readContent(storyFilePath)) - .toContain(`import React from 'react'; -import { TestUiLib, TestUiLibProps } from './test-ui-lib'; - -export default { - component: TestUiLib, - title: 'TestUiLib' -}; - -export const primary = () => { - /* tslint-disable-next-line */ - const props: TestUiLibProps = {}; - - return ; -};`); + expect(stripIndents`${tree.readContent(storyFilePath)}`) + .toContain(stripIndents` + import React from 'react'; + import { TestUiLib, TestUiLibProps } from './test-ui-lib'; + + export default { + component: TestUiLib, + title: 'TestUiLib', + }; + + export const primary = () => { + /* tslint-disable-next-line */ + const props: TestUiLibProps = {}; + + return ; + }; + `); }); }); }); @@ -410,7 +419,7 @@ export async function createTestUILib( appTree = createEmptyWorkspace(appTree); appTree = await callRule( externalSchematic('@nrwl/react', 'library', { - name: libName + name: libName, }), appTree ); diff --git a/packages/react/src/schematics/component-story/component-story.ts b/packages/react/src/schematics/component-story/component-story.ts index b0510e3f45e52..ff1c54a1fd6f7 100644 --- a/packages/react/src/schematics/component-story/component-story.ts +++ b/packages/react/src/schematics/component-story/component-story.ts @@ -7,20 +7,20 @@ import { move, url, SchematicsException, - applyTemplates + applyTemplates, } from '@angular-devkit/schematics'; import { normalize } from '@angular-devkit/core'; import { getProjectConfig, formatFiles } from '@nrwl/workspace'; import { join } from 'path'; import { applyWithSkipExisting, - findNodes + findNodes, } from '@nrwl/workspace/src/utils/ast-utils'; import * as ts from 'typescript'; import { findDefaultExport, getComponentName, - getComponentPropsInterface + getComponentPropsInterface, } from '../../utils/ast-utils'; export interface CreateComponentStoriesFileSchema { @@ -35,7 +35,7 @@ export function getKnobDefaultValue(property: ts.SyntaxKind): string { const typeNameToDefault: Record = { [ts.SyntaxKind.StringKeyword]: "''", [ts.SyntaxKind.NumberKeyword]: 0, - [ts.SyntaxKind.BooleanKeyword]: false + [ts.SyntaxKind.BooleanKeyword]: false, }; const resolvedValue = typeNameToDefault[property]; @@ -49,7 +49,7 @@ export function getKnobDefaultValue(property: ts.SyntaxKind): string { export function createComponentStoriesFile({ // name, project, - componentPath + componentPath, }: CreateComponentStoriesFileSchema): Rule { return (tree: Tree, context: SchematicContext): Rule => { const proj = getProjectConfig(tree, project); @@ -114,13 +114,13 @@ export function createComponentStoriesFile({ const initializerKindToKnobType: Record = { [ts.SyntaxKind.StringKeyword]: 'text', [ts.SyntaxKind.NumberKeyword]: 'number', - [ts.SyntaxKind.BooleanKeyword]: 'boolean' + [ts.SyntaxKind.BooleanKeyword]: 'boolean', }; return { name: (member.name as ts.Identifier).text, type: initializerKindToKnobType[member.type.kind], - defaultValue: getKnobDefaultValue(member.type.kind) + defaultValue: getKnobDefaultValue(member.type.kind), }; }); } @@ -131,18 +131,18 @@ export function createComponentStoriesFile({ componentFileName: name, propsTypeName, props, - usedKnobs: props.map(x => x.type).join(', '), + usedKnobs: props.map((x) => x.type).join(', '), componentName: (cmpDeclaration as any).name.text, isPlainJs, fileExt, - usesEsLint + usesEsLint, }), - move(normalize(componentDirectory)) - ]) + move(normalize(componentDirectory)), + ]), ]); }; } -export default function(schema: CreateComponentStoriesFileSchema): Rule { +export default function (schema: CreateComponentStoriesFileSchema): Rule { return chain([createComponentStoriesFile(schema), formatFiles()]); } diff --git a/packages/react/src/schematics/component/component.spec.ts b/packages/react/src/schematics/component/component.spec.ts index c380f8bfd55f3..a04ea589b00bf 100644 --- a/packages/react/src/schematics/component/component.spec.ts +++ b/packages/react/src/schematics/component/component.spec.ts @@ -240,7 +240,7 @@ describe('component', () => { name: 'hello', project: projectName, flat: true, - directory: 'components' + directory: 'components', }, appTree ); diff --git a/packages/react/src/schematics/component/component.ts b/packages/react/src/schematics/component/component.ts index c0fff8d52e821..e478fb20e72ea 100644 --- a/packages/react/src/schematics/component/component.ts +++ b/packages/react/src/schematics/component/component.ts @@ -11,7 +11,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { Schema } from './schema'; import { formatFiles, getWorkspace, names, toFileName } from '@nrwl/workspace'; @@ -19,12 +19,12 @@ import { addDepsToPackageJson, addGlobal, getProjectConfig, - insert + insert, } from '@nrwl/workspace/src/utils/ast-utils'; import { CSS_IN_JS_DEPENDENCIES } from '../../utils/styled'; import { typesReactRouterDomVersion, - reactRouterDomVersion + reactRouterDomVersion, } from '../../utils/versions'; import { assertValidStyle } from '../../utils/assertion'; import { toJS } from '@nrwl/workspace/src/utils/rules/to-js'; @@ -37,7 +37,7 @@ interface NormalizedSchema extends Schema { hasStyles: boolean; } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return async (host: Tree, context: SchematicContext) => { const options = await normalizeOptions(host, schema, context); return chain([ @@ -50,7 +50,7 @@ export default function(schema: Schema): Rule { { '@types/react-router-dom': typesReactRouterDomVersion } ) : noop(), - formatFiles({ skipFormat: false }) + formatFiles({ skipFormat: false }), ]); }; } @@ -61,14 +61,14 @@ function createComponentFiles(options: NormalizedSchema): Rule { apply(url(`./files`), [ template({ ...options, - tmpl: '' + tmpl: '', }), - options.skipTests ? filter(file => !/.*spec.tsx/.test(file)) : noop(), + options.skipTests ? filter((file) => !/.*spec.tsx/.test(file)) : noop(), options.styledModule || !options.hasStyles - ? filter(file => !file.endsWith(`.${options.style}`)) + ? filter((file) => !file.endsWith(`.${options.style}`)) : noop(), move(componentDir), - options.js ? toJS() : noop() + options.js ? toJS() : noop(), ]) ); } @@ -155,7 +155,7 @@ async function normalizeOptions( hasStyles: options.style !== 'none', className, fileName: componentFileName, - projectSourceRoot + projectSourceRoot, }; } @@ -179,10 +179,10 @@ function assertValidOptions(options: Schema) { assertValidStyle(options.style); const slashes = ['/', '\\']; - slashes.forEach(s => { + slashes.forEach((s) => { if (options.name.indexOf(s) !== -1) { const [name, ...rest] = options.name.split(s).reverse(); - let suggestion = rest.map(x => x.toLowerCase()).join(s); + let suggestion = rest.map((x) => x.toLowerCase()).join(s); if (options.directory) { suggestion = `${options.directory}${s}${suggestion}`; } diff --git a/packages/react/src/schematics/init/init.spec.ts b/packages/react/src/schematics/init/init.spec.ts index a57230b18e60c..34f13beb5e2e1 100644 --- a/packages/react/src/schematics/init/init.spec.ts +++ b/packages/react/src/schematics/init/init.spec.ts @@ -43,7 +43,7 @@ describe('init', () => { const result = await runSchematic( 'init', { - unitTestRunner: 'none' + unitTestRunner: 'none', }, tree ); diff --git a/packages/react/src/schematics/init/init.ts b/packages/react/src/schematics/init/init.ts index e5f1d5468e8f4..2589507dcb3bd 100644 --- a/packages/react/src/schematics/init/init.ts +++ b/packages/react/src/schematics/init/init.ts @@ -2,7 +2,7 @@ import { chain, noop, Rule } from '@angular-devkit/schematics'; import { addPackageWithInit, updateJsonInTree, - updateWorkspace + updateWorkspace, } from '@nrwl/workspace'; import { Schema } from './schema'; import { @@ -11,32 +11,32 @@ import { reactVersion, testingLibraryReactVersion, typesReactDomVersion, - typesReactVersion + typesReactVersion, } from '../../utils/versions'; import { JsonObject } from '@angular-devkit/core'; import { setDefaultCollection } from '@nrwl/workspace/src/utils/rules/workspace'; export function updateDependencies(): Rule { - return updateJsonInTree('package.json', json => { + return updateJsonInTree('package.json', (json) => { delete json.dependencies['@nrwl/react']; json.dependencies = { ...json.dependencies, react: reactVersion, - 'react-dom': reactDomVersion + 'react-dom': reactDomVersion, }; json.devDependencies = { ...json.devDependencies, '@nrwl/react': nxVersion, '@types/react': typesReactVersion, '@types/react-dom': typesReactDomVersion, - '@testing-library/react': testingLibraryReactVersion + '@testing-library/react': testingLibraryReactVersion, }; return json; }); } function setDefault(): Rule { - const updateReactWorkspace = updateWorkspace(workspace => { + const updateReactWorkspace = updateWorkspace((workspace) => { // Also generate all new react apps with babel. workspace.extensions.schematics = jsonIdentity(workspace.extensions.schematics) || {}; @@ -49,9 +49,9 @@ function setDefault(): Rule { ...reactSchematics, application: { ...jsonIdentity(reactSchematics.application), - babel: true - } - } + babel: true, + }, + }, }; }); return chain([setDefaultCollection('@nrwl/react'), updateReactWorkspace]); @@ -61,7 +61,7 @@ function jsonIdentity(x: any): JsonObject { return x as JsonObject; } -export default function(schema: Schema) { +export default function (schema: Schema) { return chain([ setDefault(), schema.unitTestRunner === 'jest' @@ -71,6 +71,6 @@ export default function(schema: Schema) { ? addPackageWithInit('@nrwl/cypress') : noop(), addPackageWithInit('@nrwl/web', schema), - updateDependencies() + updateDependencies(), ]); } diff --git a/packages/react/src/schematics/library/library.spec.ts b/packages/react/src/schematics/library/library.spec.ts index 77cfed51d734d..e1d7a183cb1ac 100644 --- a/packages/react/src/schematics/library/library.spec.ts +++ b/packages/react/src/schematics/library/library.spec.ts @@ -24,9 +24,9 @@ describe('lib', () => { exclude: ['**/node_modules/**', '!libs/my-lib/**'], tsConfig: [ 'libs/my-lib/tsconfig.lib.json', - 'libs/my-lib/tsconfig.spec.json' - ] - } + 'libs/my-lib/tsconfig.spec.json', + ], + }, }); }); @@ -39,8 +39,8 @@ describe('lib', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-lib': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -48,7 +48,7 @@ describe('lib', () => { const tree = await runSchematic('lib', { name: 'myLib' }, appTree); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ - 'libs/my-lib/src/index.ts' + 'libs/my-lib/src/index.ts', ]); }); @@ -62,13 +62,13 @@ describe('lib', () => { jsx: 'react', allowSyntheticDefaultImports: true, esModuleInterop: true, - types: ['node', 'jest'] + types: ['node', 'jest'], }, files: [ '../../node_modules/@nrwl/react/typings/cssmodule.d.ts', - '../../node_modules/@nrwl/react/typings/image.d.ts' + '../../node_modules/@nrwl/react/typings/image.d.ts', ], - include: ['**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx'] + include: ['**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx'], }); }); @@ -108,15 +108,15 @@ describe('lib', () => { { name: 'myLib', directory: 'myDir', - tags: 'one' + tags: 'one', }, appTree ); const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] - } + tags: ['one'], + }, }); const tree2 = await runSchematic( @@ -124,18 +124,18 @@ describe('lib', () => { { name: 'myLib2', directory: 'myDir', - tags: 'one,two' + tags: 'one,two', }, tree ); const nxJson2 = readJsonInTree(tree2, '/nx.json'); expect(nxJson2.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] + tags: ['one'], }, 'my-dir-my-lib2': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -175,9 +175,9 @@ describe('lib', () => { exclude: ['**/node_modules/**', '!libs/my-dir/my-lib/**'], tsConfig: [ 'libs/my-dir/my-lib/tsconfig.lib.json', - 'libs/my-dir/my-lib/tsconfig.spec.json' - ] - } + 'libs/my-dir/my-lib/tsconfig.spec.json', + ], + }, }); }); @@ -188,9 +188,9 @@ describe('lib', () => { appTree ); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); - expect(tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib']).toEqual( - ['libs/my-dir/my-lib/src/index.ts'] - ); + expect( + tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib'] + ).toEqual(['libs/my-dir/my-lib/src/index.ts']); expect( tsconfigJson.compilerOptions.paths['my-dir-my-lib/*'] ).toBeUndefined(); @@ -214,13 +214,13 @@ describe('lib', () => { jsx: 'react', allowSyntheticDefaultImports: true, esModuleInterop: true, - types: ['node', 'jest'] + types: ['node', 'jest'], }, files: [ '../../../node_modules/@nrwl/react/typings/cssmodule.d.ts', - '../../../node_modules/@nrwl/react/typings/image.d.ts' + '../../../node_modules/@nrwl/react/typings/image.d.ts', ], - include: ['**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx'] + include: ['**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx'], }); }); }); @@ -305,7 +305,7 @@ describe('lib', () => { 'lib', { name: 'myLib', - appProject: 'my-app' + appProject: 'my-app', }, appTree ); @@ -327,7 +327,7 @@ describe('lib', () => { 'lib', { name: 'myLib', - appProject: 'my-app' + appProject: 'my-app', }, appTree ); @@ -349,7 +349,7 @@ describe('lib', () => { 'lib', { name: 'myLib', - publishable: true + publishable: true, }, appTree ); @@ -365,8 +365,8 @@ describe('lib', () => { project: 'libs/my-lib/package.json', tsConfig: 'libs/my-lib/tsconfig.lib.json', babelConfig: '@nrwl/react/plugins/bundle-babel', - rollupConfig: '@nrwl/react/plugins/bundle-rollup' - } + rollupConfig: '@nrwl/react/plugins/bundle-rollup', + }, }); }); @@ -376,7 +376,7 @@ describe('lib', () => { { name: 'myLib', publishable: true, - style: 'styled-components' + style: 'styled-components', }, appTree ); @@ -385,8 +385,8 @@ describe('lib', () => { expect(workspaceJson.projects['my-lib'].architect.build).toMatchObject({ options: { - external: ['react', 'react-dom', 'styled-components'] - } + external: ['react', 'react-dom', 'styled-components'], + }, }); }); @@ -396,7 +396,7 @@ describe('lib', () => { { name: 'myLib', publishable: true, - style: '@emotion/styled' + style: '@emotion/styled', }, appTree ); @@ -405,8 +405,8 @@ describe('lib', () => { expect(workspaceJson.projects['my-lib'].architect.build).toMatchObject({ options: { - external: ['react', 'react-dom', '@emotion/styled', '@emotion/core'] - } + external: ['react', 'react-dom', '@emotion/styled', '@emotion/core'], + }, }); }); @@ -416,7 +416,7 @@ describe('lib', () => { { name: 'myLib', publishable: true, - style: 'none' + style: 'none', }, appTree ); @@ -425,8 +425,8 @@ describe('lib', () => { expect(workspaceJson.projects['my-lib'].architect.build).toMatchObject({ options: { - external: ['react', 'react-dom'] - } + external: ['react', 'react-dom'], + }, }); }); @@ -435,7 +435,7 @@ describe('lib', () => { 'lib', { name: 'myLib', - publishable: true + publishable: true, }, appTree ); @@ -452,7 +452,7 @@ describe('lib', () => { 'lib', { name: 'myLib', - js: true + js: true, }, appTree ); diff --git a/packages/react/src/schematics/library/library.ts b/packages/react/src/schematics/library/library.ts index 484726021f640..754124c0fdd0d 100644 --- a/packages/react/src/schematics/library/library.ts +++ b/packages/react/src/schematics/library/library.ts @@ -11,7 +11,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { CSS_IN_JS_DEPENDENCIES } from '@nrwl/react'; import { @@ -29,7 +29,7 @@ import { toClassName, toFileName, updateJsonInTree, - updateWorkspaceInTree + updateWorkspaceInTree, } from '@nrwl/workspace'; import { toJS } from '@nrwl/workspace/src/utils/rules/to-js'; import * as ts from 'typescript'; @@ -38,12 +38,12 @@ import { addBrowserRouter, addInitialRoutes, addRoute, - findComponentImportPath + findComponentImportPath, } from '../../utils/ast-utils'; import { extraEslintDependencies, reactEslintJson } from '../../utils/lint'; import { reactRouterDomVersion, - typesReactRouterDomVersion + typesReactRouterDomVersion, } from '../../utils/versions'; import { Schema } from './schema'; @@ -58,7 +58,7 @@ export interface NormalizedSchema extends Schema { appSourceRoot?: Path; } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema, context); @@ -68,7 +68,7 @@ export default function(schema: Schema): Rule { return chain([ addLintFiles(options.projectRoot, options.linter, { localConfig: reactEslintJson, - extraPackageDeps: extraEslintDependencies + extraPackageDeps: extraEslintDependencies, }), createFiles(options), !options.skipTsConfig ? updateTsConfig(options) : noop(), @@ -80,7 +80,7 @@ export default function(schema: Schema): Rule { setupFile: 'none', supportTsx: true, skipSerializers: true, - babelJest: options.babelJest + babelJest: options.babelJest, }) : noop(), options.component @@ -93,18 +93,18 @@ export default function(schema: Schema): Rule { export: true, routing: options.routing, js: options.js, - pascalCaseFiles: options.pascalCaseFiles + pascalCaseFiles: options.pascalCaseFiles, }) : noop(), options.publishable ? updateLibPackageNpmScope(options) : noop(), updateAppRoutes(options, context), - formatFiles(options) + formatFiles(options), ])(host, context); }; } function addProject(options: NormalizedSchema): Rule { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const architect: { [key: string]: any } = {}; architect.lint = generateProjectLint( @@ -136,8 +136,8 @@ function addProject(options: NormalizedSchema): Rule { entryFile: maybeJs(options, `${options.projectRoot}/src/index.ts`), external, babelConfig: `@nrwl/react/plugins/bundle-babel`, - rollupConfig: `@nrwl/react/plugins/bundle-rollup` - } + rollupConfig: `@nrwl/react/plugins/bundle-rollup`, + }, }; } @@ -146,7 +146,7 @@ function addProject(options: NormalizedSchema): Rule { sourceRoot: join(normalize(options.projectRoot), 'src'), projectType: 'library', schematics: {}, - architect + architect, }; return json; }); @@ -156,15 +156,15 @@ function updateTsConfig(options: NormalizedSchema): Rule { return chain([ (host: Tree, context: SchematicContext) => { const nxJson = readJsonInTree(host, 'nx.json'); - return updateJsonInTree('tsconfig.json', json => { + return updateJsonInTree('tsconfig.json', (json) => { const c = json.compilerOptions; delete c.paths[options.name]; c.paths[`@${nxJson.npmScope}/${options.projectDirectory}`] = [ - maybeJs(options, `libs/${options.projectDirectory}/src/index.ts`) + maybeJs(options, `libs/${options.projectDirectory}/src/index.ts`), ]; return json; })(host, context); - } + }, ]); } @@ -175,19 +175,19 @@ function createFiles(options: NormalizedSchema): Rule { ...options, ...names(options.name), tmpl: '', - offsetFromRoot: offsetFromRoot(options.projectRoot) + offsetFromRoot: offsetFromRoot(options.projectRoot), }), move(options.projectRoot), options.publishable ? noop() - : filter(file => !file.endsWith('package.json')), - options.js ? toJS() : noop() + : filter((file) => !file.endsWith('package.json')), + options.js ? toJS() : noop(), ]) ); } function updateNxJson(options: NormalizedSchema): Rule { - return updateJsonInTree('nx.json', json => { + return updateJsonInTree('nx.json', (json) => { json.projects[options.name] = { tags: options.parsedTags }; return json; }); @@ -256,13 +256,13 @@ function updateAppRoutes( { routePath: options.routePath, componentName: toClassName(options.name), - moduleName: `@${npmScope}/${options.projectDirectory}` + moduleName: `@${npmScope}/${options.projectDirectory}`, }, context ) ); }, - addDepsToPackageJson({ 'react-router-dom': reactRouterDomVersion }, {}) + addDepsToPackageJson({ 'react-router-dom': reactRouterDomVersion }, {}), ]); }; } @@ -302,7 +302,7 @@ function normalizeOptions( const projectRoot = normalize(`libs/${projectDirectory}`); const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const normalized: NormalizedSchema = { @@ -312,7 +312,7 @@ function normalizeOptions( name: projectName, projectRoot, projectDirectory, - parsedTags + parsedTags, }; if (options.appProject) { @@ -341,7 +341,7 @@ function normalizeOptions( function updateLibPackageNpmScope(options: NormalizedSchema): Rule { return (host: Tree) => { - return updateJsonInTree(`${options.projectRoot}/package.json`, json => { + return updateJsonInTree(`${options.projectRoot}/package.json`, (json) => { json.name = `@${getNpmScope(host)}/${options.name}`; return json; }); diff --git a/packages/react/src/schematics/redux/redux.ts b/packages/react/src/schematics/redux/redux.ts index 52bf64a1ed706..b76e567a40261 100644 --- a/packages/react/src/schematics/redux/redux.ts +++ b/packages/react/src/schematics/redux/redux.ts @@ -9,7 +9,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import '@nrwl/tao/src/compat/compat'; import { formatFiles, getWorkspace, names, toFileName } from '@nrwl/workspace'; @@ -18,7 +18,7 @@ import { addGlobal, getProjectConfig, insert, - readJsonInTree + readJsonInTree, } from '@nrwl/workspace/src/utils/ast-utils'; import { toJS } from '@nrwl/workspace/src/utils/rules/to-js'; import * as path from 'path'; @@ -27,11 +27,11 @@ import { addReduxStoreToMain, updateReduxStore } from '../../utils/ast-utils'; import { reactReduxVersion, reduxjsToolkitVersion, - typesReactReduxVersion + typesReactReduxVersion, } from '../../utils/versions'; import { NormalizedSchema, Schema } from './schema'; -export default function(schema: any): Rule { +export default function (schema: any): Rule { return async (host: Tree, context: SchematicContext) => { const options = await normalizeOptions(host, schema); @@ -41,7 +41,7 @@ export default function(schema: any): Rule { addReduxPackageDependencies, addStoreConfiguration(options, context), updateReducerConfiguration(options, context), - formatFiles() + formatFiles(), ]); }; } @@ -50,7 +50,7 @@ function generateReduxFiles(options: NormalizedSchema) { const templateSource = apply(url('./files'), [ template({ ...options, tmpl: '' }), move(options.filesPath), - options.js ? toJS() : noop() + options.js ? toJS() : noop(), ]); return mergeWith(templateSource); @@ -61,7 +61,7 @@ function addReduxPackageDependencies(): Rule { { '@reduxjs/toolkit': reduxjsToolkitVersion, 'react-redux': reactReduxVersion, - '@types/react-redux': typesReactReduxVersion + '@types/react-redux': typesReactReduxVersion, }, {} ); @@ -93,7 +93,7 @@ function addExportsToBarrel(options: NormalizedSchema): Rule { indexSourceFile, indexFilePath, `export * from '${statePath}.slice';` - ) + ), ]); } @@ -149,7 +149,7 @@ function updateReducerConfiguration( updateReduxStore(options.appMainFilePath, mainSourceFile, context, { keyName: `${options.constantName}_FEATURE_KEY`, reducerName: `${options.propertyName}Reducer`, - modulePath: `${options.projectModulePath}` + modulePath: `${options.projectModulePath}`, }) ); return host; @@ -175,8 +175,8 @@ async function normalizeOptions( const modulePath = projectType === 'application' ? `./app/${extraNames.fileName}.slice` - : Object.keys(tsPaths).find(k => - tsPaths[k].some(s => s.includes(sourceRoot)) + : Object.keys(tsPaths).find((k) => + tsPaths[k].some((s) => s.includes(sourceRoot)) ); // If --project is set to an app, automatically configure store // for it without needing to specify --appProject. @@ -211,6 +211,6 @@ async function normalizeOptions( projectModulePath: modulePath, appProjectSourcePath, appMainFilePath, - filesPath: join(sourceRoot, projectType === 'application' ? 'app' : 'lib') + filesPath: join(sourceRoot, projectType === 'application' ? 'app' : 'lib'), }; } diff --git a/packages/react/src/schematics/stories/stories.spec.ts b/packages/react/src/schematics/stories/stories.spec.ts index 967be818c9b9c..9d173cbfd9fcd 100644 --- a/packages/react/src/schematics/stories/stories.spec.ts +++ b/packages/react/src/schematics/stories/stories.spec.ts @@ -41,7 +41,7 @@ describe('react:stories', () => { tree = await runSchematic( 'stories', { - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); @@ -59,7 +59,7 @@ describe('react:stories', () => { 'stories', { project: 'test-ui-lib', - generateCypressSpecs: true + generateCypressSpecs: true, }, appTree ); @@ -88,7 +88,7 @@ describe('react:stories', () => { tree = await runSchematic( 'stories', { - project: 'test-ui-lib' + project: 'test-ui-lib', }, appTree ); @@ -109,7 +109,7 @@ export async function createTestUILib( appTree = createEmptyWorkspace(appTree); appTree = await callRule( externalSchematic('@nrwl/react', 'library', { - name: libName + name: libName, }), appTree ); @@ -119,7 +119,7 @@ export async function createTestUILib( appTree = await callRule( externalSchematic('@nrwl/react', 'application', { name: `${libName}-e2e`, - js: plainJS + js: plainJS, } as Partial), appTree ); diff --git a/packages/react/src/schematics/stories/stories.ts b/packages/react/src/schematics/stories/stories.ts index 5dd5def2a1c76..dd41f0d09ddee 100644 --- a/packages/react/src/schematics/stories/stories.ts +++ b/packages/react/src/schematics/stories/stories.ts @@ -5,7 +5,7 @@ import { SchematicContext, Tree, SchematicsException, - noop + noop, } from '@angular-devkit/schematics'; import { getProjectConfig } from '@nrwl/workspace'; import { join } from 'path'; @@ -49,7 +49,7 @@ export function createAllStories( const libPath = join(projectSrcRoot, '/lib'); let componentPaths: string[] = []; - tree.getDir(libPath).visit(filePath => { + tree.getDir(libPath).visit((filePath) => { if ( (filePath.endsWith('.tsx') && !filePath.endsWith('.spec.tsx')) || (filePath.endsWith('.js') && !filePath.endsWith('.spec.js')) || @@ -60,7 +60,7 @@ export function createAllStories( }); return chain( - componentPaths.map(componentPath => { + componentPaths.map((componentPath) => { const relativeCmpDir = componentPath.replace( join('/', projectSrcRoot, '/'), '' @@ -73,7 +73,7 @@ export function createAllStories( return chain([ schematic('component-story', { componentPath: relativeCmpDir, - project: projectName + project: projectName, }), generateCypressSpecs ? schematic( @@ -81,18 +81,18 @@ export function createAllStories( { project: projectName, componentPath: relativeCmpDir, - js + js, } ) - : () => {} + : () => {}, ]); }) ); }; } -export default function(schema: StorybookStoriesSchema): Rule { +export default function (schema: StorybookStoriesSchema): Rule { return chain([ - createAllStories(schema.project, schema.generateCypressSpecs, schema.js) + createAllStories(schema.project, schema.generateCypressSpecs, schema.js), ]); } diff --git a/packages/react/src/schematics/storybook-configuration/configuration.spec.ts b/packages/react/src/schematics/storybook-configuration/configuration.spec.ts index 545f351ddfbbb..de026c9582447 100644 --- a/packages/react/src/schematics/storybook-configuration/configuration.spec.ts +++ b/packages/react/src/schematics/storybook-configuration/configuration.spec.ts @@ -17,7 +17,7 @@ describe('react:storybook-configuration', () => { 'storybook-configuration', { name: 'test-ui-lib', - configureCypress: true + configureCypress: true, }, appTree ); @@ -36,7 +36,7 @@ describe('react:storybook-configuration', () => { 'storybook-configuration', { name: 'test-ui-lib', - generateStories: true + generateStories: true, }, appTree ); @@ -73,7 +73,7 @@ describe('react:storybook-configuration', () => { name: 'test-ui-lib', generateCypressSpecs: true, generateStories: true, - js: true + js: true, }, appTree ); @@ -93,7 +93,7 @@ export async function createTestUILib( appTree = await callRule( externalSchematic('@nrwl/react', 'library', { name: libName, - js: plainJS + js: plainJS, }), appTree ); diff --git a/packages/react/src/schematics/storybook-configuration/configuration.ts b/packages/react/src/schematics/storybook-configuration/configuration.ts index d236379a62df9..65532a1f25fd6 100644 --- a/packages/react/src/schematics/storybook-configuration/configuration.ts +++ b/packages/react/src/schematics/storybook-configuration/configuration.ts @@ -3,7 +3,7 @@ import { externalSchematic, Rule, schematic, - noop + noop, } from '@angular-devkit/schematics'; import { StorybookConfigureSchema } from './schema'; import { StorybookStoriesSchema } from '../stories/stories'; @@ -14,20 +14,20 @@ function generateStories(schema: StorybookConfigureSchema): Rule { project: schema.name, generateCypressSpecs: schema.configureCypress && schema.generateCypressSpecs, - js: schema.js + js: schema.js, }); }; } -export default function(schema: StorybookConfigureSchema): Rule { +export default function (schema: StorybookConfigureSchema): Rule { return chain([ externalSchematic('@nrwl/storybook', 'configuration', { name: schema.name, uiFramework: '@storybook/react', configureCypress: schema.configureCypress, js: schema.js, - linter: schema.linter + linter: schema.linter, }), - schema.generateStories ? generateStories(schema) : noop() + schema.generateStories ? generateStories(schema) : noop(), ]); } diff --git a/packages/react/src/utils/assertion.spec.ts b/packages/react/src/utils/assertion.spec.ts index c05fb1d558e0b..6bfb9ef9aa33c 100644 --- a/packages/react/src/utils/assertion.spec.ts +++ b/packages/react/src/utils/assertion.spec.ts @@ -5,13 +5,13 @@ describe('assertValidStyle', () => { const schemas = [ require('../schematics/application/schema.json'), require('../schematics/component/schema.json'), - require('../schematics/library/schema.json') + require('../schematics/library/schema.json'), ]; - schemas.forEach(schema => { + schemas.forEach((schema) => { const values = schema.properties.style['x-prompt'].items; expect(() => - values.forEach(value => assertValidStyle(value)).not.toThrow() + values.forEach((value) => assertValidStyle(value)).not.toThrow() ); }); }); diff --git a/packages/react/src/utils/assertion.ts b/packages/react/src/utils/assertion.ts index 0f1e0a7d1cc95..04ac144836e00 100644 --- a/packages/react/src/utils/assertion.ts +++ b/packages/react/src/utils/assertion.ts @@ -5,7 +5,7 @@ const VALID_STYLES = [ 'styl', 'styled-components', '@emotion/styled', - 'none' + 'none', ]; export function assertValidStyle(style: string): void { if (VALID_STYLES.indexOf(style) === -1) { diff --git a/packages/react/src/utils/ast-utils.spec.ts b/packages/react/src/utils/ast-utils.spec.ts index cd6c9e1e8cb59..3c171ffa5d073 100644 --- a/packages/react/src/utils/ast-utils.spec.ts +++ b/packages/react/src/utils/ast-utils.spec.ts @@ -99,7 +99,7 @@ describe('addRoute', () => { beforeEach(() => { context = { - warn: jest.fn() + warn: jest.fn(), }; tree = Tree.empty(); }); @@ -172,7 +172,7 @@ export default App; { routePath: '/about', componentName: 'About', - moduleName: '@example/about' + moduleName: '@example/about', }, context ) @@ -191,7 +191,7 @@ describe('addBrowserRouter', () => { beforeEach(() => { context = { - warn: jest.fn() + warn: jest.fn(), }; tree = Tree.empty(); }); @@ -228,7 +228,7 @@ describe('findMainRenderStatement', () => { beforeEach(() => { context = { - warn: jest.fn() + warn: jest.fn(), }; tree = Tree.empty(); }); @@ -290,7 +290,7 @@ describe('addReduxStoreToMain', () => { beforeEach(() => { context = { - warn: jest.fn() + warn: jest.fn(), }; tree = Tree.empty(); }); @@ -329,7 +329,7 @@ describe('updateReduxStore', () => { beforeEach(() => { context = { - warn: jest.fn() + warn: jest.fn(), }; tree = Tree.empty(); }); @@ -355,7 +355,7 @@ const store = configureStore({ utils.updateReduxStore('/main.tsx', source, context, { keyName: 'SLICE_KEY', reducerName: 'sliceReducer', - modulePath: '@test/slice' + modulePath: '@test/slice', }) ); @@ -385,7 +385,7 @@ const store = createStore(combineReducer({})); utils.updateReduxStore('/main.tsx', source, context, { keyName: 'SLICE_KEY', reducerName: 'sliceReducer', - modulePath: '@test/slice' + modulePath: '@test/slice', }) ); @@ -407,7 +407,7 @@ describe('getComponentName', () => {

Welcome to test component, {props.name}

);`, - expectedName: 'Test' + expectedName: 'Test', }, { testName: 'defining a function and then default exporting it', @@ -421,7 +421,7 @@ describe('getComponentName', () => { }; export default Test; `, - expectedName: 'Test' + expectedName: 'Test', }, { testName: 'defining an arrow function and then exporting it', @@ -435,7 +435,7 @@ describe('getComponentName', () => { }; export default Test; `, - expectedName: 'Test' + expectedName: 'Test', }, { testName: 'defining an arrow function that directly returns JSX', @@ -443,7 +443,7 @@ describe('getComponentName', () => { const Test = (props: TestProps) =>

Welcome to test component, {props.name}

; export default Test `, - expectedName: 'Test' + expectedName: 'Test', }, { testName: 'exporting a react class component', @@ -454,7 +454,7 @@ describe('getComponentName', () => { } } `, - expectedName: 'Test' + expectedName: 'Test', }, { testName: 'defining a react class component & then default exporting it', @@ -465,9 +465,9 @@ describe('getComponentName', () => { } } `, - expectedName: 'Test' - } - ].forEach(testConfig => { + expectedName: 'Test', + }, + ].forEach((testConfig) => { it(`should find the component when ${testConfig.testName}`, () => { const source = ts.createSourceFile( 'some-component.tsx', diff --git a/packages/react/src/utils/ast-utils.ts b/packages/react/src/utils/ast-utils.ts index 37fb373ba6fff..d4502c1202fb7 100644 --- a/packages/react/src/utils/ast-utils.ts +++ b/packages/react/src/utils/ast-utils.ts @@ -3,12 +3,12 @@ import { Change, findNodes, InsertChange, - ReplaceChange + ReplaceChange, } from '@nrwl/workspace/src/utils/ast-utils'; import * as ts from 'typescript'; import { SchematicContext, - SchematicsException + SchematicsException, } from '@angular-devkit/schematics'; export function findMainRenderStatement( @@ -37,7 +37,7 @@ export function findMainRenderStatement( ts.SyntaxKind.ImportDeclaration ) as ts.ImportDeclaration[]; const hasRenderImport = imports.some( - i => + (i) => i.moduleSpecifier.getText().includes('react-dom') && /\brender\b/.test(i.importClause.namedBindings.getText()) ); @@ -76,8 +76,8 @@ export function findDefaultExportDeclaration( >; const exported = all - .filter(x => x.name.kind === ts.SyntaxKind.Identifier) - .find(x => (x.name as ts.Identifier).text === identifier.text); + .filter((x) => x.name.kind === ts.SyntaxKind.Identifier) + .find((x) => (x.name as ts.Identifier).text === identifier.text); return exported || null; } else { @@ -94,8 +94,8 @@ export function findDefaultExportIdentifier( ) as ts.ExportAssignment[]; const identifier = exports - .map(x => x.expression) - .find(x => x.kind === ts.SyntaxKind.Identifier) as ts.Identifier; + .map((x) => x.expression) + .find((x) => x.kind === ts.SyntaxKind.Identifier) as ts.Identifier; return identifier || null; } @@ -124,8 +124,8 @@ function hasDefaultExportModifier( ) { return ( x.modifiers && - x.modifiers.some(m => m.kind === ts.SyntaxKind.ExportKeyword) && - x.modifiers.some(m => m.kind === ts.SyntaxKind.DefaultKeyword) + x.modifiers.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) && + x.modifiers.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword) ); } @@ -156,9 +156,9 @@ export function findComponentImportPath( export function findElements(source: ts.SourceFile, tagName: string) { const nodes = findNodes(source, [ ts.SyntaxKind.JsxSelfClosingElement, - ts.SyntaxKind.JsxOpeningElement + ts.SyntaxKind.JsxOpeningElement, ]); - return nodes.filter(node => isTag(tagName, node)); + return nodes.filter((node) => isTag(tagName, node)); } export function findClosestOpening(tagName: string, node: ts.Node) { @@ -198,7 +198,7 @@ export function addInitialRoutes( ): Change[] { const jsxClosingElements = findNodes(source, [ ts.SyntaxKind.JsxClosingElement, - ts.SyntaxKind.JsxClosingFragment + ts.SyntaxKind.JsxClosingFragment, ]); const outerMostJsxClosing = jsxClosingElements[jsxClosingElements.length - 1]; @@ -249,7 +249,7 @@ export function addInitialRoutes( sourcePath, `import { Route, Link } from 'react-router-dom';` ), - insertRoutes + insertRoutes, ]; } @@ -331,7 +331,7 @@ export function addBrowserRouter( `import { BrowserRouter } from 'react-router-dom';` ), new InsertChange(sourcePath, app.getStart(), ``), - new InsertChange(sourcePath, app.getEnd(), ``) + new InsertChange(sourcePath, app.getEnd(), ``), ]; } else { context.logger.warn( @@ -370,7 +370,7 @@ const store = configureStore({ ` ), new InsertChange(sourcePath, jsx.getStart(), ``), - new InsertChange(sourcePath, jsx.getEnd(), ``) + new InsertChange(sourcePath, jsx.getEnd(), ``), ]; } @@ -447,7 +447,7 @@ export function updateReduxStore( `[${feature.keyName}]: ${feature.reducerName}${ reducerDescriptor.properties.length > 0 ? ',' : '' }` - ) + ), ]; } @@ -474,7 +474,7 @@ export function getComponentPropsInterface( if (ts.isFunctionDeclaration(cmpDeclaration)) { const propsParam: ts.ParameterDeclaration = cmpDeclaration.parameters.find( - x => ts.isParameter(x) && (x.name as ts.Identifier).text === 'props' + (x) => ts.isParameter(x) && (x.name as ts.Identifier).text === 'props' ); if (propsParam && propsParam.type) { @@ -489,7 +489,7 @@ export function getComponentPropsInterface( .initializer as ts.ArrowFunction; const propsParam: ts.ParameterDeclaration = arrowFn.parameters.find( - x => ts.isParameter(x) && (x.name as ts.Identifier).text === 'props' + (x) => ts.isParameter(x) && (x.name as ts.Identifier).text === 'props' ); if (propsParam && propsParam.type) { @@ -506,7 +506,7 @@ export function getComponentPropsInterface( if (heritageClause) { const propsTypeExpression = heritageClause.types.find( - x => + (x) => (x.expression as ts.PropertyAccessExpression).name.text === 'Component' || (x.expression as ts.PropertyAccessExpression).name.text === diff --git a/packages/react/src/utils/babel-utils.ts b/packages/react/src/utils/babel-utils.ts index b8b3d0aaa7347..0a54bb7a6ffb2 100644 --- a/packages/react/src/utils/babel-utils.ts +++ b/packages/react/src/utils/babel-utils.ts @@ -5,13 +5,13 @@ import { join } from 'path'; export function updateBabelOptions(options: any): void { // Add react babel preset const idx = options.presets.findIndex( - p => Array.isArray(p) && p[0].indexOf('@babel/preset-env') !== -1 + (p) => Array.isArray(p) && p[0].indexOf('@babel/preset-env') !== -1 ); options.presets.splice(idx + 1, 0, [ require.resolve('@babel/preset-react'), { - useBuiltIns: true - } + useBuiltIns: true, + }, ]); // TODO: Remove this once we have composable webpack and babel plugins. @@ -27,8 +27,8 @@ export function updateBabelOptions(options: any): void { options.plugins.splice(0, 0, [ require.resolve('babel-plugin-styled-components'), { - pure: true - } + pure: true, + }, ]); } if (hasEmotion && !hasStyledComponents) { diff --git a/packages/react/src/utils/lint.ts b/packages/react/src/utils/lint.ts index ea16d42ceb4b7..9a74f8f437da2 100644 --- a/packages/react/src/utils/lint.ts +++ b/packages/react/src/utils/lint.ts @@ -2,7 +2,7 @@ import { eslintPluginImportVersion, eslintPluginReactVersion, eslintPluginReactHooksVersion, - eslintPluginJsxA11yVersion + eslintPluginJsxA11yVersion, } from './versions'; import * as restrictedGlobals from 'confusing-browser-globals'; @@ -12,8 +12,8 @@ export const extraEslintDependencies = { 'eslint-plugin-import': eslintPluginImportVersion, 'eslint-plugin-jsx-a11y': eslintPluginJsxA11yVersion, 'eslint-plugin-react': eslintPluginReactVersion, - 'eslint-plugin-react-hooks': eslintPluginReactHooksVersion - } + 'eslint-plugin-react-hooks': eslintPluginReactHooksVersion, + }, }; /** @@ -25,12 +25,12 @@ export const reactEslintJson = { commonjs: true, es6: true, jest: true, - node: true + node: true, }, settings: { react: { - version: 'detect' - } + version: 'detect', + }, }, plugins: ['import', 'jsx-a11y', 'react', 'react-hooks'], @@ -78,10 +78,10 @@ export const reactEslintJson = { ['&', '|', '^', '~', '<<', '>>', '>>>'], ['==', '!=', '===', '!==', '>', '>=', '<', '<='], ['&&', '||'], - ['in', 'instanceof'] + ['in', 'instanceof'], ], - allowSamePrecedence: false - } + allowSamePrecedence: false, + }, ], 'no-multi-str': 'warn', 'no-native-reassign': 'warn', @@ -113,8 +113,8 @@ export const reactEslintJson = { { allowShortCircuit: true, allowTernary: true, - allowTaggedTemplates: true - } + allowTaggedTemplates: true, + }, ], 'no-unused-labels': 'warn', 'no-useless-computed-key': 'warn', @@ -125,8 +125,8 @@ export const reactEslintJson = { { ignoreDestructuring: false, ignoreImport: false, - ignoreExport: false - } + ignoreExport: false, + }, ], 'no-with': 'warn', 'no-whitespace-before-property': 'warn', @@ -143,14 +143,14 @@ export const reactEslintJson = { object: 'require', property: 'ensure', message: - 'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting' + 'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting', }, { object: 'System', property: 'import', message: - 'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting' - } + 'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting', + }, ], 'getter-return': 'warn', @@ -175,8 +175,8 @@ export const reactEslintJson = { 'warn', { allowAllCaps: true, - ignore: [] - } + ignore: [], + }, ], 'react/jsx-uses-react': 'warn', 'react/jsx-uses-vars': 'warn', @@ -198,8 +198,8 @@ export const reactEslintJson = { 'jsx-a11y/anchor-is-valid': [ 'warn', { - aspects: ['noHref', 'invalidHref'] - } + aspects: ['noHref', 'invalidHref'], + }, ], 'jsx-a11y/aria-activedescendant-has-tabindex': 'warn', 'jsx-a11y/aria-props': 'warn', @@ -246,18 +246,18 @@ export const reactEslintJson = { functions: false, classes: false, variables: false, - typedefs: false - } + typedefs: false, + }, ], 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': [ 'warn', { args: 'none', - ignoreRestSiblings: true - } + ignoreRestSiblings: true, + }, ], 'no-useless-constructor': 'off', - '@typescript-eslint/no-useless-constructor': 'warn' - } + '@typescript-eslint/no-useless-constructor': 'warn', + }, }; diff --git a/packages/react/src/utils/styled.ts b/packages/react/src/utils/styled.ts index aff6f58d0e67f..d49dfccf1e581 100644 --- a/packages/react/src/utils/styled.ts +++ b/packages/react/src/utils/styled.ts @@ -2,7 +2,7 @@ import { emotionCoreVersion, emotionStyledVersion, styledComponentsVersion, - typesStyledComponentsVersion + typesStyledComponentsVersion, } from './versions'; import { PackageDependencies } from './dependencies'; @@ -11,17 +11,17 @@ export const CSS_IN_JS_DEPENDENCIES: { } = { 'styled-components': { dependencies: { - 'styled-components': styledComponentsVersion + 'styled-components': styledComponentsVersion, }, devDependencies: { - '@types/styled-components': typesStyledComponentsVersion - } + '@types/styled-components': typesStyledComponentsVersion, + }, }, '@emotion/styled': { dependencies: { '@emotion/styled': emotionStyledVersion, - '@emotion/core': emotionCoreVersion + '@emotion/core': emotionCoreVersion, }, - devDependencies: {} - } + devDependencies: {}, + }, }; diff --git a/packages/react/src/utils/testing.ts b/packages/react/src/utils/testing.ts index 2a2df135275cc..49a40b2fbf64c 100644 --- a/packages/react/src/utils/testing.ts +++ b/packages/react/src/utils/testing.ts @@ -36,13 +36,13 @@ export function createApp(tree: Tree, appName: string): Promise { const { fileName } = names(appName); return callRule( - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: fileName, root: `apps/${fileName}`, projectType: 'application', sourceRoot: `apps/${fileName}/src`, - targets: {} + targets: {}, }); }), tree @@ -55,13 +55,13 @@ export function createLib(tree: Tree, libName: string): Promise { tree.create(`/libs/${fileName}/src/index.ts`, `\n`); return callRule( - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: fileName, root: `libs/${fileName}`, projectType: 'library', sourceRoot: `libs/${fileName}/src`, - targets: {} + targets: {}, }); }), tree diff --git a/packages/storybook/src/builders/build-storybook/build-storybook.impl.spec.ts b/packages/storybook/src/builders/build-storybook/build-storybook.impl.spec.ts index 34ba4507cafa1..3dc8151d2ae15 100644 --- a/packages/storybook/src/builders/build-storybook/build-storybook.impl.spec.ts +++ b/packages/storybook/src/builders/build-storybook/build-storybook.impl.spec.ts @@ -37,8 +37,8 @@ describe('Build storybook', () => { srcRoot: join( __dirname, `/../../schematics/configuration/root-files/.storybook/tsconfig.json` - ) - } + ), + }, }, context ).toPromise(); diff --git a/packages/storybook/src/builders/build-storybook/build-storybook.impl.ts b/packages/storybook/src/builders/build-storybook/build-storybook.impl.ts index 483d8d7bffe0c..e0d01262ccbec 100644 --- a/packages/storybook/src/builders/build-storybook/build-storybook.impl.ts +++ b/packages/storybook/src/builders/build-storybook/build-storybook.impl.ts @@ -1,7 +1,7 @@ import { BuilderContext, createBuilder, - BuilderOutput + BuilderOutput, } from '@angular-devkit/architect'; import { JsonObject } from '@angular-devkit/core'; import { Observable, from } from 'rxjs'; @@ -50,15 +50,15 @@ export function run( const frameworkPath = `${options.uiFramework}/dist/server/options`; return from(import(frameworkPath)).pipe( - map(m => m.default), - switchMap(frameworkOptions => + map((m) => m.default), + switchMap((frameworkOptions) => from(storybookOptionMapper(options, frameworkOptions, context)) ), - switchMap(option => { + switchMap((option) => { context.logger.info(`Storybook builder starting ...`); return runInstance(option); }), - map(loaded => { + map((loaded) => { context.logger.info(`Storybook builder finished ...`); context.logger.info(`Storybook files availble in ${options.outputPath}`); const builder: BuilderOutput = { success: true } as BuilderOutput; @@ -88,7 +88,7 @@ async function storybookOptionMapper( ...frameworkOptions, frameworkPresets: [...(frameworkOptions.frameworkPresets || [])], watch: false, - docsMode: builderOptions.docsMode + docsMode: builderOptions.docsMode, }; optionsWithFramework.config; return optionsWithFramework; diff --git a/packages/storybook/src/builders/storybook/storybook.impl.ts b/packages/storybook/src/builders/storybook/storybook.impl.ts index 99b0a77fba575..b2598b4d13a1d 100644 --- a/packages/storybook/src/builders/storybook/storybook.impl.ts +++ b/packages/storybook/src/builders/storybook/storybook.impl.ts @@ -1,7 +1,7 @@ import { BuilderContext, createBuilder, - BuilderOutput + BuilderOutput, } from '@angular-devkit/architect'; import { Observable, from } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; @@ -51,12 +51,12 @@ function run( ): Observable { const frameworkPath = `${options.uiFramework}/dist/server/options`; return from(import(frameworkPath)).pipe( - map(m => m.default), - switchMap(frameworkOptions => + map((m) => m.default), + switchMap((frameworkOptions) => from(storybookOptionMapper(options, frameworkOptions, context)) ), - switchMap(option => runInstance(option)), - map(loaded => { + switchMap((option) => runInstance(option)), + map((loaded) => { const builder: BuilderOutput = { success: true } as BuilderOutput; return builder; }) @@ -64,10 +64,10 @@ function run( } function runInstance(options: StorybookBuilderOptions) { - return new Observable(obs => { + return new Observable((obs) => { buildDevStandalone({ ...options, ci: true }) - .then(sucess => obs.next(sucess)) - .catch(err => obs.error(err)); + .then((sucess) => obs.next(sucess)) + .catch((err) => obs.error(err)); }); } @@ -85,7 +85,7 @@ async function storybookOptionMapper( mode: 'dev', configDir: storybookConfig, ...frameworkOptions, - frameworkPresets: [...(frameworkOptions.frameworkPresets || [])] + frameworkPresets: [...(frameworkOptions.frameworkPresets || [])], }; optionsWithFramework.config; return optionsWithFramework; diff --git a/packages/storybook/src/migrations/update-8-8-2/update-builder-8-8-2.spec.ts b/packages/storybook/src/migrations/update-8-8-2/update-builder-8-8-2.spec.ts index 8fe2ed17ac5e3..614b77a9b40ed 100644 --- a/packages/storybook/src/migrations/update-8-8-2/update-builder-8-8-2.spec.ts +++ b/packages/storybook/src/migrations/update-8-8-2/update-builder-8-8-2.spec.ts @@ -5,7 +5,7 @@ import { readJsonInTree, updateWorkspaceInTree, readWorkspace, - getWorkspacePath + getWorkspacePath, } from '@nrwl/workspace'; import * as path from 'path'; @@ -39,11 +39,11 @@ describe('Update 8-8-2', () => { uiFramework: '@storybook/angular', port: 4400, config: { - configFolder: 'libs/home/ui/.storybook' - } - } - } - } + configFolder: 'libs/home/ui/.storybook', + }, + }, + }, + }, }, ['home-ui-e2e']: { root: 'apps/home-ui-e2e', @@ -56,18 +56,18 @@ describe('Update 8-8-2', () => { tsConfig: 'apps/home-ui-e2e/tsconfig.e2e.json', devServerTarget: 'home-ui:storybook', headless: false, - watch: true + watch: true, }, configurations: { headless: { devServerTarget: 'home-ui:storybook:ci', - headless: true - } - } - } - } - } - } + headless: true, + }, + }, + }, + }, + }, + }, }) ); @@ -93,7 +93,7 @@ describe('Update 8-8-2', () => { JSON.stringify({ extends: '../tsconfig.json', exclude: ['../src/test.ts', '../**/*.spec.ts'], - include: ['../src/**/*'] + include: ['../src/**/*'], }) ); tree.create( @@ -112,11 +112,11 @@ describe('Update 8-8-2', () => { uiFramework: '@storybook/angular', port: 4400, config: { - configFolder: 'libs/home/ui/.storybook' - } - } - } - } + configFolder: 'libs/home/ui/.storybook', + }, + }, + }, + }, }, ['home-ui-e2e']: { root: 'apps/home-ui-e2e', @@ -129,18 +129,18 @@ describe('Update 8-8-2', () => { tsConfig: 'apps/home-ui-e2e/tsconfig.e2e.json', devServerTarget: 'home-ui:storybook', headless: false, - watch: true + watch: true, }, configurations: { headless: { devServerTarget: 'home-ui:storybook:ci', - headless: true - } - } - } - } - } - } + headless: true, + }, + }, + }, + }, + }, + }, }) ); diff --git a/packages/storybook/src/migrations/update-8-8-2/update-builder-8-8-2.ts b/packages/storybook/src/migrations/update-8-8-2/update-builder-8-8-2.ts index 43f7c0a066a21..e36ffd156904c 100644 --- a/packages/storybook/src/migrations/update-8-8-2/update-builder-8-8-2.ts +++ b/packages/storybook/src/migrations/update-8-8-2/update-builder-8-8-2.ts @@ -4,14 +4,14 @@ import { readWorkspaceJson, readWorkspace, updateJsonInTree, - formatFiles + formatFiles, } from '@nrwl/workspace'; export default function update(): Rule { return chain([ - updateWorkspaceInTree(config => { + updateWorkspaceInTree((config) => { const filteredProjects = []; - Object.keys(config.projects).forEach(name => { + Object.keys(config.projects).forEach((name) => { if ( config.projects[name].architect && config.projects[name].architect.e2e && @@ -24,7 +24,7 @@ export default function update(): Rule { filteredProjects.push(config.projects[name]); } }); - filteredProjects.forEach(p => { + filteredProjects.forEach((p) => { delete p.architect.e2e.options.headless; delete p.architect.e2e.options.watch; delete p.architect.e2e.configurations; @@ -34,7 +34,7 @@ export default function update(): Rule { (tree, context) => { const workspace = readWorkspace(tree); const tsconfigUpdateRules = []; - Object.keys(workspace.projects).forEach(name => { + Object.keys(workspace.projects).forEach((name) => { if ( workspace.projects[name].architect && workspace.projects[name].architect.storybook && @@ -47,17 +47,20 @@ export default function update(): Rule { workspace.projects[name].architect.storybook.options.config .configFolder; tsconfigUpdateRules.push( - updateJsonInTree(`${storybookFolderPath}/tsconfig.json`, json => ({ - ...json, - compilerOptions: { - emitDecoratorMetadata: true - } - })) + updateJsonInTree( + `${storybookFolderPath}/tsconfig.json`, + (json) => ({ + ...json, + compilerOptions: { + emitDecoratorMetadata: true, + }, + }) + ) ); } }); return chain(tsconfigUpdateRules); }, - formatFiles() + formatFiles(), ]); } diff --git a/packages/storybook/src/migrations/update-9-0-0/update-9-0-0.ts b/packages/storybook/src/migrations/update-9-0-0/update-9-0-0.ts index c90ee45a19e57..89beb2d13d301 100644 --- a/packages/storybook/src/migrations/update-9-0-0/update-9-0-0.ts +++ b/packages/storybook/src/migrations/update-9-0-0/update-9-0-0.ts @@ -7,6 +7,6 @@ const updatePackages = updatePackagesInPackageJson( '9.0.0' ); -export default function() { +export default function () { return chain([updatePackages, formatFiles()]); } diff --git a/packages/storybook/src/migrations/update-9-2-0/update-9-2-0.ts b/packages/storybook/src/migrations/update-9-2-0/update-9-2-0.ts index 062520fbceaa0..240e7be70556e 100644 --- a/packages/storybook/src/migrations/update-9-2-0/update-9-2-0.ts +++ b/packages/storybook/src/migrations/update-9-2-0/update-9-2-0.ts @@ -2,6 +2,6 @@ import { chain } from '@angular-devkit/schematics'; import { addCacheableOperation } from '../../schematics/init/init'; import { formatFiles } from '@nrwl/workspace'; -export default function() { +export default function () { return chain([addCacheableOperation, formatFiles()]); } diff --git a/packages/storybook/src/schematics/configuration/configuration.spec.ts b/packages/storybook/src/schematics/configuration/configuration.spec.ts index 1e49f1b3173ca..84750e1d747bd 100644 --- a/packages/storybook/src/schematics/configuration/configuration.spec.ts +++ b/packages/storybook/src/schematics/configuration/configuration.spec.ts @@ -2,7 +2,7 @@ import { Tree } from '@angular-devkit/schematics'; import { readJsonInTree, readWorkspaceJson, - getProjectConfig + getProjectConfig, } from '@nrwl/workspace'; import { createTestUILib, runSchematic } from '../../utils/testing'; import { StorybookConfigureSchema } from './schema'; @@ -40,15 +40,15 @@ describe('schematic:configuration', () => { builder: '@nrwl/storybook:storybook', configurations: { ci: { - quiet: true - } + quiet: true, + }, }, options: { port: 4400, config: { - configFolder: 'libs/test-ui-lib/.storybook' - } - } + configFolder: 'libs/test-ui-lib/.storybook', + }, + }, }); }); diff --git a/packages/storybook/src/schematics/configuration/configuration.ts b/packages/storybook/src/schematics/configuration/configuration.ts index 7ddf54427cf73..ace6f3cd7c241 100644 --- a/packages/storybook/src/schematics/configuration/configuration.ts +++ b/packages/storybook/src/schematics/configuration/configuration.ts @@ -8,13 +8,13 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { getProjectConfig, offsetFromRoot, readJsonFile, - updateWorkspace + updateWorkspace, } from '@nrwl/workspace'; import { join, normalize } from '@angular-devkit/core'; import { StorybookStoriesSchema } from '../../../../angular/src/schematics/stories/stories'; @@ -23,7 +23,7 @@ import { CypressConfigureSchema } from '../cypress-project/cypress-project'; import { StorybookConfigureSchema } from './schema'; import { toJS } from '@nrwl/workspace/src/utils/rules/to-js'; -export default function(schema: StorybookConfigureSchema): Rule { +export default function (schema: StorybookConfigureSchema): Rule { return chain([ schematic('ng-add', {}), createRootStorybookDir(schema.name, schema.js), @@ -34,9 +34,9 @@ export default function(schema: StorybookConfigureSchema): Rule { ? schematic('cypress-project', { name: schema.name, js: schema.js, - linter: schema.linter + linter: schema.linter, }) - : () => {} + : () => {}, ]); } @@ -45,7 +45,7 @@ function createRootStorybookDir(projectName: string, js: boolean): Rule { context.logger.debug('adding .storybook folder to lib'); return chain([ - applyWithSkipExisting(url('./root-files'), [js ? toJS() : noop()]) + applyWithSkipExisting(url('./root-files'), [js ? toJS() : noop()]), ])(tree, context); }; } @@ -63,11 +63,11 @@ function createLibStorybookDir( template({ tmpl: '', uiFramework, - offsetFromRoot: offsetFromRoot(projectConfig.root) + offsetFromRoot: offsetFromRoot(projectConfig.root), }), move(projectConfig.root), - js ? toJS() : noop() - ]) + js ? toJS() : noop(), + ]), ])(tree, context); }; } @@ -89,7 +89,7 @@ function configureTsConfig(projectName: string): Rule { tsConfigContent.exclude = [ ...tsConfigContent.exclude, '**/*.stories.ts', - '**/*.stories.js' + '**/*.stories.js', ]; tree.overwrite( @@ -101,7 +101,7 @@ function configureTsConfig(projectName: string): Rule { } function addStorybookTask(projectName: string, uiFramework: string): Rule { - return updateWorkspace(workspace => { + return updateWorkspace((workspace) => { const projectConfig = workspace.projects.get(projectName); projectConfig.targets.set('storybook', { builder: '@nrwl/storybook:storybook', @@ -109,14 +109,14 @@ function addStorybookTask(projectName: string, uiFramework: string): Rule { uiFramework, port: 4400, config: { - configFolder: `${projectConfig.root}/.storybook` - } + configFolder: `${projectConfig.root}/.storybook`, + }, }, configurations: { ci: { - quiet: true - } - } + quiet: true, + }, + }, }); projectConfig.targets.set('build-storybook', { builder: '@nrwl/storybook:build', @@ -128,14 +128,14 @@ function addStorybookTask(projectName: string, uiFramework: string): Rule { projectName ), config: { - configFolder: `${projectConfig.root}/.storybook` - } + configFolder: `${projectConfig.root}/.storybook`, + }, }, configurations: { ci: { - quiet: true - } - } + quiet: true, + }, + }, }); }); } diff --git a/packages/storybook/src/schematics/cypress-project/cypress-project.spec.ts b/packages/storybook/src/schematics/cypress-project/cypress-project.spec.ts index 10a0d816f258e..7a0a4e5f8f2bb 100644 --- a/packages/storybook/src/schematics/cypress-project/cypress-project.spec.ts +++ b/packages/storybook/src/schematics/cypress-project/cypress-project.spec.ts @@ -38,7 +38,7 @@ describe('schematic:cypress-project', () => { expect(project.architect.e2e.options.headless).toBeUndefined(); expect(project.architect.e2e.options.watch).toBeUndefined(); expect(project.architect.e2e.configurations).toEqual({ - ci: { devServerTarget: `test-ui-lib:storybook:ci` } + ci: { devServerTarget: `test-ui-lib:storybook:ci` }, }); }); }); diff --git a/packages/storybook/src/schematics/cypress-project/cypress-project.ts b/packages/storybook/src/schematics/cypress-project/cypress-project.ts index b31e8b1eff882..8114a4e2adc21 100644 --- a/packages/storybook/src/schematics/cypress-project/cypress-project.ts +++ b/packages/storybook/src/schematics/cypress-project/cypress-project.ts @@ -3,7 +3,7 @@ import { externalSchematic, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { getProjectConfig, updateWorkspaceInTree } from '@nrwl/workspace'; import { parseJsonAtPath, safeFileDelete } from '../../utils/utils'; @@ -15,18 +15,18 @@ export interface CypressConfigureSchema { linter: Linter; } -export default function(schema: CypressConfigureSchema): Rule { +export default function (schema: CypressConfigureSchema): Rule { const e2eProjectName = schema.name + '-e2e'; return chain([ externalSchematic('@nrwl/cypress', 'cypress-project', { name: e2eProjectName, project: schema.name, js: schema.js, - linter: schema.linter + linter: schema.linter, }), removeUnneededFiles(e2eProjectName, schema.js), addBaseUrlToCypressConfig(e2eProjectName), - updateAngularJsonBuilder(e2eProjectName, schema.name) + updateAngularJsonBuilder(e2eProjectName, schema.name), ]); } @@ -74,20 +74,20 @@ function updateAngularJsonBuilder( e2eProjectName: string, targetProjectName ): Rule { - return updateWorkspaceInTree(workspace => { + return updateWorkspaceInTree((workspace) => { const project = workspace.projects[e2eProjectName]; const e2eTarget = project.architect['e2e']; project.architect['e2e'] = { ...e2eTarget, options: { ...e2eTarget.options, - devServerTarget: `${targetProjectName}:storybook` + devServerTarget: `${targetProjectName}:storybook`, }, configurations: { ci: { - devServerTarget: `${targetProjectName}:storybook:ci` - } - } + devServerTarget: `${targetProjectName}:storybook:ci`, + }, + }, }; return workspace; }); diff --git a/packages/storybook/src/schematics/init/init.ts b/packages/storybook/src/schematics/init/init.ts index 0785a7a09952b..b2468abc0d7ae 100644 --- a/packages/storybook/src/schematics/init/init.ts +++ b/packages/storybook/src/schematics/init/init.ts @@ -2,19 +2,19 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { addDepsToPackageJson, readJsonInTree, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import { babelLoaderVersion, babelCoreVersion, storybookVersion, nxVersion, - babelPresetTypescriptVersion + babelPresetTypescriptVersion, } from '../../utils/versions'; import { Schema } from './schema'; @@ -44,7 +44,7 @@ function checkDependenciesInstalled(): Rule { }; } -export const addCacheableOperation = updateJsonInTree('nx.json', nxJson => { +export const addCacheableOperation = updateJsonInTree('nx.json', (nxJson) => { if ( !nxJson.tasksRunnerOptions || !nxJson.tasksRunnerOptions.default || @@ -73,22 +73,25 @@ export const addCacheableOperation = updateJsonInTree('nx.json', nxJson => { return nxJson; }); -const moveToDevDependencies = updateJsonInTree('package.json', packageJson => { - packageJson.dependencies = packageJson.dependencies || {}; - packageJson.devDependencies = packageJson.devDependencies || {}; +const moveToDevDependencies = updateJsonInTree( + 'package.json', + (packageJson) => { + packageJson.dependencies = packageJson.dependencies || {}; + packageJson.devDependencies = packageJson.devDependencies || {}; - if (packageJson.dependencies['@nrwl/storybook']) { - packageJson.devDependencies['@nrwl/storybook'] = - packageJson.dependencies['@nrwl/storybook']; - delete packageJson.dependencies['@nrwl/storybook']; + if (packageJson.dependencies['@nrwl/storybook']) { + packageJson.devDependencies['@nrwl/storybook'] = + packageJson.dependencies['@nrwl/storybook']; + delete packageJson.dependencies['@nrwl/storybook']; + } + return packageJson; } - return packageJson; -}); +); -export default function(schema: Schema) { +export default function (schema: Schema) { return chain([ checkDependenciesInstalled(), moveToDevDependencies, - addCacheableOperation + addCacheableOperation, ]); } diff --git a/packages/storybook/src/utils/testing.ts b/packages/storybook/src/utils/testing.ts index cace457095ebe..d00d968e27db0 100644 --- a/packages/storybook/src/utils/testing.ts +++ b/packages/storybook/src/utils/testing.ts @@ -10,7 +10,7 @@ import { TestingArchitectHost } from '@angular-devkit/architect/testing'; import { createEmptyWorkspace, - MockBuilderContext + MockBuilderContext, } from '@nrwl/workspace/testing'; const testRunner = new SchematicTestRunner( @@ -46,14 +46,14 @@ export async function createTestUILib(libName: string): Promise { appTree = createEmptyWorkspace(appTree); appTree = await callRule( externalSchematic('@nrwl/angular', 'library', { - name: libName + name: libName, }), appTree ); appTree = await callRule( externalSchematic('@nrwl/angular', 'component', { name: 'test-button', - project: libName + project: libName, }), appTree ); @@ -92,7 +92,7 @@ export class TestButtonComponent implements OnInit { appTree = await callRule( externalSchematic('@nrwl/angular', 'component', { name: 'test-other', - project: libName + project: libName, }), appTree ); diff --git a/packages/storybook/src/utils/utils.ts b/packages/storybook/src/utils/utils.ts index d0759afe4fc53..d7a7805b50dbd 100644 --- a/packages/storybook/src/utils/utils.ts +++ b/packages/storybook/src/utils/utils.ts @@ -4,7 +4,7 @@ import { Path, JsonAstObject, parseJsonAst, - JsonValue + JsonValue, } from '@angular-devkit/core'; import { @@ -15,7 +15,7 @@ import { Rule, mergeWith, apply, - forEach + forEach, } from '@angular-devkit/schematics'; import { get } from 'http'; @@ -30,10 +30,10 @@ export const Constants = { addonDependencies: ['@storybook/addons'], tsConfigExclusions: ['stories', '**/*.stories.ts'], pkgJsonScripts: { - storybook: 'start-storybook -p 9001 -c .storybook' + storybook: 'start-storybook -p 9001 -c .storybook', }, jsonIndentLevel: 2, - coreAddonPrefix: '@storybook/addon-' + coreAddonPrefix: '@storybook/addon-', }; export function safeFileDelete(tree: Tree, path: string): boolean { @@ -55,10 +55,10 @@ export function getLatestNodeVersion( ): Promise { const DEFAULT_VERSION = 'latest'; - return new Promise(resolve => { - return get(`http://registry.npmjs.org/${packageName}`, res => { + return new Promise((resolve) => { + return get(`http://registry.npmjs.org/${packageName}`, (res) => { let rawData = ''; - res.on('data', chunk => (rawData += chunk)); + res.on('data', (chunk) => (rawData += chunk)); res.on('end', () => { try { const response = JSON.parse(rawData); @@ -128,13 +128,13 @@ export function applyWithOverwrite(source: Source, rules: Rule[]): Rule { const rule = mergeWith( apply(source, [ ...rules, - forEach(fileEntry => { + forEach((fileEntry) => { if (tree.exists(fileEntry.path)) { tree.overwrite(fileEntry.path, fileEntry.content); return null; } return fileEntry; - }) + }), ]) ); @@ -147,12 +147,12 @@ export function applyWithSkipExisting(source: Source, rules: Rule[]): Rule { const rule = mergeWith( apply(source, [ ...rules, - forEach(fileEntry => { + forEach((fileEntry) => { if (tree.exists(fileEntry.path)) { return null; } return fileEntry; - }) + }), ]) ); diff --git a/packages/tao/index.ts b/packages/tao/index.ts index 456b850684519..dce253b7edcb1 100644 --- a/packages/tao/index.ts +++ b/packages/tao/index.ts @@ -59,7 +59,7 @@ export async function invokeCommand( root, [ `${projectName}:${command}`, - ...(projectNameIncluded ? commandArgs.slice(1) : commandArgs) + ...(projectNameIncluded ? commandArgs.slice(1) : commandArgs), ], isVerbose ); diff --git a/packages/tao/src/commands/generate.ts b/packages/tao/src/commands/generate.ts index dcdee51e10eaf..3dd06c89eb879 100644 --- a/packages/tao/src/commands/generate.ts +++ b/packages/tao/src/commands/generate.ts @@ -6,18 +6,18 @@ import { schema, tags, terminal, - virtualFs + virtualFs, } from '@angular-devkit/core'; import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { DryRunEvent, formats, HostTree, - Schematic + Schematic, } from '@angular-devkit/schematics'; import { NodeWorkflow, - validateOptionsWithSchema + validateOptionsWithSchema, } from '@angular-devkit/schematics/tools'; import * as fs from 'fs'; import * as inquirer from 'inquirer'; @@ -27,7 +27,7 @@ import { convertToCamelCase, handleErrors, Schema, - validateOptions + validateOptions, } from '../shared/params'; import { commandName, printHelp } from '../shared/print-help'; import minimist = require('minimist'); @@ -60,13 +60,13 @@ function parseGenerateOpts( boolean: ['help', 'dryRun', 'debug', 'force', 'interactive'], alias: { dryRun: 'dry-run', - d: 'dryRun' + d: 'dryRun', }, default: { debug: false, dryRun: false, - interactive: true - } + interactive: true, + }, }) ); @@ -99,7 +99,7 @@ function parseGenerateOpts( dryRun: schematicOptions.dryRun, force: schematicOptions.force, interactive: schematicOptions.interactive, - defaults: schematicOptions.defaults + defaults: schematicOptions.defaults, }; delete schematicOptions.debug; @@ -159,7 +159,7 @@ async function createWorkflow( dryRun: opts.dryRun, packageManager: await detectPackageManager(fsHost), root: normalize(root), - registry: new schema.CoreSchemaRegistry(formats.standardFormats) + registry: new schema.CoreSchemaRegistry(formats.standardFormats), }); const _params = opts.schematicOptions._; delete opts.schematicOptions._; @@ -184,11 +184,11 @@ async function createWorkflow( if (opts.interactive !== false && isTTY()) { workflow.registry.usePromptProvider( (definitions: Array) => { - const questions: inquirer.Questions = definitions.map(definition => { + const questions: inquirer.Questions = definitions.map((definition) => { const question = { name: definition.id, message: definition.message, - default: definition.default as any + default: definition.default as any, } as any; const validator = definition.validator; @@ -204,13 +204,13 @@ async function createWorkflow( question.type = !!definition.multiselect ? 'checkbox' : 'list'; question.choices = definition.items && - definition.items.map(item => { + definition.items.map((item) => { if (typeof item == 'string') { return item; } else { return { name: item.label, - value: item.value + value: item.value, }; } }); @@ -249,9 +249,9 @@ function printGenHelp( dryRun: { type: 'boolean', default: false, - description: `Runs through and reports activity without writing to disk.` - } - } + description: `Runs through and reports activity without writing to disk.`, + }, + }, }, logger ); @@ -322,7 +322,7 @@ async function runSchematic( ); if (schematicOptions['--'] && !allowAdditionalArgs) { - schematicOptions['--'].forEach(unmatched => { + schematicOptions['--'].forEach((unmatched) => { const message = `Could not match option '${unmatched.name}' to the ${opts.collectionName}:${opts.schematicName} schema.` + (unmatched.possible.length > 0 @@ -340,12 +340,12 @@ async function runSchematic( schematic: opts.schematicName, options: { ...defaults, ...schematicOptions }, debug: opts.debug, - logger + logger, }) .toPromise(); if (!record.error) { - record.loggingQueue.forEach(log => logger.info(log)); + record.loggingQueue.forEach((log) => logger.info(log)); } if (opts.dryRun) { diff --git a/packages/tao/src/commands/migrate.spec.ts b/packages/tao/src/commands/migrate.spec.ts index 25aec8d65e9a2..e451cdf8a3983 100644 --- a/packages/tao/src/commands/migrate.spec.ts +++ b/packages/tao/src/commands/migrate.spec.ts @@ -9,7 +9,7 @@ describe('Migration', () => { throw new Error('cannot fetch'); }, from: {}, - to: {} + to: {}, }); try { @@ -25,14 +25,14 @@ describe('Migration', () => { versions: () => '1.0.0', fetch: (p, v) => Promise.resolve({ version: '2.0.0' }), from: {}, - to: {} + to: {}, }); expect(await migrator.updatePackageJson('mypackage', '2.0.0')).toEqual({ migrations: [], packageJson: { - mypackage: { version: '2.0.0', alwaysAddToPackageJson: false } - } + mypackage: { version: '2.0.0', alwaysAddToPackageJson: false }, + }, }); }); @@ -48,11 +48,14 @@ describe('Migration', () => { version: '2.0.0', packages: { child: { version: '2.0.0' }, - newChild: { version: '3.0.0', alwaysAddToPackageJson: true } - } - } + newChild: { + version: '3.0.0', + alwaysAddToPackageJson: true, + }, + }, + }, }, - schematics: {} + schematics: {}, }); } else if (p === 'child') { return Promise.resolve({ version: '2.0.0' }); @@ -63,7 +66,7 @@ describe('Migration', () => { } }, from: {}, - to: {} + to: {}, }); expect(await migrator.updatePackageJson('parent', '2.0.0')).toEqual({ @@ -71,8 +74,8 @@ describe('Migration', () => { packageJson: { parent: { version: '2.0.0', alwaysAddToPackageJson: false }, child: { version: '2.0.0', alwaysAddToPackageJson: false }, - newChild: { version: '2.0.0', alwaysAddToPackageJson: true } - } + newChild: { version: '2.0.0', alwaysAddToPackageJson: true }, + }, }); }); @@ -87,11 +90,11 @@ describe('Migration', () => { version2: { version: '2.0.0', packages: { - child: { version: '2.0.0' } - } - } + child: { version: '2.0.0' }, + }, + }, }, - schematics: {} + schematics: {}, }); } else if (p === 'child') { return Promise.resolve({ @@ -100,26 +103,26 @@ describe('Migration', () => { version2: { version: '2.0.0', packages: { - parent: { version: '2.0.0' } - } - } + parent: { version: '2.0.0' }, + }, + }, }, - schematics: {} + schematics: {}, }); } else { return Promise.resolve(null); } }, from: {}, - to: {} + to: {}, }); expect(await migrator.updatePackageJson('parent', '2.0.0')).toEqual({ migrations: [], packageJson: { parent: { version: '2.0.0', alwaysAddToPackageJson: false }, - child: { version: '2.0.0', alwaysAddToPackageJson: false } - } + child: { version: '2.0.0', alwaysAddToPackageJson: false }, + }, }); }); @@ -135,11 +138,11 @@ describe('Migration', () => { version: '2.0.0', packages: { child1: { version: '2.0.0' }, - child2: { version: '2.0.0' } - } - } + child2: { version: '2.0.0' }, + }, + }, }, - schematics: {} + schematics: {}, }); } else if (p === 'child1') { return Promise.resolve({ @@ -148,11 +151,11 @@ describe('Migration', () => { version2: { version: '2.0.0', packages: { - grandchild: { version: '3.0.0' } - } - } + grandchild: { version: '3.0.0' }, + }, + }, }, - schematics: {} + schematics: {}, }); } else if (p === 'child2') { return Promise.resolve({ @@ -161,18 +164,18 @@ describe('Migration', () => { version2: { version: '2.0.0', packages: { - grandchild: { version: '4.0.0' } - } - } + grandchild: { version: '4.0.0' }, + }, + }, }, - schematics: {} + schematics: {}, }); } else { return Promise.resolve({ version: '4.0.0' }); } }, from: {}, - to: {} + to: {}, }); expect(await migrator.updatePackageJson('parent', '2.0.0')).toEqual({ @@ -181,8 +184,8 @@ describe('Migration', () => { parent: { version: '2.0.0', alwaysAddToPackageJson: false }, child1: { version: '2.0.0', alwaysAddToPackageJson: false }, child2: { version: '2.0.0', alwaysAddToPackageJson: false }, - grandchild: { version: '4.0.0', alwaysAddToPackageJson: false } - } + grandchild: { version: '4.0.0', alwaysAddToPackageJson: false }, + }, }); }); @@ -197,11 +200,11 @@ describe('Migration', () => { version2: { version: '2.0.0', packages: { - child: { version: '2.0.0' } - } - } + child: { version: '2.0.0' }, + }, + }, }, - schematics: {} + schematics: {}, }); } else if (p === 'child') { return Promise.resolve({ @@ -210,32 +213,32 @@ describe('Migration', () => { version2: { version: '1.0.0', packages: { - grandchild: { version: '2.0.0' } - } - } + grandchild: { version: '2.0.0' }, + }, + }, }, - schematics: {} + schematics: {}, }); } else { return Promise.resolve({ version: '2.0.0' }); } }, from: {}, - to: {} + to: {}, }); expect(await migrator.updatePackageJson('parent', '2.0.0')).toEqual({ migrations: [], packageJson: { parent: { version: '2.0.0', alwaysAddToPackageJson: false }, - child: { version: '2.0.0', alwaysAddToPackageJson: false } - } + child: { version: '2.0.0', alwaysAddToPackageJson: false }, + }, }); }); it('should conditionally process packages if they are installed', async () => { const migrator = new Migrator({ - versions: p => (p !== 'not-installed' ? '1.0.0' : null), + versions: (p) => (p !== 'not-installed' ? '1.0.0' : null), fetch: (p, v) => { if (p === 'parent') { return Promise.resolve({ @@ -247,12 +250,12 @@ describe('Migration', () => { child1: { version: '2.0.0', ifPackageInstalled: 'other' }, child2: { version: '2.0.0', - ifPackageInstalled: 'not-installed' - } - } - } + ifPackageInstalled: 'not-installed', + }, + }, + }, }, - schematics: {} + schematics: {}, }); } else if (p === 'child1') { return Promise.resolve({ version: '2.0.0' }); @@ -263,15 +266,15 @@ describe('Migration', () => { } }, from: {}, - to: {} + to: {}, }); expect(await migrator.updatePackageJson('parent', '2.0.0')).toEqual({ migrations: [], packageJson: { parent: { version: '2.0.0', alwaysAddToPackageJson: false }, - child1: { version: '2.0.0', alwaysAddToPackageJson: false } - } + child1: { version: '2.0.0', alwaysAddToPackageJson: false }, + }, }); }); @@ -282,7 +285,7 @@ describe('Migration', () => { versions: () => '1.0.0', fetch: (p, v) => Promise.resolve({ version: '2.0.0' }), from: {}, - to: {} + to: {}, }); expect( @@ -292,13 +295,13 @@ describe('Migration', () => { packageJson: { '@nrwl/workspace': { version: '2.0.0', - alwaysAddToPackageJson: false + alwaysAddToPackageJson: false, }, '@nrwl/angular': { version: '2.0.0', alwaysAddToPackageJson: false }, '@nrwl/cypress': { version: '2.0.0', alwaysAddToPackageJson: false }, '@nrwl/eslint-plugin-nx': { version: '2.0.0', - alwaysAddToPackageJson: false + alwaysAddToPackageJson: false, }, '@nrwl/express': { version: '2.0.0', alwaysAddToPackageJson: false }, '@nrwl/jest': { version: '2.0.0', alwaysAddToPackageJson: false }, @@ -308,47 +311,47 @@ describe('Migration', () => { '@nrwl/node': { version: '2.0.0', alwaysAddToPackageJson: false }, '@nrwl/nx-plugin': { version: '2.0.0', - alwaysAddToPackageJson: false + alwaysAddToPackageJson: false, }, '@nrwl/react': { version: '2.0.0', alwaysAddToPackageJson: false }, '@nrwl/storybook': { version: '2.0.0', - alwaysAddToPackageJson: false + alwaysAddToPackageJson: false, }, '@nrwl/tao': { version: '2.0.0', alwaysAddToPackageJson: false }, - '@nrwl/web': { version: '2.0.0', alwaysAddToPackageJson: false } - } + '@nrwl/web': { version: '2.0.0', alwaysAddToPackageJson: false }, + }, }); }); it('should not throw when packages are missing', async () => { const migrator = new Migrator({ - versions: p => (p === '@nrwl/nest' ? null : '1.0.0'), + versions: (p) => (p === '@nrwl/nest' ? null : '1.0.0'), fetch: (p, v) => Promise.resolve({ version: '2.0.0', - packageJsonUpdates: { one: { version: '2.0.0', packages: {} } } + packageJsonUpdates: { one: { version: '2.0.0', packages: {} } }, }), from: {}, - to: {} + to: {}, }); await migrator.updatePackageJson('@nrwl/workspace', '2.0.0'); }); it('should only fetch packages that are installed', async () => { const migrator = new Migrator({ - versions: p => (p === '@nrwl/nest' ? null : '1.0.0'), + versions: (p) => (p === '@nrwl/nest' ? null : '1.0.0'), fetch: (p, v) => { if (p === '@nrwl/nest') { throw new Error('Boom'); } return Promise.resolve({ version: '2.0.0', - packageJsonUpdates: { one: { version: '2.0.0', packages: {} } } + packageJsonUpdates: { one: { version: '2.0.0', packages: {} } }, }); }, from: {}, - to: {} + to: {}, }); await migrator.updatePackageJson('@nrwl/workspace', '2.0.0'); }); @@ -357,7 +360,7 @@ describe('Migration', () => { describe('migrations', () => { it('should create a list of migrations to run', async () => { const migrator = new Migrator({ - versions: p => { + versions: (p) => { if (p === 'parent') return '1.0.0'; if (p === 'child') return '1.0.0'; return null; @@ -372,17 +375,17 @@ describe('Migration', () => { packages: { child: { version: '2.0.0' }, newChild: { - version: '3.0.0' - } - } - } + version: '3.0.0', + }, + }, + }, }, schematics: { version2: { version: '2.0.0', - factory: 'parent-factory' - } - } + factory: 'parent-factory', + }, + }, }); } else if (p === 'child') { return Promise.resolve({ @@ -390,9 +393,9 @@ describe('Migration', () => { schematics: { version2: { version: '2.0.0', - factory: 'child-factory' - } - } + factory: 'child-factory', + }, + }, }); } else if (p === 'newChild') { return Promise.resolve({ @@ -400,16 +403,16 @@ describe('Migration', () => { schematics: { version2: { version: '2.0.0', - factory: 'new-child-factory' - } - } + factory: 'new-child-factory', + }, + }, }); } else { return Promise.resolve(null); } }, from: {}, - to: {} + to: {}, }); expect(await migrator.updatePackageJson('parent', '2.0.0')).toEqual({ migrations: [ @@ -417,20 +420,20 @@ describe('Migration', () => { package: 'parent', version: '2.0.0', name: 'version2', - factory: 'parent-factory' + factory: 'parent-factory', }, { package: 'child', version: '2.0.0', name: 'version2', - factory: 'child-factory' - } + factory: 'child-factory', + }, ], packageJson: { parent: { version: '2.0.0', alwaysAddToPackageJson: false }, child: { version: '2.0.0', alwaysAddToPackageJson: false }, - newChild: { version: '3.0.0', alwaysAddToPackageJson: false } - } + newChild: { version: '3.0.0', alwaysAddToPackageJson: false }, + }, }); }); }); @@ -461,7 +464,7 @@ describe('Migration', () => { '--from', '@myscope/a@12.3,@myscope/b@1.1.1', '--to', - '@myscope/c@12.3.1' + '@myscope/c@12.3.1', ]); expect(r).toEqual({ type: 'generateMigrations', @@ -469,42 +472,42 @@ describe('Migration', () => { targetVersion: '8.12.0', from: { '@myscope/a': '12.3.0', - '@myscope/b': '1.1.1' + '@myscope/b': '1.1.1', }, to: { - '@myscope/c': '12.3.1' - } + '@myscope/c': '12.3.1', + }, }); }); it('should handle different variations of the target package', () => { expect(parseMigrationsOptions(['8.12'])).toMatchObject({ targetPackage: '@nrwl/workspace', - targetVersion: '8.12.0' + targetVersion: '8.12.0', }); expect(parseMigrationsOptions(['8'])).toMatchObject({ targetPackage: '@nrwl/workspace', - targetVersion: '8.0.0' + targetVersion: '8.0.0', }); expect(parseMigrationsOptions(['next'])).toMatchObject({ targetPackage: '@nrwl/workspace', - targetVersion: 'next' + targetVersion: 'next', }); expect(parseMigrationsOptions(['@nrwl/workspace@8.12'])).toMatchObject({ targetPackage: '@nrwl/workspace', - targetVersion: '8.12.0' + targetVersion: '8.12.0', }); expect(parseMigrationsOptions(['mypackage@8.12'])).toMatchObject({ targetPackage: 'mypackage', - targetVersion: '8.12.0' + targetVersion: '8.12.0', }); expect(parseMigrationsOptions(['mypackage'])).toMatchObject({ targetPackage: 'mypackage', - targetVersion: 'latest' + targetVersion: 'latest', }); expect(parseMigrationsOptions(['@nrwl/workspace@latest'])).toMatchObject({ targetPackage: '@nrwl/workspace', - targetVersion: 'latest' + targetVersion: 'latest', }); }); diff --git a/packages/tao/src/commands/migrate.ts b/packages/tao/src/commands/migrate.ts index 22d12a212cb50..73d5df7b4aab1 100644 --- a/packages/tao/src/commands/migrate.ts +++ b/packages/tao/src/commands/migrate.ts @@ -64,7 +64,7 @@ export class Migrator { [k: string]: { version: string; alwaysAddToPackageJson: boolean }; }) { const migrations = await Promise.all( - Object.keys(versions).map(async c => { + Object.keys(versions).map(async (c) => { const currentVersion = this.versions(c); if (currentVersion === null) return []; @@ -73,14 +73,14 @@ export class Migrator { if (!migrationsJson.schematics) return []; return Object.keys(migrationsJson.schematics) .filter( - r => + (r) => this.gt(migrationsJson.schematics[r].version, currentVersion) & this.lte(migrationsJson.schematics[r].version, target.version) ) - .map(r => ({ + .map((r) => ({ ...migrationsJson.schematics[r], package: c, - name: r + name: r, })); }) ); @@ -104,8 +104,8 @@ export class Migrator { return { [targetPackage]: { version: target.version, - alwaysAddToPackageJson: !!target.alwaysAddToPackageJson - } + alwaysAddToPackageJson: !!target.alwaysAddToPackageJson, + }, }; } @@ -130,22 +130,22 @@ export class Migrator { const childCalls = await Promise.all( Object.keys(packages) - .filter(r => { + .filter((r) => { return ( !collectedVersions[r] || this.gt(packages[r].version, collectedVersions[r].version) ); }) - .map(u => + .map((u) => this._updatePackageJson(u, packages[u], { ...collectedVersions, - [targetPackage]: target + [targetPackage]: target, }) ) ); return childCalls.reduce( (m, c) => { - Object.keys(c).forEach(r => { + Object.keys(c).forEach((r) => { if (!m[r] || this.gt(c[r].version, m[r].version)) { m[r] = c[r]; } @@ -155,8 +155,8 @@ export class Migrator { { [targetPackage]: { version: migrationsJson.version, - alwaysAddToPackageJson: target.alwaysAddToPackageJson || false - } + alwaysAddToPackageJson: target.alwaysAddToPackageJson || false, + }, } ); } @@ -187,20 +187,20 @@ export class Migrator { '@nrwl/react', '@nrwl/storybook', '@nrwl/tao', - '@nrwl/web' + '@nrwl/web', ].reduce( (m, c) => ({ ...m, - [c]: { version: targetVersion, alwaysAddToPackageJson: false } + [c]: { version: targetVersion, alwaysAddToPackageJson: false }, }), {} - ) + ), }; } if (!m.packageJsonUpdates || !this.versions(packageName)) return {}; return Object.keys(m.packageJsonUpdates) - .filter(r => { + .filter((r) => { return ( this.gt( m.packageJsonUpdates[r].version, @@ -208,13 +208,13 @@ export class Migrator { ) && this.lte(m.packageJsonUpdates[r].version, targetVersion) ); }) - .map(r => m.packageJsonUpdates[r].packages) - .map(packages => { + .map((r) => m.packageJsonUpdates[r].packages) + .map((packages) => { if (!packages) return {}; return Object.keys(packages) .filter( - p => + (p) => !packages[p].ifPackageInstalled || this.versions(packages[p].ifPackageInstalled) ) @@ -223,8 +223,8 @@ export class Migrator { ...m, [c]: { version: packages[c].version, - alwaysAddToPackageJson: packages[c].alwaysAddToPackageJson - } + alwaysAddToPackageJson: packages[c].alwaysAddToPackageJson, + }, }), {} ); @@ -295,8 +295,8 @@ export function parseMigrationsOptions( minimist(args, { string: ['runMigrations', 'from', 'to'], alias: { - runMigrations: 'run-migrations' - } + runMigrations: 'run-migrations', + }, }) ); if (!options.runMigrations) { @@ -310,7 +310,7 @@ export function parseMigrationsOptions( targetPackage, targetVersion, from, - to + to, }; } else { return { type: 'runMigrations', runMigrations: options.runMigrations }; @@ -345,12 +345,12 @@ function parseTargetPackageAndVersion(args: string) { if (args.match(/[0-9]/) || args === 'latest' || args === 'next') { return { targetPackage: '@nrwl/workspace', - targetVersion: normalizeVersionWithTagCheck(args) + targetVersion: normalizeVersionWithTagCheck(args), }; } else { return { targetPackage: args, - targetVersion: 'latest' + targetVersion: 'latest', }; } } @@ -358,7 +358,7 @@ function parseTargetPackageAndVersion(args: string) { function versionOverrides(overrides: string, param: string) { const res = {}; - overrides.split(',').forEach(p => { + overrides.split(',').forEach((p) => { const split = p.lastIndexOf('@'); if (split === -1 || split === 0) { throw new Error( @@ -404,7 +404,7 @@ function createFetcher(logger: logging.Logger) { const dir = dirSync().name; logger.info(`Fetching ${packageName}@${packageVersion}`); execSync(`npm install ${packageName}@${packageVersion} --prefix=${dir}`, { - stdio: [] + stdio: [], }); const json = JSON.parse( stripJsonComments( @@ -435,11 +435,11 @@ function createFetcher(logger: logging.Logger) { cache[`${packageName}-${packageVersion}`] = { version: resolvedVersion, schematics: json.schematics, - packageJsonUpdates: json.packageJsonUpdates + packageJsonUpdates: json.packageJsonUpdates, }; } else { cache[`${packageName}-${packageVersion}`] = { - version: resolvedVersion + version: resolvedVersion, }; } } catch (e) { @@ -447,7 +447,7 @@ function createFetcher(logger: logging.Logger) { `Could not find '${migrationsFile}' in '${packageName}'. Skipping it` ); cache[`${packageName}-${packageVersion}`] = { - version: resolvedVersion + version: resolvedVersion, }; } } @@ -474,7 +474,7 @@ function updatePackageJson( const json = JSON.parse( stripJsonComments(readFileSync(packageJsonPath).toString()) ); - Object.keys(updatedPackages).forEach(p => { + Object.keys(updatedPackages).forEach((p) => { if (json.devDependencies && json.devDependencies[p]) { json.devDependencies[p] = updatedPackages[p].version; } else if (json.dependencies && json.dependencies[p]) { @@ -504,7 +504,7 @@ async function generateMigrationsJsonAndUpdatePackageJson( versions: versions(root, opts.from), fetch: createFetcher(logger), from: opts.from, - to: opts.to + to: opts.to, }); const { migrations, packageJson } = await migrator.updatePackageJson( opts.targetPackage, @@ -568,7 +568,7 @@ class MigrationEngineHost extends NodeModulesEngineHost { name: NodePackageName, create: () => Promise.resolve(() => { - return new Promise(res => { + return new Promise((res) => { if (!this.nodeInstallLogPrinted) { logger.warn( `An installation of node_modules has been required. Make sure to run it after the migration` @@ -578,7 +578,7 @@ class MigrationEngineHost extends NodeModulesEngineHost { res(); }); - }) + }), }); this.registerTaskExecutor(BuiltinTaskExecutor.RunSchematic); @@ -627,7 +627,7 @@ class MigrationsWorkflow extends BaseWorkflow { host, engineHost: new MigrationEngineHost(logger), force: true, - dryRun: false + dryRun: false, }); } } @@ -644,7 +644,7 @@ async function runMigrations( const host = new virtualFs.ScopedHost(new NodeJsSyncHost(), normalize(root)); const workflow = new MigrationsWorkflow(host, logger); let p = Promise.resolve(null); - migrationsFile.migrations.forEach(m => { + migrationsFile.migrations.forEach((m) => { p = p.then(() => { logger.info(`Running migration ${m.package}:${m.name}`); return workflow @@ -653,7 +653,7 @@ async function runMigrations( schematic: m.name, options: {}, debug: false, - logger + logger, }) .toPromise() .then(() => { diff --git a/packages/tao/src/commands/run.ts b/packages/tao/src/commands/run.ts index 800f8f2d5ec31..d161c4b65a353 100644 --- a/packages/tao/src/commands/run.ts +++ b/packages/tao/src/commands/run.ts @@ -7,7 +7,7 @@ import { normalize, schema, terminal, - workspaces + workspaces, } from '@angular-devkit/core'; import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { getLogger } from '../shared/logger'; @@ -15,7 +15,7 @@ import { coerceTypes, convertToCamelCase, handleErrors, - Schema + Schema, } from '../shared/params'; import { commandName, printHelp } from '../shared/print-help'; import minimist = require('minimist'); @@ -43,7 +43,7 @@ function parseRunOpts( const runOptions = convertToCamelCase( minimist(args, { boolean: ['help', 'prod'], - string: ['configuration', 'project'] + string: ['configuration', 'project'], }) ); const help = runOptions.help; @@ -164,7 +164,7 @@ export async function run(root: string, args: string[], isVerbose: boolean) { const builderConf = await architectHost.getBuilderNameForTarget({ project: opts.project, - target: opts.target + target: opts.target, }); const builderDesc = await architectHost.resolveBuilder(builderConf); const flattenedSchema = await registry @@ -181,7 +181,7 @@ export async function run(root: string, args: string[], isVerbose: boolean) { { project: opts.project, target: opts.target, - configuration: opts.configuration + configuration: opts.configuration, }, runOptions, { logger } diff --git a/packages/tao/src/compat/compat.ts b/packages/tao/src/compat/compat.ts index 8dd138c6f9a0b..38d1466d9ac3d 100644 --- a/packages/tao/src/compat/compat.ts +++ b/packages/tao/src/compat/compat.ts @@ -1,18 +1,18 @@ const Module = require('module'); const originalRequire = Module.prototype.require; -Module.prototype.require = function() { +Module.prototype.require = function () { const result = originalRequire.apply(this, arguments); if (arguments[0].startsWith('@angular-devkit/core')) { const Workspace = originalRequire.apply(this, [ - `@angular-devkit/core/src/experimental/workspace` + `@angular-devkit/core/src/experimental/workspace`, ]).Workspace; Workspace._workspaceFileNames = [ 'workspace.json', - ...Workspace._workspaceFileNames + ...Workspace._workspaceFileNames, ]; const core = originalRequire.apply(this, [ - `@angular-devkit/core/src/workspace/core` + `@angular-devkit/core/src/workspace/core`, ]); core._test_addWorkspaceFile('workspace.json', core.WorkspaceFormat.JSON); } diff --git a/packages/tao/src/shared/detect-package-manager.ts b/packages/tao/src/shared/detect-package-manager.ts index 2ee76eeaab98d..17c086af0ed5f 100644 --- a/packages/tao/src/shared/detect-package-manager.ts +++ b/packages/tao/src/shared/detect-package-manager.ts @@ -50,7 +50,7 @@ function fileExists( function isPackageManagerInstalled(packageManager: string) { try { execSync(`${packageManager} --version`, { - stdio: ['ignore', 'ignore', 'ignore'] + stdio: ['ignore', 'ignore', 'ignore'], }); return true; } catch (e) { diff --git a/packages/tao/src/shared/logger.ts b/packages/tao/src/shared/logger.ts index 0d402dfff0195..ec935f6a6df27 100644 --- a/packages/tao/src/shared/logger.ts +++ b/packages/tao/src/shared/logger.ts @@ -11,22 +11,22 @@ let logger: logging.Logger; export const getLogger = (isVerbose: boolean = false): logging.Logger => { if (!logger) { logger = createConsoleLogger(isVerbose, process.stdout, process.stderr, { - warn: s => terminal.bold(terminal.yellow(s)), - error: s => { + warn: (s) => terminal.bold(terminal.yellow(s)), + error: (s) => { if (s.startsWith('NX ')) { return `\n${NX_ERROR} ${terminal.bold(terminal.red(s.substr(3)))}\n`; } return terminal.bold(terminal.red(s)); }, - fatal: s => terminal.bold(terminal.red(s)), - info: s => { + fatal: (s) => terminal.bold(terminal.red(s)), + info: (s) => { if (s.startsWith('NX ')) { return `\n${NX_PREFIX} ${terminal.bold(s.substr(3))}\n`; } return terminal.white(s); - } + }, }); } diff --git a/packages/tao/src/shared/params.spec.ts b/packages/tao/src/shared/params.spec.ts index fa88b8abff7bc..f42cf58267d02 100644 --- a/packages/tao/src/shared/params.spec.ts +++ b/packages/tao/src/shared/params.spec.ts @@ -5,30 +5,30 @@ describe('params', () => { it('should convert dash case to camel case', () => { expect( convertToCamelCase({ - 'one-two': 1 + 'one-two': 1, }) ).toEqual({ - oneTwo: 1 + oneTwo: 1, }); }); it('should not convert camel case', () => { expect( convertToCamelCase({ - oneTwo: 1 + oneTwo: 1, }) ).toEqual({ - oneTwo: 1 + oneTwo: 1, }); }); it('should handle mixed case', () => { expect( convertToCamelCase({ - 'one-Two': 1 + 'one-Two': 1, }) ).toEqual({ - oneTwo: 1 + oneTwo: 1, }); }); }); @@ -41,7 +41,7 @@ describe('params', () => { { properties: { directory: { type: 'string', alias: 'd' } }, required: [], - description: '' + description: '', } ) ).toEqual({ directory: 'test' }); @@ -54,16 +54,16 @@ describe('params', () => { { properties: { directory: { type: 'string' } }, required: [], - description: '' + description: '', } ) ).toEqual({ '--': [ { name: 'd', - possible: [] - } - ] + possible: [], + }, + ], }); }); }); @@ -76,23 +76,23 @@ describe('params', () => { '--': [ { name: 'directoy', - possible: [] - } - ] + possible: [], + }, + ], }, { properties: { directory: { type: 'string' } }, required: [], - description: '' + description: '', } ) ).toEqual({ '--': [ { name: 'directoy', - possible: ['directory'] - } - ] + possible: ['directory'], + }, + ], }); }); @@ -103,23 +103,23 @@ describe('params', () => { '--': [ { name: 'directoy', - possible: [] - } - ] + possible: [], + }, + ], }, { properties: { faraway: { type: 'string' } }, required: [], - description: '' + description: '', } ) ).toEqual({ '--': [ { name: 'directoy', - possible: [] - } - ] + possible: [], + }, + ], }); }); }); diff --git a/packages/tao/src/shared/params.ts b/packages/tao/src/shared/params.ts index f46d8e72ea286..54ba3ab12f548 100644 --- a/packages/tao/src/shared/params.ts +++ b/packages/tao/src/shared/params.ts @@ -62,7 +62,7 @@ function camelCase(input: string): string { * */ export function coerceTypes(opts: Options, schema: Schema): Options { - Object.keys(opts).forEach(k => { + Object.keys(opts).forEach((k) => { if (schema.properties[k] && schema.properties[k].type == 'boolean') { opts[k] = opts[k] === true || opts[k] === 'true'; } else if (schema.properties[k] && schema.properties[k].type == 'number') { @@ -95,7 +95,7 @@ export function convertAliases(opts: Options, schema: Schema): Options { } acc['--'].push({ name: k, - possible: [] + possible: [], }); } } @@ -114,9 +114,9 @@ export function lookupUnmatched(opts: Options, schema: Schema): Options { if (opts['--']) { const props = Object.keys(schema.properties); - opts['--'].forEach(unmatched => { + opts['--'].forEach((unmatched) => { unmatched.possible = props.filter( - p => levenshtein.get(p, unmatched.name) < 3 + (p) => levenshtein.get(p, unmatched.name) < 3 ); }); } diff --git a/packages/tao/src/shared/print-help.ts b/packages/tao/src/shared/print-help.ts index b9a3f17e375b4..d56d998d91a27 100644 --- a/packages/tao/src/shared/print-help.ts +++ b/packages/tao/src/shared/print-help.ts @@ -6,13 +6,13 @@ export function printHelp( schema: Schema, logger: logging.Logger ) { - const allPositional = Object.keys(schema.properties).filter(key => { + const allPositional = Object.keys(schema.properties).filter((key) => { const p = schema.properties[key]; return p['$default'] && p['$default']['$source'] === 'argv'; }); const positional = allPositional.length > 0 ? ` [${allPositional[0]}]` : ''; const args = Object.keys(schema.properties) - .map(name => { + .map((name) => { const d = schema.properties[name]; const def = d.default ? ` (default: ${d.default})` : ''; return formatOption(name, `${d.description}${def}`); diff --git a/packages/web/src/builders/build/build.impl.ts b/packages/web/src/builders/build/build.impl.ts index 49391481bbcbf..53db20e898af8 100644 --- a/packages/web/src/builders/build/build.impl.ts +++ b/packages/web/src/builders/build/build.impl.ts @@ -2,7 +2,7 @@ import { BuilderContext, createBuilder } from '@angular-devkit/architect'; import { join as devkitJoin, JsonObject, - normalize + normalize, } from '@angular-devkit/core'; import { BuildResult, runWebpack } from '@angular-devkit/build-webpack'; import { from, of } from 'rxjs'; @@ -19,7 +19,7 @@ import { basename } from 'path'; import { createProjectGraph } from '@nrwl/workspace/src/core/project-graph'; import { calculateProjectDependencies, - createTmpTsConfig + createTmpTsConfig, } from '@nrwl/workspace/src/utils/buildable-libs-utils'; export interface WebBuildBuilderOptions extends BuildBuilderOptions { @@ -59,9 +59,7 @@ export function run(options: WebBuildBuilderOptions, context: BuilderContext) { // Node versions 12.2-12.8 has a bug where prod builds will hang for 2-3 minutes // after the program exits. - const nodeVersion = execSync(`node --version`) - .toString('utf-8') - .trim(); + const nodeVersion = execSync(`node --version`).toString('utf-8').trim(); const supportedRange = new Range('10 || >=12.9'); if (!satisfies(nodeVersion, supportedRange)) { throw new Error( @@ -85,7 +83,7 @@ export function run(options: WebBuildBuilderOptions, context: BuilderContext) { return from(getSourceRoot(context, host)) .pipe( - map(sourceRoot => { + map((sourceRoot) => { options = normalizeWebBuildOptions( options, context.workspaceRoot, @@ -111,31 +109,31 @@ export function run(options: WebBuildBuilderOptions, context: BuilderContext) { false, isScriptOptimizeOn ) - : undefined + : undefined, ] .filter(Boolean) - .map(config => + .map((config) => options.webpackConfig ? require(options.webpackConfig)(config, { options, - configuration: context.target.configuration + configuration: context.target.configuration, }) : config ); }) ) .pipe( - switchMap(configs => + switchMap((configs) => from(configs).pipe( // Run build sequentially and bail when first one fails. mergeScan( (acc, config) => { if (acc.success) { return runWebpack(config, context, { - logging: stats => { + logging: (stats) => { context.logger.info(stats.toString(config.stats)); }, - webpackFactory: require('webpack') + webpackFactory: require('webpack'), }); } else { return of(); @@ -149,7 +147,7 @@ export function run(options: WebBuildBuilderOptions, context: BuilderContext) { ) ), switchMap(([result1, result2 = { success: true, emittedFiles: [] }]) => { - const success = [result1, result2].every(result => result.success); + const success = [result1, result2].every((result) => result.success); return (options.optimization ? writeIndexHtml({ host, @@ -161,13 +159,13 @@ export function run(options: WebBuildBuilderOptions, context: BuilderContext) { normalize(context.workspaceRoot), options.index ), - files: result1.emittedFiles.filter(x => x.extension === '.css'), + files: result1.emittedFiles.filter((x) => x.extension === '.css'), noModuleFiles: result2.emittedFiles, moduleFiles: result1.emittedFiles, baseHref: options.baseHref, deployUrl: options.deployUrl, scripts: options.scripts, - styles: options.styles + styles: options.styles, }) : of(null) ).pipe( @@ -175,7 +173,10 @@ export function run(options: WebBuildBuilderOptions, context: BuilderContext) { () => ({ success, - emittedFiles: [...result1.emittedFiles, ...result2.emittedFiles] + emittedFiles: [ + ...result1.emittedFiles, + ...result2.emittedFiles, + ], } as BuildResult) ) ); diff --git a/packages/web/src/builders/dev-server/dev-server.impl.ts b/packages/web/src/builders/dev-server/dev-server.impl.ts index e21c395e48481..0911060cb3043 100644 --- a/packages/web/src/builders/dev-server/dev-server.impl.ts +++ b/packages/web/src/builders/dev-server/dev-server.impl.ts @@ -1,7 +1,7 @@ import { BuilderContext, createBuilder, - targetFromTargetString + targetFromTargetString, } from '@angular-devkit/architect'; import { JsonObject } from '@angular-devkit/core'; @@ -18,7 +18,7 @@ import { buildServePath } from '../../utils/serve-path'; import { getSourceRoot } from '../../utils/source-root'; import { runWebpackDevServer, - DevServerBuildOutput + DevServerBuildOutput, } from '@angular-devkit/build-webpack'; import { NodeJsSyncHost } from '@angular-devkit/core/node'; @@ -66,7 +66,7 @@ function run( if (buildOptions.webpackConfig) { webpackConfig = require(buildOptions.webpackConfig)(webpackConfig, { buildOptions, - configuration: serveOptions.buildTarget.split(':')[2] + configuration: serveOptions.buildTarget.split(':')[2], }); } return [webpackConfig, buildOptions] as [ @@ -80,7 +80,7 @@ function run( protocol: serveOptions.ssl ? 'https' : 'http', hostname: serveOptions.host, port: serveOptions.port.toString(), - pathname: path + pathname: path, }); context.logger.info(stripIndents` @@ -90,7 +90,7 @@ function run( `); if (serveOptions.open) { opn(serverUrl, { - wait: false + wait: false, }); } return [_, options, serverUrl] as [ @@ -101,13 +101,13 @@ function run( }), switchMap(([config, options, serverUrl]) => { return runWebpackDevServer(config, context, { - logging: stats => { + logging: (stats) => { context.logger.info(stats.toString(config.stats)); }, webpackFactory: require('webpack'), - webpackDevServerFactory: require('webpack-dev-server') + webpackDevServerFactory: require('webpack-dev-server'), }).pipe( - map(output => { + map((output) => { output.baseUrl = serverUrl; return output; }) @@ -131,7 +131,7 @@ function getBuildOptions( return from( Promise.all([ context.getTargetOptions(target), - context.getBuilderNameForTarget(target) + context.getBuilderNameForTarget(target), ]) .then(([options, builderName]) => context.validateOptions( @@ -139,9 +139,9 @@ function getBuildOptions( builderName ) ) - .then(options => ({ + .then((options) => ({ ...options, - ...overrides + ...overrides, })) ); } diff --git a/packages/web/src/builders/package/package.impl.spec.ts b/packages/web/src/builders/package/package.impl.spec.ts index ff66c0b871557..89872a1b96164 100644 --- a/packages/web/src/builders/package/package.impl.spec.ts +++ b/packages/web/src/builders/package/package.impl.spec.ts @@ -13,7 +13,7 @@ import { BundleBuilderOptions } from '../../utils/types'; import * as projectGraphUtils from '@nrwl/workspace/src/core/project-graph'; import { ProjectGraph, - ProjectType + ProjectType, } from '@nrwl/workspace/src/core/project-graph'; jest.mock('tsconfig-paths-webpack-plugin'); @@ -32,26 +32,26 @@ describe('WebPackagebuilder', () => { outputPath: 'dist/ui', project: 'libs/ui/package.json', tsConfig: 'libs/ui/tsconfig.json', - watch: false + watch: false, }; spyOn(workspaces, 'readWorkspace').and.returnValue({ workspace: { projects: { get: () => ({ - sourceRoot: join(__dirname, '../../..') - }) - } - } + sourceRoot: join(__dirname, '../../..'), + }), + }, + }, }); spyOn(f, 'readJsonFile').and.returnValue({ - name: 'example' + name: 'example', }); writeJsonFile = spyOn(f, 'writeJsonFile'); spyOn(projectGraphUtils, 'createProjectGraph').and.callFake(() => { return { nodes: {}, - dependencies: {} + dependencies: {}, } as ProjectGraph; }); }); @@ -60,7 +60,7 @@ describe('WebPackagebuilder', () => { it('should call runRollup with esm and umd', async () => { runRollup = spyOn(rr, 'runRollup').and.callFake(() => { return of({ - success: true + success: true, }); }); spyOn(context.logger, 'info'); @@ -68,9 +68,9 @@ describe('WebPackagebuilder', () => { const result = await impl.run(testOptions, context).toPromise(); expect(runRollup).toHaveBeenCalled(); - expect(runRollup.calls.allArgs()[0][0].output.map(o => o.format)).toEqual( - expect.arrayContaining(['esm', 'umd']) - ); + expect( + runRollup.calls.allArgs()[0][0].output.map((o) => o.format) + ).toEqual(expect.arrayContaining(['esm', 'umd'])); expect(result.success).toBe(true); expect(context.logger.info).toHaveBeenCalledWith('Bundle complete.'); }); @@ -89,7 +89,7 @@ describe('WebPackagebuilder', () => { it('updates package.json', async () => { runRollup = spyOn(rr, 'runRollup').and.callFake(() => { return of({ - success: true + success: true, }); }); await impl.run(testOptions, context).toPromise(); @@ -101,7 +101,7 @@ describe('WebPackagebuilder', () => { name: 'example', main: './example.umd.js', module: './example.esm.js', - typings: './index.d.ts' + typings: './index.d.ts', }); }); }); diff --git a/packages/web/src/builders/package/package.impl.ts b/packages/web/src/builders/package/package.impl.ts index feee834652e0e..0cd77f9351b9e 100644 --- a/packages/web/src/builders/package/package.impl.ts +++ b/packages/web/src/builders/package/package.impl.ts @@ -2,7 +2,7 @@ import { relative } from 'path'; import { BuilderContext, BuilderOutput, - createBuilder + createBuilder, } from '@angular-devkit/architect'; import { JsonObject } from '@angular-devkit/core'; import { Observable, of } from 'rxjs'; @@ -19,13 +19,13 @@ import * as localResolve from 'rollup-plugin-local-resolve'; import { BundleBuilderOptions } from '../../utils/types'; import { normalizeBundleOptions, - NormalizedBundleBuilderOptions + NormalizedBundleBuilderOptions, } from '../../utils/normalize'; import { toClassName } from '@nrwl/workspace/src/utils/name-utils'; import { BuildResult } from '@angular-devkit/build-webpack'; import { readJsonFile, - writeJsonFile + writeJsonFile, } from '@nrwl/workspace/src/utils/fileutils'; import { createProjectGraph } from '@nrwl/workspace/src/core/project-graph'; import { @@ -33,7 +33,7 @@ import { checkDependentProjectsHaveBeenBuilt, DependentBuildableProjectNode, computeCompilerOptionsPaths, - updateBuildableProjectPackageJsonDependencies + updateBuildableProjectPackageJsonDependencies, } from '@nrwl/workspace/src/utils/buildable-libs-utils'; // These use require because the ES import isn't correct. @@ -52,7 +52,7 @@ interface OutputConfig { const outputConfigs: OutputConfig[] = [ { format: 'umd', extension: 'umd' }, - { format: 'esm', extension: 'esm' } + { format: 'esm', extension: 'esm' }, ]; const fileExtensions = ['.js', '.jsx', '.ts', '.tsx']; @@ -68,7 +68,7 @@ export function run( ); return of(checkDependentProjectsHaveBeenBuilt(context, dependencies)).pipe( - switchMap(result => { + switchMap((result) => { if (!result) { return of({ success: false }); } @@ -82,9 +82,9 @@ export function run( ); if (options.watch) { - return new Observable(obs => { + return new Observable((obs) => { const watcher = rollup.watch([rollupOptions]); - watcher.on('event', data => { + watcher.on('event', (data) => { if (data.code === 'START') { context.logger.info('Bundling...'); } else if (data.code === 'END') { @@ -112,13 +112,13 @@ export function run( } else { context.logger.info('Bundling...'); return runRollup(rollupOptions).pipe( - catchError(e => { + catchError((e) => { console.error(e); return of({ success: false }); }), last(), tap({ - next: result => { + next: (result) => { if (result.success) { updatePackageJson( options, @@ -131,7 +131,7 @@ export function run( } else { context.logger.error('Bundle failed.'); } - } + }, }) ); } @@ -162,32 +162,32 @@ function createRollupOptions( rootDir: options.entryRoot, allowJs: false, declaration: true, - paths: compilerOptionPaths - } - } + paths: compilerOptionPaths, + }, + }, }), peerDepsExternal({ - packageJsonPath: options.project + packageJsonPath: options.project, }), postcss({ inject: true, extract: options.extractCss, autoModules: true, - plugins: [autoprefixer] + plugins: [autoprefixer], }), localResolve(), resolve({ preferBuiltins: true, - extensions: fileExtensions + extensions: fileExtensions, }), babel({ ...createBabelConfig(options, options.projectRoot), extensions: fileExtensions, externalHelpers: false, - exclude: 'node_modules/**' + exclude: 'node_modules/**', }), commonjs(), - filesize() + filesize(), ]; const globals = options.globals @@ -198,22 +198,22 @@ function createRollupOptions( : {}; const externalPackages = dependencies - .map(d => d.name) + .map((d) => d.name) .concat(options.external || []) .concat(Object.keys(packageJson.dependencies || {})); const rollupConfig = { input: options.entryFile, - output: outputConfigs.map(o => { + output: outputConfigs.map((o) => { return { globals, format: o.format, file: `${options.outputPath}/${context.target.project}.${o.extension}.js`, - name: toClassName(context.target.project) + name: toClassName(context.target.project), }; }), - external: id => externalPackages.includes(id), - plugins + external: (id) => externalPackages.includes(id), + plugins, }; return options.rollupConfig @@ -250,7 +250,7 @@ function upsert( ) { if ( !config[type].some( - p => + (p) => (Array.isArray(p) && p[0].indexOf(pluginOrPreset) !== -1) || p.indexOf(pluginOrPreset) !== -1 ) diff --git a/packages/web/src/builders/package/run-rollup.ts b/packages/web/src/builders/package/run-rollup.ts index 443acdbab50c9..774cd0780bc08 100644 --- a/packages/web/src/builders/package/run-rollup.ts +++ b/packages/web/src/builders/package/run-rollup.ts @@ -4,13 +4,15 @@ import { map, switchMap } from 'rxjs/operators'; export function runRollup(options: rollup.RollupOptions) { return from(rollup.rollup(options)).pipe( - switchMap(bundle => { + switchMap((bundle) => { const outputOptions = Array.isArray(options.output) ? options.output : [options.output]; return from( Promise.all( - (>outputOptions).map(o => bundle.write(o)) + (>outputOptions).map((o) => + bundle.write(o) + ) ) ); }), diff --git a/packages/web/src/migrations/update-8-5-0/update-builder-8-5-0.spec.ts b/packages/web/src/migrations/update-8-5-0/update-builder-8-5-0.spec.ts index 1a02fb64aaf0a..dbcc41f3ef9d4 100644 --- a/packages/web/src/migrations/update-8-5-0/update-builder-8-5-0.spec.ts +++ b/packages/web/src/migrations/update-8-5-0/update-builder-8-5-0.spec.ts @@ -5,7 +5,7 @@ import { readJsonInTree, updateWorkspaceInTree, readWorkspace, - getWorkspacePath + getWorkspacePath, } from '@nrwl/workspace'; import * as path from 'path'; @@ -35,12 +35,12 @@ describe('Update 8-5-0', () => { build: { builder: '@nrwl/web:build', options: { - differentialLoading: true - } - } - } - } - } + differentialLoading: true, + }, + }, + }, + }, + }, }) ); diff --git a/packages/web/src/migrations/update-8-5-0/update-builder-8-5-0.ts b/packages/web/src/migrations/update-8-5-0/update-builder-8-5-0.ts index cc8daa744ba46..8609283d12a97 100644 --- a/packages/web/src/migrations/update-8-5-0/update-builder-8-5-0.ts +++ b/packages/web/src/migrations/update-8-5-0/update-builder-8-5-0.ts @@ -3,9 +3,9 @@ import { formatFiles, updateWorkspaceInTree } from '@nrwl/workspace'; export default function update(): Rule { return chain([ - updateWorkspaceInTree(config => { + updateWorkspaceInTree((config) => { const filteredProjects = []; - Object.keys(config.projects).forEach(name => { + Object.keys(config.projects).forEach((name) => { if ( config.projects[name].architect && config.projects[name].architect.build && @@ -14,11 +14,11 @@ export default function update(): Rule { filteredProjects.push(config.projects[name]); } }); - filteredProjects.forEach(p => { + filteredProjects.forEach((p) => { delete p.architect.build.options.differentialLoading; }); return config; }), - formatFiles() + formatFiles(), ]); } diff --git a/packages/web/src/migrations/update-9-0-0/update-builder-9-0-0.ts b/packages/web/src/migrations/update-9-0-0/update-builder-9-0-0.ts index cf00d84cf79f8..8a27386fe3f74 100644 --- a/packages/web/src/migrations/update-9-0-0/update-builder-9-0-0.ts +++ b/packages/web/src/migrations/update-9-0-0/update-builder-9-0-0.ts @@ -3,7 +3,7 @@ import { formatFiles, updateWorkspaceInTree } from '@nrwl/workspace'; export default function update(): Rule { return chain([ - updateWorkspaceInTree(workspaceJson => { + updateWorkspaceInTree((workspaceJson) => { Object.entries(workspaceJson.projects).forEach( ([projectName, project]) => { Object.entries(project.architect).forEach( @@ -19,6 +19,6 @@ export default function update(): Rule { ); return workspaceJson; }), - formatFiles() + formatFiles(), ]); } diff --git a/packages/web/src/migrations/update-9-2-0/set-build-libs-from-source.spec.ts b/packages/web/src/migrations/update-9-2-0/set-build-libs-from-source.spec.ts index 06807bd04c81e..8f1325d524d0c 100644 --- a/packages/web/src/migrations/update-9-2-0/set-build-libs-from-source.spec.ts +++ b/packages/web/src/migrations/update-9-2-0/set-build-libs-from-source.spec.ts @@ -27,11 +27,11 @@ describe('set buildLibsFromSource to true', () => { architect: { build: { builder: '@nrwl/web:build', - options: {} - } - } - } - } + options: {}, + }, + }, + }, + }, }) ); @@ -41,7 +41,7 @@ describe('set buildLibsFromSource to true', () => { const config = readWorkspace(tree); expect(config.projects.demo.architect.build.options).toEqual({ - buildLibsFromSource: true + buildLibsFromSource: true, }); }); }); diff --git a/packages/web/src/migrations/update-9-2-0/set-build-libs-from-source.ts b/packages/web/src/migrations/update-9-2-0/set-build-libs-from-source.ts index bab278bc7e1a7..f4008621e5635 100644 --- a/packages/web/src/migrations/update-9-2-0/set-build-libs-from-source.ts +++ b/packages/web/src/migrations/update-9-2-0/set-build-libs-from-source.ts @@ -3,7 +3,7 @@ import { formatFiles, updateWorkspaceInTree } from '@nrwl/workspace'; export default function update(): Rule { return chain([ - updateWorkspaceInTree(workspaceJson => { + updateWorkspaceInTree((workspaceJson) => { Object.entries(workspaceJson.projects).forEach( ([projectName, project]) => { Object.entries(project.architect).forEach( @@ -21,6 +21,6 @@ export default function update(): Rule { ); return workspaceJson; }), - formatFiles() + formatFiles(), ]); } diff --git a/packages/web/src/schematics/application/application.spec.ts b/packages/web/src/schematics/application/application.spec.ts index de0930ab0a217..1165a2be12b1c 100644 --- a/packages/web/src/schematics/application/application.spec.ts +++ b/packages/web/src/schematics/application/application.spec.ts @@ -33,12 +33,12 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-app': { - tags: ['one', 'two'] + tags: ['one', 'two'], }, 'my-app-e2e': { tags: [], - implicitDependencies: ['my-app'] - } + implicitDependencies: ['my-app'], + }, }); }); @@ -101,12 +101,12 @@ describe('app', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-app': { - tags: ['one', 'two'] + tags: ['one', 'two'], }, 'my-dir-my-app-e2e': { tags: [], - implicitDependencies: ['my-dir-my-app'] - } + implicitDependencies: ['my-dir-my-app'], + }, }); }); @@ -128,8 +128,8 @@ describe('app', () => { 'apps/my-dir/my-app/src/main.ts', 'apps/my-dir/my-app/src/app/app.element.ts', 'apps/my-dir/my-app/src/app/app.element.spec.ts', - 'apps/my-dir/my-app/src/app/app.element.css' - ].forEach(path => { + 'apps/my-dir/my-app/src/app/app.element.css', + ].forEach((path) => { expect(tree.exists(path)).toBeTruthy(); }); @@ -137,29 +137,29 @@ describe('app', () => { [ { path: 'apps/my-dir/my-app/tsconfig.json', - lookupFn: json => json.extends, - expectedValue: '../../../tsconfig.json' + lookupFn: (json) => json.extends, + expectedValue: '../../../tsconfig.json', }, { path: 'apps/my-dir/my-app/tsconfig.app.json', - lookupFn: json => json.compilerOptions.outDir, - expectedValue: '../../../dist/out-tsc' + lookupFn: (json) => json.compilerOptions.outDir, + expectedValue: '../../../dist/out-tsc', }, { path: 'apps/my-dir/my-app-e2e/tsconfig.json', - lookupFn: json => json.extends, - expectedValue: '../../../tsconfig.json' + lookupFn: (json) => json.extends, + expectedValue: '../../../tsconfig.json', }, { path: 'apps/my-dir/my-app-e2e/tsconfig.e2e.json', - lookupFn: json => json.compilerOptions.outDir, - expectedValue: '../../../dist/out-tsc' + lookupFn: (json) => json.compilerOptions.outDir, + expectedValue: '../../../dist/out-tsc', }, { path: 'apps/my-dir/my-app/tslint.json', - lookupFn: json => json.extends, - expectedValue: '../../../tslint.json' - } + lookupFn: (json) => json.extends, + expectedValue: '../../../tslint.json', + }, ].forEach(hasJsonValue); }); }); @@ -195,7 +195,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-App' + name: 'my-App', }, appTree ); @@ -209,7 +209,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-App' + name: 'my-App', }, appTree ); @@ -224,7 +224,7 @@ describe('app', () => { polyfills: 'apps/my-app/src/polyfills.ts', scripts: [], styles: ['apps/my-app/src/styles.css'], - tsConfig: 'apps/my-app/tsconfig.app.json' + tsConfig: 'apps/my-app/tsconfig.app.json', }); expect(architectConfig.build.configurations.production).toEqual({ optimization: true, @@ -232,21 +232,21 @@ describe('app', () => { { maximumError: '5mb', maximumWarning: '2mb', - type: 'initial' - } + type: 'initial', + }, ], extractCss: true, extractLicenses: true, fileReplacements: [ { replace: 'apps/my-app/src/environments/environment.ts', - with: 'apps/my-app/src/environments/environment.prod.ts' - } + with: 'apps/my-app/src/environments/environment.prod.ts', + }, ], namedChunks: false, outputHashing: 'all', sourceMap: false, - vendorChunk: false + vendorChunk: false, }); }); @@ -254,7 +254,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-App' + name: 'my-App', }, appTree ); @@ -262,10 +262,10 @@ describe('app', () => { const architectConfig = workspaceJson.projects['my-app'].architect; expect(architectConfig.serve.builder).toEqual('@nrwl/web:dev-server'); expect(architectConfig.serve.options).toEqual({ - buildTarget: 'my-app:build' + buildTarget: 'my-app:build', }); expect(architectConfig.serve.configurations.production).toEqual({ - buildTarget: 'my-app:build:production' + buildTarget: 'my-app:build:production', }); }); @@ -273,7 +273,7 @@ describe('app', () => { const tree = await runSchematic( 'app', { - name: 'my-App' + name: 'my-App', }, appTree ); @@ -285,9 +285,9 @@ describe('app', () => { exclude: ['**/node_modules/**', '!apps/my-app/**'], tsConfig: [ 'apps/my-app/tsconfig.app.json', - 'apps/my-app/tsconfig.spec.json' - ] - } + 'apps/my-app/tsconfig.spec.json', + ], + }, }); }); diff --git a/packages/web/src/schematics/application/application.ts b/packages/web/src/schematics/application/application.ts index dd51d2c9d75f9..878c783405387 100644 --- a/packages/web/src/schematics/application/application.ts +++ b/packages/web/src/schematics/application/application.ts @@ -11,7 +11,7 @@ import { url, externalSchematic, noop, - filter + filter, } from '@angular-devkit/schematics'; import { Schema } from './schema'; import { @@ -24,7 +24,7 @@ import { formatFiles, updateWorkspaceInTree, generateProjectLint, - addLintFiles + addLintFiles, } from '@nrwl/workspace'; import init from '../init/init'; @@ -43,25 +43,25 @@ function createApplicationFiles(options: NormalizedSchema): Rule { ...options, ...names(options.name), tmpl: '', - offsetFromRoot: offsetFromRoot(options.appProjectRoot) + offsetFromRoot: offsetFromRoot(options.appProjectRoot), }), options.unitTestRunner === 'none' - ? filter(file => file !== '/src/app/app.spec.ts') + ? filter((file) => file !== '/src/app/app.spec.ts') : noop(), - move(options.appProjectRoot) + move(options.appProjectRoot), ]) ); } function updateNxJson(options: NormalizedSchema): Rule { - return updateJsonInTree('nx.json', json => { + return updateJsonInTree('nx.json', (json) => { json.projects[options.projectName] = { tags: options.parsedTags }; return json; }); } function addProject(options: NormalizedSchema): Rule { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const architect: { [key: string]: any } = {}; architect.build = { @@ -74,12 +74,15 @@ function addProject(options: NormalizedSchema): Rule { tsConfig: join(normalize(options.appProjectRoot), 'tsconfig.app.json'), assets: [ join(normalize(options.appProjectRoot), 'src/favicon.ico'), - join(normalize(options.appProjectRoot), 'src/assets') + join(normalize(options.appProjectRoot), 'src/assets'), ], styles: [ - join(normalize(options.appProjectRoot), `src/styles.${options.style}`) + join( + normalize(options.appProjectRoot), + `src/styles.${options.style}` + ), ], - scripts: [] + scripts: [], }, configurations: { production: { @@ -92,8 +95,8 @@ function addProject(options: NormalizedSchema): Rule { with: join( normalize(options.appProjectRoot), `src/environments/environment.prod.ts` - ) - } + ), + }, ], optimization: true, outputHashing: 'all', @@ -106,23 +109,23 @@ function addProject(options: NormalizedSchema): Rule { { type: 'initial', maximumWarning: '2mb', - maximumError: '5mb' - } - ] - } - } + maximumError: '5mb', + }, + ], + }, + }, }; architect.serve = { builder: '@nrwl/web:dev-server', options: { - buildTarget: `${options.projectName}:build` + buildTarget: `${options.projectName}:build`, }, configurations: { production: { - buildTarget: `${options.projectName}:build:production` - } - } + buildTarget: `${options.projectName}:build:production`, + }, + }, }; architect.lint = generateProjectLint( @@ -136,7 +139,7 @@ function addProject(options: NormalizedSchema): Rule { sourceRoot: join(normalize(options.appProjectRoot), 'src'), projectType: 'application', schematics: {}, - architect + architect, }; json.defaultProject = json.defaultProject || options.projectName; @@ -145,14 +148,14 @@ function addProject(options: NormalizedSchema): Rule { }); } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(host, schema); return chain([ init({ ...options, - skipFormat: true + skipFormat: true, }), addLintFiles(options.appProjectRoot, options.linter), createApplicationFiles(options), @@ -163,17 +166,17 @@ export default function(schema: Schema): Rule { ...options, name: options.name + '-e2e', directory: options.directory, - project: options.projectName + project: options.projectName, }) : noop(), options.unitTestRunner === 'jest' ? externalSchematic('@nrwl/jest', 'jest-project', { project: options.projectName, skipSerializers: true, - setupFile: 'web-components' + setupFile: 'web-components', }) : noop(), - formatFiles(options) + formatFiles(options), ])(host, context); }; } @@ -190,7 +193,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { const e2eProjectRoot = `apps/${appDirectory}-e2e`; const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; const defaultPrefix = getNpmScope(host); @@ -202,6 +205,6 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema { appProjectRoot, e2eProjectRoot, e2eProjectName, - parsedTags + parsedTags, }; } diff --git a/packages/web/src/schematics/init/init.spec.ts b/packages/web/src/schematics/init/init.spec.ts index 62ded575a52af..1ef8a8f0b4eeb 100644 --- a/packages/web/src/schematics/init/init.spec.ts +++ b/packages/web/src/schematics/init/init.spec.ts @@ -44,7 +44,7 @@ describe('init', () => { const result = await runSchematic( 'init', { - unitTestRunner: 'none' + unitTestRunner: 'none', }, tree ); diff --git a/packages/web/src/schematics/init/init.ts b/packages/web/src/schematics/init/init.ts index bbc0d6afb0763..a9b79ee25aa44 100644 --- a/packages/web/src/schematics/init/init.ts +++ b/packages/web/src/schematics/init/init.ts @@ -2,31 +2,31 @@ import { chain, noop, Rule } from '@angular-devkit/schematics'; import { addPackageWithInit, formatFiles, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace'; import { Schema } from './schema'; import { documentRegisterElementVersion, - nxVersion + nxVersion, } from '../../utils/versions'; import { setDefaultCollection } from '@nrwl/workspace/src/utils/rules/workspace'; function updateDependencies(): Rule { - return updateJsonInTree('package.json', json => { + return updateJsonInTree('package.json', (json) => { delete json.dependencies['@nrwl/web']; json.dependencies = { ...json.dependencies, - 'document-register-element': documentRegisterElementVersion + 'document-register-element': documentRegisterElementVersion, }; json.devDependencies = { ...json.devDependencies, - '@nrwl/web': nxVersion + '@nrwl/web': nxVersion, }; return json; }); } -export default function(schema: Schema) { +export default function (schema: Schema) { return chain([ setDefaultCollection('@nrwl/web'), schema.unitTestRunner === 'jest' @@ -36,6 +36,6 @@ export default function(schema: Schema) { ? addPackageWithInit('@nrwl/cypress') : noop(), updateDependencies(), - formatFiles(schema) + formatFiles(schema), ]); } diff --git a/packages/web/src/utils/babel-config.ts b/packages/web/src/utils/babel-config.ts index 62ceba3b307a4..a0eef71a58faf 100644 --- a/packages/web/src/utils/babel-config.ts +++ b/packages/web/src/utils/babel-config.ts @@ -21,10 +21,10 @@ export function createBabelConfig( exclude: ['transform-typeof-symbol'], // Let babel-env figure which modern browsers to support. // See: https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/built-in-modules.json - targets: esm ? { esmodules: true } : undefined - } + targets: esm ? { esmodules: true } : undefined, + }, ], - [require.resolve('@babel/preset-typescript')] + [require.resolve('@babel/preset-typescript')], ], plugins: [ require.resolve('babel-plugin-macros'), @@ -32,8 +32,8 @@ export function createBabelConfig( [require.resolve('@babel/plugin-proposal-decorators'), { legacy: true }], [ require.resolve('@babel/plugin-proposal-class-properties'), - { loose: true } - ] + { loose: true }, + ], ], overrides: [ { @@ -42,11 +42,11 @@ export function createBabelConfig( [ require.resolve('babel-plugin-const-enum'), { - transform: 'removeConst' - } - ] - ] - } - ] + transform: 'removeConst', + }, + ], + ], + }, + ], }; } diff --git a/packages/web/src/utils/config.spec.ts b/packages/web/src/utils/config.spec.ts index d9fd09c64dce4..e9a2f4f1ab03f 100644 --- a/packages/web/src/utils/config.spec.ts +++ b/packages/web/src/utils/config.spec.ts @@ -19,11 +19,11 @@ describe('getBaseWebpackPartial', () => { tsConfig: 'tsconfig.json', fileReplacements: [], root: '/root', - statsJson: false + statsJson: false, }; - (TsConfigPathsPlugin).mockImplementation( - function MockPathsPlugin() {} - ); + (( + TsConfigPathsPlugin + )).mockImplementation(function MockPathsPlugin() {}); }); describe('unconditional options', () => { @@ -42,7 +42,7 @@ describe('getBaseWebpackPartial', () => { it('should have a rule for typescript', () => { const result = getBaseWebpackPartial(input); - const rule = result.module.rules.find(rule => + const rule = result.module.rules.find((rule) => (rule.test as RegExp).test('app/main.ts') ); expect(rule).toBeTruthy(); @@ -54,7 +54,7 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin).toBeTruthy(); }); @@ -63,7 +63,7 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); expect(result.performance).toEqual({ - hints: false + hints: false, }); }); @@ -75,15 +75,15 @@ describe('getBaseWebpackPartial', () => { '.tsx', '.mjs', '.js', - '.jsx' + '.jsx', ]); }); it('should include module and main in mainFields', () => { spyOn(ts, 'parseJsonConfigFileContent').and.returnValue({ options: { - target: 'es5' - } + target: 'es5', + }, }); const result = getBaseWebpackPartial(input); @@ -102,7 +102,7 @@ describe('getBaseWebpackPartial', () => { cachedAssets: false, modules: false, warnings: true, - errors: true + errors: true, }) ); }); @@ -113,7 +113,7 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); expect(result.entry).toEqual({ - main: ['main.ts'] + main: ['main.ts'], }); }); }); @@ -131,7 +131,7 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input); const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin.options.tsconfig).toBe('tsconfig.json'); }); @@ -140,14 +140,14 @@ describe('getBaseWebpackPartial', () => { spyOn(ts, 'parseJsonConfigFileContent').and.returnValue({ options: { paths: { - '@npmScope/libraryName': ['libs/libraryName/src/index.ts'] - } - } + '@npmScope/libraryName': ['libs/libraryName/src/index.ts'], + }, + }, }); const result = getBaseWebpackPartial(input); expect( result.resolve.plugins.some( - plugin => plugin instanceof TsConfigPathsPlugin + (plugin) => plugin instanceof TsConfigPathsPlugin ) ).toEqual(true); }); @@ -163,12 +163,12 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input, true); expect( - (result.module.rules.find(rule => rule.loader === 'babel-loader') + (result.module.rules.find((rule) => rule.loader === 'babel-loader') .options as any).presets.find( - p => p[0].indexOf('@babel/preset-env') !== -1 + (p) => p[0].indexOf('@babel/preset-env') !== -1 )[1] ).toMatchObject({ - targets: { esmodules: true } + targets: { esmodules: true }, }); }); @@ -176,12 +176,12 @@ describe('getBaseWebpackPartial', () => { const result = getBaseWebpackPartial(input, false); expect( - (result.module.rules.find(rule => rule.loader === 'babel-loader') + (result.module.rules.find((rule) => rule.loader === 'babel-loader') .options as any).presets.find( - p => p[0].indexOf('@babel/preset-env') !== -1 + (p) => p[0].indexOf('@babel/preset-env') !== -1 )[1] ).toMatchObject({ - targets: undefined + targets: undefined, }); }); }); @@ -189,7 +189,7 @@ describe('getBaseWebpackPartial', () => { describe('the file replacements option', () => { it('should set aliases', () => { spyOn(ts, 'parseJsonConfigFileContent').and.returnValue({ - options: {} + options: {}, }); const result = getBaseWebpackPartial({ @@ -197,13 +197,13 @@ describe('getBaseWebpackPartial', () => { fileReplacements: [ { replace: 'environments/environment.ts', - with: 'environments/environment.prod.ts' - } - ] + with: 'environments/environment.prod.ts', + }, + ], }); expect(result.resolve.alias).toEqual({ - 'environments/environment.ts': 'environments/environment.prod.ts' + 'environments/environment.ts': 'environments/environment.prod.ts', }); }); }); @@ -212,7 +212,7 @@ describe('getBaseWebpackPartial', () => { it('should enable file watching', () => { const result = getBaseWebpackPartial({ ...input, - watch: true + watch: true, }); expect(result.watch).toEqual(true); @@ -223,7 +223,7 @@ describe('getBaseWebpackPartial', () => { it('should determine the polling rate', () => { const result = getBaseWebpackPartial({ ...input, - poll: 1000 + poll: 1000, }); expect(result.watchOptions.poll).toEqual(1000); @@ -234,7 +234,7 @@ describe('getBaseWebpackPartial', () => { it('should enable source-map devtool', () => { const result = getBaseWebpackPartial({ ...input, - sourceMap: true + sourceMap: true, }); expect(result.devtool).toEqual('source-map'); @@ -243,7 +243,7 @@ describe('getBaseWebpackPartial', () => { it('should disable source-map devtool', () => { const result = getBaseWebpackPartial({ ...input, - sourceMap: false + sourceMap: false, }); expect(result.devtool).toEqual(false); @@ -272,11 +272,11 @@ describe('getBaseWebpackPartial', () => { it('should set the memory limit for the type checker', () => { const result = getBaseWebpackPartial({ ...input, - memoryLimit: 1024 + memoryLimit: 1024, }); const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin.options.memoryLimit).toEqual(1024); }); @@ -286,11 +286,11 @@ describe('getBaseWebpackPartial', () => { it('should set the maximum workers for the type checker', () => { const result = getBaseWebpackPartial({ ...input, - maxWorkers: 1 + maxWorkers: 1, }); const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin.options.workers).toEqual(1); }); @@ -304,20 +304,20 @@ describe('getBaseWebpackPartial', () => { { input: 'assets', glob: '**/*', - output: 'assets' + output: 'assets', }, { input: '', glob: 'file.txt', - output: '' - } - ] + output: '', + }, + ], }); // This test isn't great because it's hard to find CopyWebpackPlugin expect( result.plugins.some( - plugin => !(plugin instanceof ForkTsCheckerWebpackPlugin) + (plugin) => !(plugin instanceof ForkTsCheckerWebpackPlugin) ) ).toBeTruthy(); }); @@ -327,12 +327,12 @@ describe('getBaseWebpackPartial', () => { it('should show warnings for circular dependencies', () => { const result = getBaseWebpackPartial({ ...input, - showCircularDependencies: true + showCircularDependencies: true, }); expect( result.plugins.find( - plugin => plugin instanceof CircularDependencyPlugin + (plugin) => plugin instanceof CircularDependencyPlugin ) ).toBeTruthy(); }); @@ -340,11 +340,11 @@ describe('getBaseWebpackPartial', () => { it('should exclude node modules', () => { const result = getBaseWebpackPartial({ ...input, - showCircularDependencies: true + showCircularDependencies: true, }); const circularDependencyPlugin: CircularDependencyPlugin = result.plugins.find( - plugin => plugin instanceof CircularDependencyPlugin + (plugin) => plugin instanceof CircularDependencyPlugin ); expect(circularDependencyPlugin.options.exclude).toEqual( /[\\\/]node_modules[\\\/]/ @@ -356,11 +356,11 @@ describe('getBaseWebpackPartial', () => { it('should extract licenses to a separate file', () => { const result = getBaseWebpackPartial({ ...input, - extractLicenses: true + extractLicenses: true, }); const licensePlugin = result.plugins.find( - plugin => plugin instanceof LicenseWebpackPlugin + (plugin) => plugin instanceof LicenseWebpackPlugin ); expect(licensePlugin).toBeTruthy(); @@ -371,11 +371,11 @@ describe('getBaseWebpackPartial', () => { it('should show build progress', () => { const result = getBaseWebpackPartial({ ...input, - progress: true + progress: true, }); expect( - result.plugins.find(plugin => plugin instanceof ProgressPlugin) + result.plugins.find((plugin) => plugin instanceof ProgressPlugin) ).toBeTruthy(); }); }); @@ -397,7 +397,7 @@ describe('getBaseWebpackPartial', () => { version: false, errorDetails: false, moduleTrace: false, - usedExports: false + usedExports: false, }) ); }); @@ -420,7 +420,7 @@ describe('getBaseWebpackPartial', () => { version: true, errorDetails: true, moduleTrace: true, - usedExports: true + usedExports: true, }) ); }); diff --git a/packages/web/src/utils/config.ts b/packages/web/src/utils/config.ts index 2086c2e50ad57..1b54a6ea92c9a 100644 --- a/packages/web/src/utils/config.ts +++ b/packages/web/src/utils/config.ts @@ -14,7 +14,7 @@ import { createBabelConfig } from './babel-config'; const IGNORED_WEBPACK_WARNINGS = [ /The comment file/i, - /could not find any license/i + /could not find any license/i, ]; export function getBaseWebpackPartial( @@ -36,14 +36,14 @@ export function getBaseWebpackPartial( const webpackConfig: Configuration = { entry: { - main: [options.main] + main: [options.main], }, devtool: options.sourceMap ? 'source-map' : false, mode, output: { path: options.outputPath, filename, - chunkFilename + chunkFilename, }, module: { rules: [ @@ -54,10 +54,10 @@ export function getBaseWebpackPartial( options: { ...createBabelConfig(dirname(options.main), esm, options.verbose), cacheDirectory: true, - cacheCompression: false - } - } - ] + cacheCompression: false, + }, + }, + ], }, resolve: { extensions, @@ -66,16 +66,16 @@ export function getBaseWebpackPartial( new TsConfigPathsPlugin({ configFile: options.tsConfig, extensions, - mainFields - }) + mainFields, + }), ], // Search closest node_modules first, and then fallback to to default node module resolution scheme. // This ensures we are pulling the correct versions of dependencies, such as `core-js`. modules: [resolve(__dirname, '..', '..', 'node_modules'), 'node_modules'], - mainFields + mainFields, }, performance: { - hints: false + hints: false, }, plugins: [ new ForkTsCheckerWebpackPlugin({ @@ -84,21 +84,21 @@ export function getBaseWebpackPartial( options.memoryLimit || ForkTsCheckerWebpackPlugin.DEFAULT_MEMORY_LIMIT, workers: options.maxWorkers || ForkTsCheckerWebpackPlugin.TWO_CPUS_FREE, - useTypescriptIncrementalApi: false + useTypescriptIncrementalApi: false, }), - new webpack.DefinePlugin(getClientEnvironment(mode).stringified) + new webpack.DefinePlugin(getClientEnvironment(mode).stringified), ], watch: options.watch, watchOptions: { - poll: options.poll + poll: options.poll, }, - stats: getStatsConfig(options) + stats: getStatsConfig(options), }; if (isScriptOptimizeOn) { webpackConfig.optimization = { minimizer: [createTerserPlugin(esm, !!options.sourceMap)], - runtimeChunk: true + runtimeChunk: true, }; } @@ -109,13 +109,15 @@ export function getBaseWebpackPartial( } if (options.extractLicenses) { - extraPlugins.push((new LicenseWebpackPlugin({ - stats: { - errors: false - }, - perChunkOutput: false, - outputFilename: `3rdpartylicenses.txt` - }) as unknown) as webpack.Plugin); + extraPlugins.push( + (new LicenseWebpackPlugin({ + stats: { + errors: false, + }, + perChunkOutput: false, + outputFilename: `3rdpartylicenses.txt`, + }) as unknown) as webpack.Plugin + ); } // process asset entries @@ -128,13 +130,13 @@ export function getBaseWebpackPartial( ignore: asset.ignore, from: { glob: asset.glob, - dot: true - } + dot: true, + }, }; }); const copyWebpackPluginOptions = { - ignore: ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'] + ignore: ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'], }; const copyWebpackPluginInstance = new CopyWebpackPlugin( @@ -147,7 +149,7 @@ export function getBaseWebpackPartial( if (options.showCircularDependencies) { extraPlugins.push( new CircularDependencyPlugin({ - exclude: /[\\\/]node_modules[\\\/]/ + exclude: /[\\\/]node_modules[\\\/]/, }) ); } @@ -161,7 +163,7 @@ function getAliases(options: BuildBuilderOptions): { [key: string]: string } { return options.fileReplacements.reduce( (aliases, replacement) => ({ ...aliases, - [replacement.replace]: replacement.with + [replacement.replace]: replacement.with, }), {} ); @@ -178,9 +180,9 @@ export function createTerserPlugin(esm: boolean, sourceMap: boolean) { output: { ascii_only: true, comments: false, - webkit: true - } - } + webkit: true, + }, + }, }); } @@ -204,7 +206,7 @@ function getStatsConfig(options: BuildBuilderOptions): Stats.ToStringOptions { errorDetails: !!options.verbose, moduleTrace: !!options.verbose, usedExports: !!options.verbose, - warningsFilter: IGNORED_WEBPACK_WARNINGS + warningsFilter: IGNORED_WEBPACK_WARNINGS, }; } @@ -216,7 +218,7 @@ function getClientEnvironment(mode) { const NX_APP = /^NX_/i; const raw = Object.keys(process.env) - .filter(key => NX_APP.test(key)) + .filter((key) => NX_APP.test(key)) .reduce( (env, key) => { env[key] = process.env[key]; @@ -224,7 +226,7 @@ function getClientEnvironment(mode) { }, { // Useful for determining whether we’re running in production mode. - NODE_ENV: process.env.NODE_ENV || mode + NODE_ENV: process.env.NODE_ENV || mode, } ); @@ -233,7 +235,7 @@ function getClientEnvironment(mode) { 'process.env': Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; - }, {}) + }, {}), }; return { stringified }; diff --git a/packages/web/src/utils/devserver.config.spec.ts b/packages/web/src/utils/devserver.config.spec.ts index 0ab6dc550bba3..90c7f5c07ef14 100644 --- a/packages/web/src/utils/devserver.config.spec.ts +++ b/packages/web/src/utils/devserver.config.spec.ts @@ -28,17 +28,17 @@ describe('getDevServerConfig', () => { scripts: true, styles: true, hidden: false, - vendors: false + vendors: false, }, optimization: { scripts: false, - styles: false + styles: false, }, styles: [], scripts: [], outputPath: 'dist', tsConfig: 'tsconfig.json', - fileReplacements: [] + fileReplacements: [], }; root = join(__dirname, '../../../..'); sourceRoot = join(root, 'apps/app'); @@ -51,21 +51,21 @@ describe('getDevServerConfig', () => { liveReload: true, open: false, watch: true, - allowedHosts: null + allowedHosts: null, }; - (TsConfigPathsPlugin).mockImplementation( - function MockPathsPlugin() {} - ); + (( + TsConfigPathsPlugin + )).mockImplementation(function MockPathsPlugin() {}); mockCompilerOptions = { - target: 'es2015' + target: 'es2015', }; spyOn(ts, 'readConfigFile').and.callFake(() => ({ config: { - compilerOptions: mockCompilerOptions - } + compilerOptions: mockCompilerOptions, + }, })); }); @@ -160,7 +160,7 @@ describe('getDevServerConfig', () => { expect(result.historyApiFallback).toEqual({ index: '//index.html', disableDotRule: true, - htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] + htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'], }); }); @@ -185,8 +185,8 @@ describe('getDevServerConfig', () => { ...buildInput, optimization: { scripts: true, - styles: false - } + styles: false, + }, }, serveInput, logger @@ -203,8 +203,8 @@ describe('getDevServerConfig', () => { ...buildInput, optimization: { scripts: false, - styles: true - } + styles: true, + }, }, serveInput, logger @@ -221,8 +221,8 @@ describe('getDevServerConfig', () => { ...buildInput, optimization: { scripts: true, - styles: true - } + styles: true, + }, }, serveInput, logger @@ -239,8 +239,8 @@ describe('getDevServerConfig', () => { ...buildInput, optimization: { scripts: false, - styles: false - } + styles: false, + }, }, serveInput, logger @@ -257,8 +257,8 @@ describe('getDevServerConfig', () => { ...buildInput, optimization: { scripts: true, - styles: true - } + styles: true, + }, }, serveInput, logger @@ -290,7 +290,7 @@ describe('getDevServerConfig', () => { buildInput, { ...serveInput, - publicHost: 'www.example.com' + publicHost: 'www.example.com', }, logger ); @@ -310,7 +310,7 @@ describe('getDevServerConfig', () => { { ...serveInput, ssl: true, - publicHost: 'www.example.com' + publicHost: 'www.example.com', }, logger ); @@ -332,8 +332,8 @@ describe('getDevServerConfig', () => { ...buildInput, optimization: { scripts: true, - styles: true - } + styles: true, + }, }, serveInput, logger @@ -343,7 +343,7 @@ describe('getDevServerConfig', () => { }); it('should configure it with the key and cert provided when on', () => { - spyOn(fs, 'readFileSync').and.callFake(path => { + spyOn(fs, 'readFileSync').and.callFake((path) => { if (path.endsWith('ssl.key')) { return 'sslKeyContents'; } else if (path.endsWith('ssl.cert')) { @@ -359,14 +359,14 @@ describe('getDevServerConfig', () => { ...serveInput, ssl: true, sslKey: 'ssl.key', - sslCert: 'ssl.cert' + sslCert: 'ssl.cert', }, logger ) as any; expect(result.https).toEqual({ key: 'sslKeyContents', - cert: 'sslCertContents' + cert: 'sslCertContents', }); }); }); @@ -376,10 +376,10 @@ describe('getDevServerConfig', () => { jest.mock( join(root, 'proxy.conf'), () => ({ - proxyConfig: 'proxyConfig' + proxyConfig: 'proxyConfig', }), { - virtual: true + virtual: true, } ); @@ -389,13 +389,13 @@ describe('getDevServerConfig', () => { buildInput, { ...serveInput, - proxyConfig: 'proxy.conf' + proxyConfig: 'proxy.conf', }, logger ) as any; expect(result.proxy).toEqual({ - proxyConfig: 'proxyConfig' + proxyConfig: 'proxyConfig', }); }); }); @@ -408,7 +408,7 @@ describe('getDevServerConfig', () => { buildInput, { ...serveInput, - allowedHosts: 'host.com,subdomain.host.com' + allowedHosts: 'host.com,subdomain.host.com', }, logger ) as any; @@ -423,7 +423,7 @@ describe('getDevServerConfig', () => { buildInput, { ...serveInput, - allowedHosts: 'host.com' + allowedHosts: 'host.com', }, logger ) as any; @@ -454,7 +454,7 @@ describe('getDevServerConfig', () => { ) as any; const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin.options.workers).toEqual(1); }); @@ -471,7 +471,7 @@ describe('getDevServerConfig', () => { ) as any; const typeCheckerPlugin = result.plugins.find( - plugin => plugin instanceof ForkTsCheckerWebpackPlugin + (plugin) => plugin instanceof ForkTsCheckerWebpackPlugin ) as ForkTsCheckerWebpackPlugin; expect(typeCheckerPlugin.options.memoryLimit).toEqual(1024); }); diff --git a/packages/web/src/utils/devserver.config.ts b/packages/web/src/utils/devserver.config.ts index 672387cb43456..f783854e90fb8 100644 --- a/packages/web/src/utils/devserver.config.ts +++ b/packages/web/src/utils/devserver.config.ts @@ -1,6 +1,6 @@ import { Configuration as WebpackDevServerConfiguration, - HistoryApiFallbackConfig + HistoryApiFallbackConfig, } from 'webpack-dev-server'; import { readFileSync } from 'fs'; import * as path from 'path'; @@ -68,7 +68,7 @@ function getDevServerPartial( const { scripts: scriptsOptimization, - styles: stylesOptimization + styles: stylesOptimization, } = buildOptions.optimization as OptimizationOptions; const config: WebpackDevServerConfiguration = { @@ -78,22 +78,22 @@ function getDevServerPartial( historyApiFallback: { index: `${servePath}/${path.basename(buildOptions.index)}`, disableDotRule: true, - htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] + htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'], } as HistoryApiFallbackConfig, stats: false, compress: scriptsOptimization || stylesOptimization, https: options.ssl, overlay: { errors: !(scriptsOptimization || stylesOptimization), - warnings: false + warnings: false, }, watchOptions: { - poll: buildOptions.poll + poll: buildOptions.poll, }, public: options.publicHost, publicPath: servePath, contentBase: false, - allowedHosts: [] + allowedHosts: [], }; if (options.ssl && options.sslKey && options.sslCert) { @@ -114,7 +114,7 @@ function getDevServerPartial( function getSslConfig(root: string, options: WebDevServerOptions) { return { key: readFileSync(path.resolve(root, options.sslKey), 'utf-8'), - cert: readFileSync(path.resolve(root, options.sslCert), 'utf-8') + cert: readFileSync(path.resolve(root, options.sslCert), 'utf-8'), }; } diff --git a/packages/web/src/utils/hash-format.ts b/packages/web/src/utils/hash-format.ts index 08668e32acfaf..a85e2cf1a3c84 100644 --- a/packages/web/src/utils/hash-format.ts +++ b/packages/web/src/utils/hash-format.ts @@ -15,14 +15,14 @@ export function getOutputHashFormat(option: string, length = 20): HashFormat { chunk: `.[chunkhash:${length}]`, extract: `.[contenthash:${length}]`, file: '', - script: `.[hash:${length}]` + script: `.[hash:${length}]`, }, all: { chunk: `.[chunkhash:${length}]`, extract: `.[contenthash:${length}]`, file: `.[hash:${length}]`, - script: `.[hash:${length}]` - } + script: `.[hash:${length}]`, + }, }; return hashFormats[option] || hashFormats['none']; } diff --git a/packages/web/src/utils/normalize.spec.ts b/packages/web/src/utils/normalize.spec.ts index 355300007e8d8..0087c1b8e1515 100644 --- a/packages/web/src/utils/normalize.spec.ts +++ b/packages/web/src/utils/normalize.spec.ts @@ -17,16 +17,16 @@ describe('normalizeBuildOptions', () => { fileReplacements: [ { replace: 'apps/environment/environment.ts', - with: 'apps/environment/environment.prod.ts' + with: 'apps/environment/environment.prod.ts', }, { replace: 'module1.ts', - with: 'module2.ts' - } + with: 'module2.ts', + }, ], assets: [], statsJson: false, - webpackConfig: 'apps/nodeapp/webpack.config' + webpackConfig: 'apps/nodeapp/webpack.config', }; root = '/root'; sourceRoot = normalize('apps/nodeapp/src'); @@ -49,7 +49,7 @@ describe('normalizeBuildOptions', () => { it('should normalize asset patterns', () => { spyOn(fs, 'statSync').and.returnValue({ - isDirectory: () => true + isDirectory: () => true, }); const result = normalizeBuildOptions( { @@ -61,9 +61,9 @@ describe('normalizeBuildOptions', () => { input: 'outsideproj', output: 'output', glob: '**/*', - ignore: ['**/*.json'] - } - ] + ignore: ['**/*.json'], + }, + ], }, root, sourceRoot @@ -72,14 +72,14 @@ describe('normalizeBuildOptions', () => { { input: '/root/apps/nodeapp/src/assets', output: 'assets', - glob: '**/*' + glob: '**/*', }, { input: '/root/outsideproj', output: 'output', glob: '**/*', - ignore: ['**/*.json'] - } + ignore: ['**/*.json'], + }, ]); }); @@ -88,12 +88,12 @@ describe('normalizeBuildOptions', () => { expect(result.fileReplacements).toEqual([ { replace: '/root/apps/environment/environment.ts', - with: '/root/apps/environment/environment.prod.ts' + with: '/root/apps/environment/environment.prod.ts', }, { replace: '/root/module1.ts', - with: '/root/module2.ts' - } + with: '/root/module2.ts', + }, ]); }); @@ -104,7 +104,7 @@ describe('normalizeBuildOptions', () => { result = normalizeBuildOptions( { ...testOptions, - webpackConfig: 'react' // something that exists in node_modules + webpackConfig: 'react', // something that exists in node_modules }, root, sourceRoot @@ -126,7 +126,7 @@ describe('normalizeBundleOptions', () => { entryFile: 'apps/nodeapp/src/main.ts', tsConfig: 'apps/nodeapp/tsconfig.app.json', babelConfig: 'apps/nodeapp/babel.config', - rollupConfig: 'apps/nodeapp/rollup.config' + rollupConfig: 'apps/nodeapp/rollup.config', }; root = '/root'; sourceRoot = normalize('apps/nodeapp/src'); @@ -142,7 +142,7 @@ describe('normalizeBundleOptions', () => { ...testOptions, // something that exists in node_modules rollupConfig: 'react', - babelConfig: 'react' + babelConfig: 'react', }, root ); diff --git a/packages/web/src/utils/normalize.ts b/packages/web/src/utils/normalize.ts index 8505901e08c02..ca8fe3bd9e58b 100644 --- a/packages/web/src/utils/normalize.ts +++ b/packages/web/src/utils/normalize.ts @@ -31,7 +31,7 @@ export function normalizeBundleOptions( entryRoot, project, projectRoot, - outputPath + outputPath, }; } @@ -47,7 +47,7 @@ export function normalizeBuildOptions( tsConfig: resolve(root, options.tsConfig), fileReplacements: normalizeFileReplacements(root, options.fileReplacements), assets: normalizeAssets(options.assets, root, sourceRoot), - webpackConfig: normalizePluginPath(options.webpackConfig, root) + webpackConfig: normalizePluginPath(options.webpackConfig, root), }; } @@ -67,7 +67,7 @@ function normalizeAssets( root: string, sourceRoot: string ): any[] { - return assets.map(asset => { + return assets.map((asset) => { if (typeof asset === 'string') { const assetPath = normalize(asset); const resolvedAssetPath = resolve(root, assetPath); @@ -88,7 +88,7 @@ function normalizeAssets( return { input, output, - glob + glob, }; } else { if (asset.output.startsWith('..')) { @@ -103,7 +103,7 @@ function normalizeAssets( ...asset, input: resolvedAssetPath, // Now we remove starting slash to make Webpack place it from the output root. - output: asset.output.replace(/^\//, '') + output: asset.output.replace(/^\//, ''), }; } }); @@ -113,9 +113,9 @@ function normalizeFileReplacements( root: string, fileReplacements: FileReplacement[] ): FileReplacement[] { - return fileReplacements.map(fileReplacement => ({ + return fileReplacements.map((fileReplacement) => ({ replace: resolve(root, fileReplacement.replace), - with: resolve(root, fileReplacement.with) + with: resolve(root, fileReplacement.with), })); } @@ -130,7 +130,7 @@ export function normalizeWebBuildOptions( typeof options.optimization !== 'object' ? { scripts: options.optimization, - styles: options.optimization + styles: options.optimization, } : options.optimization, sourceMap: @@ -140,12 +140,12 @@ export function normalizeWebBuildOptions( scripts: options.sourceMap, styles: options.sourceMap, hidden: false, - vendors: false + vendors: false, }, polyfills: options.polyfills ? resolve(root, options.polyfills) : undefined, es2015Polyfills: options.es2015Polyfills ? resolve(root, options.es2015Polyfills) - : undefined + : undefined, }; } @@ -157,6 +157,6 @@ export function convertBuildOptions(buildOptions: WebBuildBuilderOptions): any { aot: false, forkTypeChecker: false, lazyModules: [] as string[], - assets: [] as string[] + assets: [] as string[], }; } diff --git a/packages/web/src/utils/serve-path.ts b/packages/web/src/utils/serve-path.ts index bfce3d9b4c53c..a97502f5c0d5c 100644 --- a/packages/web/src/utils/serve-path.ts +++ b/packages/web/src/utils/serve-path.ts @@ -33,7 +33,9 @@ export function _findDefaultServePath( // normalize baseHref // for nx serve the starting base is always `/` so a relative // and root relative value are identical - const baseHrefParts = (baseHref || '').split('/').filter(part => part !== ''); + const baseHrefParts = (baseHref || '') + .split('/') + .filter((part) => part !== ''); if (baseHref && !baseHref.endsWith('/')) { baseHrefParts.pop(); } diff --git a/packages/web/src/utils/third-party/browser/schema.ts b/packages/web/src/utils/third-party/browser/schema.ts index ac80a6b48e1e2..5293372b26fa0 100644 --- a/packages/web/src/utils/third-party/browser/schema.ts +++ b/packages/web/src/utils/third-party/browser/schema.ts @@ -300,7 +300,7 @@ export enum Type { AnyComponentStyle = 'anyComponentStyle', AnyScript = 'anyScript', Bundle = 'bundle', - Initial = 'initial' + Initial = 'initial', } /** @@ -309,7 +309,7 @@ export enum Type { export enum CrossOrigin { Anonymous = 'anonymous', None = 'none', - UseCredentials = 'use-credentials' + UseCredentials = 'use-credentials', } export interface FileReplacement { @@ -325,7 +325,7 @@ export interface FileReplacement { export enum I18NMissingTranslation { Error = 'error', Ignore = 'ignore', - Warning = 'warning' + Warning = 'warning', } /** @@ -370,7 +370,7 @@ export enum OutputHashing { All = 'all', Bundles = 'bundles', Media = 'media', - None = 'none' + None = 'none', } export type ExtraEntryPoint = ExtraEntryPointClass | string; diff --git a/packages/web/src/utils/third-party/cli-files/models/build-options.ts b/packages/web/src/utils/third-party/cli-files/models/build-options.ts index c5c45cfa7e8f3..4ee1706c1d98a 100644 --- a/packages/web/src/utils/third-party/cli-files/models/build-options.ts +++ b/packages/web/src/utils/third-party/cli-files/models/build-options.ts @@ -15,7 +15,7 @@ import { Budget, ExtraEntryPoint, OptimizationClass, - SourceMapClass + SourceMapClass, } from '../../browser/schema'; import { NormalizedFileReplacement } from '../../utils/normalize-file-replacements'; diff --git a/packages/web/src/utils/third-party/cli-files/models/safari-nomodule.js b/packages/web/src/utils/third-party/cli-files/models/safari-nomodule.js index 0e01bcddc8d66..3ed244256f3a9 100644 --- a/packages/web/src/utils/third-party/cli-files/models/safari-nomodule.js +++ b/packages/web/src/utils/third-party/cli-files/models/safari-nomodule.js @@ -1,10 +1,10 @@ -(function() { +(function () { var check = document.createElement('script'); if (!('noModule' in check) && 'onbeforeload' in check) { var support = false; document.addEventListener( 'beforeload', - function(e) { + function (e) { if (e.target === check) { support = true; } else if (!e.target.hasAttribute('nomodule') || !support) { diff --git a/packages/web/src/utils/third-party/cli-files/models/webpack-configs/browser.ts b/packages/web/src/utils/third-party/cli-files/models/webpack-configs/browser.ts index 8e771e06ed451..87a90ae99df23 100644 --- a/packages/web/src/utils/third-party/cli-files/models/webpack-configs/browser.ts +++ b/packages/web/src/utils/third-party/cli-files/models/webpack-configs/browser.ts @@ -11,7 +11,7 @@ import { WebpackConfigOptions } from '../build-options'; import { getSourceMapDevTool, isPolyfillsEntry, - normalizeExtraEntryPoints + normalizeExtraEntryPoints, } from './utils'; const SubresourceIntegrityPlugin = require('webpack-subresource-integrity'); @@ -25,12 +25,12 @@ export function getBrowserConfig( let isEval = false; const { styles: stylesOptimization, - scripts: scriptsOptimization + scripts: scriptsOptimization, } = buildOptions.optimization; const { styles: stylesSourceMap, scripts: scriptsSourceMap, - hidden: hiddenSourceMap + hidden: hiddenSourceMap, } = buildOptions.sourceMap; // See https://webpack.js.org/configuration/devtool/ for sourcemap types. @@ -47,7 +47,7 @@ export function getBrowserConfig( if (buildOptions.subresourceIntegrity) { extraPlugins.push( new SubresourceIntegrityPlugin({ - hashFuncNames: ['sha384'] + hashFuncNames: ['sha384'], }) ); } @@ -57,10 +57,10 @@ export function getBrowserConfig( new LicenseWebpackPlugin({ stats: { warnings: false, - errors: false + errors: false, }, perChunkOutput: false, - outputFilename: `3rdpartylicenses.txt` + outputFilename: `3rdpartylicenses.txt`, }) ); } @@ -78,7 +78,7 @@ export function getBrowserConfig( const globalStylesBundleNames = normalizeExtraEntryPoints( buildOptions.styles, 'styles' - ).map(style => style.bundleName); + ).map((style) => style.bundleName); return { devtool: isEval ? 'eval' : false, @@ -87,13 +87,13 @@ export function getBrowserConfig( ...(wco.supportES2015 ? ['es2015'] : []), 'browser', 'module', - 'main' - ] + 'main', + ], }, output: { crossOriginLoading: buildOptions.subresourceIntegrity ? 'anonymous' - : false + : false, }, optimization: { runtimeChunk: 'single', @@ -103,14 +103,14 @@ export function getBrowserConfig( default: !!buildOptions.commonChunk && { chunks: 'async', minChunks: 2, - priority: 10 + priority: 10, }, common: !!buildOptions.commonChunk && { name: 'common', chunks: 'async', minChunks: 2, enforce: true, - priority: 5 + priority: 5, }, vendors: false, vendor: !!buildOptions.vendorChunk && { @@ -133,12 +133,12 @@ export function getBrowserConfig( globalStylesBundleNames.includes(name) ) ); - } - } - } - } + }, + }, + }, + }, }, plugins: extraPlugins, - node: false + node: false, }; } diff --git a/packages/web/src/utils/third-party/cli-files/models/webpack-configs/common.ts b/packages/web/src/utils/third-party/cli-files/models/webpack-configs/common.ts index cd2985c74957f..6eb621b9e9041 100644 --- a/packages/web/src/utils/third-party/cli-files/models/webpack-configs/common.ts +++ b/packages/web/src/utils/third-party/cli-files/models/webpack-configs/common.ts @@ -7,7 +7,7 @@ */ import { BuildOptimizerWebpackPlugin, - buildOptimizerLoaderPath + buildOptimizerLoaderPath, } from '@angular-devkit/build-optimizer'; import { tags } from '@angular-devkit/core'; import * as CopyWebpackPlugin from 'copy-webpack-plugin'; @@ -19,7 +19,7 @@ import { ContextReplacementPlugin, HashedModuleIdsPlugin, compilation, - debug + debug, } from 'webpack'; import { RawSource } from 'webpack-sources'; import { AssetPatternClass, ExtraEntryPoint } from '../../../browser/schema'; @@ -34,17 +34,17 @@ import { WebpackConfigOptions } from '../build-options'; import { getEsVersionForFileName, getOutputHashFormat, - normalizeExtraEntryPoints + normalizeExtraEntryPoints, } from './utils'; export const GLOBAL_DEFS_FOR_TERSER = { ngDevMode: false, - ngI18nClosureMode: false + ngI18nClosureMode: false, }; export const GLOBAL_DEFS_FOR_TERSER_WITH_AOT = { ...GLOBAL_DEFS_FOR_TERSER, - ngJitMode: false + ngJitMode: false, }; const ProgressPlugin = require('webpack/lib/ProgressPlugin'); @@ -59,12 +59,12 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { const { root, projectRoot, buildOptions, tsConfig } = wco; const { styles: stylesOptimization, - scripts: scriptsOptimization + scripts: scriptsOptimization, } = buildOptions.optimization; const { styles: stylesSourceMap, scripts: scriptsSourceMap, - vendor: vendorSourceMap + vendor: vendorSourceMap, } = buildOptions.sourceMap; const nodeModules = findUp('node_modules', projectRoot); @@ -111,7 +111,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { if (buildBrowserFeatures.isNoModulePolyfillNeeded()) { const noModuleScript: ExtraEntryPoint = { bundleName: 'polyfills-nomodule-es5', - input: path.join(__dirname, '..', 'safari-nomodule.js') + input: path.join(__dirname, '..', 'safari-nomodule.js'), }; buildOptions.scripts = buildOptions.scripts ? [...buildOptions.scripts, noModuleScript] @@ -126,7 +126,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { : 'polyfills-es5'; entryPoints[polyfillsChunkName] = [ - path.join(__dirname, '..', 'es5-polyfills.js') + path.join(__dirname, '..', 'es5-polyfills.js'), ]; if (!fullDifferential && differentialLoadingNeeded) { // Add zone.js legacy support to the es5 polyfills @@ -156,14 +156,14 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { if (buildOptions.polyfills) { entryPoints['polyfills'] = [ ...(entryPoints['polyfills'] || []), - path.resolve(root, buildOptions.polyfills) + path.resolve(root, buildOptions.polyfills), ]; } if (!buildOptions.aot) { entryPoints['polyfills'] = [ ...(entryPoints['polyfills'] || []), - path.join(__dirname, '..', 'jit-polyfills.js') + path.join(__dirname, '..', 'jit-polyfills.js'), ]; } } @@ -174,7 +174,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { outputPath: path.resolve( root, `chrome-profiler-events${targetInFileName}.json` - ) + ), }) ); } @@ -193,7 +193,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { ) => { const bundleName = curr.bundleName; const resolvedPath = path.resolve(root, curr.input); - const existingEntry = prev.find(el => el.bundleName === bundleName); + const existingEntry = prev.find((el) => el.bundleName === bundleName); if (existingEntry) { if (existingEntry.inject && !curr.inject) { // All entries have to be lazy for the bundle to be lazy. @@ -207,7 +207,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { prev.push({ bundleName, paths: [resolvedPath], - inject: curr.inject + inject: curr.inject, }); } @@ -218,7 +218,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { if (globalScriptsByBundleName.length > 0) { // Add a new asset for each entry. - globalScriptsByBundleName.forEach(script => { + globalScriptsByBundleName.forEach((script) => { // Lazy scripts don't get a hash, otherwise they can't be loaded by name. const hash = script.inject ? hashFormat.script : ''; const bundleName = script.bundleName; @@ -229,7 +229,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { sourceMap: scriptsSourceMap, filename: `${path.basename(bundleName)}${hash}.js`, scripts: script.paths, - basePath: projectRoot + basePath: projectRoot, }) ); }); @@ -261,14 +261,14 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { ignore: asset.ignore, from: { glob: asset.glob, - dot: true - } + dot: true, + }, }; } ); const copyWebpackPluginOptions = { - ignore: ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'] + ignore: ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'], }; const copyWebpackPluginInstance = new CopyWebpackPlugin( @@ -285,7 +285,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { if (buildOptions.showCircularDependencies) { extraPlugins.push( new CircularDependencyPlugin({ - exclude: /([\\\/]node_modules[\\\/])|(ngfactory\.js$)/ + exclude: /([\\\/]node_modules[\\\/])|(ngfactory\.js$)/, }) ); } @@ -294,7 +294,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { extraPlugins.push( new (class { apply(compiler: Compiler) { - compiler.hooks.emit.tap('angular-cli-stats', compilation => { + compiler.hooks.emit.tap('angular-cli-stats', (compilation) => { const data = JSON.stringify( compilation.getStats().toJson('verbose') ); @@ -316,9 +316,9 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { sourceMapUseRule = { use: [ { - loader: 'source-map-loader' - } - ] + loader: 'source-map-loader', + }, + ], }; } @@ -329,9 +329,9 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { use: [ { loader: buildOptimizerLoaderPath, - options: { sourceMap: scriptsSourceMap } - } - ] + options: { sourceMap: scriptsSourceMap }, + }, + ], }; } @@ -349,7 +349,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { ? 'rxjs/_esm2015/path-mapping' : 'rxjs/_esm5/path-mapping'; const rxPaths = require(require.resolve(rxjsPathMappingImport, { - paths: [projectRoot] + paths: [projectRoot], })); alias = rxPaths(nodeModules); } catch {} @@ -360,7 +360,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { new CleanCssWebpackPlugin({ sourceMap: stylesSourceMap, // component styles retain their original file name - test: file => /\.(?:css|scss|sass|less|styl)$/.test(file) + test: (file) => /\.(?:css|scss|sass|less|styl)$/.test(file), }) ); } @@ -368,7 +368,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { if (scriptsOptimization) { let angularGlobalDefinitions = { ngDevMode: false, - ngI18nClosureMode: false + ngI18nClosureMode: false, }; if (GLOBAL_DEFS_FOR_TERSER) { @@ -380,7 +380,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { if (GLOBAL_DEFS_FOR_TERSER_WITH_AOT) { angularGlobalDefinitions = { ...angularGlobalDefinitions, - ...GLOBAL_DEFS_FOR_TERSER_WITH_AOT + ...GLOBAL_DEFS_FOR_TERSER_WITH_AOT, }; } } @@ -394,7 +394,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { output: { ecma: terserEcma, comments: false, - webkit: true + webkit: true, }, // On server, we don't want to compress anything. We still set the ngDevMode = false for it // to remove dev code, and ngI18nClosureMode to remove Closure compiler i18n code @@ -403,7 +403,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { ? { ecma: terserEcma, global_defs: angularGlobalDefinitions, - keep_fnames: true + keep_fnames: true, } : { ecma: terserEcma, @@ -411,7 +411,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { // PURE comments work best with 3 passes. // See https://github.com/webpack/webpack/issues/2899#issuecomment-317425926. passes: buildOptions.buildOptimizer ? 3 : 1, - global_defs: angularGlobalDefinitions + global_defs: angularGlobalDefinitions, }, // We also want to avoid mangling on server. // Name mangling is handled within the browser builder @@ -419,7 +419,7 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { !manglingDisabled && buildOptions.platform !== 'server' && (!differentialLoadingNeeded || - (differentialLoadingNeeded && fullDifferential)) + (differentialLoadingNeeded && fullDifferential)), }; extraMinimizers.push( @@ -428,8 +428,8 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { parallel: true, cache: true, chunkFilter: (chunk: compilation.Chunk) => - !globalScriptsByBundleName.some(s => s.bundleName === chunk.name), - terserOptions + !globalScriptsByBundleName.some((s) => s.bundleName === chunk.name), + terserOptions, }), // Script bundles are fully optimized here in one step since they are never downleveled. // They are shared between ES2015 & ES5 outputs so must support ES5. @@ -438,19 +438,19 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { parallel: true, cache: true, chunkFilter: (chunk: compilation.Chunk) => - globalScriptsByBundleName.some(s => s.bundleName === chunk.name), + globalScriptsByBundleName.some((s) => s.bundleName === chunk.name), terserOptions: { ...terserOptions, compress: { ...terserOptions.compress, - ecma: 5 + ecma: 5, }, output: { ...terserOptions.output, - ecma: 5 + ecma: 5, }, - mangle: !manglingDisabled && buildOptions.platform !== 'server' - } + mangle: !manglingDisabled && buildOptions.platform !== 'server', + }, }) ); } @@ -464,10 +464,10 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { extensions: ['.ts', '.tsx', '.mjs', '.js'], symlinks: !buildOptions.preserveSymlinks, modules: [wco.tsConfig.options.baseUrl || projectRoot, 'node_modules'], - alias + alias, }, resolveLoader: { - modules: loaderNodeModules + modules: loaderNodeModules, }, context: projectRoot, entry: entryPoints, @@ -475,14 +475,14 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { futureEmitAssets: true, path: path.resolve(root, buildOptions.outputPath as string), publicPath: buildOptions.deployUrl, - filename: `[name]${targetInFileName}${hashFormat.chunk}.js` + filename: `[name]${targetInFileName}${hashFormat.chunk}.js`, }, watch: buildOptions.watch, watchOptions: { - poll: buildOptions.poll + poll: buildOptions.poll, }, performance: { - hints: false + hints: false, }, module: { // Show an error for missing exports instead of a warning. @@ -492,30 +492,30 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { test: /\.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/, loader: 'file-loader', options: { - name: `[name]${hashFormat.file}.[ext]` - } + name: `[name]${hashFormat.file}.[ext]`, + }, }, { test: /[\/\\]hot[\/\\]emitter\.js$/, - parser: { node: { events: true } } + parser: { node: { events: true } }, }, { test: /[\/\\]webpack-dev-server[\/\\]client[\/\\]utils[\/\\]createSocketUrl\.js$/, - parser: { node: { querystring: true } } + parser: { node: { querystring: true } }, }, { test: /\.js$/, // Factory files are processed by BO in the rules added in typescript.ts. exclude: /(ngfactory|ngstyle)\.js$/, - ...buildOptimizerUseRule + ...buildOptimizerUseRule, }, { test: /\.js$/, exclude: /(ngfactory|ngstyle)\.js$/, enforce: 'pre', - ...sourceMapUseRule - } - ] + ...sourceMapUseRule, + }, + ], }, optimization: { noEmitOnErrors: true, @@ -523,15 +523,15 @@ export function getCommonConfig(wco: WebpackConfigOptions): Configuration { new HashedModuleIdsPlugin(), // TODO: check with Mike what this feature needs. new BundleBudgetPlugin({ budgets: buildOptions.budgets }), - ...extraMinimizers - ] + ...extraMinimizers, + ], }, plugins: [ // Always replace the context for the System.import in angular/core to prevent warnings. // https://github.com/angular/angular/issues/11580 // With VE the correct context is added in @ngtools/webpack, but Ivy doesn't need it at all. new ContextReplacementPlugin(/\@angular(\\|\/)core(\\|\/)/), - ...extraPlugins - ] + ...extraPlugins, + ], }; } diff --git a/packages/web/src/utils/third-party/cli-files/models/webpack-configs/styles.ts b/packages/web/src/utils/third-party/cli-files/models/webpack-configs/styles.ts index b5573474b2303..ec06da6fe0c27 100644 --- a/packages/web/src/utils/third-party/cli-files/models/webpack-configs/styles.ts +++ b/packages/web/src/utils/third-party/cli-files/models/webpack-configs/styles.ts @@ -12,7 +12,7 @@ import { PostcssCliResources, RawCssLoader, RemoveHashPlugin, - SuppressExtractedTextChunksWebpackPlugin + SuppressExtractedTextChunksWebpackPlugin, } from '../../plugins/webpack'; import { WebpackConfigOptions } from '../build-options'; import { getOutputHashFormat, normalizeExtraEntryPoints } from './utils'; @@ -46,7 +46,7 @@ export function getStylesConfig(wco: WebpackConfigOptions) { // Determine hashing format. const hashFormat = getOutputHashFormat(buildOptions.outputHashing as string); - const postcssPluginCreator = function(loader: webpack.loader.LoaderContext) { + const postcssPluginCreator = function (loader: webpack.loader.LoaderContext) { return [ postcssImports({ resolve: (url: string) => (url.startsWith('~') ? url.substr(1) : url), @@ -63,7 +63,7 @@ export function getStylesConfig(wco: WebpackConfigOptions) { resolve(content); }); }); - } + }, }), PostcssCliResources({ baseHref: buildOptions.baseHref, @@ -71,9 +71,9 @@ export function getStylesConfig(wco: WebpackConfigOptions) { resourcesOutputPath: buildOptions.resourcesOutputPath, loader, rebaseRootRelative: buildOptions.rebaseRootRelativeCssUrls, - filename: `[name]${hashFormat.file}.[ext]` + filename: `[name]${hashFormat.file}.[ext]`, }), - autoprefixer() + autoprefixer(), ]; }; @@ -91,7 +91,7 @@ export function getStylesConfig(wco: WebpackConfigOptions) { includePaths.push(path.resolve(root, includePath)) ); lessPathOptions = { - paths: includePaths + paths: includePaths, }; } @@ -99,23 +99,25 @@ export function getStylesConfig(wco: WebpackConfigOptions) { if (buildOptions.styles.length > 0) { const chunkNames: string[] = []; - normalizeExtraEntryPoints(buildOptions.styles, 'styles').forEach(style => { - const resolvedPath = path.resolve(root, style.input); - // Add style entry points. - if (entryPoints[style.bundleName]) { - entryPoints[style.bundleName].push(resolvedPath); - } else { - entryPoints[style.bundleName] = [resolvedPath]; - } + normalizeExtraEntryPoints(buildOptions.styles, 'styles').forEach( + (style) => { + const resolvedPath = path.resolve(root, style.input); + // Add style entry points. + if (entryPoints[style.bundleName]) { + entryPoints[style.bundleName].push(resolvedPath); + } else { + entryPoints[style.bundleName] = [resolvedPath]; + } - // Add non injected styles to the list. - if (!style.inject) { - chunkNames.push(style.bundleName); - } + // Add non injected styles to the list. + if (!style.inject) { + chunkNames.push(style.bundleName); + } - // Add global css paths. - globalStylePaths.push(resolvedPath); - }); + // Add global css paths. + globalStylePaths.push(resolvedPath); + } + ); if (chunkNames.length > 0) { // Add plugin to remove hashes from lazy styles. @@ -151,10 +153,10 @@ export function getStylesConfig(wco: WebpackConfigOptions) { sourceMap: cssSourceMap, // bootstrap-sass requires a minimum precision of 8 precision: 8, - includePaths - } - } - ] + includePaths, + }, + }, + ], }, { test: /\.less$/, @@ -164,10 +166,10 @@ export function getStylesConfig(wco: WebpackConfigOptions) { options: { sourceMap: cssSourceMap, javascriptEnabled: true, - ...lessPathOptions - } - } - ] + ...lessPathOptions, + }, + }, + ], }, { test: /\.styl$/, @@ -176,11 +178,11 @@ export function getStylesConfig(wco: WebpackConfigOptions) { loader: 'stylus-loader', options: { sourceMap: cssSourceMap, - paths: includePaths - } - } - ] - } + paths: includePaths, + }, + }, + ], + }, ]; // load component css as raw strings @@ -203,11 +205,11 @@ export function getStylesConfig(wco: WebpackConfigOptions) { // for component css. !buildOptions.sourceMap.hidden ? 'inline' - : false - } + : false, + }, }, - ...(use as webpack.Loader[]) - ] + ...(use as webpack.Loader[]), + ], })); // load global css as css files @@ -232,11 +234,11 @@ export function getStylesConfig(wco: WebpackConfigOptions) { !buildOptions.extractCss && !buildOptions.sourceMap.hidden ? 'inline' - : cssSourceMap - } + : cssSourceMap, + }, }, - ...(use as webpack.Loader[]) - ] + ...(use as webpack.Loader[]), + ], }; }) ); @@ -254,6 +256,6 @@ export function getStylesConfig(wco: WebpackConfigOptions) { return { entry: entryPoints, module: { rules }, - plugins: extraPlugins + plugins: extraPlugins, }; } diff --git a/packages/web/src/utils/third-party/cli-files/models/webpack-configs/utils.ts b/packages/web/src/utils/third-party/cli-files/models/webpack-configs/utils.ts index f7df21616c65e..3b8a3516ac7eb 100644 --- a/packages/web/src/utils/third-party/cli-files/models/webpack-configs/utils.ts +++ b/packages/web/src/utils/third-party/cli-files/models/webpack-configs/utils.ts @@ -28,14 +28,14 @@ export function getOutputHashFormat(option: string, length = 20): HashFormat { chunk: `.[chunkhash:${length}]`, extract: `.[contenthash:${length}]`, file: '', - script: `.[hash:${length}]` + script: `.[hash:${length}]`, }, all: { chunk: `.[chunkhash:${length}]`, extract: `.[contenthash:${length}]`, file: `.[hash:${length}]`, - script: `.[hash:${length}]` - } + script: `.[hash:${length}]`, + }, }; return hashFormats[option] || hashFormats['none']; } @@ -48,13 +48,13 @@ export function normalizeExtraEntryPoints( extraEntryPoints: ExtraEntryPoint[], defaultBundleName: string ): NormalizedEntryPoint[] { - return extraEntryPoints.map(entry => { + return extraEntryPoints.map((entry) => { let normalizedEntry; if (typeof entry === 'string') { normalizedEntry = { input: entry, inject: true, - bundleName: defaultBundleName + bundleName: defaultBundleName, }; } else { const { lazy, inject = true, ...newEntry } = entry; @@ -103,7 +103,7 @@ export function getSourceMapDevTool( // there is no way to set the 'webRoot' sourceRoot: inlineSourceMap ? '' : 'webpack:///', moduleFilenameTemplate: '[resource-path]', - append: hiddenSourceMap ? false : undefined + append: hiddenSourceMap ? false : undefined, }); } diff --git a/packages/web/src/utils/third-party/cli-files/plugins/bundle-budget.ts b/packages/web/src/utils/third-party/cli-files/plugins/bundle-budget.ts index 728b8544b1c43..f4a5e12d859f9 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/bundle-budget.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/bundle-budget.ts @@ -10,7 +10,7 @@ import { Budget, Type } from '../../browser/schema'; import { Size, calculateBytes, - calculateSizes + calculateSizes, } from '../utilities/bundle-calculator'; import { formatSize } from '../utilities/stats'; @@ -54,7 +54,7 @@ export class BundleBudgetPlugin { } const filteredBudgets = budgets.filter( - budget => budget.type === Type.AnyComponentStyle + (budget) => budget.type === Type.AnyComponentStyle ); this.runChecks(filteredBudgets, compilation); } @@ -66,7 +66,7 @@ export class BundleBudgetPlugin { 'BundleBudgetPlugin', (compilation: compilation.Compilation) => { const filteredBudgets = budgets.filter( - budget => budget.type !== Type.AnyComponentStyle + (budget) => budget.type !== Type.AnyComponentStyle ); this.runChecks(filteredBudgets, compilation); } @@ -170,13 +170,13 @@ export class BundleBudgetPlugin { private runChecks(budgets: Budget[], compilation: compilation.Compilation) { budgets - .map(budget => ({ + .map((budget) => ({ budget, thresholds: this.calculate(budget), - sizes: calculateSizes(budget, compilation) + sizes: calculateSizes(budget, compilation), })) - .forEach(budgetCheck => { - budgetCheck.sizes.forEach(size => { + .forEach((budgetCheck) => { + budgetCheck.sizes.forEach((size) => { this.checkMaximum( budgetCheck.thresholds.maximumWarning, size, diff --git a/packages/web/src/utils/third-party/cli-files/plugins/cleancss-webpack-plugin.ts b/packages/web/src/utils/third-party/cli-files/plugins/cleancss-webpack-plugin.ts index da86f37fa7a55..14d2aa0d6e4e3 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/cleancss-webpack-plugin.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/cleancss-webpack-plugin.ts @@ -26,7 +26,7 @@ function hook( (compilation: compilation.Compilation) => { compilation.hooks.optimizeChunkAssets.tapPromise( 'cleancss-webpack-plugin', - chunks => action(compilation, chunks) + (chunks) => action(compilation, chunks) ); } ); @@ -38,8 +38,8 @@ export class CleanCssWebpackPlugin { constructor(options: Partial) { this._options = { sourceMap: false, - test: file => file.endsWith('.css'), - ...options + test: (file) => file.endsWith('.css'), + ...options, }; } @@ -53,26 +53,26 @@ export class CleanCssWebpackPlugin { 2: { skipProperties: [ 'transition', // Fixes #12408 - 'font' // Fixes #9648 - ] - } + 'font', // Fixes #9648 + ], + }, }, inline: false, returnPromise: true, - sourceMap: this._options.sourceMap + sourceMap: this._options.sourceMap, }); const files: string[] = [...compilation.additionalChunkAssets]; - chunks.forEach(chunk => { + chunks.forEach((chunk) => { if (chunk.files && chunk.files.length > 0) { files.push(...chunk.files); } }); const actions = files - .filter(file => this._options.test(file)) - .map(async file => { + .filter((file) => this._options.test(file)) + .map(async (file) => { const asset = compilation.assets[file] as Source; if (!asset) { return; diff --git a/packages/web/src/utils/third-party/cli-files/plugins/index-html-webpack-plugin.ts b/packages/web/src/utils/third-party/cli-files/plugins/index-html-webpack-plugin.ts index aabaa3f84dd12..aa17874e2b026 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/index-html-webpack-plugin.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/index-html-webpack-plugin.ts @@ -11,7 +11,7 @@ import { RawSource } from 'webpack-sources'; import { CrossOriginValue, FileInfo, - augmentIndexHtml + augmentIndexHtml, } from '../utilities/index-file/augment-index-html'; import { IndexHtmlTransform } from '../utilities/index-file/write-index-html'; import { stripBom } from '../utilities/strip-bom'; @@ -60,14 +60,14 @@ export class IndexHtmlWebpackPlugin { noModuleEntrypoints: [], moduleEntrypoints: [], sri: false, - ...options + ...options, }; } apply(compiler: Compiler) { compiler.hooks.emit.tapPromise( 'index-html-webpack-plugin', - async compilation => { + async (compilation) => { // Get input html file const inputContent = await readFile(this._options.input, compilation); compilation.fileDependencies.add(this._options.input); @@ -85,7 +85,7 @@ export class IndexHtmlWebpackPlugin { (f: string): FileInfo => ({ name: entryName, file: f, - extension: path.extname(f) + extension: path.extname(f), }) ); @@ -111,7 +111,7 @@ export class IndexHtmlWebpackPlugin { noModuleFiles, loadOutputFile, moduleFiles, - entrypoints: this._options.entrypoints + entrypoints: this._options.entrypoints, }); if (this._options.postTransform) { diff --git a/packages/web/src/utils/third-party/cli-files/plugins/named-chunks-plugin.ts b/packages/web/src/utils/third-party/cli-files/plugins/named-chunks-plugin.ts index 190830d2efeb9..1865492e27362 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/named-chunks-plugin.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/named-chunks-plugin.ts @@ -16,26 +16,29 @@ const Template = require('webpack/lib/Template'); export class NamedLazyChunksPlugin { constructor() {} apply(compiler: Compiler): void { - compiler.hooks.compilation.tap('named-lazy-chunks-plugin', compilation => { - // The dependencyReference hook isn't in the webpack typings so we have to type it as any. - // tslint:disable-next-line: no-any - (compilation.hooks as any).dependencyReference.tap( - 'named-lazy-chunks-plugin', + compiler.hooks.compilation.tap( + 'named-lazy-chunks-plugin', + (compilation) => { + // The dependencyReference hook isn't in the webpack typings so we have to type it as any. // tslint:disable-next-line: no-any - (_: any, dependency: any) => { - if ( - // Check this dependency is from an `import()` statement. - dependency instanceof ImportDependency && - dependency.block instanceof ImportDependenciesBlock && - // Don't rename chunks that already have a name. - dependency.block.chunkName === null - ) { - // Convert the request to a valid chunk name using the same logic used - // in webpack/lib/ContextModule.js - dependency.block.chunkName = Template.toPath(dependency.request); + (compilation.hooks as any).dependencyReference.tap( + 'named-lazy-chunks-plugin', + // tslint:disable-next-line: no-any + (_: any, dependency: any) => { + if ( + // Check this dependency is from an `import()` statement. + dependency instanceof ImportDependency && + dependency.block instanceof ImportDependenciesBlock && + // Don't rename chunks that already have a name. + dependency.block.chunkName === null + ) { + // Convert the request to a valid chunk name using the same logic used + // in webpack/lib/ContextModule.js + dependency.block.chunkName = Template.toPath(dependency.request); + } } - } - ); - }); + ); + } + ); } } diff --git a/packages/web/src/utils/third-party/cli-files/plugins/postcss-cli-resources.ts b/packages/web/src/utils/third-party/cli-files/plugins/postcss-cli-resources.ts index c20e648611566..95bee6d022720 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/postcss-cli-resources.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/postcss-cli-resources.ts @@ -54,7 +54,7 @@ export default postcss.plugin( resourcesOutputPath = '', rebaseRootRelative = false, filename, - loader + loader, } = options; const dedupeSlashes = (url: string) => url.replace(/\/\/+/g, '/'); @@ -165,9 +165,9 @@ export default postcss.plugin( }); }; - return root => { + return (root) => { const urlDeclarations: Array = []; - root.walkDecls(decl => { + root.walkDecls((decl) => { if (decl.value && decl.value.includes('url')) { urlDeclarations.push(decl); } @@ -180,7 +180,7 @@ export default postcss.plugin( const resourceCache = new Map(); return Promise.all( - urlDeclarations.map(async decl => { + urlDeclarations.map(async (decl) => { const value = decl.value; const urlRegex = /url\(\s*(?:"([^"]+)"|'([^']+)'|(.+?))\s*\)/g; const segments: string[] = []; diff --git a/packages/web/src/utils/third-party/cli-files/plugins/raw-css-loader.ts b/packages/web/src/utils/third-party/cli-files/plugins/raw-css-loader.ts index 9f7ff68b30323..851bff7069126 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/raw-css-loader.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/raw-css-loader.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -export default function(content: string, map: object) { +export default function (content: string, map: object) { const stringifiedContent = JSON.stringify(content); const stringifiedMap = map ? JSON.stringify(map) : `''`; diff --git a/packages/web/src/utils/third-party/cli-files/plugins/remove-hash-plugin.ts b/packages/web/src/utils/third-party/cli-files/plugins/remove-hash-plugin.ts index 9d341ab60eed5..20887aabe1db5 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/remove-hash-plugin.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/remove-hash-plugin.ts @@ -17,7 +17,7 @@ export class RemoveHashPlugin { constructor(private options: RemoveHashPluginOptions) {} apply(compiler: Compiler): void { - compiler.hooks.compilation.tap('remove-hash-plugin', compilation => { + compiler.hooks.compilation.tap('remove-hash-plugin', (compilation) => { const mainTemplate = compilation.mainTemplate as compilation.MainTemplate & { hooks: compilation.CompilationHooks; }; diff --git a/packages/web/src/utils/third-party/cli-files/plugins/scripts-webpack-plugin.ts b/packages/web/src/utils/third-party/cli-files/plugins/scripts-webpack-plugin.ts index 576fe01eb65bd..299820100207d 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/scripts-webpack-plugin.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/scripts-webpack-plugin.ts @@ -21,7 +21,7 @@ import { ConcatSource, OriginalSource, RawSource, - Source + Source, } from 'webpack-sources'; import { interpolateName } from 'loader-utils'; import * as path from 'path'; @@ -111,8 +111,8 @@ export class ScriptsWebpackPlugin { } const scripts = this.options.scripts - .filter(script => !!script) - .map(script => path.resolve(this.options.basePath || '', script)); + .filter((script) => !!script) + .map((script) => path.resolve(this.options.basePath || '', script)); hook(compiler, (compilation, callback) => { if (this.shouldSkip(compilation, scripts)) { @@ -126,7 +126,7 @@ export class ScriptsWebpackPlugin { return; } - const sourceGetters = scripts.map(fullPath => { + const sourceGetters = scripts.map((fullPath) => { return new Promise((resolve, reject) => { compilation.inputFileSystem.readFile( fullPath, @@ -158,9 +158,9 @@ export class ScriptsWebpackPlugin { }); Promise.all(sourceGetters) - .then(sources => { + .then((sources) => { const concatSource = new ConcatSource(); - sources.forEach(source => { + sources.forEach((source) => { concatSource.add(source); concatSource.add('\n;'); }); diff --git a/packages/web/src/utils/third-party/cli-files/plugins/webpack.ts b/packages/web/src/utils/third-party/cli-files/plugins/webpack.ts index 58308cc639d4e..09866a02d40ad 100644 --- a/packages/web/src/utils/third-party/cli-files/plugins/webpack.ts +++ b/packages/web/src/utils/third-party/cli-files/plugins/webpack.ts @@ -9,26 +9,22 @@ // Exports the webpack plugins we use internally. export { CleanCssWebpackPlugin, - CleanCssWebpackPluginOptions + CleanCssWebpackPluginOptions, } from './cleancss-webpack-plugin'; export { BundleBudgetPlugin, BundleBudgetPluginOptions } from './bundle-budget'; export { ScriptsWebpackPlugin, - ScriptsWebpackPluginOptions + ScriptsWebpackPluginOptions, } from './scripts-webpack-plugin'; -export { - SuppressExtractedTextChunksWebpackPlugin -} from './suppress-entry-chunks-webpack-plugin'; +export { SuppressExtractedTextChunksWebpackPlugin } from './suppress-entry-chunks-webpack-plugin'; export { RemoveHashPlugin, - RemoveHashPluginOptions + RemoveHashPluginOptions, } from './remove-hash-plugin'; -export { - NamedLazyChunksPlugin as NamedChunksPlugin -} from './named-chunks-plugin'; +export { NamedLazyChunksPlugin as NamedChunksPlugin } from './named-chunks-plugin'; export { default as PostcssCliResources, - PostcssCliResourcesOptions + PostcssCliResourcesOptions, } from './postcss-cli-resources'; import { join } from 'path'; diff --git a/packages/web/src/utils/third-party/cli-files/utilities/bundle-calculator.ts b/packages/web/src/utils/third-party/cli-files/utilities/bundle-calculator.ts index b5bbc57bbf6e2..dee76288f465d 100644 --- a/packages/web/src/utils/third-party/cli-files/utilities/bundle-calculator.ts +++ b/packages/web/src/utils/third-party/cli-files/utilities/bundle-calculator.ts @@ -30,7 +30,7 @@ export function calculateSizes( anyScript: AnyScriptCalculator, anyComponentStyle: AnyComponentStyleCalculator, bundle: BundleCalculator, - initial: InitialCalculator + initial: InitialCalculator, }; const ctor = calculatorMap[budget.type]; @@ -51,7 +51,7 @@ export abstract class Calculator { class BundleCalculator extends Calculator { calculate() { const size: number = this.compilation.chunks - .filter(chunk => chunk.name === this.budget.name) + .filter((chunk) => chunk.name === this.budget.name) .reduce((files, chunk) => [...files, ...chunk.files], []) .filter((file: string) => !file.endsWith('.map')) .map((file: string) => this.compilation.assets[file].size()) @@ -66,7 +66,7 @@ class BundleCalculator extends Calculator { */ class InitialCalculator extends Calculator { calculate() { - const initialChunks = this.compilation.chunks.filter(chunk => + const initialChunks = this.compilation.chunks.filter((chunk) => chunk.isOnlyInitial() ); const size: number = initialChunks @@ -85,9 +85,9 @@ class InitialCalculator extends Calculator { class AllScriptCalculator extends Calculator { calculate() { const size: number = Object.keys(this.compilation.assets) - .filter(key => key.endsWith('.js')) - .map(key => this.compilation.assets[key]) - .map(asset => asset.size()) + .filter((key) => key.endsWith('.js')) + .map((key) => this.compilation.assets[key]) + .map((asset) => asset.size()) .reduce((total: number, size: number) => total + size, 0); return [{ size, label: 'total scripts' }]; @@ -100,8 +100,8 @@ class AllScriptCalculator extends Calculator { class AllCalculator extends Calculator { calculate() { const size: number = Object.keys(this.compilation.assets) - .filter(key => !key.endsWith('.map')) - .map(key => this.compilation.assets[key].size()) + .filter((key) => !key.endsWith('.map')) + .map((key) => this.compilation.assets[key].size()) .reduce((total: number, size: number) => total + size, 0); return [{ size, label: 'total' }]; @@ -114,10 +114,10 @@ class AllCalculator extends Calculator { class AnyComponentStyleCalculator extends Calculator { calculate() { return Object.keys(this.compilation.assets) - .filter(key => key.endsWith('.css')) - .map(key => ({ + .filter((key) => key.endsWith('.css')) + .map((key) => ({ size: this.compilation.assets[key].size(), - label: key + label: key, })); } } @@ -128,13 +128,13 @@ class AnyComponentStyleCalculator extends Calculator { class AnyScriptCalculator extends Calculator { calculate() { return Object.keys(this.compilation.assets) - .filter(key => key.endsWith('.js')) - .map(key => { + .filter((key) => key.endsWith('.js')) + .map((key) => { const asset = this.compilation.assets[key]; return { size: asset.size(), - label: key + label: key, }; }); } @@ -146,13 +146,13 @@ class AnyScriptCalculator extends Calculator { class AnyCalculator extends Calculator { calculate() { return Object.keys(this.compilation.assets) - .filter(key => !key.endsWith('.map')) - .map(key => { + .filter((key) => !key.endsWith('.map')) + .map((key) => { const asset = this.compilation.assets[key]; return { size: asset.size(), - label: key + label: key, }; }); } diff --git a/packages/web/src/utils/third-party/cli-files/utilities/index-file/augment-index-html.ts b/packages/web/src/utils/third-party/cli-files/utilities/index-file/augment-index-html.ts index a7b8c2935d87d..3ee4cb42479d2 100644 --- a/packages/web/src/utils/third-party/cli-files/utilities/index-file/augment-index-html.ts +++ b/packages/web/src/utils/third-party/cli-files/utilities/index-file/augment-index-html.ts @@ -64,7 +64,7 @@ export async function augmentIndexHtml( files, noModuleFiles = [], moduleFiles = [], - entrypoints + entrypoints, } = params; let { crossOrigin = 'none' } = params; @@ -98,7 +98,7 @@ export async function augmentIndexHtml( const treeAdapter = parse5.treeAdapters.default; const document = parse5.parse(params.inputContent, { treeAdapter, - locationInfo: true + locationInfo: true, }); let headElement; let bodyElement; @@ -146,7 +146,7 @@ export async function augmentIndexHtml( let scriptElements = ''; for (const script of scripts) { const attrs: { name: string; value: string | null }[] = [ - { name: 'src', value: (params.deployUrl || '') + script } + { name: 'src', value: (params.deployUrl || '') + script }, ]; if (crossOrigin !== 'none') { @@ -183,7 +183,7 @@ export async function augmentIndexHtml( } const attributes = attrs - .map(attr => + .map((attr) => attr.value === null ? attr.name : `${attr.name}="${attr.value}"` ) .join(' '); @@ -205,7 +205,7 @@ export async function augmentIndexHtml( if (!baseElement) { baseElement = treeAdapter.createElement('base', undefined, [ - { name: 'href', value: params.baseHref } + { name: 'href', value: params.baseHref }, ]); treeAdapter.appendChild(baseFragment, baseElement); @@ -239,7 +239,7 @@ export async function augmentIndexHtml( for (const stylesheet of stylesheets) { const attrs = [ { name: 'rel', value: 'stylesheet' }, - { name: 'href', value: (params.deployUrl || '') + stylesheet } + { name: 'href', value: (params.deployUrl || '') + stylesheet }, ]; if (crossOrigin !== 'none') { @@ -265,9 +265,7 @@ export async function augmentIndexHtml( function _generateSriAttributes(content: string) { const algo = 'sha384'; - const hash = createHash(algo) - .update(content, 'utf8') - .digest('base64'); + const hash = createHash(algo).update(content, 'utf8').digest('base64'); return [{ name: 'integrity', value: `${algo}-${hash}` }]; } diff --git a/packages/web/src/utils/third-party/cli-files/utilities/index-file/augment-index-html_spec.ts b/packages/web/src/utils/third-party/cli-files/utilities/index-file/augment-index-html_spec.ts index 161ec718e5d8d..c8ba726b7c62b 100644 --- a/packages/web/src/utils/third-party/cli-files/utilities/index-file/augment-index-html_spec.ts +++ b/packages/web/src/utils/third-party/cli-files/utilities/index-file/augment-index-html_spec.ts @@ -9,7 +9,7 @@ import { tags } from '@angular-devkit/core'; import { AugmentIndexHtmlOptions, FileInfo, - augmentIndexHtml + augmentIndexHtml, } from './augment-index-html'; describe('augment-index-html', () => { @@ -20,7 +20,7 @@ describe('augment-index-html', () => { sri: false, files: [], loadOutputFile: async (_fileName: string) => '', - entrypoints: ['scripts', 'polyfills', 'main', 'styles'] + entrypoints: ['scripts', 'polyfills', 'main', 'styles'], }; const oneLineHtml = (html: TemplateStringsArray) => @@ -34,8 +34,8 @@ describe('augment-index-html', () => { { file: 'runtime.js', extension: '.js', name: 'main' }, { file: 'main.js', extension: '.js', name: 'main' }, { file: 'runtime.js', extension: '.js', name: 'polyfills' }, - { file: 'polyfills.js', extension: '.js', name: 'polyfills' } - ] + { file: 'polyfills.js', extension: '.js', name: 'polyfills' }, + ], }); const html = await source; @@ -58,24 +58,24 @@ describe('augment-index-html', () => { { file: 'runtime-es2015.js', extension: '.js', name: 'main' }, { file: 'main-es2015.js', extension: '.js', name: 'main' }, { file: 'runtime-es2015.js', extension: '.js', name: 'polyfills' }, - { file: 'polyfills-es2015.js', extension: '.js', name: 'polyfills' } + { file: 'polyfills-es2015.js', extension: '.js', name: 'polyfills' }, ]; const es5JsFiles: FileInfo[] = [ { file: 'runtime-es5.js', extension: '.js', name: 'main' }, { file: 'main-es5.js', extension: '.js', name: 'main' }, { file: 'runtime-es5.js', extension: '.js', name: 'polyfills' }, - { file: 'polyfills-es5.js', extension: '.js', name: 'polyfills' } + { file: 'polyfills-es5.js', extension: '.js', name: 'polyfills' }, ]; const source = augmentIndexHtml({ ...indexGeneratorOptions, files: [ { file: 'styles.css', extension: '.css', name: 'styles' }, - { file: 'styles.css', extension: '.css', name: 'styles' } + { file: 'styles.css', extension: '.css', name: 'styles' }, ], moduleFiles: es2015JsFiles, - noModuleFiles: es5JsFiles + noModuleFiles: es5JsFiles, }); const html = await source; @@ -100,22 +100,22 @@ describe('augment-index-html', () => { it(`should not add 'module' and 'non-module' attr to js files which are in both module formats`, async () => { const es2015JsFiles: FileInfo[] = [ { file: 'scripts.js', extension: '.js', name: 'scripts' }, - { file: 'main-es2015.js', extension: '.js', name: 'main' } + { file: 'main-es2015.js', extension: '.js', name: 'main' }, ]; const es5JsFiles: FileInfo[] = [ { file: 'scripts.js', extension: '.js', name: 'scripts' }, - { file: 'main-es5.js', extension: '.js', name: 'main' } + { file: 'main-es5.js', extension: '.js', name: 'main' }, ]; const source = augmentIndexHtml({ ...indexGeneratorOptions, files: [ { file: 'styles.css', extension: '.css', name: 'styles' }, - { file: 'styles.css', extension: '.css', name: 'styles' } + { file: 'styles.css', extension: '.css', name: 'styles' }, ], moduleFiles: es2015JsFiles, - noModuleFiles: es5JsFiles + noModuleFiles: es5JsFiles, }); const html = await source; diff --git a/packages/web/src/utils/third-party/cli-files/utilities/index-file/write-index-html.ts b/packages/web/src/utils/third-party/cli-files/utilities/index-file/write-index-html.ts index c6045446266f2..671f5334fa039 100644 --- a/packages/web/src/utils/third-party/cli-files/utilities/index-file/write-index-html.ts +++ b/packages/web/src/utils/third-party/cli-files/utilities/index-file/write-index-html.ts @@ -12,7 +12,7 @@ import { dirname, getSystemPath, join, - virtualFs + virtualFs, } from '@angular-devkit/core'; import { Observable, of } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; @@ -22,7 +22,7 @@ import { stripBom } from '../strip-bom'; import { CrossOriginValue, FileInfo, - augmentIndexHtml + augmentIndexHtml, } from './augment-index-html'; type ExtensionFilter = '.js' | '.css'; @@ -58,11 +58,11 @@ export function writeIndexHtml({ scripts = [], styles = [], postTransform, - crossOrigin + crossOrigin, }: WriteIndexHtmlOptions): Observable { return host.read(indexPath).pipe( - map(content => stripBom(virtualFs.fileBufferToString(content))), - switchMap(content => + map((content) => stripBom(virtualFs.fileBufferToString(content))), + switchMap((content) => augmentIndexHtml({ input: getSystemPath(outputPath), inputContent: content, @@ -74,19 +74,19 @@ export function writeIndexHtml({ files: filterAndMapBuildFiles(files, ['.js', '.css']), noModuleFiles: filterAndMapBuildFiles(noModuleFiles, '.js'), moduleFiles: filterAndMapBuildFiles(moduleFiles, '.js'), - loadOutputFile: async filePath => { + loadOutputFile: async (filePath) => { return host .read(join(dirname(outputPath), filePath)) - .pipe(map(data => virtualFs.fileBufferToString(data))) + .pipe(map((data) => virtualFs.fileBufferToString(data))) .toPromise(); - } + }, }) ), - switchMap(content => + switchMap((content) => postTransform ? postTransform(content) : of(content) ), - map(content => virtualFs.stringToFileBuffer(content)), - switchMap(content => host.write(outputPath, content)) + map((content) => virtualFs.stringToFileBuffer(content)), + switchMap((content) => host.write(outputPath, content)) ); } diff --git a/packages/web/src/utils/third-party/cli-files/utilities/package-chunk-sort.ts b/packages/web/src/utils/third-party/cli-files/utilities/package-chunk-sort.ts index 57dee51ccc4e3..dde94dbc6567d 100644 --- a/packages/web/src/utils/third-party/cli-files/utilities/package-chunk-sort.ts +++ b/packages/web/src/utils/third-party/cli-files/utilities/package-chunk-sort.ts @@ -21,8 +21,8 @@ export function generateEntryPoints(appConfig: { extraEntryPoints, defaultBundleName ) - .filter(entry => entry.inject) - .map(entry => entry.bundleName); + .filter((entry) => entry.inject) + .map((entry) => entry.bundleName); // remove duplicates return [...new Set(entryPoints)]; @@ -37,15 +37,15 @@ export function generateEntryPoints(appConfig: { ...extraEntryPoints(appConfig.styles, 'styles'), ...extraEntryPoints(appConfig.scripts, 'scripts'), 'vendor', - 'main' + 'main', ]; const duplicates = [ ...new Set( entryPoints.filter( - x => entryPoints.indexOf(x) !== entryPoints.lastIndexOf(x) + (x) => entryPoints.indexOf(x) !== entryPoints.lastIndexOf(x) ) - ) + ), ]; if (duplicates.length > 0) { diff --git a/packages/web/src/utils/third-party/cli-files/utilities/stats.ts b/packages/web/src/utils/third-party/cli-files/utilities/stats.ts index 2c2db5081a7b0..67737265a4506 100644 --- a/packages/web/src/utils/third-party/cli-files/utilities/stats.ts +++ b/packages/web/src/utils/third-party/cli-files/utilities/stats.ts @@ -41,11 +41,11 @@ export function generateBundleStats( const y = (x: string) => (colors ? bold(yellow(x)) : x); const size = typeof info.size === 'number' ? ` ${formatSize(info.size)}` : ''; - const files = info.files.map(f => path.basename(f)).join(', '); + const files = info.files.map((f) => path.basename(f)).join(', '); const names = info.names ? ` (${info.names.join(', ')})` : ''; const initial = y(info.entry ? '[entry]' : info.initial ? '[initial]' : ''); const flags = ['rendered', 'recorded'] - .map(f => (f && (info as any)[f] ? g(` [${f}]`) : '')) + .map((f) => (f && (info as any)[f] ? g(` [${f}]`) : '')) .join(''); return `chunk {${y(info.id.toString())}} ${g( diff --git a/packages/web/src/utils/third-party/utils/build-browser-features.ts b/packages/web/src/utils/third-party/utils/build-browser-features.ts index 10f4f5893949f..ca3475b587f25 100644 --- a/packages/web/src/utils/third-party/utils/build-browser-features.ts +++ b/packages/web/src/utils/third-party/utils/build-browser-features.ts @@ -25,7 +25,7 @@ export class BuildBrowserFeatures { private scriptTarget: ts.ScriptTarget ) { this._supportedBrowsers = browserslist(undefined, { - path: this.projectRoot + path: this.projectRoot, }); this._es6TargetOrLater = this.scriptTarget > ts.ScriptTarget.ES5; } @@ -58,7 +58,7 @@ export class BuildBrowserFeatures { const safariBrowsers = ['safari 10.1', 'ios_saf 10.3']; - return this._supportedBrowsers.some(browser => + return this._supportedBrowsers.some((browser) => safariBrowsers.includes(browser) ); } @@ -75,7 +75,7 @@ export class BuildBrowserFeatures { const data = feature(features[featureId]); - return !this._supportedBrowsers.some(browser => { + return !this._supportedBrowsers.some((browser) => { const [agentId, version] = browser.split(' '); const browserData = data.stats[agentId]; diff --git a/packages/web/src/utils/third-party/utils/build-browser-features_spec.ts b/packages/web/src/utils/third-party/utils/build-browser-features_spec.ts index 692eeed84d739..21dc0724eb1ec 100644 --- a/packages/web/src/utils/third-party/utils/build-browser-features_spec.ts +++ b/packages/web/src/utils/third-party/utils/build-browser-features_spec.ts @@ -31,7 +31,7 @@ describe('BuildBrowserFeatures', () => { describe('isDifferentialLoadingNeeded', () => { it('should be true for for IE 9-11 and ES2015', () => { host.writeMultipleFiles({ - browserslist: 'IE 9-11' + browserslist: 'IE 9-11', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -43,7 +43,7 @@ describe('BuildBrowserFeatures', () => { it('should be false for Chrome and ES2015', () => { host.writeMultipleFiles({ - browserslist: 'last 1 chrome version' + browserslist: 'last 1 chrome version', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -55,7 +55,7 @@ describe('BuildBrowserFeatures', () => { it('detects no need for differential loading for target is ES5', () => { host.writeMultipleFiles({ - browserslist: 'last 1 chrome version' + browserslist: 'last 1 chrome version', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -67,7 +67,7 @@ describe('BuildBrowserFeatures', () => { it('should be false for Safari 10.1 when target is ES2015', () => { host.writeMultipleFiles({ - browserslist: 'Safari 10.1' + browserslist: 'Safari 10.1', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -81,7 +81,7 @@ describe('BuildBrowserFeatures', () => { describe('isFeatureSupported', () => { it('should be true for es6-module and Safari 10.1', () => { host.writeMultipleFiles({ - browserslist: 'Safari 10.1' + browserslist: 'Safari 10.1', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -93,7 +93,7 @@ describe('BuildBrowserFeatures', () => { it('should be false for es6-module and IE9', () => { host.writeMultipleFiles({ - browserslist: 'IE 9' + browserslist: 'IE 9', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -105,7 +105,7 @@ describe('BuildBrowserFeatures', () => { it('should be true for es6-module and last 1 chrome version', () => { host.writeMultipleFiles({ - browserslist: 'last 1 chrome version' + browserslist: 'last 1 chrome version', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -117,7 +117,7 @@ describe('BuildBrowserFeatures', () => { it('should be true for es6-module and Edge 18', () => { host.writeMultipleFiles({ - browserslist: 'Edge 18' + browserslist: 'Edge 18', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -131,7 +131,7 @@ describe('BuildBrowserFeatures', () => { describe('isNoModulePolyfillNeeded', () => { it('should be false for Safari 10.1 when target is ES5', () => { host.writeMultipleFiles({ - browserslist: 'Safari 10.1' + browserslist: 'Safari 10.1', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -143,7 +143,7 @@ describe('BuildBrowserFeatures', () => { it('should be false for Safari 10.1 when target is ES2015', () => { host.writeMultipleFiles({ - browserslist: 'Safari 10.1' + browserslist: 'Safari 10.1', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -155,7 +155,7 @@ describe('BuildBrowserFeatures', () => { it('should be true for Safari 9+ when target is ES2015', () => { host.writeMultipleFiles({ - browserslist: 'Safari >= 9' + browserslist: 'Safari >= 9', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -167,7 +167,7 @@ describe('BuildBrowserFeatures', () => { it('should be false for Safari 9+ when target is ES5', () => { host.writeMultipleFiles({ - browserslist: 'Safari >= 9' + browserslist: 'Safari >= 9', }); const buildBrowserFeatures = new BuildBrowserFeatures( @@ -182,7 +182,7 @@ describe('BuildBrowserFeatures', () => { browserslist: ` Edge 18 IE 9 - ` + `, }); const buildBrowserFeatures = new BuildBrowserFeatures( diff --git a/packages/web/src/utils/third-party/utils/delete-output-dir.ts b/packages/web/src/utils/third-party/utils/delete-output-dir.ts index 3af6fa2b6b51e..bbdc2b9a19d01 100644 --- a/packages/web/src/utils/third-party/utils/delete-output-dir.ts +++ b/packages/web/src/utils/third-party/utils/delete-output-dir.ts @@ -23,7 +23,7 @@ export function deleteOutputDir( } return host.exists(resolvedOutputPath).pipe( - concatMap(exists => (exists ? host.delete(resolvedOutputPath) : EMPTY)), + concatMap((exists) => (exists ? host.delete(resolvedOutputPath) : EMPTY)), last(null, null) ); } diff --git a/packages/web/src/utils/third-party/utils/normalize-asset-patterns.ts b/packages/web/src/utils/third-party/utils/normalize-asset-patterns.ts index 68b3aabd3119f..b7c9e62f2a0ea 100644 --- a/packages/web/src/utils/third-party/utils/normalize-asset-patterns.ts +++ b/packages/web/src/utils/third-party/utils/normalize-asset-patterns.ts @@ -14,7 +14,7 @@ import { normalize, relative, resolve, - virtualFs + virtualFs, } from '@angular-devkit/core'; import { AssetPattern, AssetPatternClass } from '../browser/schema'; @@ -39,7 +39,7 @@ export function normalizeAssetPatterns( return []; } - return assetPatterns.map(assetPattern => { + return assetPatterns.map((assetPattern) => { // Normalize string asset patterns to objects. if (typeof assetPattern === 'string') { const assetPath = normalize(assetPattern); diff --git a/packages/web/src/utils/third-party/utils/normalize-builder-schema.ts b/packages/web/src/utils/third-party/utils/normalize-builder-schema.ts index 432e3284009af..6027285b9beb5 100644 --- a/packages/web/src/utils/third-party/utils/normalize-builder-schema.ts +++ b/packages/web/src/utils/third-party/utils/normalize-builder-schema.ts @@ -12,12 +12,12 @@ import { AssetPatternClass, OptimizationClass, Schema as BrowserBuilderSchema, - SourceMapClass + SourceMapClass, } from '../browser/schema'; import { normalizeAssetPatterns } from './normalize-asset-patterns'; import { NormalizedFileReplacement, - normalizeFileReplacements + normalizeFileReplacements, } from './normalize-file-replacements'; import { normalizeOptimization } from './normalize-optimization'; import { normalizeSourceMaps } from './normalize-source-maps'; @@ -74,8 +74,8 @@ export function normalizeBrowserSchema( includePaths: (options.stylePreprocessorOptions && options.stylePreprocessorOptions.includePaths) || - [] + [], }, - lazyModules: options.lazyModules || [] + lazyModules: options.lazyModules || [], }; } diff --git a/packages/web/src/utils/third-party/utils/normalize-file-replacements.ts b/packages/web/src/utils/third-party/utils/normalize-file-replacements.ts index b1097ef06b278..adf0a2da1e161 100644 --- a/packages/web/src/utils/third-party/utils/normalize-file-replacements.ts +++ b/packages/web/src/utils/third-party/utils/normalize-file-replacements.ts @@ -12,7 +12,7 @@ import { getSystemPath, join, normalize, - virtualFs + virtualFs, } from '@angular-devkit/core'; import { FileReplacement } from '../browser/schema'; @@ -36,7 +36,7 @@ export function normalizeFileReplacements( return []; } - const normalizedReplacement = fileReplacements.map(replacement => + const normalizedReplacement = fileReplacements.map((replacement) => normalizeFileReplacement(replacement, root) ); diff --git a/packages/web/src/utils/third-party/utils/normalize-optimization.ts b/packages/web/src/utils/third-party/utils/normalize-optimization.ts index ce71a90b87c9d..743181e5222e7 100644 --- a/packages/web/src/utils/third-party/utils/normalize-optimization.ts +++ b/packages/web/src/utils/third-party/utils/normalize-optimization.ts @@ -15,6 +15,6 @@ export function normalizeOptimization( scripts: typeof optimization === 'object' ? !!optimization.scripts : optimization, styles: - typeof optimization === 'object' ? !!optimization.styles : optimization + typeof optimization === 'object' ? !!optimization.styles : optimization, }; } diff --git a/packages/web/src/utils/third-party/utils/normalize-source-maps.ts b/packages/web/src/utils/third-party/utils/normalize-source-maps.ts index b70ffdccc95b7..fcd0bb342ea0f 100644 --- a/packages/web/src/utils/third-party/utils/normalize-source-maps.ts +++ b/packages/web/src/utils/third-party/utils/normalize-source-maps.ts @@ -18,6 +18,6 @@ export function normalizeSourceMaps(sourceMap: SourceMapUnion): SourceMapClass { vendor, hidden, scripts, - styles + styles, }; } diff --git a/packages/web/src/utils/third-party/utils/run-module-as-observable-fork.ts b/packages/web/src/utils/third-party/utils/run-module-as-observable-fork.ts index 57947ce1ea5d3..d3c15ecd2694d 100644 --- a/packages/web/src/utils/third-party/utils/run-module-as-observable-fork.ts +++ b/packages/web/src/utils/third-party/utils/run-module-as-observable-fork.ts @@ -18,18 +18,18 @@ export function runModuleAsObservableFork( // tslint:disable-next-line:no-any args: any[] ): Observable { - return new Observable(obs => { + return new Observable((obs) => { const workerPath: string = resolve(__dirname, './run-module-worker.js'); const debugArgRegex = /--inspect(?:-brk|-port)?|--debug(?:-brk|-port)/; - const execArgv = process.execArgv.filter(arg => { + const execArgv = process.execArgv.filter((arg) => { // Remove debug args. // Workaround for https://github.com/nodejs/node/issues/9435 return !debugArgRegex.test(arg); }); const forkOptions: ForkOptions = ({ cwd, - execArgv + execArgv, } as {}) as ForkOptions; // TODO: support passing in a logger to use as stdio streams @@ -76,7 +76,7 @@ export function runModuleAsObservableFork( hash: '5d4b9a5c0a4e0f9977598437b0e85bcc', modulePath, exportName, - args + args, }); // Teardown logic. When unsubscribing, kill the forked process. diff --git a/packages/web/src/utils/web.config.spec.ts b/packages/web/src/utils/web.config.spec.ts index edb4a9ffaa110..fe5c693864f40 100644 --- a/packages/web/src/utils/web.config.spec.ts +++ b/packages/web/src/utils/web.config.spec.ts @@ -25,17 +25,17 @@ describe('getWebConfig', () => { scripts: true, styles: true, hidden: false, - vendors: false + vendors: false, }, optimization: { scripts: false, - styles: false + styles: false, }, styles: [], scripts: [], outputPath: 'dist', tsConfig: 'tsconfig.json', - fileReplacements: [] + fileReplacements: [], }; root = join(__dirname, '../../../..'); sourceRoot = join(root, 'apps/app'); @@ -43,16 +43,16 @@ describe('getWebConfig', () => { mockCompilerOptions = { target: 'es2015', - paths: { path: ['mapped/path'] } + paths: { path: ['mapped/path'] }, }; - (TsConfigPathsPlugin).mockImplementation( - function MockPathsPlugin() {} - ); + (( + TsConfigPathsPlugin + )).mockImplementation(function MockPathsPlugin() {}); spyOn(ts, 'readConfigFile').and.callFake(() => ({ config: { - compilerOptions: mockCompilerOptions - } + compilerOptions: mockCompilerOptions, + }, })); }); @@ -69,7 +69,7 @@ describe('getWebConfig', () => { sourceRoot, { ...input, - polyfills: 'polyfills.ts' + polyfills: 'polyfills.ts', }, logger, false, @@ -86,7 +86,7 @@ describe('getWebConfig', () => { sourceRoot, { ...input, - es2015Polyfills: 'polyfills.es2015.ts' + es2015Polyfills: 'polyfills.es2015.ts', }, logger, false, @@ -105,7 +105,7 @@ describe('getWebConfig', () => { sourceRoot, { ...input, - polyfills: 'polyfills.ts' + polyfills: 'polyfills.ts', }, logger, true, @@ -117,7 +117,7 @@ describe('getWebConfig', () => { sourceRoot, { ...input, - polyfills: 'polyfills.ts' + polyfills: 'polyfills.ts', }, logger, false, @@ -135,7 +135,7 @@ describe('getWebConfig', () => { { ...input, polyfills: 'polyfills.ts', - es2015Polyfills: 'polyfills.es2015.ts' + es2015Polyfills: 'polyfills.es2015.ts', }, logger, false, @@ -152,7 +152,7 @@ describe('getWebConfig', () => { sourceRoot, { ...input, - polyfills: 'polyfills.ts' + polyfills: 'polyfills.ts', }, logger, true, diff --git a/packages/web/src/utils/web.config.ts b/packages/web/src/utils/web.config.ts index 8faedb3984045..005432e719272 100644 --- a/packages/web/src/utils/web.config.ts +++ b/packages/web/src/utils/web.config.ts @@ -41,14 +41,14 @@ export function getWebConfig( esm, logger, tsConfig, - tsConfigPath: options.tsConfig + tsConfigPath: options.tsConfig, }; return mergeWebpack([ _getBaseWebpackPartial(options, esm, isScriptOptimizeOn), getPolyfillsPartial(options, esm, isScriptOptimizeOn), getStylesPartial(wco, options), getCommonPartial(wco), - getBrowserPartial(wco, options, isScriptOptimizeOn) + getBrowserPartial(wco, options, isScriptOptimizeOn), ]); } @@ -66,7 +66,7 @@ function getBrowserPartial( scripts = [], styles = [], index, - baseHref + baseHref, } = options; config.plugins.push( @@ -77,7 +77,7 @@ function getBrowserPartial( entrypoints: generateEntryPoints({ scripts, styles }), deployUrl: deployUrl, sri: subresourceIntegrity, - noModuleEntrypoints: ['polyfills-es5'] + noModuleEntrypoints: ['polyfills-es5'], }) ); } @@ -111,17 +111,17 @@ function getStylesPartial( options: WebBuildBuilderOptions ): Configuration { const partial = getStylesConfig(wco); - const rules = partial.module.rules.map(rule => { + const rules = partial.module.rules.map((rule) => { if (!Array.isArray(rule.use)) { return rule; } - rule.use = rule.use.map(loaderConfig => { + rule.use = rule.use.map((loaderConfig) => { if ( typeof loaderConfig === 'object' && loaderConfig.loader === 'raw-loader' ) { return { - loader: 'style-loader' + loader: 'style-loader', }; } return loaderConfig; @@ -138,16 +138,16 @@ function getStylesPartial( { loader: options.extractCss ? MiniCssExtractPlugin.loader - : 'style-loader' + : 'style-loader', }, { loader: 'css-loader', options: { modules: true, - importLoaders: 1 - } - } - ] + importLoaders: 1, + }, + }, + ], }, { test: /\.module\.(scss|sass)$/, @@ -155,20 +155,20 @@ function getStylesPartial( { loader: options.extractCss ? MiniCssExtractPlugin.loader - : 'style-loader' + : 'style-loader', }, { loader: 'css-loader', options: { modules: true, - importLoaders: 1 - } - } - ] + importLoaders: 1, + }, + }, + ], }, - ...rules - ] - } + ...rules, + ], + }, ]; return partial; } @@ -179,7 +179,7 @@ function getPolyfillsPartial( isScriptOptimizeOn: boolean ): Configuration { const config = { - entry: {} as { [key: string]: string[] } + entry: {} as { [key: string]: string[] }, }; if (options.polyfills && esm && isScriptOptimizeOn) { @@ -189,12 +189,12 @@ function getPolyfillsPartial( require.resolve( '@nrwl/web/src/utils/third-party/cli-files/models/safari-nomodule.js' ), - ...(options.polyfills ? [options.polyfills] : []) + ...(options.polyfills ? [options.polyfills] : []), ]; } else if (options.es2015Polyfills && !esm && isScriptOptimizeOn) { config.entry.polyfills = [ options.es2015Polyfills, - ...(options.polyfills ? [options.polyfills] : []) + ...(options.polyfills ? [options.polyfills] : []), ]; } else { if (options.polyfills) { diff --git a/packages/workspace/index.ts b/packages/workspace/index.ts index 2029b9be82ddd..578354c53be27 100644 --- a/packages/workspace/index.ts +++ b/packages/workspace/index.ts @@ -4,7 +4,7 @@ export { toClassName, toFileName, names, - findModuleParent + findModuleParent, } from './src/utils/name-utils'; export { ProjectType, projectRootDir } from './src/utils/project-type'; export { @@ -14,12 +14,12 @@ export { readJsonFile, readWorkspaceConfigPath, copyFile, - createDirectory + createDirectory, } from './src/utils/fileutils'; export { offsetFromRoot, ExistingPrettierConfig, - resolveUserExistingPrettierConfig + resolveUserExistingPrettierConfig, } from './src/utils/common'; export { output } from './src/utils/output'; export { commandsObject } from './src/command-line/nx-commands'; @@ -47,7 +47,7 @@ export { renameDirSyncInTree, updateNxJsonInTree, addProjectToNxJsonInTree, - readNxJsonInTree + readNxJsonInTree, } from './src/utils/ast-utils'; export { @@ -56,7 +56,7 @@ export { replaceAppNameWithPath, editTarget, parseTarget, - serializeTarget + serializeTarget, } from './src/utils/cli-config-utils'; export { getWorkspace, updateWorkspace } from './src/utils/workspace'; @@ -70,8 +70,6 @@ export * from './src/utils/rules/ng-add'; export { updateKarmaConf } from './src/utils/rules/update-karma-conf'; import * as strings from './src/utils/strings'; export { checkAndCleanWithSemver } from './src/utils/version-utils'; -export { - updatePackagesInPackageJson -} from './src/utils/update-packages-in-package-json'; +export { updatePackagesInPackageJson } from './src/utils/update-packages-in-package-json'; export const stringUtils = strings; diff --git a/packages/workspace/src/builders/run-commands/run-commands.impl.spec.ts b/packages/workspace/src/builders/run-commands/run-commands.impl.spec.ts index 311bb0db9cf8a..b4c1a9819c7ef 100644 --- a/packages/workspace/src/builders/run-commands/run-commands.impl.spec.ts +++ b/packages/workspace/src/builders/run-commands/run-commands.impl.spec.ts @@ -7,9 +7,7 @@ import { join } from 'path'; import { TEN_MEGABYTES } from '@nrwl/workspace/src/core/file-utils'; function readFile(f: string) { - return readFileSync(f) - .toString() - .replace(/\s/g, ''); + return readFileSync(f).toString().replace(/\s/g, ''); } describe('Command Runner Builder', () => { @@ -44,7 +42,7 @@ describe('Command Runner Builder', () => { const run = await architect.scheduleBuilder( '@nrwl/workspace:run-commands', { - commands: [{}] + commands: [{}], } ); await run.result; @@ -66,13 +64,13 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `sleep 0.2 && echo 1 >> ${f}` + command: `sleep 0.2 && echo 1 >> ${f}`, }, { - command: `sleep 0.1 && echo 2 >> ${f}` - } + command: `sleep 0.1 && echo 2 >> ${f}`, + }, ], - parallel: false + parallel: false, } ); //wait a tick for the serial runner to schedule the first task @@ -94,13 +92,13 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo 1 >> ${f}` + command: `echo 1 >> ${f}`, }, { - command: `echo 2 >> ${f}` - } + command: `echo 2 >> ${f}`, + }, ], - parallel: true + parallel: true, } ); const processesCreated = exec.calls.count(); @@ -122,7 +120,7 @@ describe('Command Runner Builder', () => { { commands: [{ command: 'some command' }], parallel: false, - readyWhen: 'READY' + readyWhen: 'READY', } ); await run.result; @@ -134,22 +132,22 @@ describe('Command Runner Builder', () => { } }); - it('should return success true when the string specified is ready condition is found', async done => { + it('should return success true when the string specified is ready condition is found', async (done) => { const f = fileSync().name; const run = await architect.scheduleBuilder( '@nrwl/workspace:run-commands', { commands: [ { - command: `echo READY && sleep 0.1 && echo 1 >> ${f}` - } + command: `echo READY && sleep 0.1 && echo 1 >> ${f}`, + }, ], parallel: true, - readyWhen: 'READY' + readyWhen: 'READY', } ); let successEmitted = false; - run.output.subscribe(result => { + run.output.subscribe((result) => { successEmitted = true; expect(result.success).toEqual(true); expect(readFile(f)).toEqual(''); @@ -169,13 +167,13 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo 1 >> ${f} && exit 1` + command: `echo 1 >> ${f} && exit 1`, }, { - command: `echo 2 >> ${f}` - } + command: `echo 2 >> ${f}`, + }, ], - parallel: false + parallel: false, } ); @@ -194,10 +192,10 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo {args.key} >> ${f}` - } + command: `echo {args.key} >> ${f}`, + }, ], - args: 'key=value' + args: 'key=value', } ); await run.result; @@ -213,10 +211,10 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo {args.key} >> ${f}` - } + command: `echo {args.key} >> ${f}`, + }, ], - args: '--key=value' + args: '--key=value', } ); @@ -234,9 +232,9 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo 'Hello World'` - } - ] + command: `echo 'Hello World'`, + }, + ], } ); @@ -244,7 +242,7 @@ describe('Command Runner Builder', () => { expect(exec).toHaveBeenCalledWith(`echo 'Hello World'`, { maxBuffer: TEN_MEGABYTES, - env: { ...process.env, FORCE_COLOR: `false` } + env: { ...process.env, FORCE_COLOR: `false` }, }); }); @@ -255,10 +253,10 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo 'Hello World'` - } + command: `echo 'Hello World'`, + }, ], - color: true + color: true, } ); @@ -266,7 +264,7 @@ describe('Command Runner Builder', () => { expect(exec).toHaveBeenCalledWith(`echo 'Hello World'`, { maxBuffer: TEN_MEGABYTES, - env: { ...process.env, FORCE_COLOR: `true` } + env: { ...process.env, FORCE_COLOR: `true` }, }); }); }); @@ -276,9 +274,9 @@ describe('Command Runner Builder', () => { let run = await architect.scheduleBuilder('@nrwl/workspace:run-commands', { commands: [ { - command: `pwd >> ${f}` - } - ] + command: `pwd >> ${f}`, + }, + ], }); let result = await run.result; @@ -289,10 +287,10 @@ describe('Command Runner Builder', () => { run = await architect.scheduleBuilder('@nrwl/workspace:run-commands', { commands: [ { - command: `pwd >> ${f}` - } + command: `pwd >> ${f}`, + }, ], - cwd: 'packages' + cwd: 'packages', }); result = await run.result; @@ -322,9 +320,9 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo $NRWL_SITE >> ${f}` - } - ] + command: `echo $NRWL_SITE >> ${f}`, + }, + ], } ); @@ -343,10 +341,10 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo $NX_SITE >> ${f} && echo $NRWL_SITE >> ${f}` - } + command: `echo $NX_SITE >> ${f} && echo $NRWL_SITE >> ${f}`, + }, ], - envFile: devEnv + envFile: devEnv, } ); @@ -363,10 +361,10 @@ describe('Command Runner Builder', () => { { commands: [ { - command: `echo $NX_SITE >> ${f} && echo $NRWL_SITE >> ${f}` - } + command: `echo $NX_SITE >> ${f} && echo $NRWL_SITE >> ${f}`, + }, ], - envFile: '/somePath/.fakeEnv' + envFile: '/somePath/.fakeEnv', } ); diff --git a/packages/workspace/src/builders/run-commands/run-commands.impl.ts b/packages/workspace/src/builders/run-commands/run-commands.impl.ts index dfcd1c77e6728..f670c21580895 100644 --- a/packages/workspace/src/builders/run-commands/run-commands.impl.ts +++ b/packages/workspace/src/builders/run-commands/run-commands.impl.ts @@ -1,7 +1,7 @@ import { BuilderContext, BuilderOutput, - createBuilder + createBuilder, } from '@angular-devkit/architect'; import { JsonObject } from '@angular-devkit/core'; import { exec } from 'child_process'; @@ -40,12 +40,12 @@ function run( ): Observable { loadEnvVars(options.envFile); options.parsedArgs = parseArgs(options.args); - return Observable.create(async observer => { + return Observable.create(async (observer) => { if (!options.commands) { observer.next({ success: false, error: - 'ERROR: Bad builder config for @nrwl/run-command - "commands" option is required' + 'ERROR: Bad builder config for @nrwl/run-command - "commands" option is required', }); return; } @@ -57,7 +57,7 @@ function run( return; } - if (options.commands.some(c => !c.command)) { + if (options.commands.some((c) => !c.command)) { observer.error( 'ERROR: Bad builder config for @nrwl/run-command - "command" option is required' ); @@ -79,16 +79,16 @@ function run( } async function runInParallel(options: RunCommandsBuilderOptions) { - const procs = options.commands.map(c => + const procs = options.commands.map((c) => createProcess( c.command, options.readyWhen, options.parsedArgs, options.color, options.cwd - ).then(result => ({ + ).then((result) => ({ result, - command: c.command + command: c.command, })) ); @@ -104,9 +104,9 @@ async function runInParallel(options: RunCommandsBuilderOptions) { } } else { const r = await Promise.all(procs); - const failed = r.filter(v => !v.result); + const failed = r.filter((v) => !v.result); if (failed.length > 0) { - failed.forEach(f => { + failed.forEach((f) => { process.stderr.write( `Warning: @nrwl/run-command command "${f.command}" exited with non-zero status code` ); @@ -157,29 +157,29 @@ function createProcess( cwd: string ): Promise { command = transformCommand(command, parsedArgs); - return new Promise(res => { + return new Promise((res) => { const childProcess = exec(command, { maxBuffer: TEN_MEGABYTES, env: { ...process.env, FORCE_COLOR: `${color}` }, - cwd + cwd, }); /** * Ensure the child process is killed when the parent exits */ process.on('exit', () => childProcess.kill()); - childProcess.stdout.on('data', data => { + childProcess.stdout.on('data', (data) => { process.stdout.write(data); if (readyWhen && data.toString().indexOf(readyWhen) > -1) { res(true); } }); - childProcess.stderr.on('data', err => { + childProcess.stderr.on('data', (err) => { process.stderr.write(err); if (readyWhen && err.toString().indexOf(readyWhen) > -1) { res(true); } }); - childProcess.on('close', code => { + childProcess.on('close', (code) => { if (!readyWhen) { res(code === 0); } @@ -198,7 +198,7 @@ function parseArgs(args: string) { } return args .split(' ') - .map(t => t.trim()) + .map((t) => t.trim()) .reduce((m, c) => { if (!c.startsWith('--')) { throw new Error(`Invalid args: ${args}`); diff --git a/packages/workspace/src/command-line/affected.ts b/packages/workspace/src/command-line/affected.ts index b3ed8b34837de..eb9aec1477f6c 100644 --- a/packages/workspace/src/command-line/affected.ts +++ b/packages/workspace/src/command-line/affected.ts @@ -10,7 +10,7 @@ import { onlyWorkspaceProjects, ProjectGraphNode, ProjectType, - withDeps + withDeps, } from '../core/project-graph'; import { calculateFileChanges, readEnvironment } from '../core/file-utils'; import { printAffected } from './print-affected'; @@ -38,17 +38,17 @@ export function affected(command: string, parsedArgs: yargs.Arguments): void { const projects = parsedArgs.all ? projectGraph.nodes : affectedGraph.nodes; const env = readEnvironment(nxArgs.target, projects); const affectedProjects = Object.values(projects) - .filter(n => !parsedArgs.exclude.includes(n.name)) + .filter((n) => !parsedArgs.exclude.includes(n.name)) .filter( - n => !parsedArgs.onlyFailed || !env.workspaceResults.getResult(n.name) + (n) => !parsedArgs.onlyFailed || !env.workspaceResults.getResult(n.name) ); try { switch (command) { case 'apps': const apps = affectedProjects - .filter(p => p.type === ProjectType.app) - .map(p => p.name); + .filter((p) => p.type === ProjectType.app) + .map((p) => p.name); if (parsedArgs.plain) { console.log(apps.join(' ')); } else { @@ -56,7 +56,7 @@ export function affected(command: string, parsedArgs: yargs.Arguments): void { if (apps.length) { output.log({ title: 'Affected apps:', - bodyLines: apps.map(app => `${output.colors.gray('-')} ${app}`) + bodyLines: apps.map((app) => `${output.colors.gray('-')} ${app}`), }); } } @@ -64,8 +64,8 @@ export function affected(command: string, parsedArgs: yargs.Arguments): void { case 'libs': const libs = affectedProjects - .filter(p => p.type === ProjectType.lib) - .map(p => p.name); + .filter((p) => p.type === ProjectType.lib) + .map((p) => p.name); if (parsedArgs.plain) { console.log(libs.join(' ')); } else { @@ -73,14 +73,14 @@ export function affected(command: string, parsedArgs: yargs.Arguments): void { if (libs.length) { output.log({ title: 'Affected libs:', - bodyLines: libs.map(lib => `${output.colors.gray('-')} ${lib}`) + bodyLines: libs.map((lib) => `${output.colors.gray('-')} ${lib}`), }); } } break; case 'dep-graph': - const projectNames = affectedProjects.map(p => p.name); + const projectNames = affectedProjects.map((p) => p.name); printArgsWarning(nxArgs); generateGraph(parsedArgs as any, projectNames); break; @@ -128,7 +128,7 @@ export function affected(command: string, parsedArgs: yargs.Arguments): void { } function allProjectsWithTarget(projects: ProjectGraphNode[], nxArgs: NxArgs) { - return projects.filter(p => projectHasTarget(p, nxArgs.target)); + return projects.filter((p) => projectHasTarget(p, nxArgs.target)); } function printError(e: any, verbose?: boolean) { @@ -139,6 +139,6 @@ function printError(e: any, verbose?: boolean) { } output.error({ title: 'There was a critical error when running your command', - bodyLines + bodyLines, }); } diff --git a/packages/workspace/src/command-line/dep-graph.ts b/packages/workspace/src/command-line/dep-graph.ts index 3b131eb94bc0c..d2192c6661e69 100644 --- a/packages/workspace/src/command-line/dep-graph.ts +++ b/packages/workspace/src/command-line/dep-graph.ts @@ -6,7 +6,7 @@ import { createProjectGraph, onlyWorkspaceProjects, ProjectGraph, - ProjectGraphNode + ProjectGraphNode, } from '../core/project-graph'; import { output } from '../utils/output'; import { join, normalize, parse } from 'path'; @@ -26,7 +26,7 @@ const mimeType = { '.pdf': 'application/pdf', '.doc': 'application/msword', '.eot': 'appliaction/vnd.ms-fontobject', - '.ttf': 'aplication/font-sfnt' + '.ttf': 'aplication/font-sfnt', }; export function generateGraph( @@ -48,7 +48,7 @@ export function generateGraph( { graph, affectedProjects, - criticalPath: affectedProjects + criticalPath: affectedProjects, }, null, 2 @@ -98,7 +98,7 @@ function startServer( ); let pathname = join(__dirname, '../core/dep-graph/', sanitizePath); - exists(pathname, function(exist) { + exists(pathname, function (exist) { if (!exist) { // if the file is not found, return 404 res.statusCode = 404; @@ -115,7 +115,7 @@ function startServer( } // read file from file system - readFile(pathname, function(err, data) { + readFile(pathname, function (err, data) { if (err) { res.statusCode = 500; res.end(`Error getting the file: ${err}.`); @@ -133,11 +133,11 @@ function startServer( app.listen(4211, host); output.note({ - title: `Dep graph started at http://${host}:4211` + title: `Dep graph started at http://${host}:4211`, }); opn(`http://${host}:4211`, { - wait: false + wait: false, }); } @@ -146,11 +146,12 @@ function filterProjects( filter: string[], exclude: string[] ) { - const filteredProjects = Object.values(graph.nodes).filter(p => { + const filteredProjects = Object.values(graph.nodes).filter((p) => { const filtered = filter && filter.length > 0 ? filter.find( - f => hasPath(graph, f, p.name, []) || hasPath(graph, p.name, f, []) + (f) => + hasPath(graph, f, p.name, []) || hasPath(graph, p.name, f, []) ) : true; return !exclude diff --git a/packages/workspace/src/command-line/format.ts b/packages/workspace/src/command-line/format.ts index 618d4ac21392b..2dde3f6b13601 100644 --- a/packages/workspace/src/command-line/format.ts +++ b/packages/workspace/src/command-line/format.ts @@ -21,7 +21,7 @@ const PRETTIER_EXTENSIONS = [ 'html', 'json', 'md', - 'mdx' + 'mdx', ]; export function format(command: 'check' | 'write', args: yargs.Arguments) { @@ -32,7 +32,7 @@ export function format(command: 'check' | 'write', args: yargs.Arguments) { try { patterns = getPatterns({ ...args, - ...nxArgs + ...nxArgs, } as any); } catch (e) { output.error({ @@ -44,8 +44,8 @@ export function format(command: 'check' | 'write', args: yargs.Arguments) { '', `Or pass the list of files: ${output.bold( `npm run format:${command} -- --files="libs/mylib/index.ts,libs/mylib2/index.ts"` - )}` - ] + )}`, + ], }); process.exit(1); } @@ -55,10 +55,10 @@ export function format(command: 'check' | 'write', args: yargs.Arguments) { switch (command) { case 'write': - chunkList.forEach(chunk => write(chunk)); + chunkList.forEach((chunk) => write(chunk)); break; case 'check': - chunkList.forEach(chunk => check(chunk)); + chunkList.forEach((chunk) => check(chunk)); break; } } @@ -74,15 +74,15 @@ function getPatterns(args: NxArgs & { libsAndApps: boolean; _: string[] }) { printArgsWarning(args); const p = parseFiles(args); let patterns = p.files - .filter(f => fileExists(f)) - .filter(f => - PRETTIER_EXTENSIONS.map(ext => '.' + ext).includes(path.extname(f)) + .filter((f) => fileExists(f)) + .filter((f) => + PRETTIER_EXTENSIONS.map((ext) => '.' + ext).includes(path.extname(f)) ); const libsAndApp = args.libsAndApps; return libsAndApp ? getPatternsFromApps(patterns) - : patterns.map(f => `"${f}"`); + : patterns.map((f) => `"${f}"`); } catch (e) { return allFilesPattern; } @@ -95,7 +95,9 @@ function getPatternsFromApps(affectedFiles: string[]): string[] { calculateFileChanges(affectedFiles) ); const roots = getProjectRoots(Object.keys(affectedGraph.nodes)); - return roots.map(root => `"${root}/**/*.{${PRETTIER_EXTENSIONS.join(',')}}"`); + return roots.map( + (root) => `"${root}/**/*.{${PRETTIER_EXTENSIONS.join(',')}}"` + ); } function chunkify(target: string[], size: number): string[][] { @@ -109,7 +111,7 @@ function chunkify(target: string[], size: number): string[][] { function write(patterns: string[]) { if (patterns.length > 0) { execSync(`node "${prettierPath()}" --write ${patterns.join(' ')}`, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); } } @@ -120,7 +122,7 @@ function check(patterns: string[]) { execSync( `node "${prettierPath()}" --list-different ${patterns.join(' ')}`, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], } ); } catch (e) { diff --git a/packages/workspace/src/command-line/lint.ts b/packages/workspace/src/command-line/lint.ts index f0d12bee21c67..4bd609cc16726 100644 --- a/packages/workspace/src/command-line/lint.ts +++ b/packages/workspace/src/command-line/lint.ts @@ -1,6 +1,6 @@ import { createProjectGraph, - onlyWorkspaceProjects + onlyWorkspaceProjects, } from '../core/project-graph'; import { WorkspaceIntegrityChecks } from './workspace-integrity-checks'; import * as path from 'path'; @@ -17,7 +17,7 @@ export function workspaceLint() { ).run(); if (cliErrorOutputConfigs.length > 0) { - cliErrorOutputConfigs.forEach(errorConfig => { + cliErrorOutputConfigs.forEach((errorConfig) => { output.error(errorConfig); }); process.exit(1); @@ -26,7 +26,7 @@ export function workspaceLint() { function readAllFilesFromAppsAndLibs() { return [ - ...allFilesInDir(`${appRootPath}/apps`).map(f => f.file), - ...allFilesInDir(`${appRootPath}/libs`).map(f => f.file) - ].filter(f => !path.basename(f).startsWith('.')); + ...allFilesInDir(`${appRootPath}/apps`).map((f) => f.file), + ...allFilesInDir(`${appRootPath}/libs`).map((f) => f.file), + ].filter((f) => !path.basename(f).startsWith('.')); } diff --git a/packages/workspace/src/command-line/list.ts b/packages/workspace/src/command-line/list.ts index 595d810f2d0bb..7012c03d501a9 100644 --- a/packages/workspace/src/command-line/list.ts +++ b/packages/workspace/src/command-line/list.ts @@ -8,7 +8,7 @@ import { listCommunityPlugins, listCorePlugins, listInstalledPlugins, - listPluginCapabilities + listPluginCapabilities, } from '../utils/plugins'; export interface YargsListArgs extends yargs.Arguments, ListArgs {} @@ -24,9 +24,9 @@ export const list = { builder: (yargs: yargs.Argv) => yargs.positional('plugin', { default: null, - description: 'The name of an installed plugin to query' + description: 'The name of an installed plugin to query', }), - handler: listHandler + handler: listHandler, }; /** @@ -53,7 +53,7 @@ async function listHandler(args: YargsListArgs) { listCommunityPlugins(installedPlugins, communityPlugins); output.note({ - title: `Use "nx list [plugin]" to find out more` + title: `Use "nx list [plugin]" to find out more`, }); } } diff --git a/packages/workspace/src/command-line/nx-commands.ts b/packages/workspace/src/command-line/nx-commands.ts index cbdf12a124097..9ee0304276b64 100644 --- a/packages/workspace/src/command-line/nx-commands.ts +++ b/packages/workspace/src/command-line/nx-commands.ts @@ -43,120 +43,120 @@ export const commandsObject = yargs .command( 'affected', 'Run task for affected projects', - yargs => withAffectedOptions(withParallel(withTarget(yargs))), - args => affected('affected', { ...args }) + (yargs) => withAffectedOptions(withParallel(withTarget(yargs))), + (args) => affected('affected', { ...args }) ) .command( 'run-many', 'Run task for multiple projects', - yargs => withRunManyOptions(withParallel(withTarget(yargs))), - args => runMany({ ...args }) + (yargs) => withRunManyOptions(withParallel(withTarget(yargs))), + (args) => runMany({ ...args }) ) .command( 'affected:apps', 'Print applications affected by changes', withAffectedOptions, - args => affected('apps', { ...args }) + (args) => affected('apps', { ...args }) ) .command( 'affected:libs', 'Print libraries affected by changes', withAffectedOptions, - args => + (args) => affected('libs', { - ...args + ...args, }) ) .command( 'affected:build', 'Build applications and publishable libraries affected by changes', - yargs => withAffectedOptions(withParallel(yargs)), - args => + (yargs) => withAffectedOptions(withParallel(yargs)), + (args) => affected('affected', { ...args, - target: 'build' + target: 'build', }) ) .command( 'affected:test', 'Test projects affected by changes', - yargs => withAffectedOptions(withParallel(yargs)), - args => + (yargs) => withAffectedOptions(withParallel(yargs)), + (args) => affected('affected', { ...args, - target: 'test' + target: 'test', }) ) .command( 'affected:e2e', 'Run e2e tests for the applications affected by changes', - yargs => withAffectedOptions(withParallel(yargs)), - args => + (yargs) => withAffectedOptions(withParallel(yargs)), + (args) => affected('affected', { ...args, - target: 'e2e' + target: 'e2e', }) ) .command( 'affected:dep-graph', 'Graph dependencies affected by changes', - yargs => withAffectedOptions(withDepGraphOptions(yargs)), - args => + (yargs) => withAffectedOptions(withDepGraphOptions(yargs)), + (args) => affected('dep-graph', { - ...args + ...args, }) ) .command( 'print-affected', 'Graph execution plan', - yargs => withAffectedOptions(withPrintAffectedOptions(yargs)), - args => + (yargs) => withAffectedOptions(withPrintAffectedOptions(yargs)), + (args) => affected('print-affected', { - ...args + ...args, }) ) .command( 'affected:lint', 'Lint projects affected by changes', - yargs => withAffectedOptions(withParallel(yargs)), - args => + (yargs) => withAffectedOptions(withParallel(yargs)), + (args) => affected('affected', { ...args, - target: 'lint' + target: 'lint', }) ) .command( 'dep-graph', 'Graph dependencies within workspace', - yargs => withDepGraphOptions(yargs), - args => generateGraph(args as any, []) + (yargs) => withDepGraphOptions(yargs), + (args) => generateGraph(args as any, []) ) .command( 'format:check', 'Check for un-formatted files', withFormatOptions, - args => format('check', args) + (args) => format('check', args) ) .command( 'format:write', 'Overwrite un-formatted files', withFormatOptions, - args => format('write', args) + (args) => format('write', args) ) .alias('format:write', 'format') .command( 'workspace-lint [files..]', 'Lint workspace or list of files', noop, - _ => workspaceLint() + (_) => workspaceLint() ) .command( 'workspace-schematic [name]', 'Runs a workspace schematic from the tools/schematics directory', - yargs => { + (yargs) => { yargs.option('list-schematics', { describe: 'List the available workspace-schematics', - type: 'boolean' + type: 'boolean', }); /** * Don't require `name` if only listing available @@ -165,7 +165,7 @@ export const commandsObject = yargs if (yargs.argv.listSchematics !== true) { yargs.demandOption(['name']).positional('name', { type: 'string', - describe: 'The name of your schematic`' + describe: 'The name of your schematic`', }); } return yargs; @@ -178,14 +178,14 @@ export const commandsObject = yargs - Migrate packages and create migrations.json (e.g., nx migrate @nrwl/workspace@latest) - Run migrations (e.g., nx migrate --run-migrations=migrations.json) `, - yargs => yargs, + (yargs) => yargs, () => { const executable = platform() === 'win32' ? `.\\node_modules\\.bin\\tao` : `./node_modules/.bin/tao`; execSync(`${executable} migrate ${process.argv.slice(3).join(' ')}`, { - stdio: ['inherit', 'inherit', 'inherit'] + stdio: ['inherit', 'inherit', 'inherit'], }); } ) @@ -197,7 +197,7 @@ export const commandsObject = yargs function withFormatOptions(yargs: yargs.Argv): yargs.Argv { return withAffectedOptions(yargs).option('apps-and-libs', { - type: 'boolean' + type: 'boolean', }); } @@ -212,7 +212,7 @@ function withAffectedOptions(yargs: yargs.Argv): yargs.Argv { 'Change the way Nx is calculating the affected command by providing directly changed files, list of files delimited by commas', type: 'array', requiresArg: true, - coerce: parseCSV + coerce: parseCSV, }) .option('uncommitted', { describe: 'Uncommitted changes' }) .option('untracked', { describe: 'Untracked changes' }) @@ -220,12 +220,12 @@ function withAffectedOptions(yargs: yargs.Argv): yargs.Argv { .option('base', { describe: 'Base of the current branch (usually master)', type: 'string', - requiresArg: true + requiresArg: true, }) .option('head', { describe: 'Latest commit of the current branch (usually HEAD)', type: 'string', - requiresArg: true + requiresArg: true, }) .group( ['base'], @@ -244,39 +244,39 @@ function withAffectedOptions(yargs: yargs.Argv): yargs.Argv { describe: 'Exclude certain projects from being processed', type: 'array', coerce: parseCSV, - default: [] + default: [], }) .options('runner', { describe: 'This is the name of the tasks runner configured in nx.json', - type: 'string' + type: 'string', }) .options('skip-nx-cache', { describe: 'Rerun the tasks even when the results are available in the cache', type: 'boolean', - default: false + default: false, }) .options('configuration', { describe: 'This is the configuration to use when performing tasks on projects', - type: 'string' + type: 'string', }) .options('only-failed', { describe: 'Isolate projects which previously failed', type: 'boolean', - default: false + default: false, }) .option('verbose', { - describe: 'Print additional error stack trace on failure' + describe: 'Print additional error stack trace on failure', }) .option('plain', { - describe: 'Produces a plain output for affected:apps and affected:libs' + describe: 'Produces a plain output for affected:apps and affected:libs', }) .conflicts({ files: ['uncommitted', 'untracked', 'base', 'head', 'all'], untracked: ['uncommitted', 'files', 'base', 'head', 'all'], uncommitted: ['files', 'untracked', 'base', 'head', 'all'], - all: ['files', 'untracked', 'uncommitted', 'base', 'head'] + all: ['files', 'untracked', 'uncommitted', 'base', 'head'], }); } @@ -284,10 +284,10 @@ function withRunManyOptions(yargs: yargs.Argv): yargs.Argv { return yargs .option('projects', { describe: 'Projects to run (comma delimited)', - type: 'string' + type: 'string', }) .option('all', { - describe: 'Run the target on all projects in the workspace' + describe: 'Run the target on all projects in the workspace', }) .nargs('all', 0) .check(({ all, projects }) => { @@ -297,35 +297,35 @@ function withRunManyOptions(yargs: yargs.Argv): yargs.Argv { }) .options('runner', { describe: 'Override the tasks runner in `nx.json`', - type: 'string' + type: 'string', }) .options('skip-nx-cache', { describe: 'Rerun the tasks even when the results are available in the cache', type: 'boolean', - default: false + default: false, }) .options('configuration', { describe: 'This is the configuration to use when performing tasks on projects', - type: 'string' + type: 'string', }) .options('with-deps', { describe: 'Include dependencies of specified projects when computing what to run', type: 'boolean', - default: false + default: false, }) .options('only-failed', { describe: 'Only run the target on projects which previously failed', type: 'boolean', - default: false + default: false, }) .option('verbose', { - describe: 'Print additional error stack trace on failure' + describe: 'Print additional error stack trace on failure', }) .conflicts({ - all: 'projects' + all: 'projects', }); } @@ -333,35 +333,32 @@ function withDepGraphOptions(yargs: yargs.Argv): yargs.Argv { return yargs .option('file', { describe: 'output file (e.g. --file=output.json)', - type: 'string' + type: 'string', }) .option('filter', { describe: 'Use to limit the dependency graph to only show specific projects, list of projects delimited by commas.', type: 'array', - coerce: parseCSV + coerce: parseCSV, }) .option('exclude', { describe: 'List of projects delimited by commas to exclude from the dependency graph.', type: 'array', - coerce: parseCSV + coerce: parseCSV, }) .option('host', { describe: 'Bind the dep graph server to a specific ip address.', - type: 'string' + type: 'string', }); } function parseCSV(args: string[]) { return args - .map(arg => arg.split(',')) - .reduce( - (acc, value) => { - return [...acc, ...value]; - }, - [] as string[] - ); + .map((arg) => arg.split(',')) + .reduce((acc, value) => { + return [...acc, ...value]; + }, [] as string[]); } function withParallel(yargs: yargs.Argv): yargs.Argv { @@ -369,13 +366,13 @@ function withParallel(yargs: yargs.Argv): yargs.Argv { .option('parallel', { describe: 'Parallelize the command', type: 'boolean', - default: false + default: false, }) .option('maxParallel', { describe: 'Max number of parallel processes. This flag is ignored if the parallel option is set to `false`.', type: 'number', - default: 3 + default: 3, }); } @@ -385,6 +382,6 @@ function withTarget(yargs: yargs.Argv): yargs.Argv { type: 'string', requiresArg: true, demandOption: true, - global: false + global: false, }); } diff --git a/packages/workspace/src/command-line/print-affected.spec.ts b/packages/workspace/src/command-line/print-affected.spec.ts index a4521c93fe85d..7cd4a5e1ae17f 100644 --- a/packages/workspace/src/command-line/print-affected.spec.ts +++ b/packages/workspace/src/command-line/print-affected.spec.ts @@ -7,15 +7,15 @@ describe('print-affected', () => { tasks: [ { target: { - project: 'one' - } + project: 'one', + }, }, { target: { - project: 'two' - } - } - ] + project: 'two', + }, + }, + ], }; it('should return the result if select is empty', () => { diff --git a/packages/workspace/src/command-line/print-affected.ts b/packages/workspace/src/command-line/print-affected.ts index a29b38325e1d0..596ce740b6fe6 100644 --- a/packages/workspace/src/command-line/print-affected.ts +++ b/packages/workspace/src/command-line/print-affected.ts @@ -14,7 +14,7 @@ export function printAffected( nxArgs: NxArgs, overrides: yargs.Arguments ) { - const projectNames = affectedProjects.map(p => p.name); + const projectNames = affectedProjects.map((p) => p.name); const tasksJson = createTasks( affectedProjectsWithTargetAndConfig, projectGraph, @@ -24,7 +24,7 @@ export function printAffected( const result = { tasks: tasksJson, projects: projectNames, - projectGraph: serializeProjectGraph(projectGraph) + projectGraph: serializeProjectGraph(projectGraph), }; if (nxArgs.select) { console.log(selectPrintAffected(result, nxArgs.select)); @@ -40,17 +40,17 @@ function createTasks( overrides: yargs.Arguments ) { const tasks: Task[] = affectedProjectsWithTargetAndConfig.map( - affectedProject => + (affectedProject) => createTask({ project: affectedProject, target: nxArgs.target, configuration: nxArgs.configuration, - overrides: overrides + overrides: overrides, }) ); const cli = cliCommand(); const isYarn = basename(process.env.npm_execpath || 'npm').startsWith('yarn'); - return tasks.map(task => ({ + return tasks.map((task) => ({ id: task.id, overrides: overrides, target: task.target, @@ -59,12 +59,12 @@ function createTasks( isYarn, task )}`, - outputs: getOutputs(projectGraph.nodes, task) + outputs: getOutputs(projectGraph.nodes, task), })); } function serializeProjectGraph(projectGraph: ProjectGraph) { - const nodes = Object.values(projectGraph.nodes).map(n => n.name); + const nodes = Object.values(projectGraph.nodes).map((n) => n.name); return { nodes, dependencies: projectGraph.dependencies }; } @@ -80,7 +80,7 @@ export function selectPrintAffected(wholeJson: any, wholeSelect: string) { const rest = restKeys.join('.'); if (Array.isArray(first)) { - return first.map(q => _select(q, rest)).join(', '); + return first.map((q) => _select(q, rest)).join(', '); } else { return _select(first, rest); } diff --git a/packages/workspace/src/command-line/report.ts b/packages/workspace/src/command-line/report.ts index d3b805a75da2d..b16d44ccd974b 100644 --- a/packages/workspace/src/command-line/report.ts +++ b/packages/workspace/src/command-line/report.ts @@ -20,14 +20,14 @@ export const packagesWeCareAbout = [ '@nrwl/tao', '@nrwl/web', '@nrwl/workspace', - 'typescript' + 'typescript', ]; export const report = { command: 'report', describe: 'Reports useful version numbers to copy into the Nx issue template', - builder: yargs => yargs, - handler: reportHandler + builder: (yargs) => yargs, + handler: reportHandler, }; /** @@ -42,7 +42,7 @@ function reportHandler() { const nodeModulesDir = path.join(appRootPath, 'node_modules'); const bodyLines = []; - packagesWeCareAbout.forEach(p => { + packagesWeCareAbout.forEach((p) => { let status = 'Not Found'; try { const packageJson = JSON.parse( @@ -55,6 +55,6 @@ function reportHandler() { output.log({ title: 'Report complete - copy this into the issue template', - bodyLines + bodyLines, }); } diff --git a/packages/workspace/src/command-line/run-many.ts b/packages/workspace/src/command-line/run-many.ts index 91d6efe394e7e..d7d3dcebba097 100644 --- a/packages/workspace/src/command-line/run-many.ts +++ b/packages/workspace/src/command-line/run-many.ts @@ -7,7 +7,7 @@ import { onlyWorkspaceProjects, ProjectGraph, ProjectGraphNode, - withDeps + withDeps, } from '../core/project-graph'; import { readEnvironment } from '../core/file-utils'; import { DefaultReporter } from '../tasks-runner/default-reporter'; @@ -22,7 +22,7 @@ export function runMany(parsedArgs: yargs.Arguments): void { const projectGraph = createProjectGraph(); const projects = projectsToRun(nxArgs, projectGraph); const projectMap: Record = {}; - projects.forEach(proj => { + projects.forEach((proj) => { projectMap[proj.name] = proj; }); const env = readEnvironment(nxArgs.target, projectMap); @@ -44,7 +44,7 @@ function projectsToRun(nxArgs: NxArgs, projectGraph: ProjectGraph) { } else { checkForInvalidProjects(nxArgs, allProjects); let selectedProjects = allProjects.filter( - p => nxArgs.projects.indexOf(p.name) > -1 + (p) => nxArgs.projects.indexOf(p.name) > -1 ); if (nxArgs.withDeps) { selectedProjects = Object.values( @@ -60,7 +60,7 @@ function checkForInvalidProjects( allProjects: ProjectGraphNode[] ) { const invalid = nxArgs.projects.filter( - name => !allProjects.find(p => p.name === name) + (name) => !allProjects.find((p) => p.name === name) ); if (invalid.length !== 0) { throw new Error(`Invalid projects: ${invalid.join(', ')}`); @@ -86,7 +86,7 @@ function runnableForTarget( if (strict && notRunnable.length) { output.warn({ title: `the following do not have configuration for "${target}"`, - bodyLines: notRunnable.map(p => '- ' + p.name) + bodyLines: notRunnable.map((p) => '- ' + p.name), }); } diff --git a/packages/workspace/src/command-line/run-one.ts b/packages/workspace/src/command-line/run-one.ts index bcbed184d7aaa..4162c010795f7 100644 --- a/packages/workspace/src/command-line/run-one.ts +++ b/packages/workspace/src/command-line/run-one.ts @@ -16,7 +16,7 @@ export function runOne(opts: { ...opts.parsedArgs, configuration: opts.configuration, target: opts.target, - _: [] + _: [], }, 'run-one' ); @@ -30,7 +30,7 @@ export function runOne(opts: { ); const env = readEnvironment(opts.target, projectsMap); const reporter = nxArgs.withDeps - ? new (require(`../tasks-runner/run-one-reporter`)).RunOneReporter( + ? new (require(`../tasks-runner/run-one-reporter`).RunOneReporter)( opts.project ) : new EmptyReporter(); @@ -54,7 +54,7 @@ function getProjects( ): any { let projects = [projectGraph.nodes[project]]; let projectsMap = { - [project]: projectGraph.nodes[project] + [project]: projectGraph.nodes[project], }; if (includeDeps) { @@ -66,7 +66,7 @@ function getProjects( ); return { projects: projectsWithTarget, - projectsMap: deps + projectsMap: deps, }; } else { return { projects, projectsMap }; diff --git a/packages/workspace/src/command-line/shared.ts b/packages/workspace/src/command-line/shared.ts index 89e1fab82fe23..fc4d3f678b392 100644 --- a/packages/workspace/src/command-line/shared.ts +++ b/packages/workspace/src/command-line/shared.ts @@ -12,7 +12,7 @@ export function printArgsWarning(options: NxArgs) { output.note({ title: `Affected criteria defaulted to --base=${output.bold( 'master' - )} --head=${output.bold('HEAD')}` + )} --head=${output.bold('HEAD')}`, }); } @@ -25,8 +25,8 @@ export function printArgsWarning(options: NxArgs) { '', output.colors.gray( 'Learn more about checking only what is affected: ' - ) + 'https://nx.dev/guides/monorepo-affected.' - ] + ) + 'https://nx.dev/guides/monorepo-affected.', + ], }); } } @@ -36,19 +36,19 @@ export function parseFiles(options: NxArgs): { files: string[] } { if (files) { return { - files + files, }; } else if (uncommitted) { return { - files: getUncommittedFiles() + files: getUncommittedFiles(), }; } else if (untracked) { return { - files: getUntrackedFiles() + files: getUntrackedFiles(), }; } else if (base && head) { return { - files: getFilesUsingBaseAndHead(base, head) + files: getFilesUsingBaseAndHead(base, head), }; } else if (base) { return { @@ -56,9 +56,9 @@ export function parseFiles(options: NxArgs): { files: string[] } { new Set([ ...getFilesUsingBaseAndHead(base, 'HEAD'), ...getUncommittedFiles(), - ...getUntrackedFiles() + ...getUntrackedFiles(), ]) - ) + ), }; } } @@ -73,7 +73,7 @@ function getUntrackedFiles(): string[] { function getFilesUsingBaseAndHead(base: string, head: string): string[] { const mergeBase = execSync(`git merge-base ${base} ${head}`, { - maxBuffer: TEN_MEGABYTES + maxBuffer: TEN_MEGABYTES, }) .toString() .trim(); @@ -84,8 +84,8 @@ function parseGitOutput(command: string): string[] { return execSync(command, { maxBuffer: TEN_MEGABYTES }) .toString('utf-8') .split('\n') - .map(a => a.trim()) - .filter(a => a.length > 0); + .map((a) => a.trim()) + .filter((a) => a.length > 0); } // TODO: remove it in Nx 10 @@ -99,5 +99,5 @@ export function getProjectNodes( export function getProjectRoots(projectNames: string[]): string[] { const { projects } = readWorkspaceJson(); - return projectNames.map(name => projects[name].root); + return projectNames.map((name) => projects[name].root); } diff --git a/packages/workspace/src/command-line/supported-nx-commands.ts b/packages/workspace/src/command-line/supported-nx-commands.ts index a93e519d64f5b..550a8be07c3f8 100644 --- a/packages/workspace/src/command-line/supported-nx-commands.ts +++ b/packages/workspace/src/command-line/supported-nx-commands.ts @@ -20,5 +20,5 @@ export const supportedNxCommands = [ 'list', 'help', '--help', - '--version' + '--version', ]; diff --git a/packages/workspace/src/command-line/utils.spec.ts b/packages/workspace/src/command-line/utils.spec.ts index f1fa0b1ba7522..f0382e16ae073 100644 --- a/packages/workspace/src/command-line/utils.spec.ts +++ b/packages/workspace/src/command-line/utils.spec.ts @@ -9,7 +9,7 @@ describe('splitArgs', () => { head: 'sha2', notNxArg: true, _: ['--override'], - $0: '' + $0: '', }, 'affected' ).nxArgs @@ -17,7 +17,7 @@ describe('splitArgs', () => { base: 'sha1', head: 'sha2', projects: [], - skipNxCache: false + skipNxCache: false, }); }); @@ -27,14 +27,14 @@ describe('splitArgs', () => { { notNxArg: true, _: ['--override'], - $0: '' + $0: '', }, 'affected' ).nxArgs ).toEqual({ base: 'master', projects: [], - skipNxCache: false + skipNxCache: false, }); }); @@ -45,13 +45,13 @@ describe('splitArgs', () => { files: [''], notNxArg: true, _: ['--override'], - $0: '' + $0: '', }, 'affected' ).overrides ).toEqual({ notNxArg: true, - override: true + override: true, }); }); @@ -60,7 +60,7 @@ describe('splitArgs', () => { { notNxArg: true, _: ['sha1', 'sha2', '--override'], - $0: '' + $0: '', }, 'affected' ); @@ -69,11 +69,11 @@ describe('splitArgs', () => { base: 'sha1', head: 'sha2', projects: [], - skipNxCache: false + skipNxCache: false, }); expect(overrides).toEqual({ notNxArg: true, - override: true + override: true, }); }); }); diff --git a/packages/workspace/src/command-line/utils.ts b/packages/workspace/src/command-line/utils.ts index 5849f79c97d48..35413d06cacea 100644 --- a/packages/workspace/src/command-line/utils.ts +++ b/packages/workspace/src/command-line/utils.ts @@ -18,7 +18,7 @@ const runOne = [ 'withDeps', 'with-deps', 'skipNxCache', - 'skip-nx-cache' + 'skip-nx-cache', ]; const runMany = [...runOne, 'projects', 'quiet', 'all']; @@ -33,7 +33,7 @@ const runAffected = [ 'files', 'quiet', 'plain', - 'select' + 'select', ]; export interface NxArgs { diff --git a/packages/workspace/src/command-line/workspace-integrity-checks.spec.ts b/packages/workspace/src/command-line/workspace-integrity-checks.spec.ts index 21bdb87b00cae..78e034a24c89c 100644 --- a/packages/workspace/src/command-line/workspace-integrity-checks.spec.ts +++ b/packages/workspace/src/command-line/workspace-integrity-checks.spec.ts @@ -17,11 +17,11 @@ describe('WorkspaceIntegrityChecks', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/project1/src/index.ts')] - } - } + files: [createFile('libs/project1/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, }, ['libs/project1/src/index.ts'] ); @@ -40,8 +40,8 @@ describe('WorkspaceIntegrityChecks', () => { tags: [], implicitDependencies: [], architect: {}, - files: [] - } + files: [], + }, }, project2: { name: 'project2', @@ -51,11 +51,11 @@ describe('WorkspaceIntegrityChecks', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/project2/src/index.ts')] - } - } + files: [createFile('libs/project2/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, }, ['libs/project2/src/index.ts'] ); @@ -66,10 +66,10 @@ describe('WorkspaceIntegrityChecks', () => { bodyLines: [ `${chalk.grey( '-' - )} Cannot find project 'project1' in 'libs/project1'` + )} Cannot find project 'project1' in 'libs/project1'`, ], - title: 'The workspace.json file is out of sync' - } + title: 'The workspace.json file is out of sync', + }, ]); }); @@ -85,11 +85,11 @@ describe('WorkspaceIntegrityChecks', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/project1/src/index.ts')] - } - } + files: [createFile('libs/project1/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, }, ['libs/project1/src/index.ts', 'libs/project2/src/index.ts'] ); @@ -98,8 +98,8 @@ describe('WorkspaceIntegrityChecks', () => { expect(errors).toEqual([ { bodyLines: [`${chalk.grey('-')} libs/project2/src/index.ts`], - title: 'The following file(s) do not belong to any projects:' - } + title: 'The following file(s) do not belong to any projects:', + }, ]); }); }); diff --git a/packages/workspace/src/command-line/workspace-integrity-checks.ts b/packages/workspace/src/command-line/workspace-integrity-checks.ts index 7833cb5d9f4fa..c3a1f5be9c345 100644 --- a/packages/workspace/src/command-line/workspace-integrity-checks.ts +++ b/packages/workspace/src/command-line/workspace-integrity-checks.ts @@ -11,11 +11,11 @@ export class WorkspaceIntegrityChecks { private projectWithoutFilesCheck(): CLIErrorMessageConfig[] { const errors = Object.values(this.projectGraph.nodes) - .filter(n => n.data.files.length === 0) - .map(p => `Cannot find project '${p.name}' in '${p.data.root}'`); + .filter((n) => n.data.files.length === 0) + .map((p) => `Cannot find project '${p.name}' in '${p.data.root}'`); const errorGroupBodyLines = errors.map( - f => `${output.colors.gray('-')} ${f}` + (f) => `${output.colors.gray('-')} ${f}` ); return errors.length === 0 @@ -23,12 +23,12 @@ export class WorkspaceIntegrityChecks { : [ { title: `The ${workspaceFileName()} file is out of sync`, - bodyLines: errorGroupBodyLines + bodyLines: errorGroupBodyLines, /** * TODO(JamesHenry): Add support for error documentation */ // slug: 'project-has-no-files' - } + }, ]; } @@ -41,7 +41,7 @@ export class WorkspaceIntegrityChecks { : allFilesWithoutProjects; const errorGroupBodyLines = first5FilesWithoutProjects.map( - f => `${output.colors.gray('-')} ${f}` + (f) => `${output.colors.gray('-')} ${f}` ); return first5FilesWithoutProjects.length === 0 @@ -49,23 +49,23 @@ export class WorkspaceIntegrityChecks { : [ { title: `The following file(s) do not belong to any projects:`, - bodyLines: errorGroupBodyLines + bodyLines: errorGroupBodyLines, /** * TODO(JamesHenry): Add support for error documentation */ // slug: 'file-does-not-belong-to-project' - } + }, ]; } private allProjectFiles() { return Object.values(this.projectGraph.nodes).reduce( - (m, c) => [...m, ...c.data.files.map(f => f.file)], + (m, c) => [...m, ...c.data.files.map((f) => f.file)], [] ); } } function minus(a: string[], b: string[]): string[] { - return a.filter(aa => b.indexOf(aa) === -1); + return a.filter((aa) => b.indexOf(aa) === -1); } diff --git a/packages/workspace/src/command-line/workspace-results.spec.ts b/packages/workspace/src/command-line/workspace-results.spec.ts index c810c2de5570a..93c1ab27f92ef 100644 --- a/packages/workspace/src/command-line/workspace-results.spec.ts +++ b/packages/workspace/src/command-line/workspace-results.spec.ts @@ -13,9 +13,9 @@ describe('WorkspacesResults', () => { name: 'proj', type: ProjectType.app, data: { - files: [] - } - } + files: [], + }, + }, }); }); @@ -65,8 +65,8 @@ describe('WorkspacesResults', () => { serializeJson({ command: 'test', results: { - proj: false - } + proj: false, + }, }) ); }); @@ -82,8 +82,8 @@ describe('WorkspacesResults', () => { serializeJson({ command: 'test', results: { - proj: false - } + proj: false, + }, }) ); @@ -92,9 +92,9 @@ describe('WorkspacesResults', () => { name: 'proj', type: ProjectType.app, data: { - files: [] - } - } + files: [], + }, + }, }); expect(fs.readFileSync).toHaveBeenCalledWith('dist/.nx-results', 'utf-8'); @@ -110,9 +110,9 @@ describe('WorkspacesResults', () => { name: 'proj', type: ProjectType.app, data: { - files: [] - } - } + files: [], + }, + }, }); }; @@ -125,8 +125,8 @@ describe('WorkspacesResults', () => { serializeJson({ command: 'test', results: { - proj: false - } + proj: false, + }, }) ); @@ -135,9 +135,9 @@ describe('WorkspacesResults', () => { name: 'proj', type: ProjectType.app, data: { - files: [] - } - } + files: [], + }, + }, }); expect(results.getResult('proj')).toBeUndefined(); @@ -149,8 +149,8 @@ describe('WorkspacesResults', () => { command: 'test', results: { proj: true, - proj2: false - } + proj2: false, + }, }) ); @@ -159,9 +159,9 @@ describe('WorkspacesResults', () => { name: 'proj', type: ProjectType.app, data: { - files: [] - } - } + files: [], + }, + }, }); expect(results.hasFailure).toEqual(false); diff --git a/packages/workspace/src/command-line/workspace-results.ts b/packages/workspace/src/command-line/workspace-results.ts index 99006cddcad33..78b724e504eb5 100644 --- a/packages/workspace/src/command-line/workspace-results.ts +++ b/packages/workspace/src/command-line/workspace-results.ts @@ -14,7 +14,7 @@ export class WorkspaceResults { public startedWithFailedProjects: boolean; private commandResults: NxResults = { command: this.command, - results: {} + results: {}, }; get failedProjects() { @@ -24,7 +24,7 @@ export class WorkspaceResults { } public get hasFailure() { - return Object.values(this.commandResults.results).some(result => !result); + return Object.values(this.commandResults.results).some((result) => !result); } constructor( @@ -68,7 +68,7 @@ export class WorkspaceResults { } private invalidateOldResults() { - Object.keys(this.commandResults.results).forEach(projectName => { + Object.keys(this.commandResults.results).forEach((projectName) => { if (!this.projects[projectName]) { delete this.commandResults.results[projectName]; } diff --git a/packages/workspace/src/command-line/workspace-schematic.ts b/packages/workspace/src/command-line/workspace-schematic.ts index d142d6262bc50..86b1e37b653eb 100644 --- a/packages/workspace/src/command-line/workspace-schematic.ts +++ b/packages/workspace/src/command-line/workspace-schematic.ts @@ -5,18 +5,18 @@ import { schema, tags, terminal, - virtualFs + virtualFs, } from '@angular-devkit/core'; import { createConsoleLogger, NodeJsSyncHost } from '@angular-devkit/core/node'; import { formats, SchematicEngine, - UnsuccessfulWorkflowExecution + UnsuccessfulWorkflowExecution, } from '@angular-devkit/schematics'; import { NodeModulesEngineHost, NodeWorkflow, - validateOptionsWithSchema + validateOptionsWithSchema, } from '@angular-devkit/schematics/tools'; import { execSync } from 'child_process'; import * as fs from 'fs'; @@ -90,7 +90,7 @@ function compileToolsDir(outDir: string) { try { execSync(`${tsc} -p tools/tsconfig.tools.json`, { stdio: 'inherit', - cwd: rootDirectory + cwd: rootDirectory, }); } catch (e) { process.exit(1); @@ -99,20 +99,20 @@ function compileToolsDir(outDir: string) { function constructCollection() { const schematics = {}; - fs.readdirSync(schematicsDir()).forEach(c => { + fs.readdirSync(schematicsDir()).forEach((c) => { const childDir = path.join(schematicsDir(), c); if (exists(path.join(childDir, 'schema.json'))) { schematics[c] = { factory: `./${c}`, schema: `./${path.join(c, 'schema.json')}`, - description: `Schematic ${c}` + description: `Schematic ${c}`, }; } }); return { name: 'workspace-schematics', version: '1.0', - schematics + schematics, }; } @@ -134,7 +134,7 @@ function createWorkflow(dryRun: boolean) { packageManager: detectPackageManager(), root, dryRun, - registry: new schema.CoreSchemaRegistry(formats.standardFormats) + registry: new schema.CoreSchemaRegistry(formats.standardFormats), }); } @@ -154,16 +154,16 @@ function listSchematics(collectionName: string, logger: logging.Logger) { function createPromptProvider(): schema.PromptProvider { return (definitions: Array) => { - const questions: inquirer.Questions = definitions.map(definition => { + const questions: inquirer.Questions = definitions.map((definition) => { const question: inquirer.Question = { name: definition.id, message: definition.message, - default: definition.default + default: definition.default, }; const validator = definition.validator; if (validator) { - question.validate = input => validator(input); + question.validate = (input) => validator(input); } switch (definition.type) { @@ -175,16 +175,16 @@ function createPromptProvider(): schema.PromptProvider { type: !!definition.multiselect ? 'checkbox' : 'list', choices: definition.items && - definition.items.map(item => { + definition.items.map((item) => { if (typeof item == 'string') { return item; } else { return { name: item.label, - value: item.value + value: item.value, }; } - }) + }), }; default: return { ...question, type: definition.type }; @@ -258,10 +258,10 @@ async function executeSchematic( } }); - workflow.lifeCycle.subscribe(event => { + workflow.lifeCycle.subscribe((event) => { if (event.kind === 'workflow-end' || event.kind === 'post-tasks-start') { if (!hasError) { - loggingQueue.forEach(log => logger.info(log)); + loggingQueue.forEach((log) => logger.info(log)); } loggingQueue = []; @@ -300,7 +300,7 @@ async function executeSchematic( collection: path.join(outDir, 'workspace-schematics.json'), schematic: schematicName, options: options, - logger: logger + logger: logger, }) .toPromise(); @@ -331,7 +331,7 @@ function parseOptions(args: string[], outDir: string): { [k: string]: any } { ); if (properties) { booleanProps = Object.keys(properties).filter( - key => properties[key].type === 'boolean' + (key) => properties[key].type === 'boolean' ); } } @@ -339,11 +339,11 @@ function parseOptions(args: string[], outDir: string): { [k: string]: any } { boolean: ['dryRun', 'listSchematics', 'interactive', ...booleanProps], alias: { dryRun: ['d'], - listSchematics: ['l'] + listSchematics: ['l'], }, default: { - interactive: true - } + interactive: true, + }, }); } diff --git a/packages/workspace/src/core/affected-project-graph/affected-project-graph.spec.ts b/packages/workspace/src/core/affected-project-graph/affected-project-graph.spec.ts index 829ebdd41bee1..f87de62e2b284 100644 --- a/packages/workspace/src/core/affected-project-graph/affected-project-graph.spec.ts +++ b/packages/workspace/src/core/affected-project-graph/affected-project-graph.spec.ts @@ -24,73 +24,73 @@ describe('project graph', () => { packageJson = { name: '@nrwl/workspace-src', scripts: { - deploy: 'echo deploy' + deploy: 'echo deploy', }, dependencies: { - 'happy-nrwl': '1.0.0' + 'happy-nrwl': '1.0.0', }, devDependencies: { - '@nrwl/workspace': '8.0.0' - } + '@nrwl/workspace': '8.0.0', + }, }; workspaceJson = { projects: { demo: { root: 'apps/demo/', sourceRoot: 'apps/demo/src', - projectType: 'application' + projectType: 'application', }, 'demo-e2e': { root: 'apps/demo-e2e/', sourceRoot: 'apps/demo-e2e/src', - projectType: 'application' + projectType: 'application', }, ui: { root: 'libs/ui/', sourceRoot: 'libs/ui/src', - projectType: 'library' + projectType: 'library', }, util: { root: 'libs/util/', sourceRoot: 'libs/util/src', - projectType: 'library' + projectType: 'library', }, api: { root: 'apps/api/', sourceRoot: 'apps/api/src', - projectType: 'application' - } - } + projectType: 'application', + }, + }, }; nxJson = { npmScope: 'nrwl', implicitDependencies: { 'package.json': { scripts: { - deploy: ['demo', 'api'] + deploy: ['demo', 'api'], }, devDependencies: { - '@nrwl/workspace': '*' - } + '@nrwl/workspace': '*', + }, }, - 'something-for-api.txt': ['api'] + 'something-for-api.txt': ['api'], }, projects: { api: { tags: [] }, demo: { tags: [], implicitDependencies: ['api'] }, 'demo-e2e': { tags: [] }, ui: { tags: [] }, - util: { tags: [] } - } + util: { tags: [] }, + }, }; tsConfigJson = { compilerOptions: { baseUrl: '.', paths: { '@nrwl/ui': ['libs/ui/src/index.ts'], - '@nrwl/util': ['libs/util/src/index.ts'] - } - } + '@nrwl/util': ['libs/util/src/index.ts'], + }, + }, }; filesJson = { './apps/api/src/index.ts': stripIndents` @@ -111,12 +111,12 @@ describe('project graph', () => { './package.json': JSON.stringify(packageJson), './nx.json': JSON.stringify(nxJson), './workspace.json': JSON.stringify(workspaceJson), - './tsconfig.json': JSON.stringify(tsConfigJson) + './tsconfig.json': JSON.stringify(tsConfigJson), }; - files = Object.keys(filesJson).map(f => ({ + files = Object.keys(filesJson).map((f) => ({ file: f, ext: extname(f), - mtime: 1 + mtime: 1, })); readFileAtRevision = (p, r) => { const fromFs = filesJson[`./${p}`]; @@ -140,61 +140,61 @@ describe('project graph', () => { file: 'something-for-api.txt', ext: '.txt', mtime: 1, - getChanges: () => [new WholeFileChange()] + getChanges: () => [new WholeFileChange()], }, { file: 'libs/ui/src/index.ts', ext: '.ts', mtime: 1, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ]); expect(affected).toEqual({ nodes: { api: { name: 'api', type: 'app', - data: expect.anything() + data: expect.anything(), }, demo: { name: 'demo', type: 'app', - data: expect.anything() + data: expect.anything(), }, 'demo-e2e': { name: 'demo-e2e', type: 'e2e', - data: expect.anything() + data: expect.anything(), }, ui: { name: 'ui', type: 'lib', - data: expect.anything() - } + data: expect.anything(), + }, }, dependencies: { 'demo-e2e': [ { type: 'implicit', source: 'demo-e2e', - target: 'demo' - } + target: 'demo', + }, ], demo: [ { type: 'static', source: 'demo', - target: 'ui' + target: 'ui', }, { type: 'implicit', source: 'demo', - target: 'api' - } + target: 'api', + }, ], api: [], - ui: [] - } + ui: [], + }, }); }); @@ -203,8 +203,8 @@ describe('project graph', () => { const updatedPackageJson = { ...packageJson, dependencies: { - 'happy-nrwl': '2.0.0' - } + 'happy-nrwl': '2.0.0', + }, }; const affected = filterAffected(graph, [ @@ -212,8 +212,8 @@ describe('project graph', () => { file: 'package.json', ext: '.json', mtime: 1, - getChanges: () => jsonDiff(packageJson, updatedPackageJson) - } + getChanges: () => jsonDiff(packageJson, updatedPackageJson), + }, ]); expect(affected).toEqual({ @@ -221,28 +221,28 @@ describe('project graph', () => { 'happy-nrwl': { type: 'npm', name: 'happy-nrwl', - data: expect.anything() + data: expect.anything(), }, util: { name: 'util', type: 'lib', - data: expect.anything() + data: expect.anything(), }, ui: { name: 'ui', type: 'lib', - data: expect.anything() + data: expect.anything(), }, demo: { name: 'demo', type: 'app', - data: expect.anything() + data: expect.anything(), }, 'demo-e2e': { name: 'demo-e2e', type: 'e2e', - data: expect.anything() - } + data: expect.anything(), + }, }, dependencies: { 'happy-nrwl': [], @@ -250,19 +250,19 @@ describe('project graph', () => { { type: 'implicit', source: 'demo-e2e', - target: 'demo' - } + target: 'demo', + }, ], demo: [ { type: 'static', source: 'demo', - target: 'ui' - } + target: 'ui', + }, ], ui: [{ type: 'static', source: 'ui', target: 'util' }], - util: [{ type: 'static', source: 'util', target: 'happy-nrwl' }] - } + util: [{ type: 'static', source: 'util', target: 'happy-nrwl' }], + }, }); }); @@ -271,8 +271,8 @@ describe('project graph', () => { const updatedPackageJson = { ...packageJson, scripts: { - deploy: 'echo deploy!!!' - } + deploy: 'echo deploy!!!', + }, }; const affected = filterAffected(graph, [ @@ -280,8 +280,8 @@ describe('project graph', () => { file: 'package.json', ext: '.json', mtime: 1, - getChanges: () => jsonDiff(packageJson, updatedPackageJson) - } + getChanges: () => jsonDiff(packageJson, updatedPackageJson), + }, ]); expect(Object.keys(affected.nodes)).toEqual(['demo', 'demo-e2e', 'api']); @@ -292,8 +292,8 @@ describe('project graph', () => { const updatedPackageJson = { ...packageJson, devDependencies: { - '@nrwl/workspace': '9.0.0' - } + '@nrwl/workspace': '9.0.0', + }, }; const affected = filterAffected(graph, [ @@ -301,8 +301,8 @@ describe('project graph', () => { file: 'package.json', ext: '.json', mtime: 1, - getChanges: () => jsonDiff(packageJson, updatedPackageJson) - } + getChanges: () => jsonDiff(packageJson, updatedPackageJson), + }, ]); expect(Object.keys(affected.nodes)).toEqual([ @@ -311,7 +311,7 @@ describe('project graph', () => { 'demo', 'demo-e2e', 'ui', - 'util' + 'util', ]); }); }); diff --git a/packages/workspace/src/core/affected-project-graph/affected-project-graph.ts b/packages/workspace/src/core/affected-project-graph/affected-project-graph.ts index 3f6aa9ed6b504..58c3cc46201d9 100644 --- a/packages/workspace/src/core/affected-project-graph/affected-project-graph.ts +++ b/packages/workspace/src/core/affected-project-graph/affected-project-graph.ts @@ -3,18 +3,18 @@ import { FileChange, readNxJson, readPackageJson, - readWorkspaceJson + readWorkspaceJson, } from '../file-utils'; import { NxJson } from '../shared-interfaces'; import { getImplicitlyTouchedProjects, - getTouchedProjects + getTouchedProjects, } from './locators/workspace-projects'; import { getTouchedNpmPackages } from './locators/npm-packages'; import { getImplicitlyTouchedProjectsByJsonChanges } from './locators/implicit-json-changes'; import { AffectedProjectGraphContext, - TouchedProjectLocator + TouchedProjectLocator, } from './affected-project-graph-models'; import { normalizeNxJson } from '../normalize-nx-json'; import { getTouchedProjectsInNxJson } from './locators/nx-json-changes'; @@ -37,21 +37,18 @@ export function filterAffected( getImplicitlyTouchedProjectsByJsonChanges, getTouchedProjectsInNxJson, getTouchedProjectsInWorkspaceJson, - getTouchedProjectsFromTsConfig + getTouchedProjectsFromTsConfig, ]; - const touchedProjects = touchedProjectLocators.reduce( - (acc, f) => { - return acc.concat( - f(touchedFiles, workspaceJson, normalizedNxJson, packageJson, graph) - ); - }, - [] as string[] - ); + const touchedProjects = touchedProjectLocators.reduce((acc, f) => { + return acc.concat( + f(touchedFiles, workspaceJson, normalizedNxJson, packageJson, graph) + ); + }, [] as string[]); return filterAffectedProjects(graph, { workspaceJson, nxJson: normalizedNxJson, - touchedProjects + touchedProjects, }); } @@ -63,10 +60,10 @@ function filterAffectedProjects( ): ProjectGraph { const builder = new ProjectGraphBuilder(); const reversed = reverse(graph); - ctx.touchedProjects.forEach(p => { + ctx.touchedProjects.forEach((p) => { addAffectedNodes(p, reversed, builder, []); }); - ctx.touchedProjects.forEach(p => { + ctx.touchedProjects.forEach((p) => { addAffectedDependencies(p, reversed, builder, []); }); return builder.build(); diff --git a/packages/workspace/src/core/affected-project-graph/locators/implicit-json-changes.spec.ts b/packages/workspace/src/core/affected-project-graph/locators/implicit-json-changes.spec.ts index 2d539a6de0579..115564cba5159 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/implicit-json-changes.spec.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/implicit-json-changes.spec.ts @@ -10,23 +10,23 @@ describe('getImplicitlyTouchedProjectsByJsonChanges', () => { workspaceJson = { projects: { proj1: {}, - proj2: {} - } + proj2: {}, + }, }; nxJson = { implicitDependencies: { 'package.json': { dependencies: ['proj1'], some: { - 'deep-field': ['proj2'] - } - } + 'deep-field': ['proj2'], + }, + }, }, npmScope: 'scope', projects: { proj1: {}, - proj2: {} - } + proj2: {}, + }, }; }); @@ -43,11 +43,11 @@ describe('getImplicitlyTouchedProjectsByJsonChanges', () => { path: ['some', 'deep-field'], value: { lhs: 'before', - rhs: 'after' - } - } - ] - } + rhs: 'after', + }, + }, + ], + }, ], workspaceJson, nxJson @@ -62,8 +62,8 @@ describe('getImplicitlyTouchedProjectsByJsonChanges', () => { file: 'package.json', mtime: 0, ext: '.json', - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ], workspaceJson, nxJson diff --git a/packages/workspace/src/core/affected-project-graph/locators/implicit-json-changes.ts b/packages/workspace/src/core/affected-project-graph/locators/implicit-json-changes.ts index 7206dd989c613..da2d10b117cb0 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/implicit-json-changes.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/implicit-json-changes.ts @@ -2,7 +2,7 @@ import { WholeFileChange } from '../../file-utils'; import { isJsonChange, JsonChange, - walkJsonTree + walkJsonTree, } from '../../../utils/json-diff'; import { TouchedProjectLocator } from '../affected-project-graph-models'; import { ImplicitDependencyEntry } from '../../shared-interfaces'; @@ -25,13 +25,13 @@ export const getImplicitlyTouchedProjectsByJsonChanges: TouchedProjectLocator< if (isJsonChange(c)) { const projects = getTouchedProjects(c.path, implicitDependencies[f.file]) || []; - projects.forEach(p => touched.push(p)); + projects.forEach((p) => touched.push(p)); } else { const projects = getTouchedProjectsByJsonFile( implicitDependencies, f.file ); - projects.forEach(p => touched.push(p)); + projects.forEach((p) => touched.push(p)); } } } diff --git a/packages/workspace/src/core/affected-project-graph/locators/npm-packages.spec.ts b/packages/workspace/src/core/affected-project-graph/locators/npm-packages.spec.ts index 32337351b3aee..cf4360710a168 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/npm-packages.spec.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/npm-packages.spec.ts @@ -10,23 +10,23 @@ describe('getTouchedNpmPackages', () => { workspaceJson = { projects: { proj1: {}, - proj2: {} - } + proj2: {}, + }, }; nxJson = { implicitDependencies: { 'package.json': { dependencies: ['proj1'], some: { - 'deep-field': ['proj2'] - } - } + 'deep-field': ['proj2'], + }, + }, }, npmScope: 'scope', projects: { proj1: {}, - proj2: {} - } + proj2: {}, + }, }; }); @@ -43,18 +43,18 @@ describe('getTouchedNpmPackages', () => { path: ['dependencies', 'happy-nrwl'], value: { lhs: '0.0.1', - rhs: '0.0.2' - } - } - ] - } + rhs: '0.0.2', + }, + }, + ], + }, ], workspaceJson, nxJson, { dependencies: { - 'happy-nrwl': '0.0.2' - } + 'happy-nrwl': '0.0.2', + }, } ); expect(result).toEqual(['happy-nrwl']); @@ -73,18 +73,18 @@ describe('getTouchedNpmPackages', () => { path: ['dependencies', 'sad-nrwl'], value: { lhs: '0.0.1', - rhs: undefined - } - } - ] - } + rhs: undefined, + }, + }, + ], + }, ], workspaceJson, nxJson, { dependencies: { - 'happy-nrwl': '0.0.2' - } + 'happy-nrwl': '0.0.2', + }, } ); expect(result).toEqual(['proj1', 'proj2']); @@ -103,19 +103,19 @@ describe('getTouchedNpmPackages', () => { path: ['dependencies', 'awesome-nrwl'], value: { lhs: undefined, - rhs: '0.0.1' - } - } - ] - } + rhs: '0.0.1', + }, + }, + ], + }, ], workspaceJson, nxJson, { dependencies: { 'happy-nrwl': '0.0.2', - 'awesome-nrwl': '0.0.1' - } + 'awesome-nrwl': '0.0.1', + }, } ); expect(result).toEqual(['awesome-nrwl']); @@ -128,16 +128,16 @@ describe('getTouchedNpmPackages', () => { file: 'package.json', mtime: 0, ext: '.json', - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ], workspaceJson, nxJson, { dependencies: { 'happy-nrwl': '0.0.1', - 'awesome-nrwl': '0.0.1' - } + 'awesome-nrwl': '0.0.1', + }, } ); expect(result).toEqual(['happy-nrwl', 'awesome-nrwl']); diff --git a/packages/workspace/src/core/affected-project-graph/locators/npm-packages.ts b/packages/workspace/src/core/affected-project-graph/locators/npm-packages.ts index d5b575a54393b..25fa1cd7ea6b4 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/npm-packages.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/npm-packages.ts @@ -5,7 +5,7 @@ import { TouchedProjectLocator } from '../affected-project-graph-models'; export const getTouchedNpmPackages: TouchedProjectLocator< WholeFileChange | JsonChange > = (touchedFiles, workspaceJson, nxJson, packageJson): string[] => { - const packageJsonChange = touchedFiles.find(f => f.file === 'package.json'); + const packageJsonChange = touchedFiles.find((f) => f.file === 'package.json'); if (!packageJsonChange) return []; let touched = []; @@ -28,7 +28,7 @@ export const getTouchedNpmPackages: TouchedProjectLocator< // Whole file was touched, so all npm packages are touched. touched = Object.keys({ ...(packageJson.dependencies || {}), - ...(packageJson.devDependencies || {}) + ...(packageJson.devDependencies || {}), }); break; } diff --git a/packages/workspace/src/core/affected-project-graph/locators/nx-json-changes.spec.ts b/packages/workspace/src/core/affected-project-graph/locators/nx-json-changes.spec.ts index 3261549a8d39e..d2cb270f021fc 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/nx-json-changes.spec.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/nx-json-changes.spec.ts @@ -10,17 +10,17 @@ describe('getTouchedProjectsInNxJson', () => { file: 'source.ts', ext: '.ts', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ], {}, { npmScope: 'proj', projects: { proj1: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual([]); @@ -33,20 +33,20 @@ describe('getTouchedProjectsInNxJson', () => { file: 'nx.json', ext: '.json', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ], {}, { npmScope: 'proj', projects: { proj1: { - tags: [] + tags: [], }, proj2: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual(['proj1', 'proj2']); @@ -65,23 +65,23 @@ describe('getTouchedProjectsInNxJson', () => { path: ['npmScope'], value: { lhs: 'proj', - rhs: 'awesome-proj' - } - } - ] - } + rhs: 'awesome-proj', + }, + }, + ], + }, ], {}, { npmScope: 'proj', projects: { proj1: { - tags: [] + tags: [], }, proj2: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual(['proj1', 'proj2']); @@ -101,32 +101,32 @@ describe('getTouchedProjectsInNxJson', () => { value: { lhs: undefined, rhs: { - tags: [] - } - } + tags: [], + }, + }, }, { type: DiffType.Added, path: ['projects', 'proj1', 'tags'], value: { lhs: undefined, - rhs: [] - } - } - ] - } + rhs: [], + }, + }, + ], + }, ], {}, { npmScope: 'proj', projects: { proj1: { - tags: [] + tags: [], }, proj2: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual(['proj1']); @@ -145,25 +145,25 @@ describe('getTouchedProjectsInNxJson', () => { path: ['projects', 'proj3'], value: { lhs: { - tags: [] + tags: [], }, - rhs: undefined - } - } - ] - } + rhs: undefined, + }, + }, + ], + }, ], {}, { npmScope: 'proj', projects: { proj1: { - tags: [] + tags: [], }, proj2: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual(['proj1', 'proj2']); @@ -183,40 +183,40 @@ describe('getTouchedProjectsInNxJson', () => { value: { lhs: { tags: ['scope:feat'] }, rhs: { - tags: ['scope:shared'] - } - } + tags: ['scope:shared'], + }, + }, }, { type: DiffType.Modified, path: ['projects', 'proj1', 'tags'], value: { lhs: ['scope:feat'], - rhs: ['scope:shared'] - } + rhs: ['scope:shared'], + }, }, { type: DiffType.Modified, path: ['projects', 'proj1', 'tags', '0'], value: { lhs: 'scope:feat', - rhs: 'scope:shared' - } - } - ] - } + rhs: 'scope:shared', + }, + }, + ], + }, ], {}, { npmScope: 'proj', projects: { proj1: { - tags: [] + tags: [], }, proj2: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual(['proj1']); diff --git a/packages/workspace/src/core/affected-project-graph/locators/nx-json-changes.ts b/packages/workspace/src/core/affected-project-graph/locators/nx-json-changes.ts index 068d002685686..3a4e56d5d8dbb 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/nx-json-changes.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/nx-json-changes.ts @@ -5,7 +5,7 @@ import { TouchedProjectLocator } from '../affected-project-graph-models'; export const getTouchedProjectsInNxJson: TouchedProjectLocator< WholeFileChange | JsonChange > = (touchedFiles, workspaceJson, nxJson): string[] => { - const nxJsonChange = touchedFiles.find(change => change.file === 'nx.json'); + const nxJsonChange = touchedFiles.find((change) => change.file === 'nx.json'); if (!nxJsonChange) { return []; } @@ -13,7 +13,7 @@ export const getTouchedProjectsInNxJson: TouchedProjectLocator< const changes = nxJsonChange.getChanges(); if ( - changes.some(change => { + changes.some((change) => { if (isJsonChange(change)) { return change.path[0] !== 'projects'; } diff --git a/packages/workspace/src/core/affected-project-graph/locators/tsconfig-json-changes.spec.ts b/packages/workspace/src/core/affected-project-graph/locators/tsconfig-json-changes.spec.ts index a02026cd45db0..49a6424099798 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/tsconfig-json-changes.spec.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/tsconfig-json-changes.spec.ts @@ -13,28 +13,28 @@ describe('getTouchedProjectsFromTsConfig', () => { type: 'app', data: { root: 'proj1', - files: [] - } + files: [], + }, }, proj2: { name: 'proj2', type: 'lib', data: { root: 'proj2', - files: [] - } - } + files: [], + }, + }, }, dependencies: { proj1: [ { type: DependencyType.static, source: 'proj1', - target: 'proj2' - } + target: 'proj2', + }, ], - proj2: [] - } + proj2: [], + }, }; }); it('should not return changes when tsconfig.json is not touched', () => { @@ -44,17 +44,17 @@ describe('getTouchedProjectsFromTsConfig', () => { file: 'source.ts', ext: '.ts', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ], {}, { npmScope: 'proj', projects: { proj1: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual([]); @@ -68,8 +68,8 @@ describe('getTouchedProjectsFromTsConfig', () => { file: 'tsconfig.json', ext: '.json', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ], null, null, @@ -92,16 +92,16 @@ describe('getTouchedProjectsFromTsConfig', () => { jsonDiff( { compilerOptions: { - strict: false - } + strict: false, + }, }, { compilerOptions: { - strict: true - } + strict: true, + }, } - ) - } + ), + }, ], null, null, @@ -124,18 +124,18 @@ describe('getTouchedProjectsFromTsConfig', () => { jsonDiff( { compilerOptions: { - paths: {} - } + paths: {}, + }, }, { compilerOptions: { paths: { - '@proj/proj1': ['proj1/index.ts'] - } - } + '@proj/proj1': ['proj1/index.ts'], + }, + }, } - ) - } + ), + }, ], null, null, @@ -156,18 +156,18 @@ describe('getTouchedProjectsFromTsConfig', () => { jsonDiff( { compilerOptions: { - paths: {} - } + paths: {}, + }, }, { compilerOptions: { paths: { - '@proj/proj1': ['./proj1/index.ts'] - } - } + '@proj/proj1': ['./proj1/index.ts'], + }, + }, } - ) - } + ), + }, ], null, null, @@ -191,17 +191,17 @@ describe('getTouchedProjectsFromTsConfig', () => { { compilerOptions: { paths: { - '@proj/proj1': ['proj1/index.ts'] - } - } + '@proj/proj1': ['proj1/index.ts'], + }, + }, }, { compilerOptions: { - paths: {} - } + paths: {}, + }, } - ) - } + ), + }, ], null, null, @@ -223,19 +223,19 @@ describe('getTouchedProjectsFromTsConfig', () => { { compilerOptions: { paths: { - '@proj/proj1': ['proj1/index.ts', 'proj1/index2.ts'] - } - } + '@proj/proj1': ['proj1/index.ts', 'proj1/index2.ts'], + }, + }, }, { compilerOptions: { paths: { - '@proj/proj1': ['proj1/index.ts'] - } - } + '@proj/proj1': ['proj1/index.ts'], + }, + }, } - ) - } + ), + }, ], null, null, @@ -260,19 +260,19 @@ describe('getTouchedProjectsFromTsConfig', () => { { compilerOptions: { paths: { - '@proj/proj1': ['proj1/index.ts'] - } - } + '@proj/proj1': ['proj1/index.ts'], + }, + }, }, { compilerOptions: { paths: { - '@proj/proj1': ['proj1/index2.ts'] - } - } + '@proj/proj1': ['proj1/index2.ts'], + }, + }, } - ) - } + ), + }, ], null, null, @@ -295,19 +295,19 @@ describe('getTouchedProjectsFromTsConfig', () => { { compilerOptions: { paths: { - '@proj/proj1': ['proj1/index.ts'] - } - } + '@proj/proj1': ['proj1/index.ts'], + }, + }, }, { compilerOptions: { paths: { - '@proj/proj1': ['proj2/index.ts'] - } - } + '@proj/proj1': ['proj2/index.ts'], + }, + }, } - ) - } + ), + }, ], null, null, diff --git a/packages/workspace/src/core/affected-project-graph/locators/tsconfig-json-changes.ts b/packages/workspace/src/core/affected-project-graph/locators/tsconfig-json-changes.ts index fee2de655521e..4511e0eef3631 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/tsconfig-json-changes.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/tsconfig-json-changes.ts @@ -6,7 +6,7 @@ import { TouchedProjectLocator } from '../affected-project-graph-models'; import { getSortedProjectNodes, onlyWorkspaceProjects, - ProjectGraphNode + ProjectGraphNode, } from '../../project-graph'; import { appRootPath } from '../../../utils/app-root'; @@ -14,7 +14,7 @@ export const getTouchedProjectsFromTsConfig: TouchedProjectLocator< WholeFileChange | JsonChange > = (touchedFiles, _a, _b, _c, graph): string[] => { const tsConfigJsonChanges = touchedFiles.find( - change => change.file === 'tsconfig.json' + (change) => change.file === 'tsconfig.json' ); if (!tsConfigJsonChanges) { return []; @@ -63,8 +63,8 @@ function getProjectsAffectedByPaths( const result = []; const paths: string[] = [change.value.lhs, change.value.rhs]; - paths.forEach(path => { - sortedNodes.forEach(project => { + paths.forEach((path) => { + sortedNodes.forEach((project) => { if ( path && project.data.root && diff --git a/packages/workspace/src/core/affected-project-graph/locators/workspace-json-changes.spec.ts b/packages/workspace/src/core/affected-project-graph/locators/workspace-json-changes.spec.ts index d313bdec0487d..dd4eff5d06f20 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/workspace-json-changes.spec.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/workspace-json-changes.spec.ts @@ -10,17 +10,17 @@ describe('getTouchedProjectsInWorkspaceJson', () => { file: 'source.ts', ext: '.ts', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ], {}, { npmScope: 'proj', projects: { proj1: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual([]); @@ -33,19 +33,19 @@ describe('getTouchedProjectsInWorkspaceJson', () => { file: 'workspace.json', ext: '.json', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ], { npmScope: 'proj', projects: { proj1: { - tags: [] + tags: [], }, proj2: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual(['proj1', 'proj2']); @@ -64,22 +64,22 @@ describe('getTouchedProjectsInWorkspaceJson', () => { path: ['newProjectRoot'], value: { lhs: '', - rhs: 'projects' - } - } - ] - } + rhs: 'projects', + }, + }, + ], + }, ], { newProjectRoot: 'projects', projects: { proj1: { - tags: [] + tags: [], }, proj2: { - tags: [] - } - } + tags: [], + }, + }, } ); expect(result).toEqual(['proj1', 'proj2']); @@ -99,9 +99,9 @@ describe('getTouchedProjectsInWorkspaceJson', () => { value: { lhs: undefined, rhs: { - root: 'proj1' - } - } + root: 'proj1', + }, + }, }, { @@ -109,18 +109,18 @@ describe('getTouchedProjectsInWorkspaceJson', () => { path: ['projects', 'proj1', 'root'], value: { lhs: undefined, - rhs: 'proj1' - } - } - ] - } + rhs: 'proj1', + }, + }, + ], + }, ], { projects: { proj1: { - root: 'proj1' - } - } + root: 'proj1', + }, + }, } ); expect(result).toEqual(['proj1']); @@ -139,23 +139,23 @@ describe('getTouchedProjectsInWorkspaceJson', () => { path: ['projects', 'proj3'], value: { lhs: { - root: 'proj3' + root: 'proj3', }, - rhs: undefined - } - } - ] - } + rhs: undefined, + }, + }, + ], + }, ], { projects: { proj1: { - root: 'proj1' + root: 'proj1', }, proj2: { - root: 'proj2' - } - } + root: 'proj2', + }, + }, } ); expect(result).toEqual(['proj1', 'proj2']); @@ -174,33 +174,33 @@ describe('getTouchedProjectsInWorkspaceJson', () => { path: ['projects', 'proj1'], value: { lhs: { - root: 'proj3' + root: 'proj3', }, rhs: { - root: 'proj1' - } - } + root: 'proj1', + }, + }, }, { type: DiffType.Modified, path: ['projects', 'proj1', 'root'], value: { lhs: 'proj3', - rhs: 'proj1' - } - } - ] - } + rhs: 'proj1', + }, + }, + ], + }, ], { projects: { proj1: { - root: 'proj1' + root: 'proj1', }, proj2: { - root: 'proj2' - } - } + root: 'proj2', + }, + }, } ); expect(result).toEqual(['proj1']); diff --git a/packages/workspace/src/core/affected-project-graph/locators/workspace-json-changes.ts b/packages/workspace/src/core/affected-project-graph/locators/workspace-json-changes.ts index d9c6dfa0d2b62..1e7b9b9301628 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/workspace-json-changes.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/workspace-json-changes.ts @@ -1,7 +1,7 @@ import { isWholeFileChange, WholeFileChange, - workspaceFileName + workspaceFileName, } from '../../file-utils'; import { DiffType, isJsonChange, JsonChange } from '../../../utils/json-diff'; import { TouchedProjectLocator } from '../affected-project-graph-models'; @@ -10,7 +10,7 @@ export const getTouchedProjectsInWorkspaceJson: TouchedProjectLocator< WholeFileChange | JsonChange > = (touchedFiles, workspaceJson): string[] => { const workspaceChange = touchedFiles.find( - change => change.file === workspaceFileName() + (change) => change.file === workspaceFileName() ); if (!workspaceChange) { return []; @@ -19,7 +19,7 @@ export const getTouchedProjectsInWorkspaceJson: TouchedProjectLocator< const changes = workspaceChange.getChanges(); if ( - changes.some(change => { + changes.some((change) => { if (isJsonChange(change)) { return change.path[0] !== 'projects'; } diff --git a/packages/workspace/src/core/affected-project-graph/locators/workspace-projects.spec.ts b/packages/workspace/src/core/affected-project-graph/locators/workspace-projects.spec.ts index b550a2410980b..0bd85fa415cf5 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/workspace-projects.spec.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/workspace-projects.spec.ts @@ -8,19 +8,19 @@ describe('getTouchedProjects', () => { file: 'libs/a/index.ts', ext: '.ts', mtime: 0, - getChanges: () => [new WholeFileChange()] + getChanges: () => [new WholeFileChange()], }, { file: 'libs/b/index.ts', ext: '.ts', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ]; const projects = { a: { root: 'libs/a' }, b: { root: 'libs/b' }, - c: { root: 'libs/c' } + c: { root: 'libs/c' }, }; expect(getTouchedProjects(fileChanges, { projects })).toEqual(['a', 'b']); }); @@ -31,13 +31,13 @@ describe('getTouchedProjects', () => { file: 'libs/a-b/index.ts', ext: '.ts', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ]; const projects = { a: { root: 'libs/a' }, abc: { root: 'libs/a-b-c' }, - ab: { root: 'libs/a-b' } + ab: { root: 'libs/a-b' }, }; expect(getTouchedProjects(fileChanges, { projects })).toEqual(['ab']); }); @@ -48,13 +48,13 @@ describe('getTouchedProjects', () => { file: 'libs/a-b/index.ts', ext: '.ts', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ]; const projects = { aaaaa: { root: 'libs/a' }, abc: { root: 'libs/a-b-c' }, - ab: { root: 'libs/a-b' } + ab: { root: 'libs/a-b' }, }; expect(getTouchedProjects(fileChanges, { projects })).toEqual(['ab']); }); @@ -65,12 +65,12 @@ describe('getTouchedProjects', () => { file: 'libs/a/b/index.ts', ext: '.ts', mtime: 0, - getChanges: () => [new WholeFileChange()] - } + getChanges: () => [new WholeFileChange()], + }, ]; const projects = { aaaaa: { root: 'libs/a' }, - ab: { root: 'libs/a/b' } + ab: { root: 'libs/a/b' }, }; expect(getTouchedProjects(fileChanges, { projects })).toEqual(['ab']); }); diff --git a/packages/workspace/src/core/affected-project-graph/locators/workspace-projects.ts b/packages/workspace/src/core/affected-project-graph/locators/workspace-projects.ts index d652af90ef1f3..98726a1b70dd1 100644 --- a/packages/workspace/src/core/affected-project-graph/locators/workspace-projects.ts +++ b/packages/workspace/src/core/affected-project-graph/locators/workspace-projects.ts @@ -13,8 +13,8 @@ export const getTouchedProjects: TouchedProjectLocator = ( .map(([name]) => name); return touchedFiles - .map(f => { - return projectNames.find(projectName => { + .map((f) => { + return projectNames.find((projectName) => { const p = workspaceJson.projects[projectName]; const projectRoot = p.root.endsWith('/') ? p.root : p.root + '/'; return f.file.startsWith(projectRoot); @@ -38,7 +38,7 @@ export const getImplicitlyTouchedProjects: TouchedProjectLocator = ( nxJson.implicitDependencies )) { const implicitDependencyWasChanged = fileChanges.some( - f => f.file === filePath + (f) => f.file === filePath ); if (!implicitDependencyWasChanged) { continue; diff --git a/packages/workspace/src/core/assert-workspace-validity.spec.ts b/packages/workspace/src/core/assert-workspace-validity.spec.ts index 086ee497698db..a6c433277d442 100644 --- a/packages/workspace/src/core/assert-workspace-validity.spec.ts +++ b/packages/workspace/src/core/assert-workspace-validity.spec.ts @@ -8,24 +8,24 @@ describe('assertWorkspaceValidity', () => { mockNxJson = { projects: { app1: { - tags: [] + tags: [], }, 'app1-e2e': { - tags: [] + tags: [], }, app2: { - tags: [] + tags: [], }, 'app2-e2e': { - tags: [] + tags: [], }, lib1: { - tags: [] + tags: [], }, lib2: { - tags: [] - } - } + tags: [], + }, + }, }; mockWorkspaceJson = { projects: { @@ -34,8 +34,8 @@ describe('assertWorkspaceValidity', () => { app2: {}, 'app2-e2e': {}, lib1: {}, - lib2: {} - } + lib2: {}, + }, }; }); @@ -65,7 +65,7 @@ describe('assertWorkspaceValidity', () => { it('should throw for an invalid top-level implicit dependency', () => { mockNxJson.implicitDependencies = { - 'README.md': ['invalidproj'] + 'README.md': ['invalidproj'], }; try { assertWorkspaceValidity(mockWorkspaceJson, mockNxJson); diff --git a/packages/workspace/src/core/assert-workspace-validity.ts b/packages/workspace/src/core/assert-workspace-validity.ts index d359a210bd36e..e062c8bbba02e 100644 --- a/packages/workspace/src/core/assert-workspace-validity.ts +++ b/packages/workspace/src/core/assert-workspace-validity.ts @@ -25,7 +25,7 @@ export function assertWorkspaceValidity(workspaceJson, nxJson) { const projects = { ...workspaceJson.projects, - ...nxJson.projects + ...nxJson.projects, }; const invalidImplicitDependencies = new Map(); @@ -40,7 +40,7 @@ export function assertWorkspaceValidity(workspaceJson, nxJson) { } else if (Array.isArray(value)) { acc.push([entry[0], value]); } else { - Object.values(value).forEach(v => { + Object.values(value).forEach((v) => { recur(v, acc); }); } @@ -54,7 +54,7 @@ export function assertWorkspaceValidity(workspaceJson, nxJson) { }, invalidImplicitDependencies); nxJsonProjects - .filter(nxJsonProjectName => { + .filter((nxJsonProjectName) => { const project = nxJson.projects[nxJsonProjectName]; return !!project.implicitDependencies; }) @@ -77,7 +77,7 @@ export function assertWorkspaceValidity(workspaceJson, nxJson) { `; invalidImplicitDependencies.forEach((projectNames, key) => { const str = ` ${key} - ${projectNames.map(projectName => ` ${projectName}`).join('\n')}`; + ${projectNames.map((projectName) => ` ${projectName}`).join('\n')}`; message += str; }); @@ -91,7 +91,7 @@ function detectAndSetInvalidProjectValues( validProjects: any ) { const invalidProjects = desiredProjectNames.filter( - projectName => !validProjects[projectName] + (projectName) => !validProjects[projectName] ); if (invalidProjects.length > 0) { map.set(sourceName, invalidProjects); @@ -100,8 +100,8 @@ function detectAndSetInvalidProjectValues( function minus(a: string[], b: string[]): string[] { const res = []; - a.forEach(aa => { - if (!b.find(bb => bb === aa)) { + a.forEach((aa) => { + if (!b.find((bb) => bb === aa)) { res.push(aa); } }); diff --git a/packages/workspace/src/core/dep-graph/dep-graph.js b/packages/workspace/src/core/dep-graph/dep-graph.js index c4e09d61370e2..4dff5de9ca7a3 100644 --- a/packages/workspace/src/core/dep-graph/dep-graph.js +++ b/packages/workspace/src/core/dep-graph/dep-graph.js @@ -2,13 +2,13 @@ window.focusedProject = null; window.filteredProjects = window.projects; function getProjectsByType(type) { - return window.projects.filter(project => project.type === type); + return window.projects.filter((project) => project.type === type); } function groupProjectsByDirectory(projects) { let groups = {}; - projects.forEach(project => { + projects.forEach((project) => { const split = project.data.root.split('/'); const directory = split.slice(1, -2).join('/'); @@ -29,11 +29,11 @@ function createProjectList(headerText, projects) { formGroup.className = 'form-group'; let sortedProjects = [...projects]; - sortedProjects.sort(function(a, b) { + sortedProjects.sort(function (a, b) { return a.name.localeCompare(b.name); }); - projects.forEach(project => { + projects.forEach((project) => { let formLine = document.createElement('div'); formLine.className = 'form-line'; @@ -99,7 +99,7 @@ function addProjectCheckboxes() { const sortedDirectories = Object.keys(libDirectoryGroups).sort(); - sortedDirectories.forEach(directoryName => { + sortedDirectories.forEach((directoryName) => { createProjectList(directoryName, libDirectoryGroups[directoryName]); }); } @@ -107,19 +107,19 @@ function addProjectCheckboxes() { function autoExclude() { const dependencyCounts = {}; - window.projects.forEach(p => { + window.projects.forEach((p) => { dependencyCounts[p.name] = 0; }); - Object.keys(graph.dependencies).forEach(p => { - graph.dependencies[p].forEach(d => { + Object.keys(graph.dependencies).forEach((p) => { + graph.dependencies[p].forEach((d) => { dependencyCounts[d.target]++; }); }); Object.keys(dependencyCounts) - .filter(d => dependencyCounts[d] > 5 || dependencyCounts[d] === 0) - .forEach(d => { + .filter((d) => dependencyCounts[d] > 5 || dependencyCounts[d] === 0) + .forEach((d) => { document.querySelector( `input[name=projectName][value=${d}]` ).checked = false; @@ -159,7 +159,7 @@ window.selectAffectedProjects = () => { document.getElementById('focused-project').hidden = true; document.getElementById('focused-project-name').innerText = ''; - getProjectCheckboxes().forEach(checkbox => { + getProjectCheckboxes().forEach((checkbox) => { checkbox.checked = window.affected.includes(checkbox.value); }); @@ -171,7 +171,7 @@ window.selectAllProjects = () => { document.getElementById('focused-project').hidden = true; document.getElementById('focused-project-name').innerText = ''; - getProjectCheckboxes().forEach(checkbox => { + getProjectCheckboxes().forEach((checkbox) => { checkbox.checked = true; }); @@ -183,7 +183,7 @@ window.deselectAllProjects = () => { document.getElementById('focused-project').hidden = true; document.getElementById('focused-project-name').innerText = ''; - getProjectCheckboxes().forEach(checkbox => { + getProjectCheckboxes().forEach((checkbox) => { checkbox.checked = false; }); @@ -197,7 +197,7 @@ function createDirectoryParents(g, directories) { if (!g.hasNode(childDirectoryId)) { g.setNode(childDirectoryId, { label: childDirectory, - clusterLabelPos: 'top' + clusterLabelPos: 'top', }); } @@ -207,7 +207,7 @@ function createDirectoryParents(g, directories) { if (!g.hasNode(parentDirectoryId)) { g.setNode(parentDirectoryId, { label: parentDirectory, - clusterLabelPos: 'top' + clusterLabelPos: 'top', }); } g.setParent(childDirectoryId, parentDirectoryId); @@ -219,7 +219,7 @@ function createDirectoryParents(g, directories) { function generateLayout() { const g = new window.dagreD3.graphlib.Graph({ compound: true, - orderRestarts: 10 + orderRestarts: 10, }); const groupByFolder = document.querySelector( @@ -228,14 +228,14 @@ function generateLayout() { g.setGraph({ ranksep: 150, - edgesep: 100 + edgesep: 100, }); - g.setDefaultEdgeLabel(function() { + g.setDefaultEdgeLabel(function () { return {}; }); - window.filteredProjects.forEach(p => { + window.filteredProjects.forEach((p) => { const shape = p.name === window.focusedProject ? p.type === 'app' || p.type === 'e2e' @@ -269,9 +269,9 @@ function generateLayout() { } }); - Object.keys(graph.dependencies).forEach(p => { - const filteredProjectNames = window.filteredProjects.map(f => f.name); - graph.dependencies[p].forEach(d => { + Object.keys(graph.dependencies).forEach((p) => { + const filteredProjectNames = window.filteredProjects.map((f) => f.name); + graph.dependencies[p].forEach((d) => { if ( filteredProjectNames.indexOf(p) > -1 && filteredProjectNames.indexOf(d.target) > -1 @@ -290,7 +290,7 @@ function generateLayout() { g.setEdge(p, d.target, { label: label, class: clazz, - curve: window.d3.curveBasis + curve: window.d3.curveBasis, }); } }); @@ -314,7 +314,7 @@ function createRenderer() { .attr('height', bbox.height) .attr('filter', `url(#${filter})`); - node.intersect = function(point) { + node.intersect = function (point) { return window.dagreD3.intersect.rect(node, point); }; @@ -336,7 +336,7 @@ function createRenderer() { .attr('ry', ry) .attr('filter', `url(#${filter})`); - node.intersect = function(point) { + node.intersect = function (point) { return window.dagreD3.intersect.ellipse(node, rx, ry, point); }; @@ -358,7 +358,7 @@ function render() { let inner = svg.append('g'); // Set up zoom support - var zoom = d3.zoom().on('zoom', function() { + var zoom = d3.zoom().on('zoom', function () { inner.attr('transform', d3.event.transform); }); svg.call(zoom); @@ -387,7 +387,7 @@ function render() { } function addTooltips(inner) { - const createTipTemplate = project => { + const createTipTemplate = (project) => { return `

${project.type}${project.name}

tags
${project.data.tags.join(', ')}

@@ -400,26 +400,26 @@ function addTooltips(inner) { `; }; - inner.selectAll('g.node').each(function(id) { - const project = window.projects.find(p => p.name === id); + inner.selectAll('g.node').each(function (id) { + const project = window.projects.find((p) => p.name === id); tippy(this, { content: createTipTemplate(project), interactive: true, appendTo: document.body, interactiveBorder: 10, - trigger: 'click' + trigger: 'click', }); }); } -window.focusProject = id => { +window.focusProject = (id) => { window.focusedProject = id; document.getElementById('focused-project').hidden = false; document.getElementById('focused-project-name').innerText = id; Array.from(document.querySelectorAll('input[name=projectName]')).forEach( - checkbox => { + (checkbox) => { const showProject = hasPath(id, checkbox.value, []) || hasPath(checkbox.value, id, []); checkbox.checked = showProject; @@ -436,7 +436,7 @@ window.unfocusProject = () => { document.getElementById('focused-project-name').innerText = ''; Array.from(document.querySelectorAll('input[name=projectName]')).forEach( - checkbox => { + (checkbox) => { checkbox.checked = true; checkbox.parentElement.hidden = false; } @@ -445,7 +445,7 @@ window.unfocusProject = () => { window.filterProjects(); }; -window.excludeProject = id => { +window.excludeProject = (id) => { document.querySelector( `input[name=projectName][value=${id}]` ).checked = false; @@ -459,19 +459,19 @@ window.filterProjects = () => { ); const selectedProjects = checkboxes - .filter(checkbox => checkbox.checked) - .map(checkbox => checkbox.value); + .filter((checkbox) => checkbox.checked) + .map((checkbox) => checkbox.value); const unselectedProjects = checkboxes - .filter(checkbox => !checkbox.checked) - .map(checkbox => checkbox.value); + .filter((checkbox) => !checkbox.checked) + .map((checkbox) => checkbox.value); if (selectedProjects.length === window.projects.length) { window.filteredProjects = window.projects; } else { - window.filteredProjects = window.projects.filter(p => { + window.filteredProjects = window.projects.filter((p) => { const filtered = selectedProjects.find( - f => hasPath(f, p.name, []) || hasPath(p.name, f, []) + (f) => hasPath(f, p.name, []) || hasPath(p.name, f, []) ); return unselectedProjects.indexOf(p.name) === -1 && filtered; diff --git a/packages/workspace/src/core/file-graph/file-map.spec.ts b/packages/workspace/src/core/file-graph/file-map.spec.ts index cab8013c9c863..62ccc138faee9 100644 --- a/packages/workspace/src/core/file-graph/file-map.spec.ts +++ b/packages/workspace/src/core/file-graph/file-map.spec.ts @@ -7,24 +7,24 @@ describe('createFileMap', () => { demo: { root: 'apps/demo', sourceRoot: 'apps/demo/src', - projectType: 'application' + projectType: 'application', }, 'demo-e2e': { root: 'apps/demo-e2e', sourceRoot: 'apps/demo-e2e/src', - projectType: 'application' + projectType: 'application', }, ui: { root: 'libs/ui', sourceRoot: 'libs/ui/src', - projectType: 'library' - } - } + projectType: 'library', + }, + }, }; const files = [ { file: 'apps/demo/src/main.ts', mtime: 1, ext: '.ts' }, { file: 'apps/demo-e2e/src/main.ts', mtime: 1, ext: '.ts' }, - { file: 'libs/ui/src/index.ts', mtime: 1, ext: '.ts' } + { file: 'libs/ui/src/index.ts', mtime: 1, ext: '.ts' }, ]; const result = createFileMap(workspaceJson, files); @@ -32,7 +32,7 @@ describe('createFileMap', () => { expect(result).toEqual({ demo: [{ file: 'apps/demo/src/main.ts', mtime: 1, ext: '.ts' }], 'demo-e2e': [{ file: 'apps/demo-e2e/src/main.ts', mtime: 1, ext: '.ts' }], - ui: [{ file: 'libs/ui/src/index.ts', mtime: 1, ext: '.ts' }] + ui: [{ file: 'libs/ui/src/index.ts', mtime: 1, ext: '.ts' }], }); }); }); diff --git a/packages/workspace/src/core/file-graph/file-map.ts b/packages/workspace/src/core/file-graph/file-map.ts index b330d1c408955..83fc686699015 100644 --- a/packages/workspace/src/core/file-graph/file-map.ts +++ b/packages/workspace/src/core/file-graph/file-map.ts @@ -18,10 +18,10 @@ export function createFileMap(workspaceJson: any, files: FileData[]): FileMap { ? -1 : 1; }) - .forEach(projectName => { + .forEach((projectName) => { const p = workspaceJson.projects[projectName]; fileMap[projectName] = fileMap[projectName] || []; - files.forEach(f => { + files.forEach((f) => { if (seen.has(f.file)) { return; } diff --git a/packages/workspace/src/core/file-utils.spec.ts b/packages/workspace/src/core/file-utils.spec.ts index 89585f6029efa..d3cf79c83649e 100644 --- a/packages/workspace/src/core/file-utils.spec.ts +++ b/packages/workspace/src/core/file-utils.spec.ts @@ -21,21 +21,21 @@ describe('calculateFileChanges', () => { ['package.json'], { base: 'sha1', - head: 'sha2' + head: 'sha2', }, (path, revision) => { return revision === 'sha1' ? JSON.stringify({ dependencies: { 'happy-nrwl': '0.0.1', - 'not-awesome-nrwl': '0.0.1' - } + 'not-awesome-nrwl': '0.0.1', + }, }) : JSON.stringify({ dependencies: { 'happy-nrwl': '0.0.2', - 'awesome-nrwl': '0.0.1' - } + 'awesome-nrwl': '0.0.1', + }, }); } ); @@ -45,24 +45,24 @@ describe('calculateFileChanges', () => { path: ['dependencies', 'happy-nrwl'], value: { lhs: '0.0.1', - rhs: '0.0.2' - } + rhs: '0.0.2', + }, }); expect(changes[0].getChanges()).toContainEqual({ type: DiffType.Deleted, path: ['dependencies', 'not-awesome-nrwl'], value: { lhs: '0.0.1', - rhs: undefined - } + rhs: undefined, + }, }); expect(changes[0].getChanges()).toContainEqual({ type: DiffType.Added, path: ['dependencies', 'awesome-nrwl'], value: { lhs: undefined, - rhs: '0.0.1' - } + rhs: '0.0.1', + }, }); }); diff --git a/packages/workspace/src/core/file-utils.ts b/packages/workspace/src/core/file-utils.ts index 616c21fced9fc..0504b54fae531 100644 --- a/packages/workspace/src/core/file-utils.ts +++ b/packages/workspace/src/core/file-utils.ts @@ -45,9 +45,9 @@ export function calculateFileChanges( ignore = getIgnoredGlobs() ): FileChange[] { if (ignore) { - files = files.filter(f => !ignore.ignores(f)); + files = files.filter((f) => !ignore.ignores(f)); } - return files.map(f => { + return files.map((f) => { const ext = extname(f); const _mtime = mtime(`${appRootPath}/${f}`); // Memoize results so we don't recalculate on successive invocation. @@ -77,7 +77,7 @@ export function calculateFileChanges( default: return [new WholeFileChange()]; } - } + }, }; }); } @@ -100,7 +100,7 @@ function defaultReadFileAtRevision( return !revision ? readFileSync(file).toString() : execSync(`git show ${revision}:${filePathInGitRepository}`, { - maxBuffer: TEN_MEGABYTES + maxBuffer: TEN_MEGABYTES, }) .toString() .trim(); @@ -112,12 +112,9 @@ function defaultReadFileAtRevision( function getFileData(filePath: string): FileData { const stat = fs.statSync(filePath); return { - file: path - .relative(appRootPath, filePath) - .split(path.sep) - .join('/'), + file: path.relative(appRootPath, filePath).split(path.sep).join('/'), ext: path.extname(filePath), - mtime: stat.mtimeMs + mtime: stat.mtimeMs, }; } @@ -133,7 +130,7 @@ export function allFilesInDir( let res = []; try { - fs.readdirSync(dirName).forEach(c => { + fs.readdirSync(dirName).forEach((c) => { const child = path.join(dirName, c); if (ignoredGlobs.ignores(path.relative(appRootPath, child))) { return; @@ -205,7 +202,7 @@ export function readWorkspaceFiles(): FileData[] { const files = []; files.push( - ...rootWorkspaceFileNames().map(f => getFileData(`${appRootPath}/${f}`)) + ...rootWorkspaceFileNames().map((f) => getFileData(`${appRootPath}/${f}`)) ); // Add known workspace files and directories @@ -213,7 +210,7 @@ export function readWorkspaceFiles(): FileData[] { files.push(...allFilesInDir(`${appRootPath}/tools`)); // Add files for workspace projects - Object.keys(workspaceJson.projects).forEach(projectName => { + Object.keys(workspaceJson.projects).forEach((projectName) => { const project = workspaceJson.projects[projectName]; files.push(...allFilesInDir(`${appRootPath}/${project.root}`)); }); @@ -245,7 +242,7 @@ export function mtime(filePath: string): number { export function normalizedProjectRoot(p: ProjectGraphNode): string { if (p.data && p.data.root) { - const path = p.data.root.split('/').filter(v => !!v); + const path = p.data.root.split('/').filter((v) => !!v); if (path.length === 1) { return path[0]; } diff --git a/packages/workspace/src/core/normalize-nx-json.spec.ts b/packages/workspace/src/core/normalize-nx-json.spec.ts index 32ac14dcc63e1..0ce045589b4a0 100644 --- a/packages/workspace/src/core/normalize-nx-json.spec.ts +++ b/packages/workspace/src/core/normalize-nx-json.spec.ts @@ -7,7 +7,7 @@ describe('normalizeNxJson', () => { projects: { demo: { tags: [] }, ui: { tags: [] }, - util: { tags: [] } + util: { tags: [] }, }, implicitDependencies: { 'package.json': '*', @@ -16,12 +16,12 @@ describe('normalizeNxJson', () => { b: { c: ['demo'], d: { - e: '*' - } - } - } - } - } + e: '*', + }, + }, + }, + }, + }, }); expect(result.implicitDependencies).toEqual({ @@ -31,11 +31,11 @@ describe('normalizeNxJson', () => { b: { c: ['demo'], d: { - e: ['demo', 'ui', 'util'] - } - } - } - } + e: ['demo', 'ui', 'util'], + }, + }, + }, + }, }); }); }); diff --git a/packages/workspace/src/core/normalize-nx-json.ts b/packages/workspace/src/core/normalize-nx-json.ts index ec91f6a6f88ba..6a14a5fd4cd16 100644 --- a/packages/workspace/src/core/normalize-nx-json.ts +++ b/packages/workspace/src/core/normalize-nx-json.ts @@ -22,7 +22,7 @@ export function normalizeNxJson(nxJson: NxJson): NxJson { }, {}); } } - }, {}) + }, {}), } : (nxJson as NxJson); } diff --git a/packages/workspace/src/core/project-graph/build-dependencies/build-dependencies.ts b/packages/workspace/src/core/project-graph/build-dependencies/build-dependencies.ts index 4a14f608daf43..652b7dde558b9 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/build-dependencies.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/build-dependencies.ts @@ -1,7 +1,7 @@ import { AddProjectDependency, ProjectGraphContext, - ProjectGraphNodeRecords + ProjectGraphNodeRecords, } from '../project-graph-models'; export interface BuildDependencies { diff --git a/packages/workspace/src/core/project-graph/build-dependencies/explicit-npm-dependencies.ts b/packages/workspace/src/core/project-graph/build-dependencies/explicit-npm-dependencies.ts index 2c8a1e1c67728..5139b5969f488 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/explicit-npm-dependencies.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/explicit-npm-dependencies.ts @@ -2,7 +2,7 @@ import { AddProjectDependency, DependencyType, ProjectGraphContext, - ProjectGraphNodeRecords + ProjectGraphNodeRecords, } from '../project-graph-models'; import { TypeScriptImportLocator } from './typescript-import-locator'; @@ -14,12 +14,12 @@ export function buildExplicitNpmDependencies( ) { const importLocator = new TypeScriptImportLocator(fileRead); - Object.keys(ctx.fileMap).forEach(source => { - Object.values(ctx.fileMap[source]).forEach(f => { + Object.keys(ctx.fileMap).forEach((source) => { + Object.values(ctx.fileMap[source]).forEach((f) => { importLocator.fromFile( f.file, (importExpr: string, filePath: string, type: DependencyType) => { - const key = Object.keys(nodes).find(k => + const key = Object.keys(nodes).find((k) => isNpmPackageImport(k, importExpr) ); const target = nodes[key]; diff --git a/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.spec.ts b/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.spec.ts index bbdacb882a1d3..10553c0b40145 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.spec.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.spec.ts @@ -1,5 +1,5 @@ jest.mock('../../../utils/app-root', () => ({ - appRootPath: '/root' + appRootPath: '/root', })); jest.mock('fs', () => require('memfs').fs); @@ -8,7 +8,7 @@ import { AddProjectDependency, ProjectGraphContext, ProjectGraphNode, - DependencyType + DependencyType, } from '../project-graph-models'; import { buildExplicitTypeScriptDependencies } from './explicit-project-dependencies'; import { createFileMap } from '../../file-graph'; @@ -24,30 +24,30 @@ describe('explicit project dependencies', () => { const workspaceJson = { projects: { proj: { - root: 'libs/proj' + root: 'libs/proj', }, proj2: { - root: 'libs/proj2' + root: 'libs/proj2', }, proj3a: { - root: 'libs/proj3a' + root: 'libs/proj3a', }, proj123: { - root: 'libs/proj123' + root: 'libs/proj123', }, proj1234: { - root: 'libs/proj1234' + root: 'libs/proj1234', }, 'proj1234-child': { - root: 'libs/proj1234-child' - } - } + root: 'libs/proj1234-child', + }, + }, }; const nxJson = { npmScope: 'proj', projects: { - proj1: {} - } + proj1: {}, + }, }; const tsConfig = { compilerOptions: { @@ -58,9 +58,9 @@ describe('explicit project dependencies', () => { '@proj/project-3': ['libs/proj3a/index.ts'], '@proj/proj123': ['libs/proj123/index.ts'], '@proj/proj1234': ['libs/proj1234/index.ts'], - '@proj/proj1234-child': ['libs/proj1234-child/index.ts'] - } - } + '@proj/proj1234-child': ['libs/proj1234-child/index.ts'], + }, + }, }; fsJson = { './package.json': `{ @@ -82,14 +82,14 @@ describe('explicit project dependencies', () => { './libs/proj1234/index.ts': `export const a = 6 import { a } from '@proj/proj1234-child' `, - './libs/proj1234-child/index.ts': 'export const a = 7' + './libs/proj1234-child/index.ts': 'export const a = 7', }; vol.fromJSON(fsJson, '/root'); ctx = { workspaceJson, nxJson, - fileMap: createFileMap(workspaceJson, readWorkspaceFiles()) + fileMap: createFileMap(workspaceJson, readWorkspaceFiles()), }; projects = { @@ -98,57 +98,57 @@ describe('explicit project dependencies', () => { type: 'lib', data: { root: 'libs/proj3a', - files: [] - } + files: [], + }, }, proj2: { name: 'proj2', type: 'lib', data: { root: 'libs/proj2', - files: [] - } + files: [], + }, }, proj: { name: 'proj', type: 'lib', data: { root: 'libs/proj', - files: [] - } + files: [], + }, }, proj1234: { name: 'proj1234', type: 'lib', data: { root: 'libs/proj1234', - files: [] - } + files: [], + }, }, proj123: { name: 'proj123', type: 'lib', data: { root: 'libs/proj123', - files: [] - } + files: [], + }, }, proj4ab: { name: 'proj4ab', type: 'lib', data: { root: 'libs/proj4ab', - files: [] - } + files: [], + }, }, 'proj1234-child': { name: 'proj1234-child', type: 'lib', data: { root: 'libs/proj1234-child', - files: [] - } - } + files: [], + }, + }, }; }); @@ -161,7 +161,7 @@ describe('explicit project dependencies', () => { const depObj = { type, source, - target + target, }; if (dependencyMap[source]) { dependencyMap[source].push(depObj); @@ -171,7 +171,7 @@ describe('explicit project dependencies', () => { } ); - buildExplicitTypeScriptDependencies(ctx, projects, addDependency, s => { + buildExplicitTypeScriptDependencies(ctx, projects, addDependency, (s) => { return fs.readFileSync(`${appRootPath}/${s}`).toString(); }); @@ -180,26 +180,26 @@ describe('explicit project dependencies', () => { { source: 'proj1234', target: 'proj1234-child', - type: DependencyType.static - } + type: DependencyType.static, + }, ], proj: [ { source: 'proj', target: 'proj2', - type: DependencyType.static + type: DependencyType.static, }, { source: 'proj', target: 'proj3a', - type: DependencyType.dynamic + type: DependencyType.dynamic, }, { source: 'proj', target: 'proj4ab', - type: DependencyType.dynamic - } - ] + type: DependencyType.dynamic, + }, + ], }); }); }); diff --git a/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.ts b/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.ts index b3115e428d65e..83db80dc9c4af 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.ts @@ -2,7 +2,7 @@ import { AddProjectDependency, DependencyType, ProjectGraphContext, - ProjectGraphNodeRecords + ProjectGraphNodeRecords, } from '../project-graph-models'; import { TypeScriptImportLocator } from './typescript-import-locator'; import { TargetProjectLocator } from '../../target-project-locator'; @@ -15,8 +15,8 @@ export function buildExplicitTypeScriptDependencies( ) { const importLocator = new TypeScriptImportLocator(fileRead); const targetProjectLocator = new TargetProjectLocator(nodes); - Object.keys(ctx.fileMap).forEach(source => { - Object.values(ctx.fileMap[source]).forEach(f => { + Object.keys(ctx.fileMap).forEach((source) => { + Object.values(ctx.fileMap[source]).forEach((f) => { importLocator.fromFile( f.file, (importExpr: string, filePath: string, type: DependencyType) => { diff --git a/packages/workspace/src/core/project-graph/build-dependencies/implicit-project-dependencies.ts b/packages/workspace/src/core/project-graph/build-dependencies/implicit-project-dependencies.ts index 564e4de5fe1cc..02cc7e77e0951 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/implicit-project-dependencies.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/implicit-project-dependencies.ts @@ -2,7 +2,7 @@ import { AddProjectDependency, DependencyType, ProjectGraphContext, - ProjectGraphNodeRecords + ProjectGraphNodeRecords, } from '../project-graph-models'; export function buildImplicitProjectDependencies( @@ -11,10 +11,10 @@ export function buildImplicitProjectDependencies( addDependency: AddProjectDependency, fileRead: (s: string) => string ) { - Object.keys(ctx.nxJson.projects).forEach(source => { + Object.keys(ctx.nxJson.projects).forEach((source) => { const p = ctx.nxJson.projects[source]; if (p.implicitDependencies && p.implicitDependencies.length > 0) { - p.implicitDependencies.forEach(target => { + p.implicitDependencies.forEach((target) => { addDependency(DependencyType.implicit, source, target); }); } diff --git a/packages/workspace/src/core/project-graph/build-dependencies/typescript-import-locator.ts b/packages/workspace/src/core/project-graph/build-dependencies/typescript-import-locator.ts index 9467c871e108a..a77f4ff5663e9 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/typescript-import-locator.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/typescript-import-locator.ts @@ -98,7 +98,7 @@ export class TypeScriptImportLocator { /** * Continue traversing down the AST from the current node */ - ts.forEachChild(node, child => this.fromNode(filePath, child, visitor)); + ts.forEachChild(node, (child) => this.fromNode(filePath, child, visitor)); } private getPropertyAssignmentName(nameNode: ts.PropertyName) { diff --git a/packages/workspace/src/core/project-graph/build-nodes/npm-packages.ts b/packages/workspace/src/core/project-graph/build-nodes/npm-packages.ts index 60cf4e2876045..83b31bc3aeed5 100644 --- a/packages/workspace/src/core/project-graph/build-nodes/npm-packages.ts +++ b/packages/workspace/src/core/project-graph/build-nodes/npm-packages.ts @@ -9,16 +9,16 @@ export function buildNpmPackageNodes( const packageJson = JSON.parse(stripJsonComments(fileRead('package.json'))); const deps = { ...packageJson.dependencies, - ...packageJson.devDependencies + ...packageJson.devDependencies, }; - Object.keys(deps).forEach(d => { + Object.keys(deps).forEach((d) => { addNode({ type: 'npm', name: d, data: { version: deps[d], - files: [] - } + files: [], + }, }); }); } diff --git a/packages/workspace/src/core/project-graph/build-nodes/workspace-projects.ts b/packages/workspace/src/core/project-graph/build-nodes/workspace-projects.ts index 5245c62d01466..a904e086d1cd5 100644 --- a/packages/workspace/src/core/project-graph/build-nodes/workspace-projects.ts +++ b/packages/workspace/src/core/project-graph/build-nodes/workspace-projects.ts @@ -7,7 +7,7 @@ export function buildWorkspaceProjectNodes( ) { const toAdd = []; - Object.keys(ctx.fileMap).forEach(key => { + Object.keys(ctx.fileMap).forEach((key) => { const p = ctx.workspaceJson.projects[key]; const projectType = @@ -27,8 +27,8 @@ export function buildWorkspaceProjectNodes( data: { ...p, tags, - files: ctx.fileMap[key] - } + files: ctx.fileMap[key], + }, }); }); @@ -39,11 +39,11 @@ export function buildWorkspaceProjectNodes( return a.data.root.length > b.data.root.length ? -1 : 1; }); - toAdd.forEach(n => { + toAdd.forEach((n) => { addNode({ name: n.name, type: n.type, - data: n.data + data: n.data, }); }); } diff --git a/packages/workspace/src/core/project-graph/operators.spec.ts b/packages/workspace/src/core/project-graph/operators.spec.ts index 2c410dd2a8088..aa253e07a9b9e 100644 --- a/packages/workspace/src/core/project-graph/operators.spec.ts +++ b/packages/workspace/src/core/project-graph/operators.spec.ts @@ -7,44 +7,44 @@ const graph: ProjectGraph = { app1: { name: 'app1', type: 'app', data: null }, lib1: { name: 'lib1', type: 'lib', data: null }, lib2: { name: 'lib2', type: 'lib', data: null }, - lib3: { name: 'lib3', type: 'lib', data: null } + lib3: { name: 'lib3', type: 'lib', data: null }, }, dependencies: { 'app1-e2e': [ { type: DependencyType.implicit, source: 'app1-e2e', - target: 'app1' - } + target: 'app1', + }, ], app1: [ { type: DependencyType.static, source: 'app1', - target: 'lib1' - } + target: 'lib1', + }, ], lib1: [ { type: DependencyType.static, source: 'lib1', - target: 'lib2' + target: 'lib2', }, { type: DependencyType.static, source: 'lib1', - target: 'lib3' - } + target: 'lib3', + }, ], lib2: [ { type: DependencyType.static, source: 'lib2', - target: 'lib3' - } + target: 'lib3', + }, ], - lib3: [] - } + lib3: [], + }, }; describe('reverse', () => { @@ -56,44 +56,44 @@ describe('reverse', () => { app1: { name: 'app1', type: 'app', data: null }, lib1: { name: 'lib1', type: 'lib', data: null }, lib2: { name: 'lib2', type: 'lib', data: null }, - lib3: { name: 'lib3', type: 'lib', data: null } + lib3: { name: 'lib3', type: 'lib', data: null }, }, dependencies: { app1: [ { type: DependencyType.implicit, source: 'app1', - target: 'app1-e2e' - } + target: 'app1-e2e', + }, ], 'app1-e2e': [], lib1: [ { type: DependencyType.static, source: 'lib1', - target: 'app1' - } + target: 'app1', + }, ], lib2: [ { type: DependencyType.static, source: 'lib2', - target: 'lib1' - } + target: 'lib1', + }, ], lib3: [ { type: DependencyType.static, source: 'lib3', - target: 'lib1' + target: 'lib1', }, { type: DependencyType.static, source: 'lib3', - target: 'lib2' - } - ] - } + target: 'lib2', + }, + ], + }, }); }); }); @@ -103,7 +103,7 @@ describe('withDeps', () => { const affectedNodes = [ { name: 'app1-e2e', type: 'app', data: null }, { name: 'app1', type: 'app', data: null }, - { name: 'lib1', type: 'lib', data: null } + { name: 'lib1', type: 'lib', data: null }, ]; const result = withDeps(graph, affectedNodes); @@ -112,87 +112,87 @@ describe('withDeps', () => { lib3: { name: 'lib3', type: 'lib', - data: null + data: null, }, lib2: { name: 'lib2', type: 'lib', - data: null + data: null, }, lib1: { name: 'lib1', type: 'lib', - data: null + data: null, }, app1: { name: 'app1', type: 'app', - data: null + data: null, }, 'app1-e2e': { name: 'app1-e2e', type: 'app', - data: null - } + data: null, + }, }, dependencies: { lib2: [ { type: 'static', source: 'lib2', - target: 'lib3' - } + target: 'lib3', + }, ], lib1: [ { type: 'static', source: 'lib1', - target: 'lib2' + target: 'lib2', }, { type: 'static', source: 'lib1', - target: 'lib3' - } + target: 'lib3', + }, ], app1: [ { type: 'static', source: 'app1', - target: 'lib1' - } + target: 'lib1', + }, ], 'app1-e2e': [ { type: 'implicit', source: 'app1-e2e', - target: 'app1' - } + target: 'app1', + }, ], - lib3: [] - } + lib3: [], + }, }); }); }); describe('filterNodes', () => { it('filters out nodes based on predicate', () => { - const result = filterNodes(n => n.type === 'app')(graph); + const result = filterNodes((n) => n.type === 'app')(graph); expect(result).toEqual({ nodes: { 'app1-e2e': { name: 'app1-e2e', type: 'app', data: null }, - app1: { name: 'app1', type: 'app', data: null } + app1: { name: 'app1', type: 'app', data: null }, }, dependencies: { 'app1-e2e': [ { type: DependencyType.implicit, source: 'app1-e2e', - target: 'app1' - } + target: 'app1', + }, ], - app1: [] - } + app1: [], + }, }); }); }); diff --git a/packages/workspace/src/core/project-graph/operators.ts b/packages/workspace/src/core/project-graph/operators.ts index e46de300ddc23..b6bfae788feba 100644 --- a/packages/workspace/src/core/project-graph/operators.ts +++ b/packages/workspace/src/core/project-graph/operators.ts @@ -2,7 +2,7 @@ import { ProjectGraphBuilder } from './project-graph-builder'; import { ProjectGraph, ProjectGraphNode, - ProjectGraphNodeRecords + ProjectGraphNodeRecords, } from './project-graph-models'; const reverseMemo = new Map(); @@ -11,11 +11,11 @@ export function reverse(graph: ProjectGraph): ProjectGraph { let result = reverseMemo.get(graph); if (!result) { const builder = new ProjectGraphBuilder(); - Object.values(graph.nodes).forEach(n => { + Object.values(graph.nodes).forEach((n) => { builder.addNode(n); }); - Object.values(graph.dependencies).forEach(byProject => { - byProject.forEach(dep => { + Object.values(graph.dependencies).forEach((byProject) => { + byProject.forEach((dep) => { builder.addDependency(dep.type, dep.target, dep.source); }); }); @@ -29,17 +29,17 @@ export function reverse(graph: ProjectGraph): ProjectGraph { export function filterNodes( predicate: (n: ProjectGraphNode) => boolean ): (p: ProjectGraph) => ProjectGraph { - return original => { + return (original) => { const builder = new ProjectGraphBuilder(); const added = new Set(); - Object.values(original.nodes).forEach(n => { + Object.values(original.nodes).forEach((n) => { if (predicate(n)) { builder.addNode(n); added.add(n.name); } }); - Object.values(original.dependencies).forEach(ds => { - ds.forEach(d => { + Object.values(original.dependencies).forEach((ds) => { + ds.forEach((d) => { if (added.has(d.source) && added.has(d.target)) { builder.addDependency(d.type, d.source, d.target); } @@ -88,13 +88,13 @@ export function withDeps( function recur(node) { const ds = original.dependencies[node.name]; // 1. Recursively add all source nodes - ds.forEach(n => { + ds.forEach((n) => { recur(original.nodes[n.target]); }); // 2. Add current node builder.addNode(node); // 3. Add all source dependencies - ds.forEach(n => { + ds.forEach((n) => { builder.addDependency(n.type, n.source, n.target); }); } diff --git a/packages/workspace/src/core/project-graph/project-graph-builder.spec.ts b/packages/workspace/src/core/project-graph/project-graph-builder.spec.ts index 1ac22d0d460af..8d06a9049767a 100644 --- a/packages/workspace/src/core/project-graph/project-graph-builder.spec.ts +++ b/packages/workspace/src/core/project-graph/project-graph-builder.spec.ts @@ -35,28 +35,32 @@ describe('ProjectGraphBuilder', () => { [libA.name]: libA, [libB.name]: libB, [libC.name]: libC, - [happyNrwl.name]: happyNrwl + [happyNrwl.name]: happyNrwl, }, dependencies: { [myapp.name]: [ { type: DependencyType.static, source: myapp.name, - target: libA.name + target: libA.name, + }, + { + type: DependencyType.static, + source: myapp.name, + target: libB.name, }, - { type: DependencyType.static, source: myapp.name, target: libB.name } ], [libB.name]: [ - { type: DependencyType.static, source: libB.name, target: libC.name } + { type: DependencyType.static, source: libB.name, target: libC.name }, ], [libC.name]: [ { type: DependencyType.static, source: libC.name, - target: happyNrwl.name - } - ] - } + target: happyNrwl.name, + }, + ], + }, }); }); }); @@ -65,6 +69,6 @@ function createNode(name: string, type: string): ProjectGraphNode { return { type, name, - data: null + data: null, }; } diff --git a/packages/workspace/src/core/project-graph/project-graph-builder.ts b/packages/workspace/src/core/project-graph/project-graph-builder.ts index 95cd91141c803..d388dfd9f3cfe 100644 --- a/packages/workspace/src/core/project-graph/project-graph-builder.ts +++ b/packages/workspace/src/core/project-graph/project-graph-builder.ts @@ -2,7 +2,7 @@ import { DependencyType, ProjectGraph, ProjectGraphDependency, - ProjectGraphNode + ProjectGraphNode, } from './project-graph-models'; export class ProjectGraphBuilder { @@ -14,9 +14,9 @@ export class ProjectGraphBuilder { constructor(g?: ProjectGraph) { if (g) { - Object.values(g.nodes).forEach(n => this.addNode(n)); - Object.values(g.dependencies).forEach(ds => { - ds.forEach(d => this.addDependency(d.type, d.source, d.target)); + Object.values(g.nodes).forEach((n) => this.addNode(n)); + Object.values(g.dependencies).forEach((ds) => { + ds.forEach((d) => this.addDependency(d.type, d.source, d.target)); }); } } @@ -45,20 +45,17 @@ export class ProjectGraphBuilder { ] = { type, source: sourceProjectName, - target: targetProjectName + target: targetProjectName, }; } build(): ProjectGraph { return { nodes: this.nodes as ProjectGraph['nodes'], - dependencies: Object.keys(this.dependencies).reduce( - (acc, k) => { - acc[k] = Object.values(this.dependencies[k]); - return acc; - }, - {} as ProjectGraph['dependencies'] - ) + dependencies: Object.keys(this.dependencies).reduce((acc, k) => { + acc[k] = Object.values(this.dependencies[k]); + return acc; + }, {} as ProjectGraph['dependencies']), }; } } diff --git a/packages/workspace/src/core/project-graph/project-graph-models.ts b/packages/workspace/src/core/project-graph/project-graph-models.ts index 2d203e42d2653..53d246eda0f0e 100644 --- a/packages/workspace/src/core/project-graph/project-graph-models.ts +++ b/packages/workspace/src/core/project-graph/project-graph-models.ts @@ -10,7 +10,7 @@ export interface ProjectGraph { export enum DependencyType { static = 'static', dynamic = 'dynamic', - implicit = 'implicit' + implicit = 'implicit', } export interface ProjectGraphNode { @@ -48,5 +48,5 @@ export interface ProjectGraphContext { export enum ProjectType { app = 'app', e2e = 'e2e', - lib = 'lib' + lib = 'lib', } diff --git a/packages/workspace/src/core/project-graph/project-graph.spec.ts b/packages/workspace/src/core/project-graph/project-graph.spec.ts index 3d554e48d78c3..9963cb220ad99 100644 --- a/packages/workspace/src/core/project-graph/project-graph.spec.ts +++ b/packages/workspace/src/core/project-graph/project-graph.spec.ts @@ -19,59 +19,59 @@ describe('project graph', () => { name: '@nrwl/workspace-src', dependencies: { express: '4.0.0', - 'happy-nrwl': '1.0.0' + 'happy-nrwl': '1.0.0', }, devDependencies: { - '@nrwl/workspace': '*' - } + '@nrwl/workspace': '*', + }, }; workspaceJson = { projects: { demo: { root: 'apps/demo/', sourceRoot: 'apps/demo/src', - projectType: 'application' + projectType: 'application', }, 'demo-e2e': { root: 'apps/demo-e2e/', sourceRoot: 'apps/demo-e2e/src', - projectType: 'application' + projectType: 'application', }, ui: { root: 'libs/ui/', sourceRoot: 'libs/ui/src', - projectType: 'library' + projectType: 'library', }, 'shared-util': { root: 'libs/shared/util/', sourceRoot: 'libs/shared/util/src', - projectType: 'library' + projectType: 'library', }, 'shared-util-data': { root: 'libs/shared/util/data', sourceRoot: 'libs/shared/util/data/src', - projectType: 'library' + projectType: 'library', }, 'lazy-lib': { root: 'libs/lazy-lib', sourceRoot: 'libs/lazy-lib', - projectType: 'library' + projectType: 'library', }, api: { root: 'apps/api/', sourceRoot: 'apps/api/src', - projectType: 'application' - } - } + projectType: 'application', + }, + }, }; nxJson = { npmScope: 'nrwl', implicitDependencies: { 'package.json': { scripts: { - deploy: '*' - } - } + deploy: '*', + }, + }, }, projects: { api: { tags: [] }, @@ -80,8 +80,8 @@ describe('project graph', () => { ui: { tags: [] }, 'shared-util': { tags: [] }, 'shared-util-data': { tags: [] }, - 'lazy-lib': { tags: [] } - } + 'lazy-lib': { tags: [] }, + }, }; tsConfigJson = { compilerOptions: { @@ -90,9 +90,9 @@ describe('project graph', () => { '@nrwl/shared/util': ['libs/shared/util/src/index.ts'], '@nrwl/shared-util-data': ['libs/shared/util/data/src/index.ts'], '@nrwl/ui': ['libs/ui/src/index.ts'], - '@nrwl/lazy-lib': ['libs/lazy-lib/src/index.ts'] - } - } + '@nrwl/lazy-lib': ['libs/lazy-lib/src/index.ts'], + }, + }, }; filesJson = { './apps/api/src/index.ts': stripIndents` @@ -122,7 +122,7 @@ describe('project graph', () => { './package.json': JSON.stringify(packageJson), './nx.json': JSON.stringify(nxJson), './workspace.json': JSON.stringify(workspaceJson), - './tsconfig.json': JSON.stringify(tsConfigJson) + './tsconfig.json': JSON.stringify(tsConfigJson), }; vol.reset(); vol.fromJSON(filesJson, '/root'); @@ -140,53 +140,53 @@ describe('project graph', () => { 'shared-util-data': { name: 'shared-util-data', type: 'lib' }, 'lazy-lib': { name: 'lazy-lib', type: 'lib' }, 'happy-nrwl': { name: 'happy-nrwl', type: 'npm' }, - express: { name: 'express', type: 'npm' } + express: { name: 'express', type: 'npm' }, }); expect(graph.dependencies).toMatchObject({ api: [{ type: DependencyType.static, source: 'api', target: 'express' }], 'demo-e2e': [ - { type: DependencyType.implicit, source: 'demo-e2e', target: 'demo' } + { type: DependencyType.implicit, source: 'demo-e2e', target: 'demo' }, ], demo: [ { type: DependencyType.static, source: 'demo', target: 'ui' }, { type: DependencyType.static, source: 'demo', - target: 'shared-util-data' + target: 'shared-util-data', }, { type: DependencyType.dynamic, source: 'demo', - target: 'lazy-lib' + target: 'lazy-lib', }, - { type: DependencyType.implicit, source: 'demo', target: 'api' } + { type: DependencyType.implicit, source: 'demo', target: 'api' }, ], ui: [ { type: DependencyType.static, source: 'ui', target: 'shared-util' }, - { type: DependencyType.dynamic, source: 'ui', target: 'lazy-lib' } + { type: DependencyType.dynamic, source: 'ui', target: 'lazy-lib' }, ], 'shared-util': [ { type: DependencyType.static, source: 'shared-util', - target: 'happy-nrwl' - } - ] + target: 'happy-nrwl', + }, + ], }); }); it('should update the graph if the workspace file changes ', async () => { let graph = createProjectGraph(); expect(graph.nodes).toMatchObject({ - demo: { name: 'demo', type: 'app' } + demo: { name: 'demo', type: 'app' }, }); workspaceJson.projects.demo.projectType = 'library'; //wait a tick to ensure the modified time of workspace.json will be after the creation of the project graph file - await new Promise(resolve => setTimeout(resolve, 1)); + await new Promise((resolve) => setTimeout(resolve, 1)); fs.writeFileSync('/root/workspace.json', JSON.stringify(workspaceJson)); graph = createProjectGraph(); expect(graph.nodes).toMatchObject({ - demo: { name: 'demo', type: 'lib' } + demo: { name: 'demo', type: 'lib' }, }); }); @@ -202,20 +202,20 @@ describe('project graph', () => { { type: DependencyType.static, source: 'shared-util', - target: 'ui' - } + target: 'ui', + }, ]); expect(graph.dependencies['ui']).toEqual([ { type: DependencyType.static, source: 'ui', - target: 'shared-util' + target: 'shared-util', }, { type: DependencyType.dynamic, source: 'ui', - target: 'lazy-lib' - } + target: 'lazy-lib', + }, ]); }); }); diff --git a/packages/workspace/src/core/project-graph/project-graph.ts b/packages/workspace/src/core/project-graph/project-graph.ts index 8f2c9cf094404..2e81c9e58e757 100644 --- a/packages/workspace/src/core/project-graph/project-graph.ts +++ b/packages/workspace/src/core/project-graph/project-graph.ts @@ -4,7 +4,7 @@ import { directoryExists, fileExists, readJsonFile, - writeJsonFile + writeJsonFile, } from '../../utils/fileutils'; import { assertWorkspaceValidity } from '../assert-workspace-validity'; import { createFileMap, FileMap } from '../file-graph'; @@ -14,19 +14,19 @@ import { mtime, readNxJson, readWorkspaceFiles, - readWorkspaceJson + readWorkspaceJson, } from '../file-utils'; import { normalizeNxJson } from '../normalize-nx-json'; import { BuildDependencies, buildExplicitNpmDependencies, buildExplicitTypeScriptDependencies, - buildImplicitProjectDependencies + buildImplicitProjectDependencies, } from './build-dependencies'; import { BuildNodes, buildNpmPackageNodes, - buildWorkspaceProjectNodes + buildWorkspaceProjectNodes, } from './build-nodes'; import { ProjectGraphBuilder } from './project-graph-builder'; import { ProjectGraph } from './project-graph-models'; @@ -52,22 +52,24 @@ export function createProjectGraph( const ctx = { workspaceJson, nxJson: normalizedNxJson, - fileMap: incremental.fileMap + fileMap: incremental.fileMap, }; const builder = new ProjectGraphBuilder(incremental.projectGraph); const buildNodesFns: BuildNodes[] = [ buildWorkspaceProjectNodes, - buildNpmPackageNodes + buildNpmPackageNodes, ]; const buildDependenciesFns: BuildDependencies[] = [ buildExplicitTypeScriptDependencies, buildImplicitProjectDependencies, - buildExplicitNpmDependencies + buildExplicitNpmDependencies, ]; - buildNodesFns.forEach(f => f(ctx, builder.addNode.bind(builder), fileRead)); + buildNodesFns.forEach((f) => + f(ctx, builder.addNode.bind(builder), fileRead) + ); - buildDependenciesFns.forEach(f => + buildDependenciesFns.forEach((f) => f(ctx, builder.nodes, builder.addDependency.bind(builder), fileRead) ); @@ -75,7 +77,7 @@ export function createProjectGraph( if (shouldCache) { writeCache({ projectGraph, - fileMap + fileMap, }); } return projectGraph; @@ -134,7 +136,7 @@ function writeCache(cache: ProjectGraphCache): void { } function maxMTime(files: FileData[]) { - return Math.max(...files.map(f => f.mtime)); + return Math.max(...files.map((f) => f.mtime)); } function rootWorkspaceFileData(workspaceFiles: FileData[]): FileData[] { @@ -143,9 +145,9 @@ function rootWorkspaceFileData(workspaceFiles: FileData[]): FileData[] { 'workspace.json', 'angular.json', `nx.json`, - `tsconfig.json` + `tsconfig.json`, ].reduce((acc: FileData[], curr: string) => { - const fileData = workspaceFiles.find(x => x.file === curr); + const fileData = workspaceFiles.find((x) => x.file === curr); if (fileData) { acc.push(fileData); } @@ -176,10 +178,10 @@ function modifiedSinceCache( // Projects are same -> compute projects with file changes const modifiedSince: FileMap = {}; - currentProjects.forEach(p => { + currentProjects.forEach((p) => { let projectFilesChanged = false; for (const f of fileMap[p]) { - const fromCache = cachedFileMap[p].find(x => x.file === f.file); + const fromCache = cachedFileMap[p].find((x) => x.file === f.file); if (!fromCache || f.mtime > fromCache.mtime) { projectFilesChanged = true; break; @@ -191,7 +193,7 @@ function modifiedSinceCache( }); // Re-compute nodes and dependencies for each project in file map. - Object.keys(modifiedSince).forEach(key => { + Object.keys(modifiedSince).forEach((key) => { delete c.data.projectGraph.dependencies[key]; }); diff --git a/packages/workspace/src/core/target-project-locator.spec.ts b/packages/workspace/src/core/target-project-locator.spec.ts index 2bbcf407f6b6a..560dd7cfbd27d 100644 --- a/packages/workspace/src/core/target-project-locator.spec.ts +++ b/packages/workspace/src/core/target-project-locator.spec.ts @@ -2,12 +2,12 @@ import { fs, vol } from 'memfs'; import { join } from 'path'; import { ProjectGraphContext, - ProjectGraphNode + ProjectGraphNode, } from './project-graph/project-graph-models'; import { TargetProjectLocator } from './target-project-locator'; jest.mock('../utils/app-root', () => ({ - appRootPath: '/root' + appRootPath: '/root', })); jest.mock('fs', () => require('memfs').fs); @@ -19,14 +19,14 @@ describe('findTargetProjectWithImport', () => { beforeEach(() => { const workspaceJson = { projects: { - proj1: {} - } + proj1: {}, + }, }; const nxJson = { npmScope: 'proj', projects: { - proj1: {} - } + proj1: {}, + }, }; const tsConfig = { compilerOptions: { @@ -37,9 +37,9 @@ describe('findTargetProjectWithImport', () => { '@proj/project-3': ['libs/proj3a/index.ts'], '@proj/proj123': ['libs/proj123/index.ts'], '@proj/proj1234': ['libs/proj1234/index.ts'], - '@proj/proj1234-child': ['libs/proj1234-child/index.ts'] - } - } + '@proj/proj1234-child': ['libs/proj1234-child/index.ts'], + }, + }, }; fsJson = { './workspace.json': JSON.stringify(workspaceJson), @@ -54,7 +54,7 @@ describe('findTargetProjectWithImport', () => { './libs/proj4ab/index.ts': `export const a = 4;`, './libs/proj123/index.ts': 'export const a = 5', './libs/proj1234/index.ts': 'export const a = 6', - './libs/proj1234-child/index.ts': 'export const a = 7' + './libs/proj1234-child/index.ts': 'export const a = 7', }; vol.fromJSON(fsJson, '/root'); @@ -66,52 +66,52 @@ describe('findTargetProjectWithImport', () => { { file: 'libs/proj/index.ts', mtime: 0, - ext: '.ts' - } + ext: '.ts', + }, ], proj2: [ { file: 'libs/proj2/index.ts', mtime: 0, - ext: '.ts' - } + ext: '.ts', + }, ], proj3a: [ { file: 'libs/proj3a/index.ts', mtime: 0, - ext: '.ts' - } + ext: '.ts', + }, ], proj4ab: [ { file: 'libs/proj4ab/index.ts', mtime: 0, - ext: '.ts' - } + ext: '.ts', + }, ], proj123: [ { file: 'libs/proj123/index.ts', mtime: 0, - ext: '.ts' - } + ext: '.ts', + }, ], proj1234: [ { file: 'libs/proj1234/index.ts', mtime: 0, - ext: '.ts' - } + ext: '.ts', + }, ], 'proj1234-child': [ { file: 'libs/proj1234-child/index.ts', mtime: 0, - ext: '.ts' - } - ] - } + ext: '.ts', + }, + ], + }, }; projects = { @@ -120,78 +120,78 @@ describe('findTargetProjectWithImport', () => { type: 'lib', data: { root: 'libs/proj3a', - files: [] - } + files: [], + }, }, proj2: { name: 'proj2', type: 'lib', data: { root: 'libs/proj2', - files: [] - } + files: [], + }, }, proj: { name: 'proj', type: 'lib', data: { root: 'libs/proj', - files: [] - } + files: [], + }, }, proj1234: { name: 'proj1234', type: 'lib', data: { root: 'libs/proj1234', - files: [] - } + files: [], + }, }, proj123: { name: 'proj123', type: 'lib', data: { root: 'libs/proj123', - files: [] - } + files: [], + }, }, proj4ab: { name: 'proj4ab', type: 'lib', data: { root: 'libs/proj4ab', - files: [] - } + files: [], + }, }, '@ng/core': { name: '@ng/core', type: 'npm', data: { - files: [] - } + files: [], + }, }, '@ng/common': { name: '@ng/common', type: 'npm', data: { - files: [] - } + files: [], + }, }, 'npm-package': { name: 'npm-package', type: 'npm', data: { - files: [] - } + files: [], + }, }, 'proj1234-child': { name: 'proj1234-child', type: 'lib', data: { root: 'libs/proj1234-child', - files: [] - } - } + files: [], + }, + }, }; targetProjectLocator = new TargetProjectLocator(projects); @@ -255,7 +255,7 @@ describe('findTargetProjectWithImport', () => { 'proj', '@ng/core', '@ng/common', - 'npm-package' + 'npm-package', ]); }); }); diff --git a/packages/workspace/src/core/target-project-locator.ts b/packages/workspace/src/core/target-project-locator.ts index 50d868fa1eaef..5e48c0aff8324 100644 --- a/packages/workspace/src/core/target-project-locator.ts +++ b/packages/workspace/src/core/target-project-locator.ts @@ -24,7 +24,7 @@ export class TargetProjectLocator { filePath ); - return this._sortedNodeNames.find(projectName => { + return this._sortedNodeNames.find((projectName) => { const p = this.nodes[projectName]; if (!isWorkspaceProject(p)) { diff --git a/packages/workspace/src/migrations/update-8-10-0/fix-tslint-json.spec.ts b/packages/workspace/src/migrations/update-8-10-0/fix-tslint-json.spec.ts index 67533c1b98afe..58285e8424217 100644 --- a/packages/workspace/src/migrations/update-8-10-0/fix-tslint-json.spec.ts +++ b/packages/workspace/src/migrations/update-8-10-0/fix-tslint-json.spec.ts @@ -4,13 +4,13 @@ import { join } from 'path'; import { readJsonInTree, updateJsonInTree, - updateWorkspaceInTree + updateWorkspaceInTree, } from '@nrwl/workspace'; import { createEmptyWorkspace } from '@nrwl/workspace/testing'; import { callRule, createLibWithTests, - runMigration + runMigration, } from '../../utils/testing'; import { updateWorkspace } from '@nrwl/workspace/src/utils/workspace'; @@ -25,15 +25,15 @@ describe('Update 8.10.0', () => { it('should fix projects with invalid tslint configs', async () => { tree = await callRule( chain([ - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: 'proj-with-invalid-tslint', - root: 'proj-with-invalid-tslint' + root: 'proj-with-invalid-tslint', }); }), updateJsonInTree('proj-with-invalid-tslint/tslint.json', () => ({ - rules: [] - })) + rules: [], + })), ]), tree ); @@ -48,17 +48,17 @@ describe('Update 8.10.0', () => { it('should fix projects with valid tslint configs', async () => { tree = await callRule( chain([ - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: 'proj-with-valid-tslint', - root: 'proj-with-valid-tslint' + root: 'proj-with-valid-tslint', }); }), updateJsonInTree('proj-with-valid-tslint/tslint.json', () => ({ rules: { - rule: [true] - } - })) + rule: [true], + }, + })), ]), tree ); @@ -68,19 +68,19 @@ describe('Update 8.10.0', () => { expect( readJsonInTree(result, 'proj-with-valid-tslint/tslint.json').rules ).toEqual({ - rule: [true] + rule: [true], }); }); it('should not add tslint configs to projects without tslint configs', async () => { tree = await callRule( chain([ - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: 'proj-without-tslint', - root: 'proj-without-tslint' + root: 'proj-without-tslint', }); - }) + }), ]), tree ); diff --git a/packages/workspace/src/migrations/update-8-10-0/fix-tslint-json.ts b/packages/workspace/src/migrations/update-8-10-0/fix-tslint-json.ts index 56ebc01e70bd0..399aae1b384ff 100644 --- a/packages/workspace/src/migrations/update-8-10-0/fix-tslint-json.ts +++ b/packages/workspace/src/migrations/update-8-10-0/fix-tslint-json.ts @@ -2,7 +2,7 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { join, normalize } from '@angular-devkit/core'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; @@ -14,7 +14,7 @@ import { formatFiles } from '@nrwl/workspace'; async function fixTslints(host: Tree) { const workspace = await getWorkspace(host); const rules: Rule[] = []; - workspace.projects.forEach(proj => { + workspace.projects.forEach((proj) => { const tslintPath = join(normalize(proj.root), 'tslint.json'); if (host.exists(tslintPath)) { rules.push( @@ -47,6 +47,6 @@ function showInfo(host: Tree, context: SchematicContext) { `); } -export default function(): Rule { +export default function (): Rule { return chain([showInfo, fixTslints]); } diff --git a/packages/workspace/src/migrations/update-8-12-0/add-implicit-e2e-deps.spec.ts b/packages/workspace/src/migrations/update-8-12-0/add-implicit-e2e-deps.spec.ts index 564835ca351d4..5b2b377bf1083 100644 --- a/packages/workspace/src/migrations/update-8-12-0/add-implicit-e2e-deps.spec.ts +++ b/packages/workspace/src/migrations/update-8-12-0/add-implicit-e2e-deps.spec.ts @@ -11,15 +11,15 @@ describe('Update 8.12.0', () => { tree = Tree.empty(); tree = createEmptyWorkspace(tree); tree = await callRule( - updateJsonInTree('nx.json', json => { + updateJsonInTree('nx.json', (json) => { json.projects['my-app'] = { - tags: [] + tags: [], }; json.projects['my-app-e2e'] = { - tags: [] + tags: [], }; json.projects['my-non-existent-app-e2e'] = { - tags: [] + tags: [], }; return json; }), @@ -34,17 +34,17 @@ describe('Update 8.12.0', () => { expect(nxJson.projects['my-app-e2e']).toEqual({ tags: [], - implicitDependencies: ['my-app'] + implicitDependencies: ['my-app'], }); expect(nxJson.projects['my-non-existent-app-e2e']).toEqual({ - tags: [] + tags: [], }); }); it('should not add duplicate implicit dependencies for e2e projects', async () => { tree = await callRule( - updateJsonInTree('nx.json', json => { + updateJsonInTree('nx.json', (json) => { json.projects['my-app-e2e'].implicitDependencies = ['my-app']; return json; }), @@ -56,11 +56,11 @@ describe('Update 8.12.0', () => { expect(nxJson.projects['my-app-e2e']).toEqual({ tags: [], - implicitDependencies: ['my-app'] + implicitDependencies: ['my-app'], }); expect(nxJson.projects['my-non-existent-app-e2e']).toEqual({ - tags: [] + tags: [], }); }); }); diff --git a/packages/workspace/src/migrations/update-8-12-0/add-implicit-e2e-deps.ts b/packages/workspace/src/migrations/update-8-12-0/add-implicit-e2e-deps.ts index d0295e3823df1..e7b659fdd0c19 100644 --- a/packages/workspace/src/migrations/update-8-12-0/add-implicit-e2e-deps.ts +++ b/packages/workspace/src/migrations/update-8-12-0/add-implicit-e2e-deps.ts @@ -2,7 +2,7 @@ import { chain, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; @@ -10,19 +10,24 @@ import { updateJsonInTree } from '../../utils/ast-utils'; import { NxJson } from '../../core/shared-interfaces'; import { formatFiles } from '@nrwl/workspace/src/utils/rules/format-files'; -const addE2eImplicitDependencies = updateJsonInTree('nx.json', json => { - Object.keys(json.projects).forEach(proj => { - const implicitE2eName = proj.replace(/-e2e$/, ''); - if (proj.endsWith('-e2e') && json.projects[implicitE2eName]) { - json.projects[proj].implicitDependencies = - json.projects[proj].implicitDependencies || []; - if (!json.projects[proj].implicitDependencies.includes(implicitE2eName)) { - json.projects[proj].implicitDependencies.push(implicitE2eName); +const addE2eImplicitDependencies = updateJsonInTree( + 'nx.json', + (json) => { + Object.keys(json.projects).forEach((proj) => { + const implicitE2eName = proj.replace(/-e2e$/, ''); + if (proj.endsWith('-e2e') && json.projects[implicitE2eName]) { + json.projects[proj].implicitDependencies = + json.projects[proj].implicitDependencies || []; + if ( + !json.projects[proj].implicitDependencies.includes(implicitE2eName) + ) { + json.projects[proj].implicitDependencies.push(implicitE2eName); + } } - } - }); - return json; -}); + }); + return json; + } +); function showInfo(host: Tree, context: SchematicContext) { context.logger.info(stripIndents` @@ -32,6 +37,6 @@ function showInfo(host: Tree, context: SchematicContext) { `); } -export default function(): Rule { +export default function (): Rule { return chain([showInfo, addE2eImplicitDependencies, formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-8-12-0/update-enforce-boundary-lint-rule.spec.ts b/packages/workspace/src/migrations/update-8-12-0/update-enforce-boundary-lint-rule.spec.ts index 14c2524414865..87d192e692470 100644 --- a/packages/workspace/src/migrations/update-8-12-0/update-enforce-boundary-lint-rule.spec.ts +++ b/packages/workspace/src/migrations/update-8-12-0/update-enforce-boundary-lint-rule.spec.ts @@ -5,7 +5,7 @@ import { runMigration } from '../../utils/testing'; import { createEmptyWorkspace } from '../../utils/testing-utils'; import { _test_addWorkspaceFile, - WorkspaceFormat + WorkspaceFormat, } from '@angular-devkit/core/src/workspace/core'; import { NxJson } from '../../core/shared-interfaces'; @@ -28,7 +28,7 @@ describe('Add update-enforce-boundary-lint rule', () => { JSON.stringify({ name: 'test-name', dependencies: {}, - devDependencies: {} + devDependencies: {}, }) ); tree.create( @@ -52,10 +52,10 @@ describe('Add update-enforce-boundary-lint rule', () => { { npmScope: '<%= npmScope %>', lazyLoad: [], - allow: [] - } - ] - } + allow: [], + }, + ], + }, }) ); }); @@ -86,10 +86,10 @@ describe('Add update-enforce-boundary-lint rule', () => { { npmScope: '<%= npmScope %>', lazyLoad: [], - allow: [] - } - ] - } + allow: [], + }, + ], + }, }) ); }); diff --git a/packages/workspace/src/migrations/update-8-12-0/update-enforce-boundary-lint-rule.ts b/packages/workspace/src/migrations/update-8-12-0/update-enforce-boundary-lint-rule.ts index cb48ce09f4365..7aa470a99ea65 100644 --- a/packages/workspace/src/migrations/update-8-12-0/update-enforce-boundary-lint-rule.ts +++ b/packages/workspace/src/migrations/update-8-12-0/update-enforce-boundary-lint-rule.ts @@ -3,7 +3,7 @@ import { updateJsonInTree } from '../../utils/ast-utils'; export const addEnforceBuildablePackageTslintRule = (host: Tree) => { if (host.exists('tslint.json')) { - return updateJsonInTree('tslint.json', json => { + return updateJsonInTree('tslint.json', (json) => { const ruleName = 'nx-enforce-module-boundaries'; const rule = ruleName in json.rules ? json.rules[ruleName] : null; @@ -19,7 +19,7 @@ export const addEnforceBuildablePackageTslintRule = (host: Tree) => { export const addEnforceBuildablePackageEslintRule = (host: Tree) => { if (host.exists('.eslintrc')) { - return updateJsonInTree('.eslintrc', json => { + return updateJsonInTree('.eslintrc', (json) => { const ruleName = '@nrwl/nx/enforce-module-boundaries'; const rule = ruleName in json.rules ? json.rules[ruleName] : null; @@ -33,9 +33,9 @@ export const addEnforceBuildablePackageEslintRule = (host: Tree) => { } }; -export default function(): Rule { +export default function (): Rule { return chain([ addEnforceBuildablePackageTslintRule, - addEnforceBuildablePackageEslintRule + addEnforceBuildablePackageEslintRule, ]); } diff --git a/packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.spec.ts b/packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.spec.ts index 58c53fcf14127..5f4eae6cafebe 100644 --- a/packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.spec.ts +++ b/packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.spec.ts @@ -24,8 +24,8 @@ describe('Update 8.12.0: package.json deps', () => { '@angular-devkit/build-optimizer': '0.803.14', '@angular-devkit/build-webpack': '0.803.14', '@angular-devkit/schematics': '8.3.14', - '@angular/cli': '8.3.14' - } + '@angular/cli': '8.3.14', + }, }) ); diff --git a/packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.ts b/packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.ts index cb20c922b7309..d97223d39efe5 100644 --- a/packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.ts +++ b/packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.ts @@ -3,12 +3,12 @@ import { formatFiles } from '@nrwl/workspace/src/utils/rules/format-files'; import * as path from 'path'; import { updatePackagesInPackageJson } from '../../utils/update-packages-in-package-json'; -export default function(): Rule { +export default function (): Rule { return chain([ updatePackagesInPackageJson( path.join(__dirname, '../../..', 'migrations.json'), '8120' ), - formatFiles() + formatFiles(), ]); } diff --git a/packages/workspace/src/migrations/update-8-2-0/update-8-2-0.spec.ts b/packages/workspace/src/migrations/update-8-2-0/update-8-2-0.spec.ts index 67e990b6f75b3..388c867cd9379 100644 --- a/packages/workspace/src/migrations/update-8-2-0/update-8-2-0.spec.ts +++ b/packages/workspace/src/migrations/update-8-2-0/update-8-2-0.spec.ts @@ -3,7 +3,7 @@ import { createEmptyWorkspace } from '@nrwl/workspace/testing'; import { callRule, runMigration } from '../../utils/testing'; import { readJsonInTree, - updateJsonInTree + updateJsonInTree, } from '@nrwl/workspace/src/utils/ast-utils'; describe('Update 8.2.0', () => { @@ -12,7 +12,7 @@ describe('Update 8.2.0', () => { beforeEach(async () => { tree = createEmptyWorkspace(Tree.empty()); tree = await callRule( - updateJsonInTree('workspace.json', json => { + updateJsonInTree('workspace.json', (json) => { json.projects['my-app'] = { root: 'my-app', architect: { @@ -20,10 +20,10 @@ describe('Update 8.2.0', () => { builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: ['my-app/tsconfig.json'], - exclude: ['**/node_modules/**'] - } - } - } + exclude: ['**/node_modules/**'], + }, + }, + }, }; return json; @@ -40,8 +40,8 @@ describe('Update 8.2.0', () => { builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: ['my-app/tsconfig.json'], - exclude: ['**/node_modules/**', '!my-app/**'] - } + exclude: ['**/node_modules/**', '!my-app/**'], + }, }); }); }); diff --git a/packages/workspace/src/migrations/update-8-2-0/update-8-2-0.ts b/packages/workspace/src/migrations/update-8-2-0/update-8-2-0.ts index a0043aee8e816..151aa8774940a 100644 --- a/packages/workspace/src/migrations/update-8-2-0/update-8-2-0.ts +++ b/packages/workspace/src/migrations/update-8-2-0/update-8-2-0.ts @@ -3,9 +3,9 @@ import { join, JsonArray, normalize } from '@angular-devkit/core'; import { formatFiles } from '@nrwl/workspace'; import { chain } from '@angular-devkit/schematics'; -const addExcludes = updateWorkspace(workspace => { - workspace.projects.forEach(project => { - project.targets.forEach(target => { +const addExcludes = updateWorkspace((workspace) => { + workspace.projects.forEach((project) => { + project.targets.forEach((target) => { if (target.builder !== '@angular-devkit/build-angular:tslint') { return; } @@ -22,6 +22,6 @@ const addExcludes = updateWorkspace(workspace => { }); }); -export default function() { +export default function () { return chain([addExcludes, formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-8-3-0/rename-lint.ts b/packages/workspace/src/migrations/update-8-3-0/rename-lint.ts index 418d8cbb15ea5..060e60cacef06 100644 --- a/packages/workspace/src/migrations/update-8-3-0/rename-lint.ts +++ b/packages/workspace/src/migrations/update-8-3-0/rename-lint.ts @@ -2,7 +2,7 @@ import { updateJsonInTree } from '../../utils/ast-utils'; import { formatFiles } from '@nrwl/workspace'; import { chain } from '@angular-devkit/schematics'; -const updateLint = updateJsonInTree('package.json', json => { +const updateLint = updateJsonInTree('package.json', (json) => { if ( json.scripts && json.scripts.lint && @@ -16,6 +16,6 @@ const updateLint = updateJsonInTree('package.json', json => { return json; }); -export default function() { +export default function () { return chain([updateLint, formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-8-3-0/update-8-3-0.spec.ts b/packages/workspace/src/migrations/update-8-3-0/update-8-3-0.spec.ts index 46dac92359371..44fd3596b6d58 100644 --- a/packages/workspace/src/migrations/update-8-3-0/update-8-3-0.spec.ts +++ b/packages/workspace/src/migrations/update-8-3-0/update-8-3-0.spec.ts @@ -2,7 +2,7 @@ import { Tree } from '@angular-devkit/schematics'; import { readJsonInTree } from '@nrwl/workspace'; import { SchematicTestRunner, - UnitTestTree + UnitTestTree, } from '@angular-devkit/schematics/testing'; import { serializeJson } from '@nrwl/workspace'; import { join } from 'path'; @@ -20,8 +20,8 @@ describe('Update 8.3.0', () => { devDependencies: { '@angular/cli': '8.0.0', '@angular-devkit/build-angular': '^0.800.0', - '@angular-devkit/build-ng-packagr': '~0.800.0' - } + '@angular-devkit/build-ng-packagr': '~0.800.0', + }, }) ); diff --git a/packages/workspace/src/migrations/update-8-3-0/update-cypress-to-34.ts b/packages/workspace/src/migrations/update-8-3-0/update-cypress-to-34.ts index 3dc6166c7fd61..a10b6efb81a9a 100644 --- a/packages/workspace/src/migrations/update-8-3-0/update-cypress-to-34.ts +++ b/packages/workspace/src/migrations/update-8-3-0/update-cypress-to-34.ts @@ -1,7 +1,7 @@ import { addInstallTask, formatFiles, updateJsonInTree } from '@nrwl/workspace'; import { chain } from '@angular-devkit/schematics'; -const updateCypress = updateJsonInTree('package.json', json => { +const updateCypress = updateJsonInTree('package.json', (json) => { json.devDependencies = json.devDependencies || {}; if (json.devDependencies['cypress']) { json.devDependencies['cypress'] = '3.4.0'; @@ -10,6 +10,6 @@ const updateCypress = updateJsonInTree('package.json', json => { return json; }); -export default function() { +export default function () { return chain([updateCypress, addInstallTask(), formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-8-3-0/update-ng-cli-8-1.ts b/packages/workspace/src/migrations/update-8-3-0/update-ng-cli-8-1.ts index 876149ee1efe9..c5b7fb1289666 100644 --- a/packages/workspace/src/migrations/update-8-3-0/update-ng-cli-8-1.ts +++ b/packages/workspace/src/migrations/update-8-3-0/update-ng-cli-8-1.ts @@ -1,12 +1,12 @@ import { updateJsonInTree, checkAndCleanWithSemver, - addInstallTask + addInstallTask, } from '@nrwl/workspace'; import { chain } from '@angular-devkit/schematics'; import { gt } from 'semver'; -const updateCLI = updateJsonInTree('package.json', json => { +const updateCLI = updateJsonInTree('package.json', (json) => { json.devDependencies = json.devDependencies || {}; const cliVersion = json.devDependencies['@angular/cli']; const cleanCliVersion = checkAndCleanWithSemver('@angular/cli', cliVersion); @@ -30,6 +30,6 @@ const updateCLI = updateJsonInTree('package.json', json => { return json; }); -export default function() { +export default function () { return chain([updateCLI, addInstallTask()]); } diff --git a/packages/workspace/src/migrations/update-8-4-0/add-nx-script.ts b/packages/workspace/src/migrations/update-8-4-0/add-nx-script.ts index d5d0d8164099f..30c472675e75a 100644 --- a/packages/workspace/src/migrations/update-8-4-0/add-nx-script.ts +++ b/packages/workspace/src/migrations/update-8-4-0/add-nx-script.ts @@ -2,13 +2,13 @@ import { updateJsonInTree } from '../../utils/ast-utils'; import { chain } from '@angular-devkit/schematics'; import { formatFiles } from '@nrwl/workspace'; -const addNxScript = updateJsonInTree('package.json', json => { +const addNxScript = updateJsonInTree('package.json', (json) => { if (json.scripts && !json.scripts.nx) { json.scripts.nx = 'nx'; } return json; }); -export default function() { +export default function () { return chain([addNxScript, formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-8-5-0/fix-tsconfig-lib-json.ts b/packages/workspace/src/migrations/update-8-5-0/fix-tsconfig-lib-json.ts index a1dcbd65dcaa5..f486e97c213c4 100644 --- a/packages/workspace/src/migrations/update-8-5-0/fix-tsconfig-lib-json.ts +++ b/packages/workspace/src/migrations/update-8-5-0/fix-tsconfig-lib-json.ts @@ -2,13 +2,13 @@ import { Tree, SchematicContext, chain } from '@angular-devkit/schematics'; import { readWorkspace, readJsonInTree } from '../../utils/ast-utils'; import { formatFiles } from '@nrwl/workspace'; -export default function() { +export default function () { return chain([ (host: Tree) => { const config = readWorkspace(host); const configsToUpdate = []; - Object.keys(config.projects).forEach(name => { + Object.keys(config.projects).forEach((name) => { const project = config.projects[name]; if ( project.projectType === 'library' && @@ -23,7 +23,7 @@ export default function() { } }); - configsToUpdate.forEach(config => { + configsToUpdate.forEach((config) => { const tsconfig = readJsonInTree(host, config); if (tsconfig.exclude && tsconfig.exclude[0] === 'src/test.ts') { tsconfig.exclude[0] = 'src/test-setup.ts'; @@ -31,6 +31,6 @@ export default function() { } }); }, - formatFiles() + formatFiles(), ]); } diff --git a/packages/workspace/src/migrations/update-9-0-0/update-9-0-0.ts b/packages/workspace/src/migrations/update-9-0-0/update-9-0-0.ts index c90ee45a19e57..89beb2d13d301 100644 --- a/packages/workspace/src/migrations/update-9-0-0/update-9-0-0.ts +++ b/packages/workspace/src/migrations/update-9-0-0/update-9-0-0.ts @@ -7,6 +7,6 @@ const updatePackages = updatePackagesInPackageJson( '9.0.0' ); -export default function() { +export default function () { return chain([updatePackages, formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-9-1-0/update-9-1-0.ts b/packages/workspace/src/migrations/update-9-1-0/update-9-1-0.ts index 8c115538882a3..5670f7c9a19a9 100644 --- a/packages/workspace/src/migrations/update-9-1-0/update-9-1-0.ts +++ b/packages/workspace/src/migrations/update-9-1-0/update-9-1-0.ts @@ -6,6 +6,6 @@ const updatePackages = updatePackagesInPackageJson( join(__dirname, '../../../', 'migrations.json'), '9.1.0' ); -export default function() { +export default function () { return chain([updatePackages, formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-9-1-0/update-lint-config.spec.ts b/packages/workspace/src/migrations/update-9-1-0/update-lint-config.spec.ts index b1c07810bbe2a..57708029d81e5 100644 --- a/packages/workspace/src/migrations/update-9-1-0/update-lint-config.spec.ts +++ b/packages/workspace/src/migrations/update-9-1-0/update-lint-config.spec.ts @@ -15,35 +15,35 @@ describe('Update 9.1.0', () => { it('should update tslint.json', async () => { tree = await callRule( chain([ - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: 'proj1', root: 'proj1', architect: { lint: { - builder: '@angular-devkit/build-angular:tslint' - } - } + builder: '@angular-devkit/build-angular:tslint', + }, + }, }); workspace.projects.add({ name: 'proj2', root: 'proj2', architect: { lint: { - builder: '@angular-devkit/build-angular:tslint' - } - } + builder: '@angular-devkit/build-angular:tslint', + }, + }, }); }), updateJsonInTree('proj1/tslint.json', () => ({ - rules: {} + rules: {}, })), updateJsonInTree('proj2/tslint.json', () => ({ rules: {}, linterOptions: { - exclude: ['whatever'] - } - })) + exclude: ['whatever'], + }, + })), ]), tree ); @@ -53,22 +53,22 @@ describe('Update 9.1.0', () => { expect(readJsonInTree(result, 'proj1/tslint.json')).toEqual({ rules: {}, linterOptions: { - exclude: ['!**/*'] - } + exclude: ['!**/*'], + }, }); expect(readJsonInTree(result, 'proj2/tslint.json')).toEqual({ rules: {}, linterOptions: { - exclude: ['!**/*', 'whatever'] - } + exclude: ['!**/*', 'whatever'], + }, }); }); it('should update .eslintrc', async () => { tree = await callRule( chain([ - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: 'proj1', root: 'proj1', @@ -76,10 +76,10 @@ describe('Update 9.1.0', () => { lint: { builder: '@nrwl/linter:lint', options: { - config: 'proj1/.eslintrc' - } - } - } + config: 'proj1/.eslintrc', + }, + }, + }, }); workspace.projects.add({ name: 'proj2', @@ -88,19 +88,19 @@ describe('Update 9.1.0', () => { lint: { builder: '@nrwl/linter:lint', options: { - config: 'proj2/.eslintrc' - } - } - } + config: 'proj2/.eslintrc', + }, + }, + }, }); }), updateJsonInTree('proj1/.eslintrc', () => ({ - rules: {} + rules: {}, })), updateJsonInTree('proj2/.eslintrc', () => ({ rules: {}, - ignorePatterns: ['whatever'] - })) + ignorePatterns: ['whatever'], + })), ]), tree ); @@ -109,12 +109,12 @@ describe('Update 9.1.0', () => { expect(readJsonInTree(result, 'proj1/.eslintrc')).toEqual({ rules: {}, - ignorePatterns: ['!**/*'] + ignorePatterns: ['!**/*'], }); expect(readJsonInTree(result, 'proj2/.eslintrc')).toEqual({ rules: {}, - ignorePatterns: ['!**/*', 'whatever'] + ignorePatterns: ['!**/*', 'whatever'], }); }); }); diff --git a/packages/workspace/src/migrations/update-9-1-0/update-lint-config.ts b/packages/workspace/src/migrations/update-9-1-0/update-lint-config.ts index 3d4a4ff0508d0..708fc7e43eb39 100644 --- a/packages/workspace/src/migrations/update-9-1-0/update-lint-config.ts +++ b/packages/workspace/src/migrations/update-9-1-0/update-lint-config.ts @@ -7,7 +7,7 @@ function updateLintConfigurations(host: Tree, context: SchematicContext) { if (!config.architect || !config.architect.lint) return; if (config.architect.lint.builder === '@nrwl/linter:lint') { updateJson( - json => { + (json) => { // Prefix it so that previously ignored files will override the whitelist. json.ignorePatterns = ['!**/*', ...(json.ignorePatterns || [])]; return json; @@ -21,14 +21,14 @@ function updateLintConfigurations(host: Tree, context: SchematicContext) { config.architect.lint.builder === '@angular-devkit/build-angular:tslint' ) { updateJson( - json => { + (json) => { json.linterOptions = { ...json.linterOptions, // Prefix it so that previously ignored files will override the whitelist. exclude: [ '!**/*', - ...((json.linterOptions && json.linterOptions.exclude) || []) - ] + ...((json.linterOptions && json.linterOptions.exclude) || []), + ], }; return json; }, @@ -51,6 +51,6 @@ function updateJson(visitor, path, host, context) { } } -export default function() { +export default function () { return chain([updateLintConfigurations, formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-9-2-0/update-9-2-0.spec.ts b/packages/workspace/src/migrations/update-9-2-0/update-9-2-0.spec.ts index b37845dc678ae..dd74f32899f41 100644 --- a/packages/workspace/src/migrations/update-9-2-0/update-9-2-0.spec.ts +++ b/packages/workspace/src/migrations/update-9-2-0/update-9-2-0.spec.ts @@ -20,9 +20,9 @@ describe('Update 9.2.0', () => { default: { runner: '@nrwl/workspace/tasks-runners/default', options: { - cacheableOperations: ['build', 'lint', 'test', 'e2e'] - } - } + cacheableOperations: ['build', 'lint', 'test', 'e2e'], + }, + }, }); }); }); @@ -31,14 +31,14 @@ describe('Update 9.2.0', () => { describe('with @nrwl/workspace/src/tasks-runner/default-task-runner', () => { it('should add configuration for cacheable operations', async () => { tree = await callRule( - updateJsonInTree('nx.json', json => { + updateJsonInTree('nx.json', (json) => { json.tasksRunnerOptions = { default: { runner: '@nrwl/workspace/src/tasks-runner/default-task-runner', options: { - cacheableOperations: ['custom-operation'] - } - } + cacheableOperations: ['custom-operation'], + }, + }, }; return json; @@ -56,10 +56,10 @@ describe('Update 9.2.0', () => { 'build', 'lint', 'test', - 'e2e' - ] - } - } + 'e2e', + ], + }, + }, }); }); }); @@ -67,14 +67,14 @@ describe('Update 9.2.0', () => { describe('with @nrwl/workspace/src/tasks-runner/tasks-runner-v2', () => { it('should add configuration for cacheable operations', async () => { tree = await callRule( - updateJsonInTree('nx.json', json => { + updateJsonInTree('nx.json', (json) => { json.tasksRunnerOptions = { default: { runner: '@nrwl/workspace/src/tasks-runner/tasks-runner-v2', options: { - cacheableOperations: ['custom-operation'] - } - } + cacheableOperations: ['custom-operation'], + }, + }, }; return json; @@ -92,10 +92,10 @@ describe('Update 9.2.0', () => { 'build', 'lint', 'test', - 'e2e' - ] - } - } + 'e2e', + ], + }, + }, }); }); }); diff --git a/packages/workspace/src/migrations/update-9-2-0/update-9-2-0.ts b/packages/workspace/src/migrations/update-9-2-0/update-9-2-0.ts index 51bd9fcefdf4a..e3e386afe5881 100644 --- a/packages/workspace/src/migrations/update-9-2-0/update-9-2-0.ts +++ b/packages/workspace/src/migrations/update-9-2-0/update-9-2-0.ts @@ -2,7 +2,7 @@ import { chain } from '@angular-devkit/schematics'; import { formatFiles, updateJsonInTree, - updatePackagesInPackageJson + updatePackagesInPackageJson, } from '@nrwl/workspace'; import { join } from 'path'; @@ -11,15 +11,15 @@ const updatePackages = updatePackagesInPackageJson( '9.2.0' ); -const addCacheableOperations = updateJsonInTree('nx.json', nxJson => { +const addCacheableOperations = updateJsonInTree('nx.json', (nxJson) => { nxJson.tasksRunnerOptions = nxJson.tasksRunnerOptions || {}; if (!nxJson.tasksRunnerOptions.default) { nxJson.tasksRunnerOptions.default = { runner: '@nrwl/workspace/tasks-runners/default', options: { - cacheableOperations: ['build', 'lint', 'test', 'e2e'] - } + cacheableOperations: ['build', 'lint', 'test', 'e2e'], + }, }; return nxJson; @@ -56,6 +56,6 @@ const addCacheableOperations = updateJsonInTree('nx.json', nxJson => { return nxJson; }); -export default function() { +export default function () { return chain([updatePackages, addCacheableOperations, formatFiles()]); } diff --git a/packages/workspace/src/migrations/update-9-3-0/update-9-3-0.ts b/packages/workspace/src/migrations/update-9-3-0/update-9-3-0.ts index af1e6746ab513..7f06981ad2ce3 100644 --- a/packages/workspace/src/migrations/update-9-3-0/update-9-3-0.ts +++ b/packages/workspace/src/migrations/update-9-3-0/update-9-3-0.ts @@ -6,6 +6,6 @@ const updatePackages = updatePackagesInPackageJson( join(__dirname, '../../../', 'migrations.json'), '9.3.0' ); -export default function() { +export default function () { return chain([updatePackages, formatFiles()]); } diff --git a/packages/workspace/src/schematics/init/files/karma.conf.js b/packages/workspace/src/schematics/init/files/karma.conf.js index 1056f2baa9a76..2c5a16ceedb8c 100644 --- a/packages/workspace/src/schematics/init/files/karma.conf.js +++ b/packages/workspace/src/schematics/init/files/karma.conf.js @@ -13,15 +13,15 @@ module.exports = () => { require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), - require('@angular-devkit/build-angular/plugins/karma') + require('@angular-devkit/build-angular/plugins/karma'), ], client: { - clearContext: false // leave Jasmine Spec Runner output visible in browser + clearContext: false, // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: join(__dirname, '../../coverage'), reports: ['html', 'lcovonly'], - fixWebpackSourcePaths: true + fixWebpackSourcePaths: true, }, reporters: ['progress', 'kjhtml'], port: 9876, @@ -29,6 +29,6 @@ module.exports = () => { logLevel: constants.LOG_INFO, autoWatch: true, browsers: ['Chrome'], - singleRun: true + singleRun: true, }; }; diff --git a/packages/workspace/src/schematics/init/init.spec.ts b/packages/workspace/src/schematics/init/init.spec.ts index f128455184654..5edb99e6a8e57 100644 --- a/packages/workspace/src/schematics/init/init.spec.ts +++ b/packages/workspace/src/schematics/init/init.spec.ts @@ -28,12 +28,12 @@ describe('workspace', () => { architect: { e2e: { options: { - protractorConfig: 'e2e/protractor.conf.js' - } - } - } - } - } + protractorConfig: 'e2e/protractor.conf.js', + }, + }, + }, + }, + }, }) ); @@ -66,8 +66,8 @@ describe('workspace', () => { proj1: {}, 'proj1-e2e': {}, proj2: {}, - 'proj2-e2e': {} - } + 'proj2-e2e': {}, + }, }) ); try { @@ -91,28 +91,28 @@ describe('workspace', () => { architect: { build: { options: { - tsConfig: 'tsconfig.app.json' + tsConfig: 'tsconfig.app.json', }, - configurations: {} + configurations: {}, }, test: { options: { - tsConfig: 'tsconfig.spec.json' - } + tsConfig: 'tsconfig.spec.json', + }, }, lint: { options: { - tsConfig: 'tsconfig.app.json' - } + tsConfig: 'tsconfig.app.json', + }, }, e2e: { options: { - protractorConfig: 'e2e/protractor.conf.js' - } - } - } - } - } + protractorConfig: 'e2e/protractor.conf.js', + }, + }, + }, + }, + }, }) ); appTree.create( @@ -144,28 +144,28 @@ describe('workspace', () => { architect: { build: { options: { - tsConfig: 'src/tsconfig.app.json' + tsConfig: 'src/tsconfig.app.json', }, - configurations: {} + configurations: {}, }, test: { options: { - tsConfig: 'src/tsconfig.spec.json' - } + tsConfig: 'src/tsconfig.spec.json', + }, }, lint: { options: { - tsConfig: 'src/tsconfig.app.json' - } + tsConfig: 'src/tsconfig.app.json', + }, }, e2e: { options: { - protractorConfig: 'e2e/protractor.conf.js' - } - } - } - } - } + protractorConfig: 'e2e/protractor.conf.js', + }, + }, + }, + }, + }, }) ); appTree.create( @@ -198,13 +198,13 @@ describe('workspace', () => { architect: { build: { options: { - tsConfig: 'tsconfig.app.json' + tsConfig: 'tsconfig.app.json', }, - configurations: {} - } - } - } - } + configurations: {}, + }, + }, + }, + }, }) ); appTree.create( diff --git a/packages/workspace/src/schematics/init/init.ts b/packages/workspace/src/schematics/init/init.ts index 98db6a9af82de..fb2db05caacde 100755 --- a/packages/workspace/src/schematics/init/init.ts +++ b/packages/workspace/src/schematics/init/init.ts @@ -7,14 +7,14 @@ import { template, Tree, url, - noop + noop, } from '@angular-devkit/schematics'; import { join, normalize } from '@angular-devkit/core'; import { Schema } from './schema'; import { angularCliVersion, nxVersion, - prettierVersion + prettierVersion, } from '../../utils/versions'; import { from } from 'rxjs'; import { mapTo, tap } from 'rxjs/operators'; @@ -28,7 +28,7 @@ import { getWorkspacePath, renameSyncInTree, renameDirSyncInTree, - addInstallTask + addInstallTask, } from '@nrwl/workspace'; import { DEFAULT_NRWL_PRETTIER_CONFIG } from '../workspace/workspace'; import { JsonArray } from '@angular-devkit/core'; @@ -36,7 +36,7 @@ import { updateWorkspace } from '../../utils/workspace'; import { basename } from 'path'; function updatePackageJson() { - return updateJsonInTree('package.json', packageJson => { + return updateJsonInTree('package.json', (packageJson) => { packageJson.scripts = packageJson.scripts || {}; packageJson.scripts = { ...packageJson.scripts, @@ -57,7 +57,7 @@ function updatePackageJson() { lint: 'nx workspace-lint && ng lint', 'dep-graph': 'nx dep-graph', 'workspace-schematic': 'nx workspace-schematic', - help: 'nx help' + help: 'nx help', }; packageJson.devDependencies = packageJson.devDependencies || {}; if (!packageJson.dependencies) { @@ -85,7 +85,7 @@ function convertPath(name: string, originalPath: string) { } function updateAngularCLIJson(options: Schema): Rule { - return updateWorkspace(workspace => { + return updateWorkspace((workspace) => { const appName: string = workspace.extensions.defaultProject as string; const e2eName = appName + '-e2e'; const e2eRoot = join(normalize('apps'), e2eName); @@ -119,15 +119,15 @@ function updateAngularCLIJson(options: Schema): Rule { (buildOptions.scripts as JsonArray).map(convertAsset); buildOptions.fileReplacements = buildOptions.fileReplacements && - buildOptions.fileReplacements.map(replacement => ({ + buildOptions.fileReplacements.map((replacement) => ({ replace: convertAsset(replacement.replace), - with: convertAsset(replacement.with) + with: convertAsset(replacement.with), })); } convertBuildOptions(defaultProject.targets.get('build').options); - Object.values(defaultProject.targets.get('build').configurations).forEach( - config => convertBuildOptions(config) - ); + Object.values( + defaultProject.targets.get('build').configurations + ).forEach((config) => convertBuildOptions(config)); if (defaultProject.targets.has('test')) { const testOptions = defaultProject.targets.get('test').options; @@ -152,7 +152,7 @@ function updateAngularCLIJson(options: Schema): Rule { if (lintTarget) { lintTarget.options.tsConfig = [ join(newRoot, 'tsconfig.app.json'), - join(newRoot, 'tsconfig.spec.json') + join(newRoot, 'tsconfig.spec.json'), ]; } @@ -167,9 +167,9 @@ function updateAngularCLIJson(options: Schema): Rule { join(normalize('apps'), appName, 'tsconfig.server.json'); serverOptions.fileReplacements = serverOptions.fileReplacements && - serverOptions.fileReplacements.map(replacement => ({ + serverOptions.fileReplacements.map((replacement) => ({ replace: convertAsset(replacement.replace), - with: convertAsset(replacement.with) + with: convertAsset(replacement.with), })); } @@ -178,7 +178,7 @@ function updateAngularCLIJson(options: Schema): Rule { convertServerOptions(serverOptions); Object.values( defaultProject.targets.get('server').configurations - ).forEach(config => convertServerOptions(config)); + ).forEach((config) => convertServerOptions(config)); } function convertAsset(asset: string | any) { @@ -192,7 +192,7 @@ function updateAngularCLIJson(options: Schema): Rule { input: asset.input && asset.input.startsWith(oldSourceRoot) ? convertPath(appName, asset.input) - : asset.input + : asset.input, }; } } @@ -204,16 +204,16 @@ function updateAngularCLIJson(options: Schema): Rule { root: e2eRoot, projectType: 'application', targets: { - e2e: defaultProject.targets.get('e2e') - } + e2e: defaultProject.targets.get('e2e'), + }, }); e2eProject.targets.add({ name: 'lint', builder: '@angular-devkit/build-angular:tslint', options: { ...lintTargetOptions, - tsConfig: join(e2eRoot, 'tsconfig.json') - } + tsConfig: join(e2eRoot, 'tsconfig.json'), + }, }); e2eProject.targets.get('e2e').options.protractorConfig = join( e2eRoot, @@ -225,7 +225,7 @@ function updateAngularCLIJson(options: Schema): Rule { } function updateTsConfig(options: Schema): Rule { - return updateJsonInTree('tsconfig.json', tsConfigJson => + return updateJsonInTree('tsconfig.json', (tsConfigJson) => setUpCompilerOptions(tsConfigJson, options.npmScope, '') ); } @@ -239,14 +239,14 @@ function updateTsConfigsJson(options: Schema) { const offset = '../../'; return chain([ - updateJsonInTree(app.architect.build.options.tsConfig, json => { + updateJsonInTree(app.architect.build.options.tsConfig, (json) => { json.extends = `${offset}tsconfig.json`; json.compilerOptions.outDir = `${offset}dist/out-tsc`; return json; }), app.architect.test - ? updateJsonInTree(app.architect.test.options.tsConfig, json => { + ? updateJsonInTree(app.architect.test.options.tsConfig, (json) => { json.extends = `${offset}tsconfig.json`; json.compilerOptions.outDir = `${offset}dist/out-tsc`; return json; @@ -254,35 +254,38 @@ function updateTsConfigsJson(options: Schema) { : noop(), app.architect.server - ? updateJsonInTree(app.architect.server.options.tsConfig, json => { + ? updateJsonInTree(app.architect.server.options.tsConfig, (json) => { json.compilerOptions.outDir = `${offset}dist/out-tsc`; return json; }) : noop(), !!e2eProject - ? updateJsonInTree(e2eProject.architect.lint.options.tsConfig, json => { - json.extends = `${offsetFromRoot(e2eProject.root)}tsconfig.json`; - json.compilerOptions = { - ...json.compilerOptions, - outDir: `${offsetFromRoot(e2eProject.root)}dist/out-tsc` - }; - return json; - }) - : noop() + ? updateJsonInTree( + e2eProject.architect.lint.options.tsConfig, + (json) => { + json.extends = `${offsetFromRoot(e2eProject.root)}tsconfig.json`; + json.compilerOptions = { + ...json.compilerOptions, + outDir: `${offsetFromRoot(e2eProject.root)}dist/out-tsc`, + }; + return json; + } + ) + : noop(), ]); }; } function updateTsLint() { - return updateJsonInTree('tslint.json', tslintJson => { + return updateJsonInTree('tslint.json', (tslintJson) => { [ 'no-trailing-whitespace', 'one-line', 'quotemark', 'typedef-whitespace', - 'whitespace' - ].forEach(key => { + 'whitespace', + ].forEach((key) => { tslintJson[key] = undefined; }); tslintJson.rulesDirectory = tslintJson.rulesDirectory || []; @@ -291,8 +294,8 @@ function updateTsLint() { true, { allow: [], - depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }] - } + depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }], + }, ]; return tslintJson; }); @@ -305,7 +308,7 @@ function updateProjectTsLint(options: Schema) { const offset = '../../'; if (host.exists(`${app.root}/tslint.json`)) { - return updateJsonInTree(`${app.root}/tslint.json`, json => { + return updateJsonInTree(`${app.root}/tslint.json`, (json) => { json.extends = `${offset}tslint.json`; return json; }); @@ -337,7 +340,7 @@ function moveOutOfSrc( const filename = !!filePath ? basename(filePath) : ''; const from = filePath; const to = join(normalize('apps'), appName, filename); - renameSyncInTree(tree, from, to, err => { + renameSyncInTree(tree, from, to, (err) => { if (!context) { return; } else if (!err) { @@ -349,7 +352,7 @@ function moveOutOfSrc( } function getE2eKey(workspaceJson: any) { - return Object.keys(workspaceJson.projects).find(key => { + return Object.keys(workspaceJson.projects).find((key) => { return !!workspaceJson.projects[key].architect.e2e; }); } @@ -417,7 +420,7 @@ function moveExistingFiles(options: Schema) { options.name, app.sourceRoot ); - renameDirSyncInTree(host, oldAppSourceRoot, newAppSourceRoot, err => { + renameDirSyncInTree(host, oldAppSourceRoot, newAppSourceRoot, (err) => { if (!err) { context.logger.info( `Renamed ${oldAppSourceRoot} -> ${newAppSourceRoot}` @@ -434,7 +437,7 @@ function moveExistingFiles(options: Schema) { normalize('apps'), getE2eKey(workspaceJson) + '-e2e' ); - renameDirSyncInTree(host, oldE2eRoot, newE2eRoot, err => { + renameDirSyncInTree(host, oldE2eRoot, newE2eRoot, (err) => { if (!err) { context.logger.info(`Renamed ${oldE2eRoot} -> ${newE2eRoot}`); } else { @@ -464,16 +467,16 @@ function createAdditionalFiles(options: Schema): Rule { 'package.json': '*', 'tsconfig.json': '*', 'tslint.json': '*', - 'nx.json': '*' + 'nx.json': '*', }, projects: { [options.name]: { - tags: [] + tags: [], }, [getE2eKey(workspaceJson) + '-e2e']: { - tags: [] - } - } + tags: [], + }, + }, }) ); host.create('libs/.gitkeep', ''); @@ -486,8 +489,8 @@ function createAdditionalFiles(options: Schema): Rule { 'nrwl.angular-console', 'angular.ng-template', 'ms-vscode.vscode-typescript-tslint-plugin', - 'esbenp.prettier-vscode' - ].forEach(extension => { + 'esbenp.prettier-vscode', + ].forEach((extension) => { if (!json.recommendations.includes(extension)) { json.recommendations.push(extension); } @@ -500,7 +503,7 @@ function createAdditionalFiles(options: Schema): Rule { // if the user does not already have a prettier configuration // of any kind, create one return from(resolveUserExistingPrettierConfig()).pipe( - tap(existingPrettierConfig => { + tap((existingPrettierConfig) => { if (!existingPrettierConfig) { host.create( '.prettierrc', @@ -554,15 +557,15 @@ function checkCanConvertToWorkspace(options: Schema) { }; } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { const options = { ...schema, - npmScope: toFileName(schema.npmScope || schema.name) + npmScope: toFileName(schema.npmScope || schema.name), }; const templateSource = apply(url('./files'), [ template({ - tmpl: '' - }) + tmpl: '', + }), ]); return chain([ checkCanConvertToWorkspace(options), @@ -575,6 +578,6 @@ export default function(schema: Schema): Rule { updateProjectTsLint(options), updateTsConfig(options), updateTsConfigsJson(options), - addInstallTask(options) + addInstallTask(options), ]); } diff --git a/packages/workspace/src/schematics/library/library.spec.ts b/packages/workspace/src/schematics/library/library.spec.ts index 9eca974e41084..72c90ae671216 100644 --- a/packages/workspace/src/schematics/library/library.spec.ts +++ b/packages/workspace/src/schematics/library/library.spec.ts @@ -25,9 +25,9 @@ describe('lib', () => { exclude: ['**/node_modules/**', '!libs/my-lib/**'], tsConfig: [ 'libs/my-lib/tsconfig.lib.json', - 'libs/my-lib/tsconfig.spec.json' - ] - } + 'libs/my-lib/tsconfig.spec.json', + ], + }, }); }); @@ -40,8 +40,8 @@ describe('lib', () => { const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-lib': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -49,7 +49,7 @@ describe('lib', () => { const tree = await runSchematic('lib', { name: 'myLib' }, appTree); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ - 'libs/my-lib/src/index.ts' + 'libs/my-lib/src/index.ts', ]); }); @@ -59,9 +59,9 @@ describe('lib', () => { expect(tsconfigJson).toEqual({ extends: '../../tsconfig.json', compilerOptions: { - types: ['node', 'jest'] + types: ['node', 'jest'], }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); }); @@ -98,15 +98,15 @@ describe('lib', () => { { name: 'myLib', directory: 'myDir', - tags: 'one' + tags: 'one', }, appTree ); const nxJson = readJsonInTree(tree, '/nx.json'); expect(nxJson.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] - } + tags: ['one'], + }, }); const tree2 = await runSchematic( @@ -115,18 +115,18 @@ describe('lib', () => { name: 'myLib2', directory: 'myDir', tags: 'one,two', - simpleModuleName: true + simpleModuleName: true, }, tree ); const nxJson2 = readJsonInTree(tree2, '/nx.json'); expect(nxJson2.projects).toEqual({ 'my-dir-my-lib': { - tags: ['one'] + tags: ['one'], }, 'my-dir-my-lib2': { - tags: ['one', 'two'] - } + tags: ['one', 'two'], + }, }); }); @@ -162,9 +162,9 @@ describe('lib', () => { exclude: ['**/node_modules/**', '!libs/my-dir/my-lib/**'], tsConfig: [ 'libs/my-dir/my-lib/tsconfig.lib.json', - 'libs/my-dir/my-lib/tsconfig.spec.json' - ] - } + 'libs/my-dir/my-lib/tsconfig.spec.json', + ], + }, }); }); @@ -175,9 +175,9 @@ describe('lib', () => { appTree ); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); - expect(tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib']).toEqual( - ['libs/my-dir/my-lib/src/index.ts'] - ); + expect( + tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib'] + ).toEqual(['libs/my-dir/my-lib/src/index.ts']); expect( tsconfigJson.compilerOptions.paths['my-dir-my-lib/*'] ).toBeUndefined(); @@ -197,9 +197,9 @@ describe('lib', () => { expect(tsconfigJson).toEqual({ extends: '../../../tsconfig.json', compilerOptions: { - types: ['node', 'jest'] + types: ['node', 'jest'], }, - include: ['**/*.ts'] + include: ['**/*.ts'], }); }); @@ -215,8 +215,8 @@ describe('lib', () => { extends: '../../../tslint.json', rules: {}, linterOptions: { - exclude: ['!**/*'] - } + exclude: ['!**/*'], + }, }); }); }); diff --git a/packages/workspace/src/schematics/library/library.ts b/packages/workspace/src/schematics/library/library.ts index 4e14ecd1ec7b3..4a5293437e04f 100644 --- a/packages/workspace/src/schematics/library/library.ts +++ b/packages/workspace/src/schematics/library/library.ts @@ -9,7 +9,7 @@ import { url, template, move, - noop + noop, } from '@angular-devkit/schematics'; import { join, normalize } from '@angular-devkit/core'; import { Schema } from './schema'; @@ -31,7 +31,7 @@ export interface NormalizedSchema extends Schema { } function addProject(options: NormalizedSchema): Rule { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { const architect: { [key: string]: any } = {}; architect.lint = generateProjectLint( @@ -45,7 +45,7 @@ function addProject(options: NormalizedSchema): Rule { sourceRoot: join(normalize(options.projectRoot), 'src'), projectType: 'library', schematics: {}, - architect + architect, }; return json; }); @@ -55,15 +55,15 @@ function updateTsConfig(options: NormalizedSchema): Rule { return chain([ (host: Tree, context: SchematicContext) => { const nxJson = readJsonInTree(host, 'nx.json'); - return updateJsonInTree('tsconfig.json', json => { + return updateJsonInTree('tsconfig.json', (json) => { const c = json.compilerOptions; delete c.paths[options.name]; c.paths[`@${nxJson.npmScope}/${options.projectDirectory}`] = [ - `libs/${options.projectDirectory}/src/index.ts` + `libs/${options.projectDirectory}/src/index.ts`, ]; return json; })(host, context); - } + }, ]); } @@ -75,9 +75,9 @@ function createFiles(options: NormalizedSchema): Rule { ...names(options.name), tmpl: '', offsetFromRoot: offsetFromRoot(options.projectRoot), - hasUnitTestRunner: options.unitTestRunner !== 'none' + hasUnitTestRunner: options.unitTestRunner !== 'none', }), - move(options.projectRoot) + move(options.projectRoot), ]) ); } @@ -86,7 +86,7 @@ function updateNxJson(options: NormalizedSchema): Rule { return addProjectToNxJsonInTree(options.name, { tags: options.parsedTags }); } -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(schema); return chain([ @@ -101,10 +101,10 @@ export default function(schema: Schema): Rule { setupFile: 'none', supportTsx: true, skipSerializers: true, - testEnvironment: options.testEnvironment + testEnvironment: options.testEnvironment, }) : noop(), - formatFiles(options) + formatFiles(options), ])(host, context); }; } @@ -122,7 +122,7 @@ function normalizeOptions(options: Schema): NormalizedSchema { const projectRoot = `libs/${projectDirectory}`; const parsedTags = options.tags - ? options.tags.split(',').map(s => s.trim()) + ? options.tags.split(',').map((s) => s.trim()) : []; return { @@ -131,6 +131,6 @@ function normalizeOptions(options: Schema): NormalizedSchema { name: projectName, projectRoot, projectDirectory, - parsedTags + parsedTags, }; } diff --git a/packages/workspace/src/schematics/move/lib/check-destination.spec.ts b/packages/workspace/src/schematics/move/lib/check-destination.spec.ts index 6067be673a91d..167cc938e0e73 100644 --- a/packages/workspace/src/schematics/move/lib/check-destination.spec.ts +++ b/packages/workspace/src/schematics/move/lib/check-destination.spec.ts @@ -15,7 +15,7 @@ describe('checkDestination Rule', () => { it('should throw an error if the path is not explicit', async () => { const schema: Schema = { projectName: 'my-lib', - destination: '../apps/not-an-app' + destination: '../apps/not-an-app', }; await expect(callRule(checkDestination(schema), tree)).rejects.toThrow( @@ -28,7 +28,7 @@ describe('checkDestination Rule', () => { const schema: Schema = { projectName: 'my-lib', - destination: 'my-other-lib' + destination: 'my-other-lib', }; await expect(callRule(checkDestination(schema), tree)).rejects.toThrow( @@ -39,7 +39,7 @@ describe('checkDestination Rule', () => { it('should NOT throw an error if the path is available', async () => { const schema: Schema = { projectName: 'my-lib', - destination: 'my-other-lib' + destination: 'my-other-lib', }; await expect( @@ -50,7 +50,7 @@ describe('checkDestination Rule', () => { it('should normalize the destination', async () => { const schema: Schema = { projectName: 'my-lib', - destination: '/my-other-lib//wibble' + destination: '/my-other-lib//wibble', }; await callRule(checkDestination(schema), tree); diff --git a/packages/workspace/src/schematics/move/lib/check-destination.ts b/packages/workspace/src/schematics/move/lib/check-destination.ts index 8f158844234f1..e22184e0ab097 100644 --- a/packages/workspace/src/schematics/move/lib/check-destination.ts +++ b/packages/workspace/src/schematics/move/lib/check-destination.ts @@ -17,7 +17,7 @@ import { getDestination, normalizeSlashes } from './utils'; export function checkDestination(schema: Schema): Rule { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const INVALID_DESTINATION = `Invalid destination: [${schema.destination}]`; if (schema.destination.includes('..')) { diff --git a/packages/workspace/src/schematics/move/lib/move-project.spec.ts b/packages/workspace/src/schematics/move/lib/move-project.spec.ts index be8ff6103698c..6d4f3111e9d8e 100644 --- a/packages/workspace/src/schematics/move/lib/move-project.spec.ts +++ b/packages/workspace/src/schematics/move/lib/move-project.spec.ts @@ -14,7 +14,7 @@ describe('moveProject Rule', () => { it('should copy all files and delete the source folder', async () => { const schema: Schema = { projectName: 'my-lib', - destination: 'my-destination' + destination: 'my-destination', }; // TODO - Currently this test will fail due to diff --git a/packages/workspace/src/schematics/move/lib/move-project.ts b/packages/workspace/src/schematics/move/lib/move-project.ts index 3c0a0b960cce2..d111ddac0b47d 100644 --- a/packages/workspace/src/schematics/move/lib/move-project.ts +++ b/packages/workspace/src/schematics/move/lib/move-project.ts @@ -13,12 +13,12 @@ import { getDestination } from './utils'; export function moveProject(schema: Schema) { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const project = workspace.projects.get(schema.projectName); const destination = getDestination(schema, workspace); const dir = tree.getDir(project.root); - dir.visit(file => { + dir.visit((file) => { const newPath = file.replace(project.root, destination); tree.create(newPath, tree.read(file)); }); diff --git a/packages/workspace/src/schematics/move/lib/update-cypress-json.spec.ts b/packages/workspace/src/schematics/move/lib/update-cypress-json.spec.ts index 6198db849abd9..766d352d4c776 100644 --- a/packages/workspace/src/schematics/move/lib/update-cypress-json.spec.ts +++ b/packages/workspace/src/schematics/move/lib/update-cypress-json.spec.ts @@ -21,7 +21,7 @@ describe('updateCypressJson Rule', () => { const schema: Schema = { projectName: 'my-lib', - destination: 'my-destination' + destination: 'my-destination', }; await expect( @@ -39,7 +39,7 @@ describe('updateCypressJson Rule', () => { video: true, videosFolder: '../../dist/cypress/libs/my-lib/videos', screenshotsFolder: '../../dist/cypress/libs/my-lib/screenshots', - chromeWebSecurity: false + chromeWebSecurity: false, }; tree = await runSchematic('lib', { name: 'my-lib' }, tree); @@ -52,7 +52,7 @@ describe('updateCypressJson Rule', () => { const schema: Schema = { projectName: 'my-lib', - destination: 'my-destination' + destination: 'my-destination', }; tree = (await callRule(updateCypressJson(schema), tree)) as UnitTestTree; @@ -60,7 +60,7 @@ describe('updateCypressJson Rule', () => { expect(readJsonInTree(tree, '/libs/my-destination/cypress.json')).toEqual({ ...cypressJson, videosFolder: '../../dist/cypress/libs/my-destination/videos', - screenshotsFolder: '../../dist/cypress/libs/my-destination/screenshots' + screenshotsFolder: '../../dist/cypress/libs/my-destination/screenshots', }); }); }); diff --git a/packages/workspace/src/schematics/move/lib/update-cypress-json.ts b/packages/workspace/src/schematics/move/lib/update-cypress-json.ts index 801807e82375a..a5756397e7139 100644 --- a/packages/workspace/src/schematics/move/lib/update-cypress-json.ts +++ b/packages/workspace/src/schematics/move/lib/update-cypress-json.ts @@ -22,7 +22,7 @@ interface PartialCypressJson { export function updateCypressJson(schema: Schema): Rule { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const project = workspace.projects.get(schema.projectName); const destination = getDestination(schema, workspace); diff --git a/packages/workspace/src/schematics/move/lib/update-imports.spec.ts b/packages/workspace/src/schematics/move/lib/update-imports.spec.ts index 24ba34f64b28e..60bdb67a6e112 100644 --- a/packages/workspace/src/schematics/move/lib/update-imports.spec.ts +++ b/packages/workspace/src/schematics/move/lib/update-imports.spec.ts @@ -16,7 +16,7 @@ describe('updateImports Rule', () => { schema = { projectName: 'my-source', - destination: 'my-destination' + destination: 'my-destination', }; }); @@ -50,14 +50,14 @@ describe('updateImports Rule', () => { let tsConfig = readJsonInTree(tree, '/tsconfig.json'); expect(tsConfig.compilerOptions.paths).toEqual({ - '@proj/my-source': ['libs/my-source/src/index.ts'] + '@proj/my-source': ['libs/my-source/src/index.ts'], }); tree = (await callRule(updateImports(schema), tree)) as UnitTestTree; tsConfig = readJsonInTree(tree, '/tsconfig.json'); expect(tsConfig.compilerOptions.paths).toEqual({ - '@proj/my-destination': ['libs/my-destination/src/index.ts'] + '@proj/my-destination': ['libs/my-destination/src/index.ts'], }); }); }); diff --git a/packages/workspace/src/schematics/move/lib/update-imports.ts b/packages/workspace/src/schematics/move/lib/update-imports.ts index 7e9c4c8ed1a85..461f8a9f10896 100644 --- a/packages/workspace/src/schematics/move/lib/update-imports.ts +++ b/packages/workspace/src/schematics/move/lib/update-imports.ts @@ -3,7 +3,7 @@ import { getWorkspace, NxJson, readJsonInTree, - serializeJson + serializeJson, } from '@nrwl/workspace'; import { from, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @@ -18,7 +18,7 @@ import { normalizeSlashes } from './utils'; export function updateImports(schema: Schema) { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const nxJson = readJsonInTree(tree, 'nx.json'); const project = workspace.projects.get(schema.projectName); @@ -31,7 +31,7 @@ export function updateImports(schema: Schema) { from: normalizeSlashes( `@${nxJson.npmScope}/${project.root.substr(5)}` ), - to: normalizeSlashes(`@${nxJson.npmScope}/${schema.destination}`) + to: normalizeSlashes(`@${nxJson.npmScope}/${schema.destination}`), }; const replaceProjectRef = new RegExp(projectRef.from, 'g'); @@ -42,7 +42,7 @@ export function updateImports(schema: Schema) { } const projectDir = tree.getDir(definition.root); - projectDir.visit(file => { + projectDir.visit((file) => { const contents = tree.read(file).toString('utf-8'); if (!replaceProjectRef.test(contents)) { return; @@ -58,7 +58,7 @@ export function updateImports(schema: Schema) { const projectRoot = { from: project.root.substr(5), - to: schema.destination + to: schema.destination, }; const tsConfigPath = 'tsconfig.json'; @@ -68,7 +68,7 @@ export function updateImports(schema: Schema) { projectRef.from ] as string[]; - contents.compilerOptions.paths[projectRef.to] = path.map(x => + contents.compilerOptions.paths[projectRef.to] = path.map((x) => x.replace(new RegExp(projectRoot.from, 'g'), projectRoot.to) ); delete contents.compilerOptions.paths[projectRef.from]; diff --git a/packages/workspace/src/schematics/move/lib/update-jest-config.spec.ts b/packages/workspace/src/schematics/move/lib/update-jest-config.spec.ts index 85661c83b6c83..33b5b8b010bff 100644 --- a/packages/workspace/src/schematics/move/lib/update-jest-config.spec.ts +++ b/packages/workspace/src/schematics/move/lib/update-jest-config.spec.ts @@ -18,7 +18,7 @@ describe('updateJestConfig Rule', () => { const schema: Schema = { projectName: 'my-source', - destination: 'my-destination' + destination: 'my-destination', }; await expect( @@ -43,7 +43,7 @@ describe('updateJestConfig Rule', () => { const schema: Schema = { projectName: 'my-source', - destination: 'my-destination' + destination: 'my-destination', }; tree = (await callRule(updateJestConfig(schema), tree)) as UnitTestTree; diff --git a/packages/workspace/src/schematics/move/lib/update-jest-config.ts b/packages/workspace/src/schematics/move/lib/update-jest-config.ts index 9f2daf2397e36..363f00d5f920e 100644 --- a/packages/workspace/src/schematics/move/lib/update-jest-config.ts +++ b/packages/workspace/src/schematics/move/lib/update-jest-config.ts @@ -17,7 +17,7 @@ import { getDestination, getNewProjectName } from './utils'; export function updateJestConfig(schema: Schema): Rule { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const project = workspace.projects.get(schema.projectName); const destination = getDestination(schema, workspace); const newProjectName = getNewProjectName(schema.destination); diff --git a/packages/workspace/src/schematics/move/lib/update-nx-json.spec.ts b/packages/workspace/src/schematics/move/lib/update-nx-json.spec.ts index 809f5de172abc..716e2db06669f 100644 --- a/packages/workspace/src/schematics/move/lib/update-nx-json.spec.ts +++ b/packages/workspace/src/schematics/move/lib/update-nx-json.spec.ts @@ -19,7 +19,7 @@ describe('updateNxJson Rule', () => { const schema: Schema = { projectName: 'my-source', - destination: 'my-destination' + destination: 'my-destination', }; tree = (await callRule(updateNxJson(schema), tree)) as UnitTestTree; @@ -28,7 +28,7 @@ describe('updateNxJson Rule', () => { expect(nxJson.projects['my-source']).toBeUndefined(); expect(nxJson.projects['my-destination']).toEqual({ - tags: [] + tags: [], }); }); }); diff --git a/packages/workspace/src/schematics/move/lib/update-nx-json.ts b/packages/workspace/src/schematics/move/lib/update-nx-json.ts index a4affdf0bd5c7..e47bd9ad709d8 100644 --- a/packages/workspace/src/schematics/move/lib/update-nx-json.ts +++ b/packages/workspace/src/schematics/move/lib/update-nx-json.ts @@ -8,9 +8,9 @@ import { getNewProjectName } from './utils'; * @param schema The options provided to the schematic */ export function updateNxJson(schema: Schema) { - return updateJsonInTree('nx.json', json => { + return updateJsonInTree('nx.json', (json) => { json.projects[getNewProjectName(schema.destination)] = { - ...json.projects[schema.projectName] + ...json.projects[schema.projectName], }; delete json.projects[schema.projectName]; return json; diff --git a/packages/workspace/src/schematics/move/lib/update-project-root-files.spec.ts b/packages/workspace/src/schematics/move/lib/update-project-root-files.spec.ts index abfa0df28b259..6ca9ffd6c55dd 100644 --- a/packages/workspace/src/schematics/move/lib/update-project-root-files.spec.ts +++ b/packages/workspace/src/schematics/move/lib/update-project-root-files.spec.ts @@ -30,7 +30,7 @@ describe('updateProjectRootFiles Rule', () => { const schema: Schema = { projectName: 'my-source', - destination: 'subfolder/my-destination' + destination: 'subfolder/my-destination', }; tree = (await callRule( diff --git a/packages/workspace/src/schematics/move/lib/update-project-root-files.ts b/packages/workspace/src/schematics/move/lib/update-project-root-files.ts index d6ff8ce19c19c..77bb45c0284c3 100644 --- a/packages/workspace/src/schematics/move/lib/update-project-root-files.ts +++ b/packages/workspace/src/schematics/move/lib/update-project-root-files.ts @@ -18,7 +18,7 @@ import { getDestination } from './utils'; export function updateProjectRootFiles(schema: Schema): Rule { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const project = workspace.projects.get(schema.projectName); const destination = getDestination(schema, workspace); @@ -41,7 +41,7 @@ export function updateProjectRootFiles(schema: Schema): Rule { const isRootFile = new RegExp(`${schema.destination}/[^/]+.js*`); const projectDir = tree.getDir(destination); - projectDir.visit(file => { + projectDir.visit((file) => { if (!isRootFile.test(file)) { return; } diff --git a/packages/workspace/src/schematics/move/lib/update-workspace.spec.ts b/packages/workspace/src/schematics/move/lib/update-workspace.spec.ts index 11e7460251332..146be305fafe1 100644 --- a/packages/workspace/src/schematics/move/lib/update-workspace.spec.ts +++ b/packages/workspace/src/schematics/move/lib/update-workspace.spec.ts @@ -32,10 +32,10 @@ describe('updateWorkspace Rule', () => { aot: false, assets: [ 'apps/my-source/src/favicon.ico', - 'apps/my-source/src/assets' + 'apps/my-source/src/assets', ], styles: ['apps/my-source/src/styles.scss'], - scripts: [] + scripts: [], }, configurations: { production: { @@ -43,8 +43,8 @@ describe('updateWorkspace Rule', () => { { replace: 'apps/my-source/src/environments/environment.ts', with: - 'apps/my-source/src/environments/environment.prod.ts' - } + 'apps/my-source/src/environments/environment.prod.ts', + }, ], optimization: true, outputHashing: 'all', @@ -59,53 +59,53 @@ describe('updateWorkspace Rule', () => { { type: 'initial', maximumWarning: '2mb', - maximumError: '5mb' + maximumError: '5mb', }, { type: 'anyComponentStyle', maximumWarning: '6kb', - maximumError: '10kb' - } - ] - } - } + maximumError: '10kb', + }, + ], + }, + }, }, serve: { builder: '@angular-devkit/build-angular:dev-server', options: { - browserTarget: 'my-source:build' + browserTarget: 'my-source:build', }, configurations: { production: { - browserTarget: 'my-source:build:production' - } - } + browserTarget: 'my-source:build:production', + }, + }, }, 'extract-i18n': { builder: '@angular-devkit/build-angular:extract-i18n', options: { - browserTarget: 'my-source:build' - } + browserTarget: 'my-source:build', + }, }, lint: { builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: [ 'apps/my-source/tsconfig.app.json', - 'apps/my-source/tsconfig.spec.json' + 'apps/my-source/tsconfig.spec.json', ], - exclude: ['**/node_modules/**', '!apps/my-source/**'] - } + exclude: ['**/node_modules/**', '!apps/my-source/**'], + }, }, test: { builder: '@nrwl/jest:jest', options: { jestConfig: 'apps/my-source/jest.config.js', tsConfig: 'apps/my-source/tsconfig.spec.json', - setupFile: 'apps/my-source/src/test-setup.ts' - } - } - } + setupFile: 'apps/my-source/src/test-setup.ts', + }, + }, + }, }, 'my-source-e2e': { root: 'apps/my-source-e2e', @@ -117,25 +117,25 @@ describe('updateWorkspace Rule', () => { options: { cypressConfig: 'apps/my-source-e2e/cypress.json', tsConfig: 'apps/my-source-e2e/tsconfig.e2e.json', - devServerTarget: 'my-source:serve' + devServerTarget: 'my-source:serve', }, configurations: { production: { - devServerTarget: 'my-source:serve:production' - } - } + devServerTarget: 'my-source:serve:production', + }, + }, }, lint: { builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: ['apps/my-source-e2e/tsconfig.e2e.json'], - exclude: ['**/node_modules/**', '!apps/my-source-e2e/**'] - } - } - } - } + exclude: ['**/node_modules/**', '!apps/my-source-e2e/**'], + }, + }, + }, + }, }, - defaultProject: 'my-source' + defaultProject: 'my-source', }; tree.overwrite('workspace.json', JSON.stringify(workspace)); @@ -144,7 +144,7 @@ describe('updateWorkspace Rule', () => { it('should rename the project', async () => { const schema: Schema = { projectName: 'my-source', - destination: 'subfolder/my-destination' + destination: 'subfolder/my-destination', }; tree = (await callRule(updateWorkspace(schema), tree)) as UnitTestTree; @@ -158,7 +158,7 @@ describe('updateWorkspace Rule', () => { it('should update the default project', async () => { const schema: Schema = { projectName: 'my-source', - destination: 'subfolder/my-destination' + destination: 'subfolder/my-destination', }; tree = (await callRule(updateWorkspace(schema), tree)) as UnitTestTree; @@ -171,7 +171,7 @@ describe('updateWorkspace Rule', () => { it('should update paths in only the intended project', async () => { const schema: Schema = { projectName: 'my-source', - destination: 'subfolder/my-destination' + destination: 'subfolder/my-destination', }; tree = (await callRule(updateWorkspace(schema), tree)) as UnitTestTree; @@ -191,7 +191,7 @@ describe('updateWorkspace Rule', () => { it('should update build targets', async () => { const schema: Schema = { projectName: 'my-source', - destination: 'subfolder/my-destination' + destination: 'subfolder/my-destination', }; tree = (await callRule(updateWorkspace(schema), tree)) as UnitTestTree; diff --git a/packages/workspace/src/schematics/move/lib/update-workspace.ts b/packages/workspace/src/schematics/move/lib/update-workspace.ts index cf36cec947f79..52ba38fa99c83 100644 --- a/packages/workspace/src/schematics/move/lib/update-workspace.ts +++ b/packages/workspace/src/schematics/move/lib/update-workspace.ts @@ -12,7 +12,7 @@ import { getDestination, getNewProjectName } from './utils'; * @param schema The options provided to the schematic */ export function updateWorkspace(schema: Schema) { - return updateWorkspaceInTree(workspace => { + return updateWorkspaceInTree((workspace) => { const project = workspace.projects[schema.projectName]; const newProjectName = getNewProjectName(schema.destination); diff --git a/packages/workspace/src/schematics/move/lib/utils.ts b/packages/workspace/src/schematics/move/lib/utils.ts index b8b5e31ceb9f3..79e77db398778 100644 --- a/packages/workspace/src/schematics/move/lib/utils.ts +++ b/packages/workspace/src/schematics/move/lib/utils.ts @@ -27,10 +27,7 @@ export function getDestination( if (projectType === 'application') { rootFolder = 'apps'; } - return path - .join(rootFolder, schema.destination) - .split(path.sep) - .join('/'); + return path.join(rootFolder, schema.destination).split(path.sep).join('/'); } /** @@ -50,6 +47,6 @@ export function getNewProjectName(path: string): string { export function normalizeSlashes(input: string): string { return input .split('/') - .filter(x => !!x) + .filter((x) => !!x) .join('/'); } diff --git a/packages/workspace/src/schematics/move/move.ts b/packages/workspace/src/schematics/move/move.ts index bfe5f54ff412d..7225df1cce0be 100644 --- a/packages/workspace/src/schematics/move/move.ts +++ b/packages/workspace/src/schematics/move/move.ts @@ -10,7 +10,7 @@ import { updateProjectRootFiles } from './lib/update-project-root-files'; import { updateWorkspace } from './lib/update-workspace'; import { Schema } from './schema'; -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return chain([ checkProjectExists(schema), checkDestination(schema), @@ -20,6 +20,6 @@ export default function(schema: Schema): Rule { updateJestConfig(schema), updateNxJson(schema), updateImports(schema), - updateWorkspace(schema) // Have to do this last because all previous rules need the information in here + updateWorkspace(schema), // Have to do this last because all previous rules need the information in here ]); } diff --git a/packages/workspace/src/schematics/ng-new/ng-new.ts b/packages/workspace/src/schematics/ng-new/ng-new.ts index b74025ada44cc..3c622d8aeae2c 100644 --- a/packages/workspace/src/schematics/ng-new/ng-new.ts +++ b/packages/workspace/src/schematics/ng-new/ng-new.ts @@ -1,6 +1,6 @@ import { Rule } from '@angular-devkit/schematics'; import { sharedNew, Schema } from '../shared-new/shared-new'; -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { return sharedNew('angular', options); } diff --git a/packages/workspace/src/schematics/preset/preset.ts b/packages/workspace/src/schematics/preset/preset.ts index c50c8f493b53c..4a6d31a2ba174 100644 --- a/packages/workspace/src/schematics/preset/preset.ts +++ b/packages/workspace/src/schematics/preset/preset.ts @@ -5,7 +5,7 @@ import { Rule, schematic, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { Schema } from './schema'; @@ -14,7 +14,7 @@ import { addGlobal, insert, insertImport, - updateWorkspaceInTree + updateWorkspaceInTree, } from '../../utils/ast-utils'; import { formatFiles } from '../../utils/rules/format-files'; @@ -22,7 +22,7 @@ import { formatFiles } from '../../utils/rules/format-files'; import * as ts from 'typescript'; import { toFileName } from '../../utils/name-utils'; -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { options = normalizeOptions(options); return (host: Tree, context: SchematicContext) => { return chain([createPreset(options), formatFiles()])(host, context); @@ -38,72 +38,72 @@ function createPreset(options: Schema): Rule { return chain([ externalSchematic('@nrwl/angular', 'application', { name: options.name, - style: options.style + style: options.style, }), - setDefaultCollection('@nrwl/angular') + setDefaultCollection('@nrwl/angular'), ]); } else if (options.preset === 'react') { return chain([ externalSchematic('@nrwl/react', 'application', { name: options.name, style: options.style, - linter + linter, }), - setDefaultCollection('@nrwl/react') + setDefaultCollection('@nrwl/react'), ]); } else if (options.preset === 'next') { return chain([ externalSchematic('@nrwl/next', 'application', { name: options.name, style: options.style, - linter + linter, }), - setDefaultCollection('@nrwl/next') + setDefaultCollection('@nrwl/next'), ]); } else if (options.preset === 'web-components') { return chain([ externalSchematic('@nrwl/web', 'application', { name: options.name, style: options.style, - linter + linter, }), addDepsToPackageJson( {}, { - '@webcomponents/custom-elements': '1.3.2' + '@webcomponents/custom-elements': '1.3.2', } ), addPolyfills(`apps/${toFileName(options.name)}/src/polyfills.ts`, [ '@webcomponents/custom-elements/custom-elements.min', - '@webcomponents/custom-elements/src/native-shim' + '@webcomponents/custom-elements/src/native-shim', ]), - setDefaultCollection('@nrwl/web') + setDefaultCollection('@nrwl/web'), ]); } else if (options.preset === 'angular-nest') { return chain([ externalSchematic('@nrwl/angular', 'application', { name: options.name, - style: options.style + style: options.style, }), externalSchematic('@nrwl/nest', 'application', { name: 'api', - frontendProject: options.name + frontendProject: options.name, }), schematic('library', { name: 'api-interfaces' }, { interactive: false }), setDefaultCollection('@nrwl/angular'), - connectAngularAndNest(options) + connectAngularAndNest(options), ]); } else if (options.preset === 'react-express') { return chain([ externalSchematic('@nrwl/react', 'application', { name: options.name, style: options.style, - linter + linter, }), externalSchematic('@nrwl/express', 'application', { name: 'api', frontendProject: options.name, - linter + linter, }), schematic( 'library', @@ -111,7 +111,7 @@ function createPreset(options: Schema): Rule { { interactive: false } ), setDefaultCollection('@nrwl/react'), - connectReactAndExpress(options) + connectReactAndExpress(options), ]); } else { throw new Error(`Invalid preset ${options.preset}`); @@ -145,7 +145,7 @@ function connectAngularAndNest(options: Schema) { moduleFile, `@angular/common/http`, `HttpClientModule` - ) + ), ]); const scope = options.npmScope; @@ -331,7 +331,7 @@ server.on('error', console.error); } function setDefaultCollection(defaultCollection: string) { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { if (!json.cli) { json.cli = {}; } @@ -354,8 +354,8 @@ function addPolyfills(polyfillsPath: string, polyfills: string[]): Rule { ...addGlobal( polyfillsSourceFile, polyfillsPath, - `\n${polyfills.map(im => `import '${im}';`).join('\n')}\n` - ) + `\n${polyfills.map((im) => `import '${im}';`).join('\n')}\n` + ), ]); }; } diff --git a/packages/workspace/src/schematics/remove/lib/check-dependencies.spec.ts b/packages/workspace/src/schematics/remove/lib/check-dependencies.spec.ts index 2fcab7ef8ca7d..87bde5f483cb5 100644 --- a/packages/workspace/src/schematics/remove/lib/check-dependencies.spec.ts +++ b/packages/workspace/src/schematics/remove/lib/check-dependencies.spec.ts @@ -17,7 +17,7 @@ describe('updateImports Rule', () => { schema = { projectName: 'my-source', skipFormat: false, - forceRemove: false + forceRemove: false, }; tree = await runSchematic('lib', { name: 'my-dependent' }, tree); @@ -61,7 +61,7 @@ describe('updateImports Rule', () => { describe('implicit dependencies', () => { beforeEach(async () => { tree = (await callRule( - updateJsonInTree('nx.json', json => { + updateJsonInTree('nx.json', (json) => { json.projects['my-dependent'].implicitDependencies = ['my-source']; return json; }), diff --git a/packages/workspace/src/schematics/remove/lib/check-dependencies.ts b/packages/workspace/src/schematics/remove/lib/check-dependencies.ts index 2edf0a924c836..81db0d66e8700 100644 --- a/packages/workspace/src/schematics/remove/lib/check-dependencies.ts +++ b/packages/workspace/src/schematics/remove/lib/check-dependencies.ts @@ -2,7 +2,7 @@ import { Rule, Tree } from '@angular-devkit/schematics'; import { FileData } from '@nrwl/workspace/src/core/file-utils'; import { readNxJsonInTree, - readWorkspace + readWorkspace, } from '@nrwl/workspace/src/utils/ast-utils'; import { getWorkspacePath } from '@nrwl/workspace/src/utils/cli-config-utils'; import * as path from 'path'; @@ -10,7 +10,7 @@ import { createProjectGraph, onlyWorkspaceProjects, ProjectGraph, - reverse + reverse, } from '../../../core/project-graph'; import { Schema } from '../schema'; @@ -30,11 +30,11 @@ export function checkDependencies(schema: Schema): Rule { const files: FileData[] = []; const mtime = Date.now(); //can't get mtime data from the tree :( const workspaceDir = path.dirname(getWorkspacePath(tree)); - tree.visit(file => { + tree.visit((file) => { files.push({ file: path.relative(workspaceDir, file), ext: path.extname(file), - mtime + mtime, }); }); @@ -42,7 +42,7 @@ export function checkDependencies(schema: Schema): Rule { readWorkspace(tree), readNxJsonInTree(tree), files, - file => tree.read(file).toString('utf-8'), + (file) => tree.read(file).toString('utf-8'), false, false ); @@ -59,7 +59,7 @@ export function checkDependencies(schema: Schema): Rule { `${ schema.projectName } is still depended on by the following projects:\n${deps - .map(x => x.target) + .map((x) => x.target) .join('\n')}` ); }; diff --git a/packages/workspace/src/schematics/remove/lib/check-targets.spec.ts b/packages/workspace/src/schematics/remove/lib/check-targets.spec.ts index bcd493efd8c99..8f51a3c51040a 100644 --- a/packages/workspace/src/schematics/remove/lib/check-targets.spec.ts +++ b/packages/workspace/src/schematics/remove/lib/check-targets.spec.ts @@ -17,11 +17,11 @@ describe('checkTargets Rule', () => { schema = { projectName: 'ng-app', skipFormat: false, - forceRemove: false + forceRemove: false, }; tree = (await callRule( - updateWorkspaceInTree(workspace => { + updateWorkspaceInTree((workspace) => { return { version: 1, projects: { @@ -34,9 +34,9 @@ describe('checkTargets Rule', () => { architect: { build: { builder: '@angular-devkit/build-angular:browser', - options: {} - } - } + options: {}, + }, + }, }, 'ng-app-e2e': { root: 'apps/ng-app-e2e', @@ -48,12 +48,12 @@ describe('checkTargets Rule', () => { options: { cypressConfig: 'apps/ng-app-e2e/cypress.json', tsConfig: 'apps/ng-app-e2e/tsconfig.e2e.json', - devServerTarget: 'ng-app:serve' - } - } - } - } - } + devServerTarget: 'ng-app:serve', + }, + }, + }, + }, + }, }; }), tree diff --git a/packages/workspace/src/schematics/remove/lib/check-targets.ts b/packages/workspace/src/schematics/remove/lib/check-targets.ts index 9d79f475f70e7..9c98ea93be5b7 100644 --- a/packages/workspace/src/schematics/remove/lib/check-targets.ts +++ b/packages/workspace/src/schematics/remove/lib/check-targets.ts @@ -14,7 +14,7 @@ export function checkTargets(schema: Schema) { return (tree: Tree) => tree; } - return updateWorkspaceInTree(workspace => { + return updateWorkspaceInTree((workspace) => { const findTarget = new RegExp(`${schema.projectName}:`); const usedIn = []; diff --git a/packages/workspace/src/schematics/remove/lib/remove-project.spec.ts b/packages/workspace/src/schematics/remove/lib/remove-project.spec.ts index cad61fa1fd030..d856534f3d9a7 100644 --- a/packages/workspace/src/schematics/remove/lib/remove-project.spec.ts +++ b/packages/workspace/src/schematics/remove/lib/remove-project.spec.ts @@ -15,7 +15,7 @@ describe('moveProject Rule', () => { schema = { projectName: 'my-lib', skipFormat: false, - forceRemove: false + forceRemove: false, }; }); diff --git a/packages/workspace/src/schematics/remove/lib/remove-project.ts b/packages/workspace/src/schematics/remove/lib/remove-project.ts index 47735a576708b..965789b9bc317 100644 --- a/packages/workspace/src/schematics/remove/lib/remove-project.ts +++ b/packages/workspace/src/schematics/remove/lib/remove-project.ts @@ -12,7 +12,7 @@ import { Schema } from '../schema'; export function removeProject(schema: Schema) { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const project = workspace.projects.get(schema.projectName); tree.delete(project.root); return tree; diff --git a/packages/workspace/src/schematics/remove/lib/update-nx-json.spec.ts b/packages/workspace/src/schematics/remove/lib/update-nx-json.spec.ts index 82d81a17cd2b5..e12302837fabb 100644 --- a/packages/workspace/src/schematics/remove/lib/update-nx-json.spec.ts +++ b/packages/workspace/src/schematics/remove/lib/update-nx-json.spec.ts @@ -23,7 +23,7 @@ describe('updateNxJson Rule', () => { const schema: Schema = { projectName: 'my-lib', skipFormat: false, - forceRemove: false + forceRemove: false, }; tree = (await callRule(updateNxJson(schema), tree)) as UnitTestTree; diff --git a/packages/workspace/src/schematics/remove/lib/update-nx-json.ts b/packages/workspace/src/schematics/remove/lib/update-nx-json.ts index 7ad7f5f061e04..bdb565f34b0cf 100644 --- a/packages/workspace/src/schematics/remove/lib/update-nx-json.ts +++ b/packages/workspace/src/schematics/remove/lib/update-nx-json.ts @@ -7,7 +7,7 @@ import { Schema } from '../schema'; * @param schema The options provided to the schematic */ export function updateNxJson(schema: Schema) { - return updateJsonInTree('nx.json', json => { + return updateJsonInTree('nx.json', (json) => { delete json.projects[schema.projectName]; return json; }); diff --git a/packages/workspace/src/schematics/remove/lib/update-tsconfig.spec.ts b/packages/workspace/src/schematics/remove/lib/update-tsconfig.spec.ts index 2ceee2770a281..a96916293a704 100644 --- a/packages/workspace/src/schematics/remove/lib/update-tsconfig.spec.ts +++ b/packages/workspace/src/schematics/remove/lib/update-tsconfig.spec.ts @@ -17,7 +17,7 @@ describe('updateTsconfig Rule', () => { schema = { projectName: 'my-lib', skipFormat: false, - forceRemove: false + forceRemove: false, }; }); @@ -26,7 +26,7 @@ describe('updateTsconfig Rule', () => { let tsConfig = readJsonInTree(tree, '/tsconfig.json'); expect(tsConfig.compilerOptions.paths).toEqual({ - '@proj/my-lib': ['libs/my-lib/src/index.ts'] + '@proj/my-lib': ['libs/my-lib/src/index.ts'], }); tree = (await callRule(updateTsconfig(schema), tree)) as UnitTestTree; diff --git a/packages/workspace/src/schematics/remove/lib/update-tsconfig.ts b/packages/workspace/src/schematics/remove/lib/update-tsconfig.ts index facebde5a0833..dcfa74d631bf6 100644 --- a/packages/workspace/src/schematics/remove/lib/update-tsconfig.ts +++ b/packages/workspace/src/schematics/remove/lib/update-tsconfig.ts @@ -3,7 +3,7 @@ import { getWorkspace, NxJson, readJsonInTree, - serializeJson + serializeJson, } from '@nrwl/workspace'; import { from, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @@ -17,7 +17,7 @@ import { Schema } from '../schema'; export function updateTsconfig(schema: Schema) { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { const nxJson = readJsonInTree(tree, 'nx.json'); const project = workspace.projects.get(schema.projectName); diff --git a/packages/workspace/src/schematics/remove/lib/update-workspace.spec.ts b/packages/workspace/src/schematics/remove/lib/update-workspace.spec.ts index 7b5c4fa212a39..f60c69002f03d 100644 --- a/packages/workspace/src/schematics/remove/lib/update-workspace.spec.ts +++ b/packages/workspace/src/schematics/remove/lib/update-workspace.spec.ts @@ -17,11 +17,11 @@ describe('updateWorkspace Rule', () => { schema = { projectName: 'ng-app', skipFormat: false, - forceRemove: false + forceRemove: false, }; tree = (await callRule( - updateWorkspaceInTree(workspace => { + updateWorkspaceInTree((workspace) => { return { version: 1, projects: { @@ -34,9 +34,9 @@ describe('updateWorkspace Rule', () => { architect: { build: { builder: '@angular-devkit/build-angular:browser', - options: {} - } - } + options: {}, + }, + }, }, 'ng-app-e2e': { root: 'apps/ng-app-e2e', @@ -48,12 +48,12 @@ describe('updateWorkspace Rule', () => { options: { cypressConfig: 'apps/ng-app-e2e/cypress.json', tsConfig: 'apps/ng-app-e2e/tsconfig.e2e.json', - devServerTarget: 'ng-app:serve' - } - } - } - } - } + devServerTarget: 'ng-app:serve', + }, + }, + }, + }, + }, }; }), tree diff --git a/packages/workspace/src/schematics/remove/lib/update-workspace.ts b/packages/workspace/src/schematics/remove/lib/update-workspace.ts index 78a8ca2596ed4..fb8edc4d00128 100644 --- a/packages/workspace/src/schematics/remove/lib/update-workspace.ts +++ b/packages/workspace/src/schematics/remove/lib/update-workspace.ts @@ -7,7 +7,7 @@ import { Schema } from '../schema'; * @param schema The options provided to the schematic */ export function updateWorkspace(schema: Schema) { - return updateWorkspaceInTree(workspace => { + return updateWorkspaceInTree((workspace) => { delete workspace.projects[schema.projectName]; return workspace; }); diff --git a/packages/workspace/src/schematics/remove/remove.ts b/packages/workspace/src/schematics/remove/remove.ts index a45c4c5a75e63..b409917c358e1 100644 --- a/packages/workspace/src/schematics/remove/remove.ts +++ b/packages/workspace/src/schematics/remove/remove.ts @@ -9,7 +9,7 @@ import { updateTsconfig } from './lib/update-tsconfig'; import { updateWorkspace } from './lib/update-workspace'; import { Schema } from './schema'; -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { return chain([ checkProjectExists(schema), checkDependencies(schema), @@ -18,6 +18,6 @@ export default function(schema: Schema): Rule { updateNxJson(schema), updateTsconfig(schema), updateWorkspace(schema), - formatFiles(schema) + formatFiles(schema), ]); } diff --git a/packages/workspace/src/schematics/shared-new/shared-new.ts b/packages/workspace/src/schematics/shared-new/shared-new.ts index 55465288e4b67..33e69b777a00a 100644 --- a/packages/workspace/src/schematics/shared-new/shared-new.ts +++ b/packages/workspace/src/schematics/shared-new/shared-new.ts @@ -5,16 +5,16 @@ import { Rule, schematic, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; import { NodePackageInstallTask, - RepositoryInitializerTask + RepositoryInitializerTask, } from '@angular-devkit/schematics/tasks'; import { addDepsToPackageJson, - updateWorkspaceInTree + updateWorkspaceInTree, } from '../../utils/ast-utils'; import { toFileName } from '../../utils/name-utils'; @@ -50,7 +50,7 @@ export interface Schema { class RunPresetTask { toConfiguration() { return { - name: 'RunPreset' + name: 'RunPreset', }; } } @@ -58,7 +58,7 @@ class RunPresetTask { function createPresetTaskExecutor(cli: string, opts: Schema) { const cliCommand = cli === 'angular' ? 'ng' : 'nx'; const parsedArgs = yargsParser(process.argv, { - boolean: ['interactive'] + boolean: ['interactive'], }); return { @@ -68,7 +68,7 @@ function createPresetTaskExecutor(cli: string, opts: Schema) { const spawnOptions = { stdio: [process.stdin, process.stdout, process.stderr], shell: true, - cwd: path.join(process.cwd(), opts.directory) + cwd: path.join(process.cwd(), opts.directory), }; const executable = platform() === 'win32' @@ -84,9 +84,9 @@ function createPresetTaskExecutor(cli: string, opts: Schema) { : `--npmScope=${opts.name}`, opts.preset ? `--preset=${opts.preset}` : null, `--cli=${cliCommand}`, - parsedArgs.interactive ? '--interactive=true' : '--interactive=false' - ].filter(e => !!e); - return new Observable(obs => { + parsedArgs.interactive ? '--interactive=true' : '--interactive=false', + ].filter((e) => !!e); + return new Observable((obs) => { spawn(executable, args, spawnOptions).on('close', (code: number) => { if (code === 0) { obs.next(); @@ -98,7 +98,7 @@ function createPresetTaskExecutor(cli: string, opts: Schema) { }); }); }); - } + }, }; } @@ -119,7 +119,7 @@ export function sharedNew(cli: string, options: Schema): Rule { addDependencies(options), move('/', options.directory), addTasks(options), - formatFiles() + formatFiles(), ])(Tree.empty(), context); }; } @@ -131,14 +131,14 @@ function addDependencies(options: Schema) { return addDepsToPackageJson( {}, { - '@nrwl/web': nxVersion + '@nrwl/web': nxVersion, }, false ); } else if (options.preset === 'angular') { return addDepsToPackageJson( { - '@nrwl/angular': nxVersion + '@nrwl/angular': nxVersion, }, {}, false @@ -146,10 +146,10 @@ function addDependencies(options: Schema) { } else if (options.preset === 'angular-nest') { return addDepsToPackageJson( { - '@nrwl/angular': nxVersion + '@nrwl/angular': nxVersion, }, { - '@nrwl/nest': nxVersion + '@nrwl/nest': nxVersion, }, false ); @@ -157,7 +157,7 @@ function addDependencies(options: Schema) { return addDepsToPackageJson( {}, { - '@nrwl/react': nxVersion + '@nrwl/react': nxVersion, }, false ); @@ -166,7 +166,7 @@ function addDependencies(options: Schema) { {}, { '@nrwl/react': nxVersion, - '@nrwl/express': nxVersion + '@nrwl/express': nxVersion, }, false ); @@ -174,7 +174,7 @@ function addDependencies(options: Schema) { return addDepsToPackageJson( {}, { - '@nrwl/next': nxVersion + '@nrwl/next': nxVersion, }, false ); @@ -194,7 +194,7 @@ function addTasks(options: Schema) { } if (options.preset !== 'empty') { const createPresetTask = context.addTask(new RunPresetTask(), [ - packageTask + packageTask, ]); presetInstallTask = context.addTask( @@ -231,7 +231,7 @@ function normalizeOptions(options: Schema): Schema { } function setDefaultLinter(linter: string) { - return updateWorkspaceInTree(json => { + return updateWorkspaceInTree((json) => { if (!json.schematics) { json.schematics = {}; } @@ -240,24 +240,24 @@ function setDefaultLinter(linter: string) { json.schematics['@nrwl/react'] = { application: { linter }, library: { linter }, - 'storybook-configuration': { linter } + 'storybook-configuration': { linter }, }; json.schematics['@nrwl/next'] = { - application: { linter } + application: { linter }, }; json.schematics['@nrwl/web'] = { application: { linter } }; json.schematics['@nrwl/node'] = { application: { linter }, - library: { linter } + library: { linter }, }; json.schematics['@nrwl/nx-plugin'] = { - plugin: { linter } + plugin: { linter }, }; json.schematics['@nrwl/nest'] = { application: { linter } }; json.schematics['@nrwl/express'] = { application: { linter }, - library: { linter } + library: { linter }, }; return json; }); diff --git a/packages/workspace/src/schematics/tao-new/tao-new.ts b/packages/workspace/src/schematics/tao-new/tao-new.ts index a35eb91528512..37e31f67462d5 100644 --- a/packages/workspace/src/schematics/tao-new/tao-new.ts +++ b/packages/workspace/src/schematics/tao-new/tao-new.ts @@ -1,6 +1,6 @@ import { Rule } from '@angular-devkit/schematics'; import { sharedNew, Schema } from '../shared-new/shared-new'; -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { return sharedNew('nx', options); } diff --git a/packages/workspace/src/schematics/workspace-schematic/workspace-schematic.ts b/packages/workspace/src/schematics/workspace-schematic/workspace-schematic.ts index e60a2dab8fc76..9f904cff4f56d 100644 --- a/packages/workspace/src/schematics/workspace-schematic/workspace-schematic.ts +++ b/packages/workspace/src/schematics/workspace-schematic/workspace-schematic.ts @@ -6,25 +6,25 @@ import { Rule, template, url, - move + move, } from '@angular-devkit/schematics'; import { Schema } from './schema'; import { formatFiles } from '@nrwl/workspace'; import { toFileName } from '@nrwl/workspace'; -export default function(schema: Schema): Rule { +export default function (schema: Schema): Rule { const options = normalizeOptions(schema); const templateSource = apply(url('./files'), [ template({ dot: '.', tmpl: '', - ...(options as any) + ...(options as any), }), - move('tools/schematics') + move('tools/schematics'), ]); return chain([ branchAndMerge(chain([mergeWith(templateSource)])), - formatFiles(options) + formatFiles(options), ]); } diff --git a/packages/workspace/src/schematics/workspace/workspace.spec.ts b/packages/workspace/src/schematics/workspace/workspace.spec.ts index 272345c4528ff..62d11c685f1c4 100644 --- a/packages/workspace/src/schematics/workspace/workspace.spec.ts +++ b/packages/workspace/src/schematics/workspace/workspace.spec.ts @@ -26,21 +26,21 @@ describe('workspace', () => { 'workspace.json': '*', 'package.json': { dependencies: '*', - devDependencies: '*' + devDependencies: '*', }, 'tsconfig.json': '*', 'tslint.json': '*', - 'nx.json': '*' + 'nx.json': '*', }, tasksRunnerOptions: { default: { runner: '@nrwl/workspace/tasks-runners/default', options: { - cacheableOperations: ['build', 'lint', 'test', 'e2e'] - } - } + cacheableOperations: ['build', 'lint', 'test', 'e2e'], + }, + }, }, - projects: {} + projects: {}, }); }); @@ -53,7 +53,7 @@ describe('workspace', () => { expect(recommendations).toEqual([ 'ms-vscode.vscode-typescript-tslint-plugin', - 'esbenp.prettier-vscode' + 'esbenp.prettier-vscode', ]); }); @@ -72,7 +72,7 @@ describe('workspace', () => { 'nrwl.angular-console', 'angular.ng-template', 'ms-vscode.vscode-typescript-tslint-plugin', - 'esbenp.prettier-vscode' + 'esbenp.prettier-vscode', ]); }); }); diff --git a/packages/workspace/src/schematics/workspace/workspace.ts b/packages/workspace/src/schematics/workspace/workspace.ts index c2630c63a899b..d89f9adbdadda 100644 --- a/packages/workspace/src/schematics/workspace/workspace.ts +++ b/packages/workspace/src/schematics/workspace/workspace.ts @@ -7,7 +7,7 @@ import { SchematicContext, template, Tree, - url + url, } from '@angular-devkit/schematics'; import { Schema } from './schema'; import { strings } from '@angular-devkit/core'; @@ -16,14 +16,14 @@ import { prettierVersion, typescriptVersion, eslintVersion, - nxVersion + nxVersion, } from '../../utils/versions'; export const DEFAULT_NRWL_PRETTIER_CONFIG = { - singleQuote: true + singleQuote: true, }; -export default function(options: Schema): Rule { +export default function (options: Schema): Rule { if (!options.name) { throw new Error(`Invalid options, "name" is required.`); } @@ -50,8 +50,8 @@ export default function(options: Schema): Rule { DEFAULT_NRWL_PRETTIER_CONFIG, null, 2 - ) - }) + ), + }), ]); return chain([branchAndMerge(chain([mergeWith(templateSource)]))])( host, diff --git a/packages/workspace/src/tasks-runner/cache.ts b/packages/workspace/src/tasks-runner/cache.ts index c001ccdcd214c..19ec4c68051f1 100644 --- a/packages/workspace/src/tasks-runner/cache.ts +++ b/packages/workspace/src/tasks-runner/cache.ts @@ -52,7 +52,7 @@ export class Cache { try { const p = spawn('node', [`"${scriptPath}"`, `"${this.cachePath}"`], { stdio: 'ignore', - detached: true + detached: true, }); p.unref(); } catch (e) { @@ -95,7 +95,7 @@ export class Cache { writeFileSync(join(td, 'terminalOutput'), terminalOutput); mkdirSync(join(td, 'outputs')); - folders.forEach(f => { + folders.forEach((f) => { const srcDir = join(this.root, f); if (existsSync(srcDir)) { const cachedDir = join(td, 'outputs', f); @@ -115,7 +115,7 @@ export class Cache { } copyFilesFromCache(cachedResult: CachedResult, outputs: string[]) { - outputs.forEach(f => { + outputs.forEach((f) => { const cachedDir = join(cachedResult.outputsPath, f); if (existsSync(cachedDir)) { const srcDir = join(this.root, f); @@ -143,7 +143,7 @@ export class Cache { if (existsSync(tdCommit)) { return { terminalOutput: readFileSync(join(td, 'terminalOutput')).toString(), - outputsPath: join(td, 'outputs') + outputsPath: join(td, 'outputs'), }; } else { return null; diff --git a/packages/workspace/src/tasks-runner/default-reporter.ts b/packages/workspace/src/tasks-runner/default-reporter.ts index 999adf97d0ee7..9c1b33730c377 100644 --- a/packages/workspace/src/tasks-runner/default-reporter.ts +++ b/packages/workspace/src/tasks-runner/default-reporter.ts @@ -22,21 +22,21 @@ export class DefaultReporter { } const bodyLines = projectNames.map( - affectedProject => `${output.colors.gray('-')} ${affectedProject}` + (affectedProject) => `${output.colors.gray('-')} ${affectedProject}` ); if (Object.keys(taskOverrides).length > 0) { bodyLines.push(''); bodyLines.push(`${output.colors.gray('With flags:')}`); Object.entries(taskOverrides) .map(([flag, value]) => ` --${flag}=${value}`) - .forEach(arg => bodyLines.push(arg)); + .forEach((arg) => bodyLines.push(arg)); } output.log({ title: `${output.colors.gray('Running target')} ${ args.target } ${output.colors.gray('for projects:')}`, - bodyLines + bodyLines, }); output.addVerticalSeparatorWithoutNewLines(); @@ -57,13 +57,13 @@ export class DefaultReporter { ? [ output.colors.gray( `Nx read the output from cache instead of running the command for ${cachedProjectNames.length} out of ${this.projectNames.length} projects.` - ) + ), ] : []; output.success({ title: `Running target "${args.target}" succeeded`, - bodyLines + bodyLines, }); if (args.onlyFailed && startedWithFailedProjects) { @@ -74,8 +74,8 @@ export class DefaultReporter { bodyLines: [ `You should verify by running ${output.underline( 'without' - )} ${output.bold('--only-failed')}` - ] + )} ${output.bold('--only-failed')}`, + ], }); } } else { @@ -83,8 +83,8 @@ export class DefaultReporter { output.colors.gray('Failed projects:'), '', ...failedProjectNames.map( - project => `${output.colors.gray('-')} ${project}` - ) + (project) => `${output.colors.gray('-')} ${project}` + ), ]; if (!args.onlyFailed && !startedWithFailedProjects) { bodyLines.push(''); @@ -96,7 +96,7 @@ export class DefaultReporter { } output.error({ title: `Running target "${args.target}" failed`, - bodyLines + bodyLines, }); } } diff --git a/packages/workspace/src/tasks-runner/default-tasks-runner.ts b/packages/workspace/src/tasks-runner/default-tasks-runner.ts index f6dcc8fd239b3..78a1984f0edb3 100644 --- a/packages/workspace/src/tasks-runner/default-tasks-runner.ts +++ b/packages/workspace/src/tasks-runner/default-tasks-runner.ts @@ -3,7 +3,7 @@ import { AffectedEventType, Task, TaskCompleteEvent, - TasksRunner + TasksRunner, } from './tasks-runner'; import { ProjectGraph } from '../core/project-graph'; import { NxJson } from '../core/shared-interfaces'; @@ -51,10 +51,10 @@ export const defaultTasksRunner: TasksRunner = ( options.lifeCycle = new NoopLifeCycle(); } - return new Observable(subscriber => { + return new Observable((subscriber) => { runAllTasks(tasks, options, context) - .then(data => data.forEach(d => subscriber.next(d))) - .catch(e => { + .then((data) => data.forEach((d) => subscriber.next(d))) + .catch((e) => { console.error('Unexpected error:'); console.error(e); process.exit(1); @@ -95,7 +95,7 @@ async function runAllTasks( res.push(...statuses); // any task failed, we need to skip further stages - if (statuses.find(s => !s.success)) { + if (statuses.find((s) => !s.success)) { res.push(...markStagesAsNotSuccessful(stages.splice(i + 1))); return res; } @@ -108,10 +108,10 @@ function markStagesAsNotSuccessful(stages: Task[][]) { } function tasksToStatuses(tasks: Task[], success: boolean) { - return tasks.map(task => ({ + return tasks.map((task) => ({ task, type: AffectedEventType.TaskComplete, - success + success, })); } diff --git a/packages/workspace/src/tasks-runner/hasher.spec.ts b/packages/workspace/src/tasks-runner/hasher.spec.ts index d9c816ed79415..352e3c4de9a24 100644 --- a/packages/workspace/src/tasks-runner/hasher.spec.ts +++ b/packages/workspace/src/tasks-runner/hasher.spec.ts @@ -8,15 +8,15 @@ jest.mock('fs'); describe('Hasher', () => { let hashes = { 'yarn.lock': 'yarn.lock.hash' }; beforeEach(() => { - hasha.mockImplementation(values => values.join('|')); - hasha.fromFile.mockImplementation(path => Promise.resolve(hashes[path])); + hasha.mockImplementation((values) => values.join('|')); + hasha.fromFile.mockImplementation((path) => Promise.resolve(hashes[path])); fs.statSync.mockReturnValue({ size: 100 }); fs.readFileSync.mockImplementation(() => JSON.stringify({ dependencies: {}, devDependencies: {} }) ); }); - it('should create project hash', async done => { + it('should create project hash', async (done) => { hashes['/file'] = 'file.hash'; const hasher = new Hasher( { @@ -24,23 +24,23 @@ describe('Hasher', () => { proj: { name: 'proj', type: 'lib', - data: { files: [{ file: '/file', ext: '.ts', mtime: 1 }] } - } + data: { files: [{ file: '/file', ext: '.ts', mtime: 1 }] }, + }, }, dependencies: { - proj: [] - } + proj: [], + }, }, {} as any, { - runtimeCacheInputs: ['echo runtime123', 'echo runtime456'] + runtimeCacheInputs: ['echo runtime123', 'echo runtime456'], } ); const hash = await hasher.hash({ target: { project: 'proj', target: 'build' }, id: 'proj-build', - overrides: { prop: 'prop-value' } + overrides: { prop: 'prop-value' }, }); expect(hash).toContain('yarn.lock.hash'); //implicits @@ -58,11 +58,11 @@ describe('Hasher', () => { const hasher = new Hasher( { nodes: {}, - dependencies: {} + dependencies: {}, }, {} as any, { - runtimeCacheInputs: ['boom'] + runtimeCacheInputs: ['boom'], } ); @@ -70,7 +70,7 @@ describe('Hasher', () => { await hasher.hash({ target: { project: 'proj', target: 'build' }, id: 'proj-build', - overrides: {} + overrides: {}, }); fail('Should not be here'); } catch (e) { @@ -82,7 +82,7 @@ describe('Hasher', () => { } }); - it('should hash when circular dependencies', async done => { + it('should hash when circular dependencies', async (done) => { hashes['/filea'] = 'a.hash'; hashes['/fileb'] = 'b.hash'; const hasher = new Hasher( @@ -91,18 +91,18 @@ describe('Hasher', () => { proja: { name: 'proja', type: 'lib', - data: { files: [{ file: '/filea', ext: '.ts', mtime: 1 }] } + data: { files: [{ file: '/filea', ext: '.ts', mtime: 1 }] }, }, projb: { name: 'projb', type: 'lib', - data: { files: [{ file: '/fileb', ext: '.ts', mtime: 1 }] } - } + data: { files: [{ file: '/fileb', ext: '.ts', mtime: 1 }] }, + }, }, dependencies: { proja: [{ source: 'proja', target: 'projb', type: 'static' }], - projb: [{ source: 'projb', target: 'proja', type: 'static' }] - } + projb: [{ source: 'projb', target: 'proja', type: 'static' }], + }, }, {} as any, {} @@ -111,7 +111,7 @@ describe('Hasher', () => { const hasha = await hasher.hash({ target: { project: 'proja', target: 'build' }, id: 'proja-build', - overrides: { prop: 'prop-value' } + overrides: { prop: 'prop-value' }, }); expect(hasha).toContain('yarn.lock.hash'); //implicits @@ -124,7 +124,7 @@ describe('Hasher', () => { const hashb = await hasher.hash({ target: { project: 'projb', target: 'build' }, id: 'projb-build', - overrides: { prop: 'prop-value' } + overrides: { prop: 'prop-value' }, }); expect(hashb).toContain('yarn.lock.hash'); //implicits @@ -137,8 +137,8 @@ describe('Hasher', () => { done(); }); - it('should handle large binary files in a special way', async done => { - fs.statSync.mockImplementation(f => { + it('should handle large binary files in a special way', async (done) => { + fs.statSync.mockImplementation((f) => { if (f === '/file') return { size: 1000000 * 5 + 1 }; return { size: 100 }; }); @@ -149,10 +149,10 @@ describe('Hasher', () => { proja: { name: 'proj', type: 'lib', - data: { files: [{ file: '/file', ext: '.ts', mtime: 1 }] } - } + data: { files: [{ file: '/file', ext: '.ts', mtime: 1 }] }, + }, }, - dependencies: {} + dependencies: {}, }, {} as any, {} @@ -161,7 +161,7 @@ describe('Hasher', () => { const hash = await hasher.hash({ target: { project: 'proja', target: 'build' }, id: 'proja-build', - overrides: { prop: 'prop-value' } + overrides: { prop: 'prop-value' }, }); expect(hash).toContain('yarn.lock.hash'); //implicits diff --git a/packages/workspace/src/tasks-runner/hasher.ts b/packages/workspace/src/tasks-runner/hasher.ts index 834ee825172da..623d6c9327e52 100644 --- a/packages/workspace/src/tasks-runner/hasher.ts +++ b/packages/workspace/src/tasks-runner/hasher.ts @@ -25,15 +25,15 @@ export class Hasher { task.target.project || '', task.target.target || '', task.target.configuration || '', - JSON.stringify(task.overrides) + JSON.stringify(task.overrides), ]; const values = await Promise.all([ this.projectHashes.hashProject(task.target.project, [ - task.target.project + task.target.project, ]), this.implicitDepsHash(), - this.runtimeInputsHash() + this.runtimeInputsHash(), ]); return hasha([Hasher.version, ...args, ...values], { algorithm: 'sha256' }); @@ -49,11 +49,7 @@ export class Hasher { if (inputs.length > 0) { try { const values = await Promise.all( - inputs.map(async i => - execSync(i) - .toString() - .trim() - ) + inputs.map(async (i) => execSync(i).toString().trim()) ); this.runtimeInputs = hasha(values, { algorithm: 'sha256' }); } catch (e) { @@ -72,12 +68,12 @@ export class Hasher { if (this.implicitDependencies) return this.implicitDependencies; const values = await Promise.all([ - ...Object.keys(this.nxJson.implicitDependencies || {}).map(r => + ...Object.keys(this.nxJson.implicitDependencies || {}).map((r) => this.fileHashes.hashFile(r) ), - ...rootWorkspaceFileNames().map(r => this.fileHashes.hashFile(r)), + ...rootWorkspaceFileNames().map((r) => this.fileHashes.hashFile(r)), this.fileHashes.hashFile('package-lock.json'), - this.fileHashes.hashFile('yarn.lock') + this.fileHashes.hashFile('yarn.lock'), ]); this.implicitDependencies = hasha(values, { algorithm: 'sha256' }); return this.implicitDependencies; @@ -95,7 +91,7 @@ export class ProjectHashes { async hashProject(projectName: string, visited: string[]) { return Promise.resolve().then(async () => { const deps = (this.projectGraph.dependencies[projectName] || []).map( - t => { + (t) => { if (visited.indexOf(t.target) > -1) { return ''; } else { @@ -111,10 +107,10 @@ export class ProjectHashes { private async hashProjectNodeSource(projectName: string) { if (!this.sourceHashes[projectName]) { - this.sourceHashes[projectName] = new Promise(async res => { + this.sourceHashes[projectName] = new Promise(async (res) => { const p = this.projectGraph.nodes[projectName]; const values = await Promise.all( - p.data.files.map(f => this.fileHashes.hashFile(f.file)) + p.data.files.map((f) => this.fileHashes.hashFile(f.file)) ); res(hasha(values, { algorithm: 'sha256' })); }); @@ -131,7 +127,7 @@ export class FileHashes { async hashFile(path: string) { if (!this.fileHashes[path]) { - this.fileHashes[path] = new Promise(res => { + this.fileHashes[path] = new Promise((res) => { this.resolvers[path] = res; this.pushFileIntoQueue(path); }); @@ -151,7 +147,7 @@ export class FileHashes { if (this.queue.length > 0) { const path = this.queue.pop(); this.processPath(path) - .then(value => { + .then((value) => { this.resolvers[path](value); }) .then(() => this.takeFromQueue()); diff --git a/packages/workspace/src/tasks-runner/remove-old-cache-records.ts b/packages/workspace/src/tasks-runner/remove-old-cache-records.ts index 266d8ecb0dfe9..e21d3a812d393 100644 --- a/packages/workspace/src/tasks-runner/remove-old-cache-records.ts +++ b/packages/workspace/src/tasks-runner/remove-old-cache-records.ts @@ -19,7 +19,7 @@ function terminalOutputs() { function cachedFiles() { try { - return fs.readdirSync(folder).filter(f => !f.endsWith('terminalOutputs')); + return fs.readdirSync(folder).filter((f) => !f.endsWith('terminalOutputs')); } catch (e) { return []; } @@ -29,7 +29,7 @@ function removeOld(records: string[]) { try { const time = mostRecentMTime(records); - records.forEach(r => { + records.forEach((r) => { const child = path.join(folder, r); try { const s = fs.statSync(child); @@ -48,7 +48,7 @@ function removeOld(records: string[]) { function mostRecentMTime(records: string[]) { let mostRecentTime = 0; - records.forEach(r => { + records.forEach((r) => { const child = path.join(folder, r); try { const s = fs.statSync(child); diff --git a/packages/workspace/src/tasks-runner/run-command.spec.ts b/packages/workspace/src/tasks-runner/run-command.spec.ts index c054f9cb1272f..a154723c93e45 100644 --- a/packages/workspace/src/tasks-runner/run-command.spec.ts +++ b/packages/workspace/src/tasks-runner/run-command.spec.ts @@ -11,7 +11,7 @@ describe('getRunner', () => { beforeEach(() => { nxJson = { npmScope: 'proj', - projects: {} + projects: {}, }; mockRunner = jest.fn(); overrides = { foo: 'bar' }; @@ -33,13 +33,13 @@ describe('getRunner', () => { it('gets a custom task runner', () => { jest.mock('custom-runner', () => mockRunner, { - virtual: true + virtual: true, }); nxJson.tasksRunnerOptions = { custom: { - runner: 'custom-runner' - } + runner: 'custom-runner', + }, }; const { tasksRunner, tasksOptions } = getRunner( @@ -54,16 +54,16 @@ describe('getRunner', () => { it('gets a custom task runner with options', () => { jest.mock('custom-runner2', () => mockRunner, { - virtual: true + virtual: true, }); nxJson.tasksRunnerOptions = { custom: { runner: 'custom-runner2', options: { - runnerOption: 'runner-option' - } - } + runnerOption: 'runner-option', + }, + }, }; const { tasksRunner, tasksOptions } = getRunner( @@ -74,19 +74,19 @@ describe('getRunner', () => { expect(tasksRunner).toBe(mockRunner); expect(tasksOptions).toEqual({ runnerOption: 'runner-option', - foo: 'bar' + foo: 'bar', }); }); it('gets a custom defined default task runner', () => { jest.mock('custom-default-runner', () => mockRunner, { - virtual: true + virtual: true, }); nxJson.tasksRunnerOptions = { default: { - runner: 'custom-default-runner' - } + runner: 'custom-default-runner', + }, }; const { tasksRunner } = getRunner({}, nxJson, overrides); diff --git a/packages/workspace/src/tasks-runner/run-command.ts b/packages/workspace/src/tasks-runner/run-command.ts index b9c284d1baea7..5f162dc7fdbd0 100644 --- a/packages/workspace/src/tasks-runner/run-command.ts +++ b/packages/workspace/src/tasks-runner/run-command.ts @@ -21,25 +21,29 @@ export async function runCommand( reporter: any, initiatingProject: string | null ) { - reporter.beforeRun(projectsToRun.map(p => p.name), nxArgs, overrides); + reporter.beforeRun( + projectsToRun.map((p) => p.name), + nxArgs, + overrides + ); const { tasksRunner, tasksOptions } = getRunner(nxArgs, nxJson, { ...nxArgs, - ...overrides + ...overrides, }); - const tasks: Task[] = projectsToRun.map(project => { + const tasks: Task[] = projectsToRun.map((project) => { return createTask({ project, target: nxArgs.target, configuration: nxArgs.configuration, - overrides: overrides + overrides: overrides, }); }); const hasher = new Hasher(projectGraph, nxJson, tasksOptions); await Promise.all( - tasks.map(async t => { + tasks.map(async (t) => { t.hash = await hasher.hash(t); }) ); @@ -49,7 +53,7 @@ export async function runCommand( initiatingProject: initiatingProject, target: nxArgs.target, projectGraph, - nxJson + nxJson, }).subscribe({ next: (event: any) => { switch (event.type) { @@ -80,7 +84,7 @@ export async function runCommand( if (workspaceResults.hasFailure) { process.exit(1); } - } + }, }); } @@ -95,7 +99,7 @@ export function createTask({ project, target, configuration, - overrides + overrides, }: TaskParams): Task { const config = projectHasTargetAndConfiguration( project, @@ -107,19 +111,19 @@ export function createTask({ const qualifiedTarget = { project: project.name, target, - configuration: config + configuration: config, }; return { id: getId(qualifiedTarget), target: qualifiedTarget, - overrides: interpolateOverrides(overrides, project.name, project.data) + overrides: interpolateOverrides(overrides, project.name, project.data), }; } function getId({ project, target, - configuration + configuration, }: { project: string; target: string; @@ -145,7 +149,7 @@ export function getRunner( const t = require('./default-tasks-runner'); return { tasksRunner: t.defaultTasksRunner, - tasksOptions: overrides + tasksOptions: overrides, }; } @@ -153,7 +157,7 @@ export function getRunner( const t = require('./default-tasks-runner'); return { tasksRunner: t.defaultTasksRunner, - tasksOptions: overrides + tasksOptions: overrides, }; } @@ -182,8 +186,8 @@ export function getRunner( tasksOptions: { ...nxJson.tasksRunnerOptions[runner].options, ...overrides, - skipNxCache: nxArgs.skipNxCache - } + skipNxCache: nxArgs.skipNxCache, + }, }; } else { throw new Error(`Could not find runner configuration for ${runner}`); diff --git a/packages/workspace/src/tasks-runner/run-one-reporter.ts b/packages/workspace/src/tasks-runner/run-one-reporter.ts index 5248f894989d3..3377132ac5abd 100644 --- a/packages/workspace/src/tasks-runner/run-one-reporter.ts +++ b/packages/workspace/src/tasks-runner/run-one-reporter.ts @@ -20,7 +20,7 @@ export class RunOneReporter { args.target } ${output.colors.gray('for project')} ${ this.initiatingProject - } ${output.colors.gray(`and its ${numberOfDeps} deps.`)}` + } ${output.colors.gray(`and its ${numberOfDeps} deps.`)}`, }); output.addVerticalSeparatorWithoutNewLines(); } @@ -41,13 +41,13 @@ export class RunOneReporter { ? [ output.colors.gray( `Nx read the output from cache instead of running the command for ${cachedProjectNames.length} out of ${this.projectNames.length} projects.` - ) + ), ] : []; output.success({ title: `Running target "${args.target}" succeeded`, - bodyLines + bodyLines, }); if (args.onlyFailed && startedWithFailedProjects) { @@ -58,8 +58,8 @@ export class RunOneReporter { bodyLines: [ `You should verify by running ${output.underline( 'without' - )} ${output.bold('--only-failed')}` - ] + )} ${output.bold('--only-failed')}`, + ], }); } } else { @@ -67,12 +67,12 @@ export class RunOneReporter { output.colors.gray('Failed projects:'), '', ...failedProjectNames.map( - project => `${output.colors.gray('-')} ${project}` - ) + (project) => `${output.colors.gray('-')} ${project}` + ), ]; output.error({ title: `Running target "${args.target}" failed`, - bodyLines + bodyLines, }); } } diff --git a/packages/workspace/src/tasks-runner/task-orchestrator.ts b/packages/workspace/src/tasks-runner/task-orchestrator.ts index 6f3bef547a2db..08f1a4ce8b739 100644 --- a/packages/workspace/src/tasks-runner/task-orchestrator.ts +++ b/packages/workspace/src/tasks-runner/task-orchestrator.ts @@ -43,11 +43,11 @@ export class TaskOrchestrator { const task = left.pop(); return that .forkProcess(task) - .then(code => { + .then((code) => { res.push({ task, success: code === 0, - type: AffectedEventType.TaskComplete + type: AffectedEventType.TaskComplete, }); }) .then(takeFromQueue) @@ -78,7 +78,7 @@ export class TaskOrchestrator { const cached: TaskWithCachedResult[] = []; const rest: Task[] = []; await Promise.all( - tasks.map(async task => { + tasks.map(async (task) => { const cachedResult = await this.cache.get(task); if (cachedResult) { cached.push({ task, cachedResult }); @@ -92,7 +92,7 @@ export class TaskOrchestrator { } private applyCachedResults(tasks: TaskWithCachedResult[]) { - tasks.forEach(t => { + tasks.forEach((t) => { this.options.lifeCycle.startTask(t.task); if ( @@ -115,7 +115,7 @@ export class TaskOrchestrator { m.push({ task: c.task, type: AffectedEventType.TaskCacheRead, - success: true + success: true, }); return m; }, []); @@ -137,9 +137,9 @@ export class TaskOrchestrator { } const p = fork(this.getCommand(), args, { stdio: ['inherit', 'inherit', 'inherit', 'ipc'], - env + env, }); - p.on('close', code => { + p.on('close', (code) => { // we didn't print any output as we were running the command // print all the collected output if (!forwardOutput) { @@ -215,7 +215,7 @@ export class TaskOrchestrator { return [ 'run', `${task.target.project}:${task.target.target}${config}`, - ...args + ...args, ]; } } diff --git a/packages/workspace/src/tasks-runner/task-orderer.spec.ts b/packages/workspace/src/tasks-runner/task-orderer.spec.ts index 66fd3e861cfc1..062ee800a8aef 100644 --- a/packages/workspace/src/tasks-runner/task-orderer.spec.ts +++ b/packages/workspace/src/tasks-runner/task-orderer.spec.ts @@ -5,7 +5,7 @@ describe('TaskStages', () => { it('should return empty for an empty array', () => { const stages = new TaskOrderer('build', { nodes: {}, - dependencies: {} + dependencies: {}, }).splitTasksIntoStages([]); expect(stages).toEqual([]); }); @@ -20,56 +20,56 @@ describe('TaskStages', () => { { source: 'parent', target: 'child1', - type: DependencyType.static + type: DependencyType.static, }, { source: 'parent', target: 'child2', - type: DependencyType.static - } + type: DependencyType.static, + }, ], grandparent: [ { source: 'grandparent', target: 'parent', - type: DependencyType.static - } - ] - } + type: DependencyType.static, + }, + ], + }, }).splitTasksIntoStages([ { - target: { project: 'parent' } + target: { project: 'parent' }, }, { - target: { project: 'child1' } + target: { project: 'child1' }, }, { - target: { project: 'child2' } + target: { project: 'child2' }, }, { - target: { project: 'grandparent' } - } + target: { project: 'grandparent' }, + }, ] as any); expect(stages).toEqual([ [ { - target: { project: 'child1' } + target: { project: 'child1' }, }, { - target: { project: 'child2' } - } + target: { project: 'child2' }, + }, ], [ { - target: { project: 'parent' } - } + target: { project: 'parent' }, + }, ], [ { - target: { project: 'grandparent' } - } - ] + target: { project: 'grandparent' }, + }, + ], ]); }); @@ -81,51 +81,51 @@ describe('TaskStages', () => { { source: 'app1', target: 'common1', - type: DependencyType.static - } + type: DependencyType.static, + }, ], app2: [ { source: 'app2', target: 'common2', - type: DependencyType.static - } + type: DependencyType.static, + }, ], common1: [], - common2: [] - } + common2: [], + }, }).splitTasksIntoStages([ { - target: { project: 'app1' } + target: { project: 'app1' }, }, { - target: { project: 'app2' } + target: { project: 'app2' }, }, { - target: { project: 'common1' } + target: { project: 'common1' }, }, { - target: { project: 'common2' } - } + target: { project: 'common2' }, + }, ] as any); expect(stages).toEqual([ [ { - target: { project: 'common1' } + target: { project: 'common1' }, }, { - target: { project: 'common2' } - } + target: { project: 'common2' }, + }, ], [ { - target: { project: 'app1' } + target: { project: 'app1' }, }, { - target: { project: 'app2' } - } - ] + target: { project: 'app2' }, + }, + ], ]); }); }); diff --git a/packages/workspace/src/tasks-runner/task-orderer.ts b/packages/workspace/src/tasks-runner/task-orderer.ts index 30ed77a1a240f..b78416f295666 100644 --- a/packages/workspace/src/tasks-runner/task-orderer.ts +++ b/packages/workspace/src/tasks-runner/task-orderer.ts @@ -13,9 +13,9 @@ export class TaskOrderer { const res = []; // console.log(this.topologicallySortTasks(tasks)) - this.topologicallySortTasks(tasks).forEach(t => { + this.topologicallySortTasks(tasks).forEach((t) => { const stageWithNoDeps = res.find( - tasksInStage => !this.taskDependsOnDeps(t, tasksInStage) + (tasksInStage) => !this.taskDependsOnDeps(t, tasksInStage) ); if (stageWithNoDeps) { stageWithNoDeps.push(t); @@ -34,17 +34,17 @@ export class TaskOrderer { return false; } - if (g.dependencies[source].find(d => d.target === target)) { + if (g.dependencies[source].find((d) => d.target === target)) { return true; } - return !!g.dependencies[source].find(r => { + return !!g.dependencies[source].find((r) => { if (visitedProjects.indexOf(r.target) > -1) return null; return hasDep(r.target, target, [...visitedProjects, r.target]); }); } - return !!deps.find(dep => + return !!deps.find((dep) => hasDep(task.target.project, dep.target.project, []) ); } @@ -56,12 +56,12 @@ export class TaskOrderer { const visitNode = (id: string) => { if (visited[id]) return; visited[id] = true; - this.projectGraph.dependencies[id].forEach(d => { + this.projectGraph.dependencies[id].forEach((d) => { visitNode(d.target); }); sorted.push(id); }; - tasks.forEach(t => visitNode(t.target.project)); + tasks.forEach((t) => visitNode(t.target.project)); const sortedTasks = [...tasks]; sortedTasks.sort((a, b) => sorted.indexOf(a.target.project) > sorted.indexOf(b.target.project) diff --git a/packages/workspace/src/tasks-runner/tasks-runner-v1.ts b/packages/workspace/src/tasks-runner/tasks-runner-v1.ts index 4da69ee1a05da..0e0eeb57fe5dd 100644 --- a/packages/workspace/src/tasks-runner/tasks-runner-v1.ts +++ b/packages/workspace/src/tasks-runner/tasks-runner-v1.ts @@ -5,7 +5,7 @@ import { AffectedEventType, Task, TaskCompleteEvent, - TasksRunner + TasksRunner, } from './tasks-runner'; import { output } from '../utils/output'; import { readJsonFile } from '../utils/fileutils'; @@ -29,17 +29,17 @@ function taskDependsOnDeps( return false; } - if (projectGraph.dependencies[source].find(d => d.target === target)) { + if (projectGraph.dependencies[source].find((d) => d.target === target)) { return true; } - return !!projectGraph.dependencies[source].find(r => { + return !!projectGraph.dependencies[source].find((r) => { if (visitedProjects.indexOf(r.target) > -1) return null; return hasDep(r.target, target, [...visitedProjects, r.target]); }); } - return !!deps.find(dep => + return !!deps.find((dep) => hasDep(task.target.project, dep.target.project, []) ); } @@ -51,12 +51,12 @@ function topologicallySortTasks(tasks: Task[], projectGraph: ProjectGraph) { const visitNode = (id: string) => { if (visited[id]) return; visited[id] = true; - projectGraph.dependencies[id].forEach(d => { + projectGraph.dependencies[id].forEach((d) => { visitNode(d.target); }); sorted.push(id); }; - tasks.forEach(t => visitNode(t.target.project)); + tasks.forEach((t) => visitNode(t.target.project)); const sortedTasks = [...tasks]; sortedTasks.sort((a, b) => sorted.indexOf(a.target.project) > sorted.indexOf(b.target.project) ? 1 : -1 @@ -70,9 +70,9 @@ export function splitTasksIntoStages( ) { if (tasks.length === 0) return []; const res = []; - topologicallySortTasks(tasks, projectGraph).forEach(t => { + topologicallySortTasks(tasks, projectGraph).forEach((t) => { const stageWithNoDeps = res.find( - tasksInStage => !taskDependsOnDeps(t, tasksInStage, projectGraph) + (tasksInStage) => !taskDependsOnDeps(t, tasksInStage, projectGraph) ); if (stageWithNoDeps) { stageWithNoDeps.push(t); @@ -88,10 +88,10 @@ export const defaultTasksRunner: TasksRunner = ( options: DefaultTasksRunnerOptions, context: { target: string; projectGraph: ProjectGraph; nxJson: NxJson } ): Observable => { - return new Observable(subscriber => { + return new Observable((subscriber) => { runTasks(tasks, options, context) - .then(data => data.forEach(d => subscriber.next(d))) - .catch(e => { + .then((data) => data.forEach((d) => subscriber.next(d))) + .catch((e) => { console.error('Unexpected error:'); console.error(e); process.exit(1); @@ -122,7 +122,7 @@ async function runTasks( for (let i = 0; i < stages.length; ++i) { const tasksInStage = stages[i]; try { - const commands = tasksInStage.map(t => + const commands = tasksInStage.map((t) => getCommandAsString(cli, isYarn, t) ); await runAll(commands, { @@ -131,7 +131,7 @@ async function runTasks( continueOnError: true, stdin: process.stdin, stdout: process.stdout, - stderr: process.stderr + stderr: process.stderr, }); res.push(...tasksToStatuses(tasksInStage, true)); } catch (e) { @@ -139,7 +139,7 @@ async function runTasks( res.push({ task: tasksInStage[i], type: AffectedEventType.TaskComplete, - success: result.code === 0 + success: result.code === 0, }); }); res.push(...markStagesAsNotSuccessful(stages.splice(i + 1))); @@ -154,10 +154,10 @@ function markStagesAsNotSuccessful(stages: Task[][]) { } function tasksToStatuses(tasks: Task[], success: boolean) { - return tasks.map(task => ({ + return tasks.map((task) => ({ task, type: AffectedEventType.TaskComplete, - success + success, })); } @@ -174,8 +174,8 @@ function assertPackageJsonScriptExists(cli: string) { ` "${cli}": "${cli}"`, output.colors.gray(' ...'), ' }', - output.colors.gray('...') - ] + output.colors.gray('...'), + ], }); return process.exit(1); } diff --git a/packages/workspace/src/tasks-runner/tasks-runner-v2.ts b/packages/workspace/src/tasks-runner/tasks-runner-v2.ts index e58f01be32b37..7b6e1f3e15031 100644 --- a/packages/workspace/src/tasks-runner/tasks-runner-v2.ts +++ b/packages/workspace/src/tasks-runner/tasks-runner-v2.ts @@ -3,7 +3,7 @@ import { defaultTasksRunner } from './default-tasks-runner'; export { DefaultTasksRunnerOptions, RemoteCache, - defaultTasksRunner as tasksRunnerV2 + defaultTasksRunner as tasksRunnerV2, } from './default-tasks-runner'; export default defaultTasksRunner; diff --git a/packages/workspace/src/tasks-runner/tasks-runner.ts b/packages/workspace/src/tasks-runner/tasks-runner.ts index 465c6d3bc37bf..70e63993ac323 100644 --- a/packages/workspace/src/tasks-runner/tasks-runner.ts +++ b/packages/workspace/src/tasks-runner/tasks-runner.ts @@ -13,7 +13,7 @@ export interface Task { export enum AffectedEventType { TaskComplete = '[Task] Complete', - TaskCacheRead = '[Task] CacheRead' + TaskCacheRead = '[Task] CacheRead', } export interface AffectedEvent { diff --git a/packages/workspace/src/tasks-runner/utils.spec.ts b/packages/workspace/src/tasks-runner/utils.spec.ts index 7540a895cf304..a3c0bff9e1b9b 100644 --- a/packages/workspace/src/tasks-runner/utils.spec.ts +++ b/packages/workspace/src/tasks-runner/utils.spec.ts @@ -10,11 +10,11 @@ describe('utils', () => { data: { architect: { build: { - outputs: ['one', 'two'] - } + outputs: ['one', 'two'], + }, }, - files: [] - } + files: [], + }, }) ).toEqual(['one', 'two']); }); @@ -28,17 +28,17 @@ describe('utils', () => { architect: { build: { options: { - outputPath: 'one' + outputPath: 'one', }, configurations: { production: { - outputPath: 'two' - } - } - } + outputPath: 'two', + }, + }, + }, }, - files: [] - } + files: [], + }, }) ).toEqual(['two']); }); @@ -52,15 +52,15 @@ describe('utils', () => { architect: { build: { options: { - outputPath: 'one' + outputPath: 'one', }, configurations: { - production: {} - } - } + production: {}, + }, + }, }, - files: [] - } + files: [], + }, }) ).toEqual(['one']); }); @@ -74,12 +74,12 @@ describe('utils', () => { architect: { build: { options: { - outputPath: 'one' - } - } + outputPath: 'one', + }, + }, }, - files: [] - } + files: [], + }, }) ).toEqual(['one']); }); @@ -92,10 +92,10 @@ describe('utils', () => { data: { root: 'root-myapp', architect: { - build: {} + build: {}, }, - files: [] - } + files: [], + }, }) ).toEqual(['dist/root-myapp']); }); diff --git a/packages/workspace/src/tasks-runner/utils.ts b/packages/workspace/src/tasks-runner/utils.ts index 0b4a514d577cf..2b381bc55e73a 100644 --- a/packages/workspace/src/tasks-runner/utils.ts +++ b/packages/workspace/src/tasks-runner/utils.ts @@ -8,9 +8,7 @@ export function getCommandAsString( isYarn: boolean, task: Task ) { - return getCommand(cliCommand, isYarn, task) - .join(' ') - .trim(); + return getCommand(cliCommand, isYarn, task).join(' ').trim(); } export function getCommand(cliCommand: string, isYarn: boolean, task: Task) { @@ -29,7 +27,7 @@ export function getCommand(cliCommand: string, isYarn: boolean, task: Task) { task.target.target, task.target.project, ...config, - ...args + ...args, ]; } else { const config = task.target.configuration @@ -41,7 +39,7 @@ export function getCommand(cliCommand: string, isYarn: boolean, task: Task) { ...(isYarn ? [] : ['--']), 'run', `${task.target.project}:${task.target.target}${config}`, - ...args + ...args, ]; } } @@ -66,7 +64,7 @@ export function getOutputsForTargetAndConfiguration( if (architect.configurations && architect.configurations[configuration]) { opts = { ...opts, - ...architect.configurations[configuration] + ...architect.configurations[configuration], }; } diff --git a/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.spec.ts b/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.spec.ts index 503e4d090db0e..beeaa003788e3 100644 --- a/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.spec.ts +++ b/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.spec.ts @@ -5,7 +5,7 @@ import * as ts from 'typescript'; import { DependencyType, ProjectGraph, - ProjectType + ProjectType, } from '../core/project-graph'; import { Rule } from './nxEnforceModuleBoundariesRule'; import { TargetProjectLocator } from '../core/target-project-locator'; @@ -33,12 +33,12 @@ const tsconfig = { '@mycompany/anotherlibName': ['libs/anotherlibName/src/index.ts'], '@mycompany/badcirclelib': ['libs/badcirclelib/src/index.ts'], '@mycompany/domain1': ['libs/domain1/src/index.ts'], - '@mycompany/domain2': ['libs/domain2/src/index.ts'] + '@mycompany/domain2': ['libs/domain2/src/index.ts'], }, - types: ['node'] + types: ['node'], }, exclude: ['**/*.spec.ts'], - include: ['**/*.ts'] + include: ['**/*.ts'], }; const fileSys = { @@ -59,7 +59,7 @@ const fileSys = { './libs/badcirclelib/src/index.ts': '', './libs/domain1/src/index.ts': '', './libs/domain2/src/index.ts': '', - './tsconfig.json': JSON.stringify(tsconfig) + './tsconfig.json': JSON.stringify(tsconfig), }; describe('Enforce Module Boundaries', () => { @@ -88,9 +88,9 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`apps/myapp/src/main.ts`), - createFile(`apps/myapp/blah.ts`) - ] - } + createFile(`apps/myapp/blah.ts`), + ], + }, }, mylibName: { name: 'mylibName', @@ -102,12 +102,12 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`libs/mylib/src/index.ts`), - createFile(`libs/mylib/src/deep.ts`) - ] - } - } + createFile(`libs/mylib/src/deep.ts`), + ], + }, + }, }, - dependencies: {} + dependencies: {}, } ); @@ -133,9 +133,9 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`apps/myapp/src/main.ts`), - createFile(`apps/myapp/src/blah.ts`) - ] - } + createFile(`apps/myapp/src/blah.ts`), + ], + }, }, myapp2Name: { name: 'myapp2Name', @@ -145,8 +145,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [] - } + files: [], + }, }, 'myapp2-mylib': { name: 'myapp2-mylib', @@ -156,11 +156,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/myapp2/mylib/src/index.ts')] - } - } + files: [createFile('libs/myapp2/mylib/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, } ); @@ -178,8 +178,8 @@ describe('Enforce Module Boundaries', () => { tags: ['api', 'domain1'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/api/src/index.ts`)] - } + files: [createFile(`libs/api/src/index.ts`)], + }, }, 'impl-both-domainsName': { name: 'impl-both-domainsName', @@ -189,8 +189,8 @@ describe('Enforce Module Boundaries', () => { tags: ['impl', 'domain1', 'domain2'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/impl-both-domains/src/index.ts`)] - } + files: [createFile(`libs/impl-both-domains/src/index.ts`)], + }, }, 'impl-domain2Name': { name: 'impl-domain2Name', @@ -200,8 +200,8 @@ describe('Enforce Module Boundaries', () => { tags: ['impl', 'domain2'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/impl-domain2/src/index.ts`)] - } + files: [createFile(`libs/impl-domain2/src/index.ts`)], + }, }, impl2Name: { name: 'impl2Name', @@ -211,8 +211,8 @@ describe('Enforce Module Boundaries', () => { tags: ['impl', 'domain1'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/impl2/src/index.ts`)] - } + files: [createFile(`libs/impl2/src/index.ts`)], + }, }, implName: { name: 'implName', @@ -222,8 +222,8 @@ describe('Enforce Module Boundaries', () => { tags: ['impl', 'domain1'], implicitDependencies: [], architect: {}, - files: [createFile(`libs/impl/src/index.ts`)] - } + files: [createFile(`libs/impl/src/index.ts`)], + }, }, untaggedName: { name: 'untaggedName', @@ -233,11 +233,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/untagged/src/index.ts`)] - } - } + files: [createFile(`libs/untagged/src/index.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, }; const depConstraints = { @@ -245,8 +245,8 @@ describe('Enforce Module Boundaries', () => { { sourceTag: 'api', onlyDependOnLibsWithTags: ['api'] }, { sourceTag: 'impl', onlyDependOnLibsWithTags: ['api', 'impl'] }, { sourceTag: 'domain1', onlyDependOnLibsWithTags: ['domain1'] }, - { sourceTag: 'domain2', onlyDependOnLibsWithTags: ['domain2'] } - ] + { sourceTag: 'domain2', onlyDependOnLibsWithTags: ['domain2'] }, + ], }; beforeEach(() => { @@ -355,7 +355,7 @@ describe('Enforce Module Boundaries', () => { it('should support wild cards', () => { const failures = runRule( { - depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }] + depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }], }, `${process.cwd()}/proj/libs/api/src/index.ts`, ` @@ -386,12 +386,12 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`libs/mylib/src/main.ts`), - createFile(`libs/mylib/other.ts`) - ] - } - } + createFile(`libs/mylib/other.ts`), + ], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toEqual(0); @@ -414,12 +414,12 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`libs/mylib/src/main.ts`), - createFile(`libs/mylib/other/index.ts`) - ] - } - } + createFile(`libs/mylib/other/index.ts`), + ], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toEqual(0); @@ -440,8 +440,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, otherName: { name: 'otherName', @@ -451,11 +451,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/other/src/index.ts')] - } - } + files: [createFile('libs/other/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures[0].getFailure()).toEqual( @@ -479,8 +479,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, otherName: { name: 'otherName', @@ -490,11 +490,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile('libs/other/src/index.ts')] - } - } + files: [createFile('libs/other/src/index.ts')], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures[0].getFailure()).toEqual( @@ -520,12 +520,12 @@ describe('Enforce Module Boundaries', () => { architect: {}, files: [ createFile(`libs/mylib/src/main.ts`), - createFile(`libs/mylib/src/other.ts`) - ] - } - } + createFile(`libs/mylib/src/other.ts`), + ], + }, + }, }, - dependencies: {} + dependencies: {}, } ); @@ -552,8 +552,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, utils: { name: 'utils', @@ -563,11 +563,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/utils/a.ts`)] - } - } + files: [createFile(`libs/utils/a.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toEqual(0); @@ -588,8 +588,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, otherName: { name: 'otherName', @@ -599,19 +599,19 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/other/index.ts`)] - } - } + files: [createFile(`libs/other/index.ts`)], + }, + }, }, dependencies: { mylibName: [ { source: 'mylibName', target: 'otherName', - type: DependencyType.dynamic - } - ] - } + type: DependencyType.dynamic, + }, + ], + }, } ); expect(failures[0].getFailure()).toEqual( @@ -634,8 +634,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, myappName: { name: 'myappName', @@ -645,11 +645,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`apps/myapp/src/index.ts`)] - } - } + files: [createFile(`apps/myapp/src/index.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures[0].getFailure()).toEqual('imports of apps are forbidden'); @@ -670,8 +670,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, anotherlibName: { name: 'anotherlibName', @@ -681,8 +681,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/anotherlib/src/main.ts`)] - } + files: [createFile(`libs/anotherlib/src/main.ts`)], + }, }, myappName: { name: 'myappName', @@ -692,19 +692,19 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`apps/myapp/src/index.ts`)] - } - } + files: [createFile(`apps/myapp/src/index.ts`)], + }, + }, }, dependencies: { mylibName: [ { source: 'mylibName', target: 'anotherlibName', - type: DependencyType.static - } - ] - } + type: DependencyType.static, + }, + ], + }, } ); expect(failures[0].getFailure()).toEqual( @@ -727,8 +727,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/mylib/src/main.ts`)] - } + files: [createFile(`libs/mylib/src/main.ts`)], + }, }, anotherlibName: { name: 'anotherlibName', @@ -738,8 +738,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/anotherlib/src/main.ts`)] - } + files: [createFile(`libs/anotherlib/src/main.ts`)], + }, }, badcirclelibName: { name: 'badcirclelibName', @@ -749,8 +749,8 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/badcirclelib/src/main.ts`)] - } + files: [createFile(`libs/badcirclelib/src/main.ts`)], + }, }, myappName: { name: 'myappName', @@ -760,33 +760,33 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`apps/myapp/index.ts`)] - } - } + files: [createFile(`apps/myapp/index.ts`)], + }, + }, }, dependencies: { mylibName: [ { source: 'mylibName', target: 'badcirclelibName', - type: DependencyType.static - } + type: DependencyType.static, + }, ], badcirclelibName: [ { source: 'badcirclelibName', target: 'anotherlibName', - type: DependencyType.static - } + type: DependencyType.static, + }, ], anotherlibName: [ { source: 'anotherlibName', target: 'mylibName', - type: DependencyType.static - } - ] - } + type: DependencyType.static, + }, + ], + }, } ); expect(failures[0].getFailure()).toEqual( @@ -798,7 +798,7 @@ describe('Enforce Module Boundaries', () => { it('should ignore the buildable library verification if the enforceBuildableLibDependency is set to false', () => { const failures = runRule( { - enforceBuildableLibDependency: false + enforceBuildableLibDependency: false, }, `${process.cwd()}/proj/libs/buildableLib/src/main.ts`, 'import "@mycompany/nonBuildableLib"', @@ -814,11 +814,11 @@ describe('Enforce Module Boundaries', () => { architect: { build: { // defines a buildable lib - builder: '@angular-devkit/build-ng-packagr:build' - } + builder: '@angular-devkit/build-ng-packagr:build', + }, }, - files: [createFile(`libs/buildableLib/src/main.ts`)] - } + files: [createFile(`libs/buildableLib/src/main.ts`)], + }, }, nonBuildableLib: { name: 'nonBuildableLib', @@ -828,11 +828,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/nonBuildableLib/src/main.ts`)] - } - } + files: [createFile(`libs/nonBuildableLib/src/main.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toBe(0); @@ -841,7 +841,7 @@ describe('Enforce Module Boundaries', () => { it('should error when buildable libraries import non-buildable libraries', () => { const failures = runRule( { - enforceBuildableLibDependency: true + enforceBuildableLibDependency: true, }, `${process.cwd()}/proj/libs/buildableLib/src/main.ts`, 'import "@mycompany/nonBuildableLib"', @@ -857,11 +857,11 @@ describe('Enforce Module Boundaries', () => { architect: { build: { // defines a buildable lib - builder: '@angular-devkit/build-ng-packagr:build' - } + builder: '@angular-devkit/build-ng-packagr:build', + }, }, - files: [createFile(`libs/buildableLib/src/main.ts`)] - } + files: [createFile(`libs/buildableLib/src/main.ts`)], + }, }, nonBuildableLib: { name: 'nonBuildableLib', @@ -871,11 +871,11 @@ describe('Enforce Module Boundaries', () => { tags: [], implicitDependencies: [], architect: {}, - files: [createFile(`libs/nonBuildableLib/src/main.ts`)] - } - } + files: [createFile(`libs/nonBuildableLib/src/main.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures[0].getFailure()).toEqual( @@ -886,7 +886,7 @@ describe('Enforce Module Boundaries', () => { it('should not error when buildable libraries import another buildable libraries', () => { const failures = runRule( { - enforceBuildableLibDependency: true + enforceBuildableLibDependency: true, }, `${process.cwd()}/proj/libs/buildableLib/src/main.ts`, 'import "@mycompany/nonBuildableLib"', @@ -902,11 +902,11 @@ describe('Enforce Module Boundaries', () => { architect: { build: { // defines a buildable lib - builder: '@angular-devkit/build-ng-packagr:build' - } + builder: '@angular-devkit/build-ng-packagr:build', + }, }, - files: [createFile(`libs/buildableLib/src/main.ts`)] - } + files: [createFile(`libs/buildableLib/src/main.ts`)], + }, }, anotherBuildableLib: { name: 'anotherBuildableLib', @@ -918,14 +918,14 @@ describe('Enforce Module Boundaries', () => { architect: { build: { // defines a buildable lib - builder: '@angular-devkit/build-ng-packagr:build' - } + builder: '@angular-devkit/build-ng-packagr:build', + }, }, - files: [createFile(`libs/anotherBuildableLib/src/main.ts`)] - } - } + files: [createFile(`libs/anotherBuildableLib/src/main.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toBe(0); @@ -934,7 +934,7 @@ describe('Enforce Module Boundaries', () => { it('should ignore the buildable library verification if no architect is specified', () => { const failures = runRule( { - enforceBuildableLibDependency: true + enforceBuildableLibDependency: true, }, `${process.cwd()}/proj/libs/buildableLib/src/main.ts`, 'import "@mycompany/nonBuildableLib"', @@ -947,8 +947,8 @@ describe('Enforce Module Boundaries', () => { root: 'libs/buildableLib', tags: [], implicitDependencies: [], - files: [createFile(`libs/buildableLib/src/main.ts`)] - } + files: [createFile(`libs/buildableLib/src/main.ts`)], + }, }, nonBuildableLib: { name: 'nonBuildableLib', @@ -957,11 +957,11 @@ describe('Enforce Module Boundaries', () => { root: 'libs/nonBuildableLib', tags: [], implicitDependencies: [], - files: [createFile(`libs/nonBuildableLib/src/main.ts`)] - } - } + files: [createFile(`libs/nonBuildableLib/src/main.ts`)], + }, + }, }, - dependencies: {} + dependencies: {}, } ); expect(failures.length).toBe(0); @@ -982,7 +982,7 @@ function runRule( const options: any = { ruleArguments: [ruleArguments], ruleSeverity: 'error', - ruleName: 'enforceModuleBoundaries' + ruleName: 'enforceModuleBoundaries', }; const sourceFile = ts.createSourceFile( diff --git a/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.ts b/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.ts index ef86a1b712a83..20271441a7632 100644 --- a/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.ts +++ b/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.ts @@ -4,7 +4,7 @@ import * as ts from 'typescript'; import { createProjectGraph, ProjectGraph, - ProjectGraphNode + ProjectGraphNode, } from '../core/project-graph'; import { appRootPath } from '../utils/app-root'; import { @@ -20,14 +20,14 @@ import { isRelativeImportIntoAnotherProject, matchImportWithWildcard, onlyLoadChildren, - hasArchitectBuildBuilder + hasArchitectBuildBuilder, } from '../utils/runtime-lint-utils'; import { normalize } from '@angular-devkit/core'; import { ProjectType } from '../core/project-graph'; import { normalizedProjectRoot, readNxJson, - readWorkspaceJson + readWorkspaceJson, } from '@nrwl/workspace/src/core/file-utils'; import { TargetProjectLocator } from '../core/target-project-locator'; @@ -94,7 +94,7 @@ class EnforceModuleBoundariesWalker extends Lint.RuleWalker { super(sourceFile, options); this.allow = Array.isArray(this.getOptions()[0].allow) - ? this.getOptions()[0].allow.map(a => `${a}`) + ? this.getOptions()[0].allow.map((a) => `${a}`) : []; this.depConstraints = Array.isArray(this.getOptions()[0].depConstraints) @@ -111,7 +111,7 @@ class EnforceModuleBoundariesWalker extends Lint.RuleWalker { .substring(1, node.moduleSpecifier.getText().length - 1); // whitelisted import - if (this.allow.some(a => matchImportWithWildcard(a, imp))) { + if (this.allow.some((a) => matchImportWithWildcard(a, imp))) { super.visitImportDeclaration(node); return; } @@ -243,7 +243,7 @@ class EnforceModuleBoundariesWalker extends Lint.RuleWalker { ) ) { const allowedTags = constraint.onlyDependOnLibsWithTags - .map(s => `"${s}"`) + .map((s) => `"${s}"`) .join(', '); const error = `A project tagged with "${constraint.sourceTag}" can only depend on libs tagged with ${allowedTags}`; this.addFailureAt(node.getStart(), node.getWidth(), error); diff --git a/packages/workspace/src/utils/ast-utils.spec.ts b/packages/workspace/src/utils/ast-utils.spec.ts index 52ad91b051001..02b28e501b176 100644 --- a/packages/workspace/src/utils/ast-utils.spec.ts +++ b/packages/workspace/src/utils/ast-utils.spec.ts @@ -2,11 +2,11 @@ import { readJsonInTree, renameSyncInTree, renameDirSyncInTree, - addDepsToPackageJson + addDepsToPackageJson, } from './ast-utils'; import { SchematicTestRunner, - UnitTestTree + UnitTestTree, } from '@angular-devkit/schematics/testing'; import { join } from 'path'; import { Tree, SchematicContext, TaskId } from '@angular-devkit/schematics'; @@ -23,11 +23,11 @@ describe('readJsonInTree', () => { tree.create( 'data.json', serializeJson({ - data: 'data' + data: 'data', }) ); expect(readJsonInTree(tree, 'data.json')).toEqual({ - data: 'data' + data: 'data', }); }); @@ -65,7 +65,7 @@ describe('renameSyncInTree', () => { it('should rename a file in the tree', () => { const content = 'my content'; tree.create('/a', content); - renameSyncInTree(tree, '/a', '/b', err => { + renameSyncInTree(tree, '/a', '/b', (err) => { expect(err).toBeFalsy(); expect(content).toEqual(tree.readContent('/b')); }); @@ -74,7 +74,7 @@ describe('renameSyncInTree', () => { it('should rename a file in the tree to a nested dir', () => { const content = 'my content'; tree.create('/a', content); - renameSyncInTree(tree, '/a', '/x/y/z/b', err => { + renameSyncInTree(tree, '/a', '/x/y/z/b', (err) => { expect(err).toBeFalsy(); expect(content).toEqual(tree.readContent('/x/y/z/b')); }); @@ -92,7 +92,7 @@ describe('renameDirSyncInTree', () => { const content = 'my content'; tree.create('/dir/a', content); tree.create('/dir/b', content); - renameDirSyncInTree(tree, 'dir', '/newdir', err => { + renameDirSyncInTree(tree, 'dir', '/newdir', (err) => { expect(err).toBeFalsy(); expect(tree.files).toContain('/newdir/a'); expect(tree.files).toContain('/newdir/b'); @@ -109,7 +109,7 @@ describe('renameDirSyncInTree', () => { tree.create('/dir/sub1/d', content); tree.create('/dir/sub1/sub2/e', content); tree.create('/dir/sub1/sub2/f', content); - renameDirSyncInTree(tree, 'dir', '/newdir', err => { + renameDirSyncInTree(tree, 'dir', '/newdir', (err) => { expect(err).toBeFalsy(); expect(tree.files).toContain('/newdir/a'); expect(tree.files).toContain('/newdir/b'); @@ -137,7 +137,7 @@ describe('addDepsToPackageJson', () => { it('should not update the package.json if dependencies have already been added', async () => { const devDeps = { - '@nrwl/jest': '1.2.3' + '@nrwl/jest': '1.2.3', }; appTree.overwrite( @@ -145,8 +145,8 @@ describe('addDepsToPackageJson', () => { JSON.stringify({ dependencies: {}, devDependencies: { - ...devDeps - } + ...devDeps, + }, }) ); @@ -159,14 +159,14 @@ describe('addDepsToPackageJson', () => { .toPromise(); expect( - testRunner.tasks.find(x => x.name === 'node-package') + testRunner.tasks.find((x) => x.name === 'node-package') ).not.toBeDefined(); }); it('should update the package.json if some of the dependencies are missing', async () => { const devDeps = { '@nrwl/jest': '1.2.3', - '@nrwl/workspace': '1.1.1' + '@nrwl/workspace': '1.1.1', }; appTree.overwrite( @@ -174,8 +174,8 @@ describe('addDepsToPackageJson', () => { JSON.stringify({ dependencies: {}, devDependencies: { - '@nrwl/jest': '1.2.3' - } + '@nrwl/jest': '1.2.3', + }, }) ); @@ -187,6 +187,8 @@ describe('addDepsToPackageJson', () => { }, appTree) .toPromise(); - expect(testRunner.tasks.find(x => x.name === 'node-package')).toBeDefined(); + expect( + testRunner.tasks.find((x) => x.name === 'node-package') + ).toBeDefined(); }); }); diff --git a/packages/workspace/src/utils/ast-utils.ts b/packages/workspace/src/utils/ast-utils.ts index b712a7aeb18ba..049bcdc3d7562 100644 --- a/packages/workspace/src/utils/ast-utils.ts +++ b/packages/workspace/src/utils/ast-utils.ts @@ -15,7 +15,7 @@ import { Source, mergeWith, apply, - forEach + forEach, } from '@angular-devkit/schematics'; import * as ts from 'typescript'; import * as stripJsonComments from 'strip-json-comments'; @@ -24,7 +24,7 @@ import { getWorkspacePath } from './cli-config-utils'; import { createProjectGraph, onlyWorkspaceProjects, - ProjectGraph + ProjectGraph, } from '../core/project-graph'; import { FileData } from '../core/file-utils'; import { extname, join, normalize, Path } from '@angular-devkit/core'; @@ -48,9 +48,7 @@ function insertAfterLastOccurrence( throw new Error(); } if (syntaxKind) { - lastItem = findNodes(lastItem, syntaxKind) - .sort(nodesByPosition) - .pop(); + lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop(); } if (!lastItem && fallbackPos == undefined) { throw new Error( @@ -81,7 +79,7 @@ export function findNodes( } if (max > 0) { for (const child of node.getChildren()) { - findNodes(child, kind, max).forEach(node => { + findNodes(child, kind, max).forEach((node) => { if (max > 0) { arr.push(node); } @@ -149,7 +147,7 @@ export class InsertChange implements Change { } apply(host: any) { - return host.read(this.path).then(content => { + return host.read(this.path).then((content) => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos); @@ -176,7 +174,7 @@ export class RemoveChange implements Change { } apply(host: any): Promise { - return host.read(this.path).then(content => { + return host.read(this.path).then((content) => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos + this.toRemove.length); return host.write(this.path, `${prefix}${suffix}`); @@ -203,7 +201,7 @@ export class ReplaceChange implements Change { } apply(host: any): Promise { - return host.read(this.path).then(content => { + return host.read(this.path).then((content) => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos + this.oldText.length); const text = content.substring(this.pos, this.pos + this.oldText.length); @@ -224,7 +222,7 @@ export function addParameterToConstructor( ): Change[] { const clazz = findClass(source, opts.className); const constructor = clazz.members.filter( - m => m.kind === ts.SyntaxKind.Constructor + (m) => m.kind === ts.SyntaxKind.Constructor )[0]; if (constructor) { throw new Error('Should be tested'); @@ -233,7 +231,7 @@ export function addParameterToConstructor( return addMethod(source, modulePath, { className: opts.className, methodHeader, - body: null + body: null, }); } } @@ -266,7 +264,7 @@ export function findClass( const clazz = ( nodes.filter( - n => + (n) => n.kind === ts.SyntaxKind.ClassDeclaration && (n).name.text === className )[0] @@ -287,7 +285,7 @@ export function offset( const lines = text .trim() .split('\n') - .map(line => { + .map((line) => { let tabs = ''; for (let c = 0; c < numberOfTabs; ++c) { tabs += ' '; @@ -331,7 +329,7 @@ export function getImport( .replace('{', '') .replace('}', '') .split(',') - .map(q => q.trim()); + .map((q) => q.trim()); return { moduleSpec, bindings }; }); } @@ -345,7 +343,7 @@ export function addGlobal( if (allImports.length > 0) { const lastImport = allImports[allImports.length - 1]; return [ - new InsertChange(modulePath, lastImport.end + 1, `\n${statement}\n`) + new InsertChange(modulePath, lastImport.end + 1, `\n${statement}\n`), ]; } else { return [new InsertChange(modulePath, 0, `${statement}\n`)]; @@ -407,21 +405,21 @@ export function getProjectGraphFromHost(host: Tree): ProjectGraph { const mtime = +Date.now(); workspaceFiles.push( - ...allFilesInDirInHost(host, normalize(''), { recursive: false }).map(f => + ...allFilesInDirInHost(host, normalize(''), { recursive: false }).map((f) => getFileDataInHost(host, f, mtime) ) ); workspaceFiles.push( - ...allFilesInDirInHost(host, normalize('tools')).map(f => + ...allFilesInDirInHost(host, normalize('tools')).map((f) => getFileDataInHost(host, f, mtime) ) ); // Add files for workspace projects - Object.keys(workspaceJson.projects).forEach(projectName => { + Object.keys(workspaceJson.projects).forEach((projectName) => { const project = workspaceJson.projects[projectName]; workspaceFiles.push( - ...allFilesInDirInHost(host, normalize(project.root)).map(f => + ...allFilesInDirInHost(host, normalize(project.root)).map((f) => getFileDataInHost(host, f, mtime) ) ); @@ -440,7 +438,7 @@ export function getFileDataInHost( return { file: path, ext: extname(normalize(path)), - mtime + mtime, }; } @@ -453,7 +451,7 @@ export function allFilesInDirInHost( ): Path[] { const dir = host.getDir(path); const res: Path[] = []; - dir.subfiles.forEach(p => { + dir.subfiles.forEach((p) => { res.push(join(path, p)); }); @@ -461,7 +459,7 @@ export function allFilesInDirInHost( return res; } - dir.subdirs.forEach(p => { + dir.subdirs.forEach((p) => { res.push(...allFilesInDirInHost(host, join(path, p))); }); return res; @@ -524,9 +522,9 @@ export function addProjectToNxJsonInTree( options: NxJsonProjectConfig ): Rule { const defaultOptions = { - tags: [] + tags: [], }; - return updateNxJsonInTree(json => { + return updateNxJsonInTree((json) => { json.projects[projectName] = { ...defaultOptions, ...options }; return json; }); @@ -550,13 +548,13 @@ function requiresAddingOfPackages(packageJsonFile, deps, devDeps): boolean { if (Object.keys(deps).length > 0) { needsDepsUpdate = Object.keys(deps).some( - entry => !packageJsonFile.dependencies[entry] + (entry) => !packageJsonFile.dependencies[entry] ); } if (Object.keys(devDeps).length > 0) { needsDevDepsUpdate = Object.keys(devDeps).some( - entry => !packageJsonFile.devDependencies[entry] + (entry) => !packageJsonFile.devDependencies[entry] ); } @@ -586,19 +584,19 @@ export function addDepsToPackageJson( json.dependencies = { ...(json.dependencies || {}), ...deps, - ...(json.dependencies || {}) + ...(json.dependencies || {}), }; json.devDependencies = { ...(json.devDependencies || {}), ...devDeps, - ...(json.devDependencies || {}) + ...(json.devDependencies || {}), }; return json; }), addInstallTask({ - skipInstall: !addInstall - }) + skipInstall: !addInstall, + }), ]); } else { return noop(); @@ -615,17 +613,17 @@ export function updatePackageJsonDependencies( updateJsonInTree('package.json', (json, context: SchematicContext) => { json.dependencies = { ...(json.dependencies || {}), - ...deps + ...deps, }; json.devDependencies = { ...(json.devDependencies || {}), - ...devDeps + ...devDeps, }; return json; }), addInstallTask({ - skipInstall: !addInstall - }) + skipInstall: !addInstall, + }), ]); } @@ -658,21 +656,21 @@ export function insertImport( const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration); // get nodes that map to import statements from the file fileName - const relevantImports = allImports.filter(node => { + 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 as ts.StringLiteral).text); + .filter((child) => child.kind === ts.SyntaxKind.StringLiteral) + .map((n) => (n as ts.StringLiteral).text); - return importFiles.filter(file => file === fileName).length === 1; + return importFiles.filter((file) => file === fileName).length === 1; }); if (relevantImports.length > 0) { let importsAsterisk = false; // imports from import file const imports: ts.Node[] = []; - relevantImports.forEach(n => { + relevantImports.forEach((n) => { Array.prototype.push.apply( imports, findNodes(n, ts.SyntaxKind.Identifier) @@ -688,7 +686,7 @@ export function insertImport( } const importTextNodes = imports.filter( - n => (n as ts.Identifier).text === symbolName + (n) => (n as ts.Identifier).text === symbolName ); // insert import if it's not there @@ -749,7 +747,7 @@ export function replaceNodeValue( node.getStart(node.getSourceFile()), node.getFullText(), content - ) + ), ]); } @@ -780,7 +778,7 @@ export function renameDirSyncInTree( cb(`Path: ${from} does not exist`); return; } - dir.visit(path => { + dir.visit((path) => { const destination = path.replace(from, to); renameFile(tree, path, destination); }); @@ -808,12 +806,12 @@ export function applyWithSkipExisting(source: Source, rules: Rule[]): Rule { const rule = mergeWith( apply(source, [ ...rules, - forEach(fileEntry => { + forEach((fileEntry) => { if (tree.exists(fileEntry.path)) { return null; } return fileEntry; - }) + }), ]) ); diff --git a/packages/workspace/src/utils/buildable-libs-utils.ts b/packages/workspace/src/utils/buildable-libs-utils.ts index 876f801fc444d..0415fefc0c755 100644 --- a/packages/workspace/src/utils/buildable-libs-utils.ts +++ b/packages/workspace/src/utils/buildable-libs-utils.ts @@ -1,14 +1,14 @@ import { ProjectGraph, ProjectGraphNode, - ProjectType + ProjectType, } from '../core/project-graph'; import { BuilderContext } from '@angular-devkit/architect'; import { join, resolve, dirname, relative } from 'path'; import { fileExists, readJsonFile, - writeJsonFile + writeJsonFile, } from '@nrwl/workspace/src/utils/fileutils'; import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { getOutputsForTargetAndConfiguration } from '@nrwl/workspace/src/tasks-runner/utils'; @@ -40,7 +40,7 @@ export function calculateProjectDependencies( projGraph, [] ) - .map(dep => { + .map((dep) => { const depNode = projGraph.nodes[dep]; if ( depNode.type === ProjectType.lib && @@ -57,13 +57,13 @@ export function calculateProjectDependencies( context.target.configuration, depNode ), - node: depNode + node: depNode, }; } else { return null; } }) - .filter(x => !!x); + .filter((x) => !!x); return { target, dependencies }; } @@ -72,7 +72,7 @@ function recursivelyCollectDependencies( projGraph: ProjectGraph, acc: string[] ) { - (projGraph.dependencies[project] || []).forEach(dependency => { + (projGraph.dependencies[project] || []).forEach((dependency) => { if (acc.indexOf(dependency.target) === -1) { acc.push(dependency.target); recursivelyCollectDependencies(dependency.target, projGraph, acc); @@ -169,8 +169,8 @@ export function checkDependentProjectsHaveBeenBuilt( const depLibsToBuildFirst: DependentBuildableProjectNode[] = []; // verify whether all dependent libraries have been built - projectDependencies.forEach(dep => { - const paths = dep.outputs.map(p => + projectDependencies.forEach((dep) => { + const paths = dep.outputs.map((p) => join(context.workspaceRoot, p, 'package.json') ); @@ -184,7 +184,7 @@ export function checkDependentProjectsHaveBeenBuilt( Some of the project ${ context.target.project }'s dependencies have not been built yet. Please build these libraries before: - ${depLibsToBuildFirst.map(x => ` - ${x.node.name}`).join('\n')} + ${depLibsToBuildFirst.map((x) => ` - ${x.node.name}`).join('\n')} Try: nx run ${context.target.project}:${context.target.target} --with-deps `); @@ -199,7 +199,7 @@ export function updatePaths( dependencies: DependentBuildableProjectNode[], paths: { [k: string]: string[] } ) { - dependencies.forEach(dep => { + dependencies.forEach((dep) => { if (dep.outputs && dep.outputs.length > 0) { paths[dep.name] = dep.outputs; } @@ -233,7 +233,7 @@ export function updateBuildableProjectPackageJsonDependencies( packageJson.dependencies = packageJson.dependencies || {}; let updatePackageJson = false; - dependencies.forEach(entry => { + dependencies.forEach((entry) => { if ( !hasDependency(packageJson, 'dependencies', entry.name) && !hasDependency(packageJson, 'devDependencies', entry.name) && diff --git a/packages/workspace/src/utils/cli-config-utils.ts b/packages/workspace/src/utils/cli-config-utils.ts index 33000bf76f96c..dbeb82758bda6 100644 --- a/packages/workspace/src/utils/cli-config-utils.ts +++ b/packages/workspace/src/utils/cli-config-utils.ts @@ -4,7 +4,7 @@ import { NxJson } from '@nrwl/workspace/src/core/shared-interfaces'; export function getWorkspacePath(host: Tree) { const possibleFiles = ['/workspace.json', '/angular.json', '/.angular.json']; - return possibleFiles.filter(path => host.exists(path))[0]; + return possibleFiles.filter((path) => host.exists(path))[0]; } export function getNpmScope(host: Tree) { @@ -16,7 +16,7 @@ export function parseTarget(targetString: string) { return { project, target, - config + config, }; } @@ -26,7 +26,7 @@ export function editTarget(targetString: string, callback) { } export function serializeTarget({ project, target, config }) { - return [project, target, config].filter(part => !!part).join(':'); + return [project, target, config].filter((part) => !!part).join(':'); } export function replaceAppNameWithPath( @@ -52,12 +52,12 @@ export function replaceAppNameWithPath( return node; } } else if (Array.isArray(node)) { - return node.map(j => replaceAppNameWithPath(j, appName, root)); + return node.map((j) => replaceAppNameWithPath(j, appName, root)); } else if (typeof node === 'object' && node) { const forbiddenPropertyList: string[] = [ 'prefix', 'builder', - 'browserTarget' + 'browserTarget', ]; // Some of the properties should not be renamed return Object.keys(node).reduce( (m, c) => ( diff --git a/packages/workspace/src/utils/common.ts b/packages/workspace/src/utils/common.ts index 14431d93a9781..2681a282bba77 100644 --- a/packages/workspace/src/utils/common.ts +++ b/packages/workspace/src/utils/common.ts @@ -14,7 +14,7 @@ export function offsetFromRoot(fullPathToSourceDir: string): string { } export const DEFAULT_NRWL_PRETTIER_CONFIG = { - singleQuote: true + singleQuote: true, }; export interface ExistingPrettierConfig { @@ -28,20 +28,20 @@ export function resolveUserExistingPrettierConfig(): Promise { + transform: (result) => { if (result && result.config) { delete result.config.$schema; } return result; - } + }, }); - return Promise.resolve(explorer.load(process.cwd())).then(result => { + return Promise.resolve(explorer.load(process.cwd())).then((result) => { if (!result) { return null; } return { sourceFilepath: result.filepath, - config: result.config + config: result.config, }; }); } diff --git a/packages/workspace/src/utils/detect-package-manager.ts b/packages/workspace/src/utils/detect-package-manager.ts index dc51e25ea4d3a..b68af146acdd8 100644 --- a/packages/workspace/src/utils/detect-package-manager.ts +++ b/packages/workspace/src/utils/detect-package-manager.ts @@ -4,7 +4,7 @@ import { fileExists } from './fileutils'; export function detectPackageManager(): string { try { const output = execSync(`nx config cli.packageManager`, { - stdio: ['ignore', 'pipe', 'ignore'] + stdio: ['ignore', 'pipe', 'ignore'], }) .toString() .trim() diff --git a/packages/workspace/src/utils/fileutils.spec.ts b/packages/workspace/src/utils/fileutils.spec.ts index bcb63601d59de..569be9a37b37e 100644 --- a/packages/workspace/src/utils/fileutils.spec.ts +++ b/packages/workspace/src/utils/fileutils.spec.ts @@ -21,7 +21,7 @@ describe('fileutils', () => { './apps/demo/src/index.ts': 'console.log("hello");', './apps/demo/tmp.txt': '...', './apps/demo/tmp.js': 'console.log("tmp")', - './workspace.json': '{}' + './workspace.json': '{}', }, '/root' ); diff --git a/packages/workspace/src/utils/fileutils.ts b/packages/workspace/src/utils/fileutils.ts index a7a293444e3af..bdd5b33522cb1 100644 --- a/packages/workspace/src/utils/fileutils.ts +++ b/packages/workspace/src/utils/fileutils.ts @@ -55,7 +55,7 @@ export function copyFile(file: string, target: string) { const source = fs.createReadStream(file); const dest = fs.createWriteStream(path.resolve(target, f)); source.pipe(dest); - source.on('error', e => console.error(e)); + source.on('error', (e) => console.error(e)); } export function directoryExists(name) { diff --git a/packages/workspace/src/utils/json-diff.spec.ts b/packages/workspace/src/utils/json-diff.spec.ts index 655030996fc72..032381884374a 100644 --- a/packages/workspace/src/utils/json-diff.spec.ts +++ b/packages/workspace/src/utils/json-diff.spec.ts @@ -15,50 +15,50 @@ describe('jsonDiff', () => { value: { lhs: { b: { - c: 1 - } + c: 1, + }, }, rhs: { b: { c: 2, - d: 2 - } - } - } + d: 2, + }, + }, + }, }, { type: DiffType.Modified, path: ['a', 'b'], value: { lhs: { - c: 1 + c: 1, }, rhs: { c: 2, - d: 2 - } - } + d: 2, + }, + }, }, { type: DiffType.Modified, path: ['a', 'b', 'c'], - value: { lhs: 1, rhs: 2 } + value: { lhs: 1, rhs: 2 }, }, { type: DiffType.Deleted, path: ['x'], - value: { lhs: 1, rhs: undefined } + value: { lhs: 1, rhs: undefined }, }, { type: DiffType.Added, path: ['y'], - value: { lhs: undefined, rhs: 2 } + value: { lhs: undefined, rhs: 2 }, }, { type: DiffType.Added, path: ['a', 'b', 'd'], - value: { lhs: undefined, rhs: 2 } - } + value: { lhs: undefined, rhs: 2 }, + }, ]) ); }); @@ -66,11 +66,11 @@ describe('jsonDiff', () => { it('should have diffs for objects as well', () => { const result = jsonDiff( { - a: { b: 0 } + a: { b: 0 }, }, { - a: { b: 1 } + a: { b: 1 }, } ); expect(result).toContainEqual({ @@ -78,43 +78,43 @@ describe('jsonDiff', () => { path: ['a'], value: { lhs: { - b: 0 + b: 0, }, rhs: { - b: 1 - } - } + b: 1, + }, + }, }); expect(result).toContainEqual({ type: DiffType.Modified, path: ['a', 'b'], value: { lhs: 0, - rhs: 1 - } + rhs: 1, + }, }); const result2 = jsonDiff( {}, { - a: {} + a: {}, } ); expect(result2).toContainEqual({ type: DiffType.Added, path: ['a'], - value: { lhs: undefined, rhs: {} } + value: { lhs: undefined, rhs: {} }, }); }); it('should work for added array values', () => { const result = jsonDiff( { - rules: undefined + rules: undefined, }, { - rules: ['rule1'] + rules: ['rule1'], } ); @@ -125,17 +125,17 @@ describe('jsonDiff', () => { path: ['rules'], value: { lhs: undefined, - rhs: ['rule1'] - } + rhs: ['rule1'], + }, }, { type: DiffType.Added, path: ['rules', '0'], value: { lhs: undefined, - rhs: 'rule1' - } - } + rhs: 'rule1', + }, + }, ]) ); }); @@ -143,10 +143,10 @@ describe('jsonDiff', () => { it('should work for added array items', () => { const result = jsonDiff( { - rules: ['rule1'] + rules: ['rule1'], }, { - rules: ['rule1', 'rule2'] + rules: ['rule1', 'rule2'], } ); @@ -157,17 +157,17 @@ describe('jsonDiff', () => { path: ['rules'], value: { lhs: ['rule1'], - rhs: ['rule1', 'rule2'] - } + rhs: ['rule1', 'rule2'], + }, }, { type: DiffType.Added, path: ['rules', '1'], value: { lhs: undefined, - rhs: 'rule2' - } - } + rhs: 'rule2', + }, + }, ]) ); }); @@ -177,33 +177,33 @@ describe('jsonDiff', () => { { dependencies: { 'happy-nrwl': '0.0.1', - 'not-awesome-nrwl': '0.0.1' - } + 'not-awesome-nrwl': '0.0.1', + }, }, { dependencies: { 'happy-nrwl': '0.0.2', - 'awesome-nrwl': '0.0.1' - } + 'awesome-nrwl': '0.0.1', + }, } ); expect(result).toContainEqual({ type: DiffType.Modified, path: ['dependencies', 'happy-nrwl'], - value: { lhs: '0.0.1', rhs: '0.0.2' } + value: { lhs: '0.0.1', rhs: '0.0.2' }, }); expect(result).toContainEqual({ type: DiffType.Deleted, path: ['dependencies', 'not-awesome-nrwl'], - value: { lhs: '0.0.1', rhs: undefined } + value: { lhs: '0.0.1', rhs: undefined }, }); expect(result).toContainEqual({ type: DiffType.Added, path: ['dependencies', 'awesome-nrwl'], - value: { lhs: undefined, rhs: '0.0.1' } + value: { lhs: undefined, rhs: '0.0.1' }, }); }); }); diff --git a/packages/workspace/src/utils/json-diff.ts b/packages/workspace/src/utils/json-diff.ts index 8dd9cc2be7122..a723ee63b7448 100644 --- a/packages/workspace/src/utils/json-diff.ts +++ b/packages/workspace/src/utils/json-diff.ts @@ -3,7 +3,7 @@ import { Change } from '../core/file-utils'; export enum DiffType { Deleted = 'JsonPropertyDeleted', Added = 'JsonPropertyAdded', - Modified = 'JsonPropertyModified' + Modified = 'JsonPropertyModified', } export interface JsonChange extends Change { @@ -36,8 +36,8 @@ export function jsonDiff(lhs: any, rhs: any): JsonChange[] { path, value: { lhs: lhsValue, - rhs: undefined - } + rhs: undefined, + }, }); } else if (!deepEquals(lhsValue, rhsValue)) { result.push({ @@ -45,8 +45,8 @@ export function jsonDiff(lhs: any, rhs: any): JsonChange[] { path, value: { lhs: lhsValue, - rhs: rhsValue - } + rhs: rhsValue, + }, }); } return typeof lhsValue === 'object' || Array.isArray(lhsValue); @@ -60,8 +60,8 @@ export function jsonDiff(lhs: any, rhs: any): JsonChange[] { path, value: { lhs: undefined, - rhs: rhsValue - } + rhs: rhsValue, + }, }); } return typeof rhsValue === 'object' || Array.isArray(rhsValue); @@ -79,7 +79,7 @@ export function walkJsonTree( if (!json || typeof json !== 'object') { return; } - Object.keys(json).forEach(key => { + Object.keys(json).forEach((key) => { const path = currPath.concat([key]); const shouldContinue = visitor(path, json[key]); if (shouldContinue) { diff --git a/packages/workspace/src/utils/lint.ts b/packages/workspace/src/utils/lint.ts index 1c8c36a4a7ac0..16b7b90b5e649 100644 --- a/packages/workspace/src/utils/lint.ts +++ b/packages/workspace/src/utils/lint.ts @@ -3,7 +3,7 @@ import { chain, Rule, Tree, - SchematicContext + SchematicContext, } from '@angular-devkit/schematics'; import { addDepsToPackageJson } from './ast-utils'; import { offsetFromRoot } from './common'; @@ -11,13 +11,13 @@ import { eslintVersion, typescriptESLintVersion, eslintConfigPrettierVersion, - nxVersion + nxVersion, } from './versions'; export const enum Linter { TsLint = 'tslint', EsLint = 'eslint', - None = 'none' + None = 'none', } export function generateProjectLint( @@ -30,8 +30,8 @@ export function generateProjectLint( builder: '@angular-devkit/build-angular:tslint', options: { tsConfig: [tsConfigPath], - exclude: ['**/node_modules/**', '!' + projectRoot + '/**'] - } + exclude: ['**/node_modules/**', '!' + projectRoot + '/**'], + }, }; } else if (linter === Linter.EsLint) { return { @@ -40,8 +40,8 @@ export function generateProjectLint( linter: 'eslint', config: projectRoot + '/.eslintrc', tsConfig: [tsConfigPath], - exclude: ['**/node_modules/**', '!' + projectRoot + '/**'] - } + exclude: ['**/node_modules/**', '!' + projectRoot + '/**'], + }, }; } else { return undefined; @@ -82,9 +82,9 @@ export function addLintFiles( extends: `${offsetFromRoot(projectRoot)}tslint.json`, // Include project files to be linted since the global one excludes all files. linterOptions: { - exclude: ['!**/*'] + exclude: ['!**/*'], }, - rules: {} + rules: {}, }) ); } @@ -102,7 +102,7 @@ export function addLintFiles( { ...(options.extraPackageDeps ? options.extraPackageDeps.dependencies - : {}) + : {}), }, { '@nrwl/eslint-plugin-nx': nxVersion, @@ -112,7 +112,7 @@ export function addLintFiles( 'eslint-config-prettier': eslintConfigPrettierVersion, ...(options.extraPackageDeps ? options.extraPackageDeps.devDependencies - : {}) + : {}), } ); }); @@ -131,12 +131,12 @@ export function addLintFiles( configJson = { rules: {}, ...options.localConfig, - extends: [...extendsOption, rootConfig] + extends: [...extendsOption, rootConfig], }; } else { configJson = { extends: rootConfig, - rules: {} + rules: {}, }; } // Include all project files to be linted (since they are turned off in the root eslintrc file). diff --git a/packages/workspace/src/utils/name-utils.ts b/packages/workspace/src/utils/name-utils.ts index 7a740d1d0dfa0..28c6d26d32cf5 100644 --- a/packages/workspace/src/utils/name-utils.ts +++ b/packages/workspace/src/utils/name-utils.ts @@ -15,7 +15,7 @@ export function names( name, className: toClassName(name), propertyName: toPropertyName(name), - fileName: toFileName(name) + fileName: toFileName(name), }; } @@ -34,7 +34,7 @@ export function toPropertyName(s: string): string { .replace(/(-|_|\.|\s)+(.)?/g, (_, __, chr) => chr ? chr.toUpperCase() : '' ) - .replace(/^([A-Z])/, m => m.toLowerCase()); + .replace(/^([A-Z])/, (m) => m.toLowerCase()); } /** diff --git a/packages/workspace/src/utils/output.ts b/packages/workspace/src/utils/output.ts index 680b518fdc7ac..16a833a51dbdc 100644 --- a/packages/workspace/src/utils/output.ts +++ b/packages/workspace/src/utils/output.ts @@ -46,7 +46,7 @@ class CLIOutput { * implementation. */ colors = { - gray: chalk.gray + gray: chalk.gray, }; bold = chalk.bold; underline = chalk.underline; @@ -57,7 +57,7 @@ class CLIOutput { private writeOutputTitle({ label, - title + title, }: { label?: string; title: string; @@ -76,7 +76,7 @@ class CLIOutput { return; } this.addNewline(); - bodyLines.forEach(bodyLine => this.writeToStdOut(' ' + bodyLine + '\n')); + bodyLines.forEach((bodyLine) => this.writeToStdOut(' ' + bodyLine + '\n')); } addNewline() { @@ -96,7 +96,7 @@ class CLIOutput { this.writeOutputTitle({ label: chalk.reset.inverse.bold.red(' ERROR '), - title: chalk.bold.red(title) + title: chalk.bold.red(title), }); this.writeOptionalOutputBody(bodyLines); @@ -122,7 +122,7 @@ class CLIOutput { this.writeOutputTitle({ label: chalk.reset.inverse.bold.yellow(' WARNING '), - title: chalk.bold.yellow(title) + title: chalk.bold.yellow(title), }); this.writeOptionalOutputBody(bodyLines); @@ -148,7 +148,7 @@ class CLIOutput { this.writeOutputTitle({ label: chalk.reset.inverse.bold.keyword('orange')(' NOTE '), - title: chalk.bold.keyword('orange')(title) + title: chalk.bold.keyword('orange')(title), }); this.writeOptionalOutputBody(bodyLines); @@ -161,7 +161,7 @@ class CLIOutput { this.writeOutputTitle({ label: chalk.reset.inverse.bold.green(' SUCCESS '), - title: chalk.bold.green(title) + title: chalk.bold.green(title), }); this.writeOptionalOutputBody(bodyLines); @@ -173,7 +173,7 @@ class CLIOutput { this.addNewline(); this.writeOutputTitle({ - title: message + title: message, }); this.addNewline(); @@ -191,7 +191,7 @@ class CLIOutput { this.addNewline(); this.writeOutputTitle({ - title: chalk.white(title) + title: chalk.white(title), }); this.writeOptionalOutputBody(bodyLines); diff --git a/packages/workspace/src/utils/plugins/community-plugins.ts b/packages/workspace/src/utils/plugins/community-plugins.ts index d84df2f85311b..b8eb35cc82541 100644 --- a/packages/workspace/src/utils/plugins/community-plugins.ts +++ b/packages/workspace/src/utils/plugins/community-plugins.ts @@ -20,23 +20,23 @@ export function listCommunityPlugins( ) { try { const installedPluginsMap: Set = new Set( - installedPlugins.map(p => p.name) + installedPlugins.map((p) => p.name) ); const availableCommunityPlugins = communityPlugins.filter( - p => !installedPluginsMap.has(p.name) + (p) => !installedPluginsMap.has(p.name) ); output.log({ title: `Community plugins:`, - bodyLines: availableCommunityPlugins.map(p => { + bodyLines: availableCommunityPlugins.map((p) => { return `${terminal.bold(p.name)} - ${p.description}`; - }) + }), }); } catch (error) { output.warn({ title: `Community plugins:`, - bodyLines: [`Error fetching plugins.`, error] + bodyLines: [`Error fetching plugins.`, error], }); } } diff --git a/packages/workspace/src/utils/plugins/core-plugins.ts b/packages/workspace/src/utils/plugins/core-plugins.ts index e79d45a57a6bc..2de09f2eec860 100644 --- a/packages/workspace/src/utils/plugins/core-plugins.ts +++ b/packages/workspace/src/utils/plugins/core-plugins.ts @@ -6,60 +6,60 @@ export function fetchCorePlugins() { const corePlugins: CorePlugin[] = [ { name: '@nrwl/angular', - capabilities: 'schematics' + capabilities: 'schematics', }, { name: '@nrwl/bazel', - capabilities: 'schematics' + capabilities: 'schematics', }, { name: '@nrwl/cypress', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/express', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/jest', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/linter', - capabilities: 'builders' + capabilities: 'builders', }, { name: '@nrwl/nest', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/next', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/node', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/nx-plugin', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/react', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/storybook', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/web', - capabilities: 'builders,schematics' + capabilities: 'builders,schematics', }, { name: '@nrwl/workspace', - capabilities: 'builders,schematics' - } + capabilities: 'builders,schematics', + }, ]; return corePlugins; } @@ -69,19 +69,19 @@ export function listCorePlugins( corePlugins: CorePlugin[] ) { const installedPluginsMap: Set = new Set( - installedPlugins.map(p => p.name) + installedPlugins.map((p) => p.name) ); const alsoAvailable = corePlugins.filter( - p => !installedPluginsMap.has(p.name) + (p) => !installedPluginsMap.has(p.name) ); if (alsoAvailable.length) { output.log({ title: `Also available:`, - bodyLines: alsoAvailable.map(p => { + bodyLines: alsoAvailable.map((p) => { return `${terminal.bold(p.name)} (${p.capabilities})`; - }) + }), }); } } diff --git a/packages/workspace/src/utils/plugins/index.ts b/packages/workspace/src/utils/plugins/index.ts index 959583e75fb65..007409e5443a7 100644 --- a/packages/workspace/src/utils/plugins/index.ts +++ b/packages/workspace/src/utils/plugins/index.ts @@ -1,13 +1,13 @@ export { fetchCommunityPlugins, - listCommunityPlugins + listCommunityPlugins, } from './community-plugins'; export { fetchCorePlugins, listCorePlugins } from './core-plugins'; export { getInstalledPluginsFromNodeModules, - listInstalledPlugins + listInstalledPlugins, } from './installed-plugins'; export { getPluginCapabilities, - listPluginCapabilities + listPluginCapabilities, } from './plugin-capabilities'; diff --git a/packages/workspace/src/utils/plugins/installed-plugins.ts b/packages/workspace/src/utils/plugins/installed-plugins.ts index 914807ea5f498..35690c04e9548 100644 --- a/packages/workspace/src/utils/plugins/installed-plugins.ts +++ b/packages/workspace/src/utils/plugins/installed-plugins.ts @@ -17,9 +17,9 @@ function getPackagesFromNodeModules( } const nodeModulesDir = path.join(workspaceRoot, 'node_modules'); - readdirSync(nodeModulesDir).forEach(npmPackageOrScope => { + readdirSync(nodeModulesDir).forEach((npmPackageOrScope) => { if (npmPackageOrScope.startsWith('@')) { - readdirSync(path.join(nodeModulesDir, npmPackageOrScope)).forEach(p => { + readdirSync(path.join(nodeModulesDir, npmPackageOrScope)).forEach((p) => { packageList.push(`${npmPackageOrScope}/${p}`); }); } else { @@ -35,24 +35,24 @@ export function getInstalledPluginsFromNodeModules( corePlugins: CorePlugin[], communityPlugins: CommunityPlugin[] ): Array { - const corePluginNames = corePlugins.map(p => p.name); - const communityPluginNames = communityPlugins.map(p => p.name); + const corePluginNames = corePlugins.map((p) => p.name); + const communityPluginNames = communityPlugins.map((p) => p.name); const packages = getPackagesFromNodeModules(workspaceRoot); return packages .filter( - name => + (name) => corePluginNames.indexOf(name) > -1 || communityPluginNames.indexOf(name) > -1 ) - .map(name => getPluginCapabilities(workspaceRoot, name)) - .filter(x => x && !!(x.schematics || x.builders)); + .map((name) => getPluginCapabilities(workspaceRoot, name)) + .filter((x) => x && !!(x.schematics || x.builders)); } export function listInstalledPlugins(installedPlugins: PluginCapabilities[]) { output.log({ title: `Installed plugins:`, - bodyLines: installedPlugins.map(p => { + bodyLines: installedPlugins.map((p) => { const capabilities = []; if (hasElements(p.builders)) { capabilities.push('builders'); @@ -61,6 +61,6 @@ export function listInstalledPlugins(installedPlugins: PluginCapabilities[]) { capabilities.push('schematics'); } return `${terminal.bold(p.name)} (${capabilities.join()})`; - }) + }), }); } diff --git a/packages/workspace/src/utils/plugins/plugin-capabilities.ts b/packages/workspace/src/utils/plugins/plugin-capabilities.ts index 1dfcc0e41fca7..fd688e795d47d 100644 --- a/packages/workspace/src/utils/plugins/plugin-capabilities.ts +++ b/packages/workspace/src/utils/plugins/plugin-capabilities.ts @@ -52,7 +52,7 @@ export function getPluginCapabilities( packageJson.schematics, 'schematics' ), - builders: tryGetCollection(pluginPath, packageJson.builders, 'builders') + builders: tryGetCollection(pluginPath, packageJson.builders, 'builders'), }; } catch { return null; @@ -66,8 +66,8 @@ export function listPluginCapabilities(pluginName: string) { output.note({ title: `${pluginName} is not currently installed`, bodyLines: [ - `Use "${getPackageManagerInstallCommand()} ${pluginName}" to add new capabilities` - ] + `Use "${getPackageManagerInstallCommand()} ${pluginName}" to add new capabilities`, + ], }); return; @@ -88,7 +88,7 @@ export function listPluginCapabilities(pluginName: string) { bodyLines.push(''); bodyLines.push( ...Object.keys(plugin.schematics).map( - name => + (name) => `${terminal.bold(name)} : ${plugin.schematics[name].description}` ) ); @@ -102,13 +102,14 @@ export function listPluginCapabilities(pluginName: string) { bodyLines.push(''); bodyLines.push( ...Object.keys(plugin.builders).map( - name => `${terminal.bold(name)} : ${plugin.builders[name].description}` + (name) => + `${terminal.bold(name)} : ${plugin.builders[name].description}` ) ); } output.log({ title: `Capabilities in ${plugin.name}:`, - bodyLines + bodyLines, }); } diff --git a/packages/workspace/src/utils/project-type.ts b/packages/workspace/src/utils/project-type.ts index a62c7ee024049..17417ade108b0 100644 --- a/packages/workspace/src/utils/project-type.ts +++ b/packages/workspace/src/utils/project-type.ts @@ -1,6 +1,6 @@ export enum ProjectType { Application = 'application', - Library = 'library' + Library = 'library', } export function projectRootDir(projectType: ProjectType) { diff --git a/packages/workspace/src/utils/rules/check-project-exists.spec.ts b/packages/workspace/src/utils/rules/check-project-exists.spec.ts index 29d07be544efa..79a1ae21d32b8 100644 --- a/packages/workspace/src/utils/rules/check-project-exists.spec.ts +++ b/packages/workspace/src/utils/rules/check-project-exists.spec.ts @@ -12,7 +12,7 @@ describe('checkProjectExists Rule', () => { it('should throw an error if the project does NOT exist', async () => { const schema = { - projectName: 'my-lib' + projectName: 'my-lib', }; await expect(callRule(checkProjectExists(schema), tree)).rejects.toThrow( @@ -24,7 +24,7 @@ describe('checkProjectExists Rule', () => { tree = await runSchematic('lib', { name: 'my-lib' }, tree); const schema = { - projectName: 'my-lib' + projectName: 'my-lib', }; await expect( diff --git a/packages/workspace/src/utils/rules/check-project-exists.ts b/packages/workspace/src/utils/rules/check-project-exists.ts index 49758fb5cabb9..021a6ca20283b 100644 --- a/packages/workspace/src/utils/rules/check-project-exists.ts +++ b/packages/workspace/src/utils/rules/check-project-exists.ts @@ -12,7 +12,7 @@ import { getWorkspace } from '../workspace'; export function checkProjectExists(schema: { projectName: string }): Rule { return (tree: Tree, _context: SchematicContext): Observable => { return from(getWorkspace(tree)).pipe( - map(workspace => { + map((workspace) => { if (!workspace.projects.has(schema.projectName)) { throw new Error( `Project not found in workspace: [${schema.projectName}]` diff --git a/packages/workspace/src/utils/rules/format-files.spec.ts b/packages/workspace/src/utils/rules/format-files.spec.ts index 52ff119efb6a5..27ca03a2bd9ae 100644 --- a/packages/workspace/src/utils/rules/format-files.spec.ts +++ b/packages/workspace/src/utils/rules/format-files.spec.ts @@ -14,14 +14,14 @@ describe('formatFiles', () => { '@nrwl/workspace', path.join(__dirname, '../../../collection.json') ); - spyOn(prettier, 'format').and.callFake(input => 'formatted :: ' + input); + spyOn(prettier, 'format').and.callFake((input) => 'formatted :: ' + input); tree = Tree.empty(); }); it('should format created files', async () => { spyOn(prettier, 'resolveConfig').and.returnValue( Promise.resolve({ - printWidth: 80 + printWidth: 80, }) ); tree.create('a.ts', 'const a=a'); @@ -30,7 +30,7 @@ describe('formatFiles', () => { .toPromise(); expect(prettier.format).toHaveBeenCalledWith('const a=a', { printWidth: 80, - filepath: appRoot.resolve('a.ts') + filepath: appRoot.resolve('a.ts'), }); expect(result.read('a.ts').toString()).toEqual('formatted :: const a=a'); }); @@ -38,7 +38,7 @@ describe('formatFiles', () => { it('should not format deleted files', async () => { spyOn(prettier, 'resolveConfig').and.returnValue( Promise.resolve({ - printWidth: 80 + printWidth: 80, }) ); tree.create('b.ts', ''); @@ -58,7 +58,7 @@ describe('formatFiles', () => { .callRule(formatFiles(), tree) .toPromise(); expect(prettier.format).toHaveBeenCalledWith('const a=b', { - filepath: appRoot.resolve('a.ts') + filepath: appRoot.resolve('a.ts'), }); expect(result.read('a.ts').toString()).toEqual('formatted :: const a=b'); }); @@ -71,7 +71,7 @@ describe('formatFiles', () => { .callRule(formatFiles(), tree) .toPromise(); expect(prettier.format).toHaveBeenCalledWith('const a=a', { - filepath: appRoot.resolve('b.ts') + filepath: appRoot.resolve('b.ts'), }); expect(result.read('b.ts').toString()).toEqual('formatted :: const a=a'); }); @@ -80,21 +80,21 @@ describe('formatFiles', () => { it('should not format created files', async () => { spyOn(prettier, 'resolveConfig').and.returnValue( Promise.resolve({ - printWidth: 80 + printWidth: 80, }) ); tree.create('a.ts', 'const a=a'); const result = await schematicRunner .callRule( formatFiles({ - skipFormat: true + skipFormat: true, }), tree ) .toPromise(); expect(prettier.format).not.toHaveBeenCalledWith('const a=a', { printWidth: 80, - filepath: appRoot.resolve('a.ts') + filepath: appRoot.resolve('a.ts'), }); expect(result.read('a.ts').toString()).toEqual('const a=a'); }); diff --git a/packages/workspace/src/utils/rules/format-files.ts b/packages/workspace/src/utils/rules/format-files.ts index 1e6455169fdfa..2654be28128d1 100644 --- a/packages/workspace/src/utils/rules/format-files.ts +++ b/packages/workspace/src/utils/rules/format-files.ts @@ -4,7 +4,7 @@ import { OverwriteFileAction, Rule, SchematicContext, - Tree + Tree, } from '@angular-devkit/schematics'; let prettier; try { @@ -24,27 +24,27 @@ export function formatFiles( return (host: Tree, context: SchematicContext) => { const files = new Set( host.actions - .filter(action => action.kind !== 'd' && action.kind !== 'r') + .filter((action) => action.kind !== 'd' && action.kind !== 'r') .map((action: OverwriteFileAction | CreateFileAction) => ({ path: action.path, - content: action.content.toString() + content: action.content.toString(), })) ); if (files.size === 0) { return host; } return from(files).pipe( - filter(file => host.exists(file.path)), - mergeMap(async file => { + filter((file) => host.exists(file.path)), + mergeMap(async (file) => { const systemPath = path.join(appRootPath, file.path); let options: any = { - filepath: systemPath + filepath: systemPath, }; const resolvedOptions = await prettier.resolveConfig(systemPath); if (resolvedOptions) { options = { ...options, - ...resolvedOptions + ...resolvedOptions, }; } const support = await prettier.getFileInfo(systemPath, options); diff --git a/packages/workspace/src/utils/rules/ng-add.ts b/packages/workspace/src/utils/rules/ng-add.ts index 7aea746ca7d6f..3233a1ee43d1c 100644 --- a/packages/workspace/src/utils/rules/ng-add.ts +++ b/packages/workspace/src/utils/rules/ng-add.ts @@ -2,7 +2,7 @@ import { Rule, Tree, externalSchematic, - noop + noop, } from '@angular-devkit/schematics'; import { readJsonInTree } from '../ast-utils'; diff --git a/packages/workspace/src/utils/rules/to-js.ts b/packages/workspace/src/utils/rules/to-js.ts index d42c3dcc81876..99937c2cbda77 100644 --- a/packages/workspace/src/utils/rules/to-js.ts +++ b/packages/workspace/src/utils/rules/to-js.ts @@ -5,17 +5,17 @@ import { normalize } from '@angular-devkit/core'; export function toJS(): Rule { return forEach( when( - path => path.endsWith('.ts') || path.endsWith('.tsx'), - entry => { + (path) => path.endsWith('.ts') || path.endsWith('.tsx'), + (entry) => { const original = entry.content.toString('utf-8'); const result = transpile(original, { allowJs: true, jsx: JsxEmit.Preserve, - target: ScriptTarget.ESNext + target: ScriptTarget.ESNext, }); return { content: Buffer.from(result, 'utf-8'), - path: normalize(entry.path.replace(/\.tsx?$/, '.js')) + path: normalize(entry.path.replace(/\.tsx?$/, '.js')), }; } ) diff --git a/packages/workspace/src/utils/rules/update-karma-conf.spec.ts b/packages/workspace/src/utils/rules/update-karma-conf.spec.ts index c172c5fc5da71..1bd3510ef79e5 100644 --- a/packages/workspace/src/utils/rules/update-karma-conf.spec.ts +++ b/packages/workspace/src/utils/rules/update-karma-conf.spec.ts @@ -10,7 +10,7 @@ import { updateJsonInTree } from '../ast-utils'; describe('updateKarmaConf', () => { let tree: Tree; let schematicRunner: SchematicTestRunner; - beforeEach(done => { + beforeEach((done) => { schematicRunner = new SchematicTestRunner( '@nrwl/workspace', path.join(__dirname, '../../../collection.json') @@ -18,16 +18,16 @@ describe('updateKarmaConf', () => { tree = createEmptyWorkspace(Tree.empty()); tree.create('apps/projectName/karma.conf.js', ''); const process$ = schematicRunner.callRule( - updateJsonInTree('/workspace.json', workspaceJson => { + updateJsonInTree('/workspace.json', (workspaceJson) => { workspaceJson.projects.projectName = { root: 'apps/projectName', architect: { test: { options: { - karmaConfig: 'apps/projectName/karma.conf.js' - } - } - } + karmaConfig: 'apps/projectName/karma.conf.js', + }, + }, + }, }; return workspaceJson; }), @@ -35,16 +35,16 @@ describe('updateKarmaConf', () => { ); process$.subscribe( - _ => done(), - error => { + (_) => done(), + (error) => { console.log(error); } ); }); - it('should overwrite the karma.conf.js', done => { + it('should overwrite the karma.conf.js', (done) => { const replaceKarmaConf = updateKarmaConf({ projectName: 'projectName' }); - schematicRunner.callRule(replaceKarmaConf, tree).subscribe(result => { + schematicRunner.callRule(replaceKarmaConf, tree).subscribe((result) => { const contents = result.read('apps/projectName/karma.conf.js'); expect(contents.toString()).toEqual(UPDATED_KARMA_CONF); done(); diff --git a/packages/workspace/src/utils/rules/workspace.spec.ts b/packages/workspace/src/utils/rules/workspace.spec.ts index 17e74ed11663a..66b3547554e1c 100644 --- a/packages/workspace/src/utils/rules/workspace.spec.ts +++ b/packages/workspace/src/utils/rules/workspace.spec.ts @@ -5,7 +5,7 @@ import { callRule } from '../testing'; import { setDefaultCollection } from './workspace'; import { _test_addWorkspaceFile, - WorkspaceFormat + WorkspaceFormat, } from '@angular-devkit/core/src/workspace/core'; describe('Workspace', () => { @@ -38,9 +38,9 @@ describe('Workspace', () => { it(`should be set if ${nrwlWorkspaceName} was set before`, async () => { tree = new UnitTestTree( await callRule( - updateJsonInTree(workspaceJsonFileName, json => { + updateJsonInTree(workspaceJsonFileName, (json) => { json.cli = { - defaultCollection: nrwlWorkspaceName + defaultCollection: nrwlWorkspaceName, }; return json; @@ -61,9 +61,9 @@ describe('Workspace', () => { const otherCollection = '@nrwl/angular'; tree = new UnitTestTree( await callRule( - updateJsonInTree(workspaceJsonFileName, json => { + updateJsonInTree(workspaceJsonFileName, (json) => { json.cli = { - defaultCollection: otherCollection + defaultCollection: otherCollection, }; json.schematics = {}; diff --git a/packages/workspace/src/utils/rules/workspace.ts b/packages/workspace/src/utils/rules/workspace.ts index 1d39f5d2dd2ac..75c2796d20a89 100644 --- a/packages/workspace/src/utils/rules/workspace.ts +++ b/packages/workspace/src/utils/rules/workspace.ts @@ -8,7 +8,7 @@ import { updateWorkspace } from '../workspace'; * @param collectionName Name of the collection to be set as defaultCollection */ export function setDefaultCollection(collectionName: string): Rule { - return updateWorkspace(workspace => { + return updateWorkspace((workspace) => { workspace.extensions.cli = workspace.extensions.cli || {}; const defaultCollection: string = diff --git a/packages/workspace/src/utils/runtime-lint-utils.ts b/packages/workspace/src/utils/runtime-lint-utils.ts index 35a5e08d140a8..835497695c335 100644 --- a/packages/workspace/src/utils/runtime-lint-utils.ts +++ b/packages/workspace/src/utils/runtime-lint-utils.ts @@ -5,7 +5,7 @@ import { DependencyType, ProjectGraph, ProjectGraphDependency, - ProjectGraphNode + ProjectGraphNode, } from '../core/project-graph'; import { TargetProjectLocator } from '../core/target-project-locator'; @@ -16,7 +16,7 @@ export type DepConstraint = { }; export function hasNoneOfTheseTags(proj: ProjectGraphNode, tags: string[]) { - return tags.filter(allowedTag => hasTag(proj, allowedTag)).length === 0; + return tags.filter((allowedTag) => hasTag(proj, allowedTag)).length === 0; } function hasTag(proj: ProjectGraphNode, tag: string) { @@ -28,7 +28,7 @@ function containsFile( targetFileWithoutExtension: string ): boolean { return !!files.filter( - f => removeExt(f.file) === targetFileWithoutExtension + (f) => removeExt(f.file) === targetFileWithoutExtension )[0]; } @@ -41,9 +41,7 @@ function removeWindowsDriveLetter(osSpecificPath: string): string { } function normalizePath(osSpecificPath: string): string { - return removeWindowsDriveLetter(osSpecificPath) - .split(path.sep) - .join('/'); + return removeWindowsDriveLetter(osSpecificPath).split(path.sep).join('/'); } export function matchImportWithWildcard( @@ -90,7 +88,7 @@ export function isRelativeImportIntoAnotherProject( } export function findProjectUsingFile(projectGraph: ProjectGraph, file: string) { - return Object.values(projectGraph.nodes).filter(n => + return Object.values(projectGraph.nodes).filter((n) => containsFile(n.data.files, file) )[0]; } @@ -165,22 +163,22 @@ function isDependingOn( if (done[sourceProjectName]) return false; if (!graph.dependencies[sourceProjectName]) return false; return graph.dependencies[sourceProjectName] - .map(dep => + .map((dep) => dep.target === targetProjectName ? true : isDependingOn(graph, dep.target, targetProjectName, { ...done, - [`${sourceProjectName}`]: true + [`${sourceProjectName}`]: true, }) ) - .some(result => result); + .some((result) => result); } export function findConstraintsFor( depConstraints: DepConstraint[], sourceProject: ProjectGraphNode ) { - return depConstraints.filter(f => hasTag(sourceProject, f.sourceTag)); + return depConstraints.filter((f) => hasTag(sourceProject, f.sourceTag)); } export function onlyLoadChildren( @@ -191,12 +189,12 @@ export function onlyLoadChildren( ) { if (visited.indexOf(sourceProjectName) > -1) return false; return ( - (graph.dependencies[sourceProjectName] || []).filter(d => { + (graph.dependencies[sourceProjectName] || []).filter((d) => { if (d.type !== DependencyType.dynamic) return false; if (d.target === targetProjectName) return true; return onlyLoadChildren(graph, d.target, targetProjectName, [ ...visited, - sourceProjectName + sourceProjectName, ]); }).length > 0 ); diff --git a/packages/workspace/src/utils/strings.ts b/packages/workspace/src/utils/strings.ts index b2832e56b7509..40fe77da08910 100644 --- a/packages/workspace/src/utils/strings.ts +++ b/packages/workspace/src/utils/strings.ts @@ -90,7 +90,7 @@ export function camelize(str: string): string { export function classify(str: string): string { return str .split('.') - .map(part => capitalize(camelize(part))) + .map((part) => capitalize(camelize(part))) .join('.'); } diff --git a/packages/workspace/src/utils/testing-utils.ts b/packages/workspace/src/utils/testing-utils.ts index 97990ee4e27ac..73882313d87cc 100644 --- a/packages/workspace/src/utils/testing-utils.ts +++ b/packages/workspace/src/utils/testing-utils.ts @@ -1,13 +1,13 @@ import { Tree } from '@angular-devkit/schematics'; import { _test_addWorkspaceFile, - WorkspaceFormat + WorkspaceFormat, } from '@angular-devkit/core/src/workspace/core'; import { NxJson } from '@nrwl/workspace/src/core/shared-interfaces'; import { Architect, BuilderContext, Target } from '@angular-devkit/architect'; import { TestingArchitectHost, - TestLogger + TestLogger, } from '@angular-devkit/architect/testing'; import { json, JsonObject } from '@angular-devkit/core'; import { ScheduleOptions } from '@angular-devkit/architect/src/api'; @@ -34,7 +34,7 @@ export function createEmptyWorkspace(tree: Tree): Tree { JSON.stringify({ name: 'test-name', dependencies: {}, - devDependencies: {} + devDependencies: {}, }) ); tree.create( @@ -46,10 +46,10 @@ export function createEmptyWorkspace(tree: Tree): Tree { default: { runner: '@nrwl/workspace/tasks-runners/default', options: { - cacheableOperations: ['build', 'lint', 'test', 'e2e'] - } - } - } + cacheableOperations: ['build', 'lint', 'test', 'e2e'], + }, + }, + }, }) ); tree.create( @@ -65,10 +65,10 @@ export function createEmptyWorkspace(tree: Tree): Tree { { npmScope: '<%= npmScope %>', lazyLoad: [], - allow: [] - } - ] - } + allow: [], + }, + ], + }, }) ); return tree; @@ -85,7 +85,7 @@ export class MockBuilderContext implements BuilderContext { target: Target = { project: null, - target: null + target: null, }; logger = new TestLogger('test'); diff --git a/packages/workspace/src/utils/testing.ts b/packages/workspace/src/utils/testing.ts index 7401477a396a5..4892bed6d2c83 100644 --- a/packages/workspace/src/utils/testing.ts +++ b/packages/workspace/src/utils/testing.ts @@ -39,7 +39,7 @@ export function createLibWithTests( tree.create(`/libs/${fileName}/src/index.ts`, `\n`); return callRule( - updateWorkspace(workspace => { + updateWorkspace((workspace) => { workspace.projects.add({ name: fileName, root: `libs/${fileName}`, @@ -49,10 +49,10 @@ export function createLibWithTests( test: { builder: testBuilder, options: { - setupFile: `libs/${fileName}/src/${testSetupFile}` - } - } - } + setupFile: `libs/${fileName}/src/${testSetupFile}`, + }, + }, + }, }); }), tree diff --git a/packages/workspace/src/utils/update-packages-in-package-json.ts b/packages/workspace/src/utils/update-packages-in-package-json.ts index 80d953aa0cd8e..f8cdd68897f5b 100644 --- a/packages/workspace/src/utils/update-packages-in-package-json.ts +++ b/packages/workspace/src/utils/update-packages-in-package-json.ts @@ -21,8 +21,8 @@ export function updatePackagesInPackageJson( const updatedPackages = packageJsonUpdates.packages; let needsInstall = false; return chain([ - updateJsonInTree('package.json', json => { - Object.keys(updatedPackages).forEach(p => { + updateJsonInTree('package.json', (json) => { + Object.keys(updatedPackages).forEach((p) => { /** * Check the updated version against semver */ @@ -60,6 +60,6 @@ export function updatePackagesInPackageJson( }); return json; }), - needsInstall ? addInstallTask(options) : noop() + needsInstall ? addInstallTask(options) : noop(), ]); } diff --git a/packages/workspace/src/utils/update-task.ts b/packages/workspace/src/utils/update-task.ts index 3e34039d6ffac..966e3082c351d 100644 --- a/packages/workspace/src/utils/update-task.ts +++ b/packages/workspace/src/utils/update-task.ts @@ -6,7 +6,7 @@ import { TaskExecutor, TaskExecutorFactory, TaskId, - Tree + Tree, } from '@angular-devkit/schematics'; import { Observable } from 'rxjs'; import { fork } from 'child_process'; @@ -30,7 +30,7 @@ export function addUpdateTask( taskRegistered = true; } - (context.engine as any)._taskSchedulers.forEach(scheduler => { + (context.engine as any)._taskSchedulers.forEach((scheduler) => { if ( scheduler._queue.peek() && scheduler._queue.peek().configuration.name === 'RunUpdate' && @@ -57,8 +57,8 @@ class RunUpdateTask implements TaskConfigurationGenerator { name: 'RunUpdate', options: { package: this._pkg, - to: this._to - } + to: this._to, + }, }; } } @@ -72,16 +72,16 @@ function createRunUpdateTask(): TaskExecutorFactory { context.logger.info(`Updating ${options.package} to ${options.to}`); const forkOptions = { stdio: [process.stdin, process.stdout, process.stderr, 'ipc'], - shell: true + shell: true, }; const ng = join('./node_modules', '@angular/cli', 'bin/ng'); const args = [ 'update', `${options.package}@${options.to}`, '--force', - '--allow-dirty' - ].filter(e => !!e); - return new Observable(obs => { + '--allow-dirty', + ].filter((e) => !!e); + return new Observable((obs) => { fork(ng, args, forkOptions as any).on('close', (code: number) => { if (code === 0) { obs.next(); @@ -94,6 +94,6 @@ function createRunUpdateTask(): TaskExecutorFactory { }); } ); - } + }, }; } diff --git a/packages/workspace/src/utils/workspace.ts b/packages/workspace/src/utils/workspace.ts index eb0733aac329b..dab223dd71e24 100644 --- a/packages/workspace/src/utils/workspace.ts +++ b/packages/workspace/src/utils/workspace.ts @@ -20,7 +20,7 @@ function createHost(tree: Tree): workspaces.WorkspaceHost { }, async isFile(path: string): Promise { return tree.exists(path); - } + }, }; } export async function getWorkspace(tree: Tree, path = '/') { diff --git a/packages/workspace/tasks-runners/default.ts b/packages/workspace/tasks-runners/default.ts index 52525b586da5e..9fe50fe4f8235 100644 --- a/packages/workspace/tasks-runners/default.ts +++ b/packages/workspace/tasks-runners/default.ts @@ -1,3 +1 @@ -export { - defaultTasksRunner as default -} from '../src/tasks-runner/default-tasks-runner'; +export { defaultTasksRunner as default } from '../src/tasks-runner/default-tasks-runner'; diff --git a/packages/workspace/testing.ts b/packages/workspace/testing.ts index 30d34daecf281..cd585f1ddaeb3 100644 --- a/packages/workspace/testing.ts +++ b/packages/workspace/testing.ts @@ -1,5 +1,5 @@ export { createEmptyWorkspace, getFileContent, - MockBuilderContext + MockBuilderContext, } from './src/utils/testing-utils'; diff --git a/scripts/check-imports.js b/scripts/check-imports.js index 73de33594f9f0..cc35d50ee951f 100644 --- a/scripts/check-imports.js +++ b/scripts/check-imports.js @@ -6,14 +6,14 @@ const fs = require('fs'); function allFilesInDir(dirName) { let res = []; try { - fs.readdirSync(dirName).forEach(c => { + fs.readdirSync(dirName).forEach((c) => { const child = path.join(dirName, c); try { const s = fs.statSync(child); if (path.extname(child) === '.ts') { res.push({ name: child, - content: fs.readFileSync(child).toString() + content: fs.readFileSync(child).toString(), }); } else if (s.isDirectory()) { res = [...res, ...allFilesInDir(child)]; @@ -35,7 +35,7 @@ function check() { 'packages/workspace/src/utils/update-task.ts', 'packages/workspace/src/migrations/update-8-3-0/update-8-3-0.spec.ts', 'packages/workspace/src/migrations/update-8-3-0/update-ng-cli-8-1.ts', - 'packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.spec.ts' + 'packages/workspace/src/migrations/update-8-12-0/update-package-json-deps.spec.ts', ]; const files = [ @@ -48,11 +48,11 @@ function check() { ...allFilesInDir('packages/node'), ...allFilesInDir('packages/react'), ...allFilesInDir('packages/web'), - ...allFilesInDir('packages/workspace') + ...allFilesInDir('packages/workspace'), ]; const invalidFiles = []; - files.forEach(f => { + files.forEach((f) => { if (f.content.indexOf('@schematics/angular') > -1) { invalidFiles.push(f.name); } @@ -67,7 +67,7 @@ function check() { } }); - return invalidFiles.filter(f => !exceptions.includes(f)); + return invalidFiles.filter((f) => !exceptions.includes(f)); } const invalid = check(); @@ -75,7 +75,7 @@ if (invalid.length > 0) { console.error( 'The following files import @schematics/angular or @angular/* or @angular-devkit/build-angular' ); - invalid.forEach(e => console.log(e)); + invalid.forEach((e) => console.log(e)); process.exit(1); } else { process.exit(0); diff --git a/scripts/check-versions.ts b/scripts/check-versions.ts index c90d1655c7a03..74634d81e7e44 100644 --- a/scripts/check-versions.ts +++ b/scripts/check-versions.ts @@ -27,7 +27,7 @@ const scoped = [ 'testing-library', 'types', - 'zeit' + 'zeit', ]; try { @@ -45,14 +45,14 @@ try { function checkFiles(files: string[]) { console.log(chalk.blue(`Checking versions in the following files...\n`)); console.log(` - ${files.join('\n - ')}\n`); - const maxFileNameLength = Math.max(...files.map(f => f.length)); + const maxFileNameLength = Math.max(...files.map((f) => f.length)); - files.forEach(f => { + files.forEach((f) => { const versions = getVersions(f); const npmPackages = getPackages(versions); const results = npmPackages.map(([p, v]) => getVersionData(p, v)); const logContext = `${f.padEnd(maxFileNameLength)}`; - results.forEach(r => { + results.forEach((r) => { if (r.outdated) { console.log( `${logContext} ❗ ${chalk.bold( @@ -79,21 +79,18 @@ function getVersions(path: string) { } function getPackages(versions: Record): string[][] { - return Object.entries(versions).reduce( - (acc, [name, version]) => { - if (!excluded.includes(name)) { - const npmName = getNpmName(name); - acc.push([npmName, version]); - } - return acc; - }, - [] as string[][] - ); + return Object.entries(versions).reduce((acc, [name, version]) => { + if (!excluded.includes(name)) { + const npmName = getNpmName(name); + acc.push([npmName, version]); + } + return acc; + }, [] as string[][]); } function getNpmName(name: string): string { const dashedName = dasherize(name.replace(/Version$/, '')); - const scope = scoped.find(s => dashedName.startsWith(`${s}-`)); + const scope = scoped.find((s) => dashedName.startsWith(`${s}-`)); if (scope) { const rest = dashedName.split(`${scope}-`)[1]; diff --git a/scripts/documentation/generate-builders-data.ts b/scripts/documentation/generate-builders-data.ts index 3d5ad6b9e460b..7f37663d677d0 100644 --- a/scripts/documentation/generate-builders-data.ts +++ b/scripts/documentation/generate-builders-data.ts @@ -6,16 +6,16 @@ import { Schematic } from '@angular-devkit/schematics/collection-schema'; import { CoreSchemaRegistry } from '@angular-devkit/core/src/json/schema'; import { htmlSelectorFormat, - pathFormat + pathFormat, } from '@angular-devkit/schematics/src/formats'; import { generateJsonFile, generateMarkdownFile, - sortAlphabeticallyFunction + sortAlphabeticallyFunction, } from './utils'; import { Configuration, - getPackageConfigurations + getPackageConfigurations, } from './get-package-configurations'; /** @@ -36,7 +36,7 @@ function generateSchematicList( const builderCollectionFile = path.join(config.root, 'builders.json'); fs.removeSync(config.builderOutput); const builderCollection = fs.readJsonSync(builderCollectionFile).builders; - return Object.keys(builderCollection).map(builderName => { + return Object.keys(builderCollection).map((builderName) => { const schemaPath = path.join( config.root, builderCollection[builderName]['schema'] @@ -44,7 +44,7 @@ function generateSchematicList( let builder = { name: builderName, ...builderCollection[builderName], - rawSchema: fs.readJsonSync(schemaPath) + rawSchema: fs.readJsonSync(schemaPath), }; if (builder.rawSchema.examplesFile) { builder.examplesFileFullPath = path.join( @@ -53,8 +53,8 @@ function generateSchematicList( ); } return parseJsonSchemaToOptions(registry, builder.rawSchema) - .then(options => ({ ...builder, options })) - .catch(error => + .then((options) => ({ ...builder, options })) + .catch((error) => console.error(`Can't parse schema option of ${builder.name}:\n${error}`) ); }); @@ -93,9 +93,11 @@ function generateTemplate( builder.options .sort((a, b) => sortAlphabeticallyFunction(a.name, b.name)) - .forEach(option => { + .forEach((option) => { const enumStr = option.enum - ? `Possible values: ${option.enum.map(e => `\`${e}\``).join(', ')}\n` + ? `Possible values: ${option.enum + .map((e) => `\`${e}\``) + .join(', ')}\n` : ``; template += dedent` ### ${option.name} ${option.required ? '(*__required__*)' : ''} ${ @@ -114,7 +116,7 @@ function generateTemplate( }`; if (option.types && option.types.length) { - const displayTypeList = option.types.map(type => + const displayTypeList = option.types.map((type) => type === 'array' ? `${option.type}[]` : type ); template += dedent` @@ -134,7 +136,7 @@ function generateTemplate( `; if (option.arrayOfType && option.arrayOfValues) { - option.arrayOfValues.forEach(optionValue => { + option.arrayOfValues.forEach((optionValue) => { template += dedent` #### ${optionValue.name} ${ optionValue.required ? '(*__required__*)' : '' @@ -154,15 +156,15 @@ Promise.all( getPackageConfigurations().map(({ framework, configs }) => { return Promise.all( configs - .filter(item => item.hasBuilders) - .map(config => { + .filter((item) => item.hasBuilders) + .map((config) => { Promise.all(generateSchematicList(config, registry)) - .then(builderList => - builderList.map(b => generateTemplate(framework, b)) + .then((builderList) => + builderList.map((b) => generateTemplate(framework, b)) ) - .then(markdownList => + .then((markdownList) => Promise.all( - markdownList.map(template => + markdownList.map((template) => generateMarkdownFile(config.builderOutput, template) ) ) @@ -181,8 +183,8 @@ Promise.all( getPackageConfigurations().forEach(async ({ framework, configs }) => { const builders = configs - .filter(item => item.hasBuilders) - .map(item => item.name); + .filter((item) => item.hasBuilders) + .map((item) => item.name); await generateJsonFile( path.join(__dirname, '../../docs', framework, 'builders.json'), builders diff --git a/scripts/documentation/generate-cli-data.ts b/scripts/documentation/generate-cli-data.ts index 19bc5d56c3614..f3c54dac63f3e 100644 --- a/scripts/documentation/generate-cli-data.ts +++ b/scripts/documentation/generate-cli-data.ts @@ -11,352 +11,352 @@ const examples = { { command: 'print-affected', description: - 'Print information about affected projects and the dependency graph.' + 'Print information about affected projects and the dependency graph.', }, { command: 'print-affected --base=master --head=HEAD', description: - 'Print information about the projects affected by the changes between master and HEAD (e.g,. PR).' + 'Print information about the projects affected by the changes between master and HEAD (e.g,. PR).', }, { command: 'print-affected --target=test', description: - 'Prints information about the affected projects and a list of tasks to test them.' + 'Prints information about the affected projects and a list of tasks to test them.', }, { command: 'print-affected --target=build --with-deps', description: - 'Prints information about the affected projects and a list of tasks to build them and their dependencies.' + 'Prints information about the affected projects and a list of tasks to build them and their dependencies.', }, { command: 'print-affected --target=build --select=projects', description: - 'Prints the projects property from the print-affected output.' + 'Prints the projects property from the print-affected output.', }, { command: 'print-affected --target=build --select=tasks.target.project', description: - 'Prints the tasks.target.project property from the print-affected output.' - } + 'Prints the tasks.target.project property from the print-affected output.', + }, ], affected: [ { command: 'affected --target=custom-target', - description: 'Run custom target for all affected projects' + description: 'Run custom target for all affected projects', }, { command: 'affected --target=test --parallel --maxParallel=5', - description: 'Run tests in parallel' + description: 'Run tests in parallel', }, { command: 'affected --target=test --only-failed', description: - 'Rerun the test target only for the projects that failed last time' + 'Rerun the test target only for the projects that failed last time', }, { command: 'affected --target=test --all', - description: 'Run the test target for all projects' + description: 'Run the test target for all projects', }, { command: 'affected --target=test --with-deps', description: - 'Run the test target for the affected projects and also all the projects the affected projects depend on.' + 'Run the test target for the affected projects and also all the projects the affected projects depend on.', }, { command: 'affected --target=test --files=libs/mylib/src/index.ts', description: - 'Run tests for all the projects affected by changing the index.ts file' + 'Run tests for all the projects affected by changing the index.ts file', }, { command: 'affected --target=test --base=master --head=HEAD', description: - 'Run tests for all the projects affected by the changes between master and HEAD (e.g., PR)' + 'Run tests for all the projects affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected --target=test --base=master~1 --head=master', description: - 'Run tests for all the projects affected by the last commit on master' + 'Run tests for all the projects affected by the last commit on master', }, { command: 'affected --target=build --base=master~1 --head=master --with-deps', description: - 'Run build for all the projects affected by the last commit on master and their dependencies' - } + 'Run build for all the projects affected by the last commit on master and their dependencies', + }, ], 'affected:test': [ { command: 'affected:test --parallel --maxParallel=5', - description: 'Run tests in parallel' + description: 'Run tests in parallel', }, { command: 'affected:test --only-failed', description: - 'Rerun the test target only for the projects that failed last time' + 'Rerun the test target only for the projects that failed last time', }, { command: 'affected:test --all', - description: 'Run the test target for all projects' + description: 'Run the test target for all projects', }, { command: 'affected:test --files=libs/mylib/src/index.ts', description: - 'Run tests for all the projects affected by changing the index.ts file' + 'Run tests for all the projects affected by changing the index.ts file', }, { command: 'affected:test --base=master --head=HEAD', description: - 'Run tests for all the projects affected by the changes between master and HEAD (e.g., PR)' + 'Run tests for all the projects affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected:test --base=master~1 --head=master', description: - 'Run tests for all the projects affected by the last commit on master' - } + 'Run tests for all the projects affected by the last commit on master', + }, ], 'affected:build': [ { command: 'affected:build --parallel --maxParallel=5', - description: 'Run build in parallel' + description: 'Run build in parallel', }, { command: 'affected:build --only-failed', description: - 'Rerun the build target only for the projects that failed last time' + 'Rerun the build target only for the projects that failed last time', }, { command: 'affected:build --all', - description: 'Run the build target for all projects' + description: 'Run the build target for all projects', }, { command: 'affected:build --with-deps', description: - 'Run the build target for the affected projects and also all the projects the affected projects depend on.' + 'Run the build target for the affected projects and also all the projects the affected projects depend on.', }, { command: 'affected:build --files=libs/mylib/src/index.ts', description: - 'Run build for all the projects affected by changing the index.ts file' + 'Run build for all the projects affected by changing the index.ts file', }, { command: 'affected:build --base=master --head=HEAD', description: - 'Run build for all the projects affected by the changes between master and HEAD (e.g., PR)' + 'Run build for all the projects affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected:build --base=master~1 --head=master', description: - 'Run build for all the projects affected by the last commit on master' + 'Run build for all the projects affected by the last commit on master', }, { command: 'affected:build --base=master~1 --head=master --with-deps', description: - 'Run build for all the projects affected by the last commit on master and their dependencies' - } + 'Run build for all the projects affected by the last commit on master and their dependencies', + }, ], 'affected:e2e': [ { command: 'affected:e2e --parallel --maxParallel=5', - description: 'Run tests in parallel' + description: 'Run tests in parallel', }, { command: 'affected:e2e --only-failed', description: - 'Rerun the test target only for the projects that failed last time' + 'Rerun the test target only for the projects that failed last time', }, { command: 'affected:e2e --all', - description: 'Run the test target for all projects' + description: 'Run the test target for all projects', }, { command: 'affected:e2e --files=libs/mylib/src/index.ts', description: - 'Run tests for all the projects affected by changing the index.ts file' + 'Run tests for all the projects affected by changing the index.ts file', }, { command: 'affected:e2e --base=master --head=HEAD', description: - 'Run tests for all the projects affected by the changes between master and HEAD (e.g., PR)' + 'Run tests for all the projects affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected:e2e --base=master~1 --head=master', description: - 'Run tests for all the projects affected by the last commit on master' - } + 'Run tests for all the projects affected by the last commit on master', + }, ], 'affected:lint': [ { command: 'affected:lint --parallel --maxParallel=5', - description: 'Run lint in parallel' + description: 'Run lint in parallel', }, { command: 'affected:lint --only-failed', description: - 'Rerun the lint target only for the projects that failed last time' + 'Rerun the lint target only for the projects that failed last time', }, { command: 'affected:lint --all', - description: 'Run the lint target for all projects' + description: 'Run the lint target for all projects', }, { command: 'affected:lint --files=libs/mylib/src/index.ts', description: - 'Run lint for all the projects affected by changing the index.ts file' + 'Run lint for all the projects affected by changing the index.ts file', }, { command: 'affected:lint --base=master --head=HEAD', description: - 'Run lint for all the projects affected by the changes between master and HEAD (e.g., PR)' + 'Run lint for all the projects affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected:lint --base=master~1 --head=master', description: - 'Run lint for all the projects affected by the last commit on master' - } + 'Run lint for all the projects affected by the last commit on master', + }, ], 'affected:apps': [ { command: 'affected:apps --files=libs/mylib/src/index.ts', description: - 'Print the names of all the apps affected by changing the index.ts file' + 'Print the names of all the apps affected by changing the index.ts file', }, { command: 'affected:apps --base=master --head=HEAD', description: - 'Print the names of all the apps affected by the changes between master and HEAD (e.g., PR)' + 'Print the names of all the apps affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected:apps --base=master~1 --head=master', description: - 'Print the names of all the apps affected by the last commit on master' - } + 'Print the names of all the apps affected by the last commit on master', + }, ], 'affected:libs': [ { command: 'affected:libs --files=libs/mylib/src/index.ts', description: - 'Print the names of all the libs affected by changing the index.ts file' + 'Print the names of all the libs affected by changing the index.ts file', }, { command: 'affected:libs --base=master --head=HEAD', description: - 'Print the names of all the libs affected by the changes between master and HEAD (e.g., PR)' + 'Print the names of all the libs affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected:libs --base=master~1 --head=master', description: - 'Print the names of all the libs affected by the last commit on master' - } + 'Print the names of all the libs affected by the last commit on master', + }, ], 'format:write': [], 'format:check': [], 'dep-graph': [ { command: 'dep-graph', - description: 'Open the dep graph of the workspace in the browser' + description: 'Open the dep graph of the workspace in the browser', }, { command: 'dep-graph --file=output.json', - description: 'Save the dep graph into a json file' + description: 'Save the dep graph into a json file', }, { command: 'dep-graph --filter=todos-feature-main', description: - 'Show the graph where every node is either an ancestor or a descendant of todos-feature-main.' + 'Show the graph where every node is either an ancestor or a descendant of todos-feature-main.', }, { command: 'dep-graph --exclude=project-one,project-two', - description: 'Exclude project-one and project-two from the dep graph.' - } + description: 'Exclude project-one and project-two from the dep graph.', + }, ], 'affected:dep-graph': [ { command: 'affected:dep-graph --files=libs/mylib/src/index.ts', description: - 'Open the dep graph of the workspace in the browser, and highlight the projects affected by changing the index.ts file' + 'Open the dep graph of the workspace in the browser, and highlight the projects affected by changing the index.ts file', }, { command: 'affected:dep-graph --base=master --head=HEAD', description: - 'Open the dep graph of the workspace in the browser, and highlight the projects affected by the changes between master and HEAD (e.g., PR)' + 'Open the dep graph of the workspace in the browser, and highlight the projects affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected:dep-graph --base=master --head=HEAD --file=output.json', description: - 'Save the dep graph of the workspace in a json file, and highlight the projects affected by the changes between master and HEAD (e.g., PR)' + 'Save the dep graph of the workspace in a json file, and highlight the projects affected by the changes between master and HEAD (e.g., PR)', }, { command: 'affected:dep-graph --base=master~1 --head=master', description: - 'Open the dep graph of the workspace in the browser, and highlight the projects affected by the last commit on master' - } + 'Open the dep graph of the workspace in the browser, and highlight the projects affected by the last commit on master', + }, ], 'workspace-schematic': [], list: [ { command: 'list', - description: 'List the plugins installed in the current workspace' + description: 'List the plugins installed in the current workspace', }, { command: 'list @nrwl/web', description: - 'List the schematics and builders available in the `@nrwl/web` plugin if it is installed (If the plugin is not installed `nx` will show advice on how to add it to your workspace)' - } + 'List the schematics and builders available in the `@nrwl/web` plugin if it is installed (If the plugin is not installed `nx` will show advice on how to add it to your workspace)', + }, ], 'run-many': [ { command: 'run-many --target=test --all', - description: 'Test all projects.' + description: 'Test all projects.', }, { command: 'run-many --target=test --projects=proj1,proj2', - description: 'Test proj1 and proj2.' + description: 'Test proj1 and proj2.', }, { command: 'run-many --target=test --projects=proj1,proj2 --parallel --maxParallel=2', - description: 'Test proj1 and proj2 in parallel.' + description: 'Test proj1 and proj2 in parallel.', }, { command: 'run-many --target=test --projects=proj1,proj2 --with-deps', - description: 'Build proj1 and proj2 and all their dependencies.' - } + description: 'Build proj1 and proj2 and all their dependencies.', + }, ], migrate: [ { command: 'migrate next', description: - 'Update @nrwl/workspace to "next". This will update other packages and will generate migrations.json.' + 'Update @nrwl/workspace to "next". This will update other packages and will generate migrations.json.', }, { command: 'migrate 9.0.0', description: - 'Update @nrwl/workspace to "9.0.0". This will update other packages and will generate migrations.json.' + 'Update @nrwl/workspace to "9.0.0". This will update other packages and will generate migrations.json.', }, { command: 'migrate @nrwl/workspace@9.0.0 --from="@nrwl/workspace@8.0.0,@nrwl/node@8.0.0"', description: - 'Update @nrwl/workspace and generate the list of migrations starting with version 8.0.0 of @nrwl/workspace and @nrwl/node, regardless of what installed locally.' + 'Update @nrwl/workspace and generate the list of migrations starting with version 8.0.0 of @nrwl/workspace and @nrwl/node, regardless of what installed locally.', }, { command: 'migrate @nrwl/workspace@9.0.0 --to="@nrwl/react@9.0.1,@nrwl/angular@9.0.1"', description: - 'Update @nrwl/workspace to "9.0.0". If it tries to update @nrwl/react or @nrwl/angular, use version "9.0.1".' + 'Update @nrwl/workspace to "9.0.0". If it tries to update @nrwl/react or @nrwl/angular, use version "9.0.1".', }, { command: 'migrate another-package@12.0.0', description: - 'Update another-package to "12.0.0". This will update other packages and will generate migrations.json file.' + 'Update another-package to "12.0.0". This will update other packages and will generate migrations.json file.', }, { command: 'migrate --run-migrations=migrations.json', description: - 'Run migrations from the migrations.json file. You can modify migrations.json and run this command many times.' - } - ] + 'Run migrations from the migrations.json file. You can modify migrations.json and run this command many times.', + }, + ], }; const sharedCommands = [ @@ -366,12 +366,12 @@ const sharedCommands = [ 'lint', 'run', 'serve', - 'test' + 'test', ]; console.log('Generating Nx Commands Documentation'); Promise.all( - ['angular', 'react'].map(async framework => { + ['angular', 'react'].map(async (framework) => { const commandsOutputDirectory = path.join( __dirname, '../../docs/', @@ -394,7 +394,7 @@ Promise.all( ) { return { command: name, - description: command['description'] + description: command['description'], }; } // Show all the options we can get from yargs @@ -405,13 +405,13 @@ Promise.all( command: name, description: command['description'], options: - Object.keys(builderDescriptions).map(key => ({ + Object.keys(builderDescriptions).map((key) => ({ command: '--'.concat(key), description: builderDescriptions[key] ? builderDescriptions[key].replace('__yargsString__:', '') : '', - default: builderDefaultOptions[key] - })) || null + default: builderDefaultOptions[key], + })) || null, }; } function generateMarkdown(command) { @@ -428,7 +428,7 @@ Promise.all( if (examples[command.command] && examples[command.command].length > 0) { template += `### Examples`; - examples[command.command].forEach(example => { + examples[command.command].forEach((example) => { template += dedent` ${example.description}: \`\`\`bash @@ -449,7 +449,7 @@ Promise.all( ) ) .forEach( - option => + (option) => (template += dedent` ### ${option.command.replace('--', '')} ${ @@ -467,7 +467,7 @@ Promise.all( .replace(':', '-') .replace(' ', '-') .replace(/[\]\[.]+/gm, ''), - template + template, }; } @@ -475,16 +475,16 @@ Promise.all( const nxCommands = getCommands(commandsObject); await Promise.all( Object.keys(nxCommands) - .filter(name => !sharedCommands.includes(name)) - .map(name => parseCommandInstance(name, nxCommands[name])) - .map(command => generateMarkdown(command)) - .map(templateObject => + .filter((name) => !sharedCommands.includes(name)) + .map((name) => parseCommandInstance(name, nxCommands[name])) + .map((command) => generateMarkdown(command)) + .map((templateObject) => generateMarkdownFile(commandsOutputDirectory, templateObject) ) ); await Promise.all( - sharedCommands.map(command => { + sharedCommands.map((command) => { const sharedCommandsDirectory = path.join( __dirname, '../../docs/shared/cli' @@ -499,7 +499,7 @@ Promise.all( name: command, template: fs .readFileSync(path.join(sharedCommandsDirectory, `${command}.md`)) - .toString('utf-8') + .toString('utf-8'), }; return generateMarkdownFile( diff --git a/scripts/documentation/generate-schematics-data.ts b/scripts/documentation/generate-schematics-data.ts index f77d869fb32c6..74ac3db839da3 100644 --- a/scripts/documentation/generate-schematics-data.ts +++ b/scripts/documentation/generate-schematics-data.ts @@ -6,16 +6,16 @@ import { Schematic } from '@angular-devkit/schematics/collection-schema'; import { CoreSchemaRegistry } from '@angular-devkit/core/src/json/schema'; import { htmlSelectorFormat, - pathFormat + pathFormat, } from '@angular-devkit/schematics/src/formats'; import { generateJsonFile, generateMarkdownFile, - sortAlphabeticallyFunction + sortAlphabeticallyFunction, } from './utils'; import { Configuration, - getPackageConfigurations + getPackageConfigurations, } from './get-package-configurations'; import { optionalCallExpression } from '@babel/types'; @@ -38,7 +38,7 @@ function generateSchematicList( fs.removeSync(config.schematicOutput); const schematicCollection = fs.readJsonSync(schematicCollectionFile) .schematics; - return Object.keys(schematicCollection).map(schematicName => { + return Object.keys(schematicCollection).map((schematicName) => { const schematic = { name: schematicName, collectionName: `@nrwl/${config.name}`, @@ -48,12 +48,12 @@ function generateSchematicList( : null, rawSchema: fs.readJsonSync( path.join(config.root, schematicCollection[schematicName]['schema']) - ) + ), }; return parseJsonSchemaToOptions(registry, schematic.rawSchema) - .then(options => ({ ...schematic, options })) - .catch(error => + .then((options) => ({ ...schematic, options })) + .catch((error) => console.error( `Can't parse schema option of ${schematic.name}:\n${error}` ) @@ -102,7 +102,7 @@ function generateTemplate( if (schematic.rawSchema.examples) { template += `### Examples`; - schematic.rawSchema.examples.forEach(example => { + schematic.rawSchema.examples.forEach((example) => { template += dedent` ${example.description}: \`\`\`bash @@ -117,7 +117,7 @@ function generateTemplate( schematic.options .sort((a, b) => sortAlphabeticallyFunction(a.name, b.name)) - .forEach(option => { + .forEach((option) => { let enumValues = []; const rawSchemaProp = schematic.rawSchema.properties[option.name]; if ( @@ -125,11 +125,11 @@ function generateTemplate( rawSchemaProp['x-prompt'] && rawSchemaProp['x-prompt'].items ) { - rawSchemaProp['x-prompt'].items.forEach(p => { + rawSchemaProp['x-prompt'].items.forEach((p) => { enumValues.push(`\`${p.value}\``); }); } else if (option.enum) { - enumValues = option.enum.map(e => `\`${e}\``); + enumValues = option.enum.map((e) => `\`${e}\``); } const enumStr = @@ -168,17 +168,17 @@ Promise.all( getPackageConfigurations().map(({ framework, configs }) => { return Promise.all( configs - .filter(item => item.hasSchematics) - .map(config => { + .filter((item) => item.hasSchematics) + .map((config) => { return Promise.all(generateSchematicList(config, registry)) - .then(schematicList => + .then((schematicList) => schematicList - .filter(s => !s.hidden) - .map(s => generateTemplate(framework, s)) + .filter((s) => !s.hidden) + .map((s) => generateTemplate(framework, s)) ) - .then(markdownList => + .then((markdownList) => Promise.all( - markdownList.map(template => + markdownList.map((template) => generateMarkdownFile(config.schematicOutput, template) ) ) @@ -197,8 +197,8 @@ Promise.all( getPackageConfigurations().forEach(async ({ framework, configs }) => { const schematics = configs - .filter(item => item.hasSchematics) - .map(item => item.name); + .filter((item) => item.hasSchematics) + .map((item) => item.name); await generateJsonFile( path.join(__dirname, '../../docs', framework, 'schematics.json'), schematics diff --git a/scripts/documentation/get-package-configurations.ts b/scripts/documentation/get-package-configurations.ts index e499f3c351a05..6a77d0d84e695 100644 --- a/scripts/documentation/get-package-configurations.ts +++ b/scripts/documentation/get-package-configurations.ts @@ -22,14 +22,14 @@ export function getPackageConfigurations( packagesDirectory: string = 'packages', documentationsDirectory: string = 'docs' ): { framework: 'angular' | 'react'; configs: Configuration[] }[] { - return ['angular', 'react'].map(framework => { + return ['angular', 'react'].map((framework) => { const packagesDir = path.resolve( path.join(__dirname, '../../', packagesDirectory) ); const documentationDir = path.resolve( path.join(__dirname, '../../', documentationsDirectory) ); - const configs = shelljs.ls(packagesDir).map(folderName => { + const configs = shelljs.ls(packagesDir).map((folderName) => { const itemList = shelljs.ls(path.join(packagesDir, folderName)); const output = path.join( documentationDir, @@ -45,7 +45,7 @@ export function getPackageConfigurations( builderOutput: path.join(output, 'builders'), schematicOutput: path.join(output, 'schematics'), hasBuilders: itemList.includes('builders.json'), - hasSchematics: itemList.includes('collection.json') + hasSchematics: itemList.includes('collection.json'), }; }); return { framework: framework as any, configs }; diff --git a/scripts/documentation/json-parser.ts b/scripts/documentation/json-parser.ts index dcdb26167f7fa..6763a5594ae2b 100644 --- a/scripts/documentation/json-parser.ts +++ b/scripts/documentation/json-parser.ts @@ -67,7 +67,7 @@ export async function parseJsonSchemaToOptions( // We only support number, string or boolean (or array of those), so remove everything else. const types = Array.from(typeSet) - .filter(x => { + .filter((x) => { switch (x) { case 'boolean': case 'number': @@ -79,7 +79,7 @@ export async function parseJsonSchemaToOptions( return false; } }) - .map(x => _getEnumFromValue(x, OptionType, OptionType.String)); + .map((x) => _getEnumFromValue(x, OptionType, OptionType.String)); if (types.length == 0) { // This means it's not usable on the command line. e.g. an Object. @@ -90,7 +90,7 @@ export async function parseJsonSchemaToOptions( const enumValues = ( (json.isJsonArray(current.enum) && current.enum) || [] - ).filter(x => { + ).filter((x) => { switch (typeof x) { case 'boolean': case 'number': @@ -136,7 +136,7 @@ export async function parseJsonSchemaToOptions( ? current.required.indexOf(name) != -1 : false; const aliases = json.isJsonArray(current.aliases) - ? [...current.aliases].map(x => '' + x) + ? [...current.aliases].map((x) => '' + x) : current.alias ? ['' + current.alias] : []; @@ -164,7 +164,7 @@ export async function parseJsonSchemaToOptions( ...(format !== undefined ? { format } : {}), hidden, ...(deprecated !== undefined ? { deprecated } : {}), - ...(positional !== undefined ? { positional } : {}) + ...(positional !== undefined ? { positional } : {}), }; if (current.type === 'array' && current.items) { @@ -177,10 +177,10 @@ export async function parseJsonSchemaToOptions( if (items.properties) { option.arrayOfType = items.type; - option.arrayOfValues = Object.keys(items.properties).map(key => ({ + option.arrayOfValues = Object.keys(items.properties).map((key) => ({ name: key, ...items.properties[key], - isRequired: items.required && items.required.includes(key) + isRequired: items.required && items.required.includes(key), })); } } diff --git a/scripts/documentation/utils.ts b/scripts/documentation/utils.ts index 0f617c2870d76..937a3b7c34994 100644 --- a/scripts/documentation/utils.ts +++ b/scripts/documentation/utils.ts @@ -38,13 +38,13 @@ export async function generateJsonFile( export async function formatWithPrettier(filePath: string, content: string) { let options: any = { - filepath: filePath + filepath: filePath, }; const resolvedOptions = await resolveConfig(filePath); if (resolvedOptions) { options = { ...options, - ...resolvedOptions + ...resolvedOptions, }; } @@ -62,14 +62,14 @@ export function getNxPackageDependencies( return { name: packageJson.name, dependencies: packageJson.dependencies - ? Object.keys(packageJson.dependencies).filter(item => + ? Object.keys(packageJson.dependencies).filter((item) => item.includes('@nrwl') ) : [], peerDependencies: packageJson.peerDependencies - ? Object.keys(packageJson.peerDependencies).filter(item => + ? Object.keys(packageJson.peerDependencies).filter((item) => item.includes('@nrwl') ) - : [] + : [], }; } diff --git a/scripts/nx-release.js b/scripts/nx-release.js index 97e6585b9df46..4c763560e6bfe 100755 --- a/scripts/nx-release.js +++ b/scripts/nx-release.js @@ -10,8 +10,8 @@ const parsedArgs = yargsParser(process.argv, { alias: { d: 'dry-run', h: 'help', - l: 'local' - } + l: 'local', + }, }); console.log('parsedArgs', parsedArgs); @@ -44,7 +44,7 @@ if (parsedArgs.help) { console.log('> git fetch --all'); childProcess.execSync('git fetch --all', { - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); function parseVersion(version) { @@ -52,7 +52,7 @@ function parseVersion(version) { return { version, isValid: false, - isPrerelease: false + isPrerelease: false, }; } const sections = version.split('-'); @@ -64,7 +64,7 @@ function parseVersion(version) { return { version, isValid: !!sections[0].match(/\d+\.\d+\.\d+$/), - isPrerelease: false + isPrerelease: false, }; } /** @@ -78,7 +78,7 @@ function parseVersion(version) { sections[0].match(/\d+\.\d+\.\d+$/) && sections[1].match(/(alpha|beta|rc)\.\d+$/) ), - isPrerelease: true + isPrerelease: true, }; } @@ -106,23 +106,23 @@ console.log('Executing build script:'); const buildCommand = `./scripts/package.sh ${parsedVersion.version} ${cliVersion} ${typescriptVersion} ${prettierVersion}`; console.log(`> ${buildCommand}`); childProcess.execSync(buildCommand, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); /** * Create working directory and copy over built packages */ childProcess.execSync('rm -rf build/npm && mkdir -p build/npm', { - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); childProcess.execSync('cp -R build/packages/* build/npm', { - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); /** * Get rid of tarballs at top of copied directory (made with npm pack) */ childProcess.execSync(`find build/npm -maxdepth 1 -name "*.tgz" -delete`, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); /** @@ -151,7 +151,7 @@ const pkgFiles = [ 'build/npm/tao/package.json', 'build/npm/eslint-plugin-nx/package.json', 'build/npm/linter/package.json', - 'build/npm/nx-plugin/package.json' + 'build/npm/nx-plugin/package.json', ]; /** * Set the static options for release-it @@ -180,23 +180,23 @@ const options = { */ token: !parsedArgs.local ? process.env.GITHUB_TOKEN_RELEASE_IT_NX - : 'dummy-gh-token' + : 'dummy-gh-token', }, npm: { /** * We don't use release-it to do the npm publish, because it is not * able to understand our multi-package setup. */ - release: false + release: false, }, - requireCleanWorkingDir: false + requireCleanWorkingDir: false, }; childProcess.execSync('rm -rf ./build/packages/bazel'); childProcess.execSync('rm -rf ./build/npm/bazel'); if (parsedArgs.local) { - pkgFiles.forEach(p => { + pkgFiles.forEach((p) => { const content = JSON.parse(fs.readFileSync(p).toString()); content.version = parsedVersion.version; fs.writeFileSync(p, JSON.stringify(content, null, 2)); @@ -204,13 +204,13 @@ if (parsedArgs.local) { childProcess.execSync( `./scripts/publish.sh ${parsedVersion.version} latest --local`, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], } ); process.exit(0); } else { releaseIt(options) - .then(output => { + .then((output) => { if (DRY_RUN) { console.warn( 'WARNING: In DRY_RUN mode - not running publishing script' @@ -226,11 +226,11 @@ if (parsedArgs.local) { `Note: You will need to authenticate with your NPM credentials` ); childProcess.execSync(npmPublishCommand, { - stdio: [0, 1, 2] + stdio: [0, 1, 2], }); process.exit(0); }) - .catch(err => { + .catch((err) => { console.error(err.message); process.exit(1); }); diff --git a/test.ts b/test.ts index 772765f4f1b6e..b6dfe2eaf61ef 100644 --- a/test.ts +++ b/test.ts @@ -6,7 +6,7 @@ import 'zone.js/dist/zone-testing'; import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, - platformBrowserDynamicTesting + platformBrowserDynamicTesting, } from '@angular/platform-browser-dynamic/testing'; // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. @@ -14,7 +14,7 @@ declare const require: any; // Prevent Karma from running prematurely. declare const __karma__: any; -__karma__.loaded = function() {}; +__karma__.loaded = function () {}; // First, initialize the Angular testing environment. getTestBed().initTestEnvironment( diff --git a/yarn.lock b/yarn.lock index c8a9487ef56dd..ef378af2e9814 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4705,10 +4705,10 @@ resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== -"@types/prettier@^1.10.0": - version "1.18.2" - resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-1.18.2.tgz#069e7d132024d436fd1f5771f6932426a695f230" - integrity sha512-2JBasa5Qaj81Qsp/dxX2Njy+MdKC767WytHUDsRM7TYEfQvKPxsnGpnCBlBS1i2Aiv1YwCpmKSbQ6O6v8TpiKg== +"@types/prettier@2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-2.0.0.tgz#dc85454b953178cc6043df5208b9e949b54a3bc4" + integrity sha512-/rM+sWiuOZ5dvuVzV37sUuklsbg+JPOP8d+nNFlo2ZtfpzPiPvh1/gc8liWOLBqe+sR+ZM7guPaIcTt6UZTo7Q== "@types/prettier@^1.19.0": version "1.19.1" @@ -18698,10 +18698,10 @@ prepend-http@^2.0.0: resolved "https://registry.yarnpkg.com/prepend-http/-/prepend-http-2.0.0.tgz#e92434bfa5ea8c19f41cdfd401d741a3c819d897" integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc= -prettier@1.18.2: - version "1.18.2" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.18.2.tgz#6823e7c5900017b4bd3acf46fe9ac4b4d7bda9ea" - integrity sha512-OeHeMc0JhFE9idD4ZdtNibzY0+TPHSpSSb9h8FqtP+YnoZZ1sl8Vc9b1sasjfymH3SonAF4QcA2+mzHPhMvIiw== +prettier@2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.0.4.tgz#2d1bae173e355996ee355ec9830a7a1ee05457ef" + integrity sha512-SVJIQ51spzFDvh4fIbCLvciiDMCrRhlN3mbZvv/+ycjvmF5E73bKdGfU8QDLNmjYJf+lsGnDBC4UUnvTe5OO0w== pretty-bytes@5.3.0: version "5.3.0"