Browse Source

fix all lint errors

pull/9837/head
mehmet-erim 5 years ago
parent
commit
682d8ab184
  1. 1
      npm/ng-packs/nx/ng-packs/.eslintignore
  2. 7
      npm/ng-packs/nx/ng-packs/.eslintrc.json
  3. 5
      npm/ng-packs/nx/ng-packs/.prettierrc
  4. 2
      npm/ng-packs/nx/ng-packs/apps/dev-app/.eslintrc.json
  5. 1
      npm/ng-packs/nx/ng-packs/package.json
  6. 2
      npm/ng-packs/nx/ng-packs/packages/account/src/lib/components/manage-profile/manage-profile.component.html
  7. 4
      npm/ng-packs/nx/ng-packs/packages/account/src/lib/models/account.ts
  8. 19
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/abstracts/ng-model.component.ts
  9. 6
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/autofocus.directive.ts
  10. 20
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/debounce.directive.ts
  11. 85
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/for.directive.ts
  12. 19
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/form-submit.directive.ts
  13. 17
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/replaceable-template.directive.ts
  14. 26
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/stop-propagation.directive.ts
  15. 3
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/visibility.directive.ts
  16. 29
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/dtos.ts
  17. 10
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/replaceable-components.ts
  18. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/utility.ts
  19. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/proxy/volo/abp/asp-net-core/mvc/application-configurations/object-extending/models.ts
  20. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/proxy/volo/abp/http/modeling/models.ts
  21. 8
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/list.service.ts
  22. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/routes.service.ts
  23. 15
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/track-by.service.ts
  24. 57
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/config-state.service.spec.ts
  25. 72
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/permission.guard.spec.ts
  26. 6
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/replaceable-template.directive.spec.ts
  27. 2
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/routes.service.spec.ts
  28. 40
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/utils/rxjs-utils.ts
  29. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/utils/tree-utils.ts
  30. 3
      npm/ng-packs/nx/ng-packs/packages/feature-management/src/lib/directives/free-text-input.directive.ts
  31. 1
      npm/ng-packs/nx/ng-packs/packages/feature-management/src/lib/proxy/validation/string-values/models.ts
  32. 12
      npm/ng-packs/nx/ng-packs/packages/identity/src/lib/proxy/identity/models.ts
  33. 15
      npm/ng-packs/nx/ng-packs/packages/schematics/.eslintrc.json
  34. 3
      npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/api/index.ts
  35. 3
      npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/proxy-index/index.ts
  36. 3
      npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/proxy-remove/index.ts
  37. 2
      npm/ng-packs/nx/ng-packs/packages/schematics/src/models/method.ts
  38. 2
      npm/ng-packs/nx/ng-packs/packages/schematics/src/models/util.ts
  39. 247
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/ast-utils.ts
  40. 571
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/config.ts
  41. 58
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/find-module.ts
  42. 1
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/workspace-models.ts
  43. 4
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/enum.ts
  44. 2
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/generics.ts
  45. 1
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/model.ts
  46. 1
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/source.ts
  47. 3
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/text.ts
  48. 1
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/workspace.ts
  49. 11
      npm/ng-packs/nx/ng-packs/packages/tenant-management/src/lib/proxy/models.ts
  50. 6
      npm/ng-packs/nx/ng-packs/packages/theme-basic/src/lib/components/account-layout/auth-wrapper/auth-wrapper.component.ts
  51. 6
      npm/ng-packs/nx/ng-packs/packages/theme-basic/src/lib/components/account-layout/tenant-box/tenant-box.component.ts
  52. 11
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/button/button.component.ts
  53. 4
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/chart/chart.component.ts
  54. 8
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/loading/loading.component.ts
  55. 6
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/table-empty-message/table-empty-message.component.ts
  56. 2
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/directives/ngx-datatable-default.directive.ts
  57. 2
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/directives/ngx-datatable-list.directive.ts
  58. 63
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts
  59. 1
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/tests/breadcrumb.component.spec.ts

1
npm/ng-packs/nx/ng-packs/.eslintignore

@ -0,0 +1 @@
*.d.ts

7
npm/ng-packs/nx/ng-packs/.eslintrc.json

@ -20,11 +20,14 @@
} }
] ]
} }
}, },
{ {
"files": ["*.ts", "*.tsx"], "files": ["*.ts", "*.tsx"],
"extends": ["plugin:@nrwl/nx/typescript"], "extends": ["plugin:@nrwl/nx/typescript"],
"rules": {} "rules": {
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-empty-function": ["warn"]
}
}, },
{ {
"files": ["*.js", "*.jsx"], "files": ["*.js", "*.jsx"],

5
npm/ng-packs/nx/ng-packs/.prettierrc

@ -1,3 +1,6 @@
{ {
"singleQuote": true "printWidth": 100,
"singleQuote": true,
"trailingComma": "all",
"arrowParens": "avoid"
} }

2
npm/ng-packs/nx/ng-packs/apps/dev-app/.eslintrc.json

@ -21,7 +21,7 @@
"error", "error",
{ {
"type": "element", "type": "element",
"prefix": "abp", "prefix": "app",
"style": "kebab-case" "style": "kebab-case"
} }
] ]

1
npm/ng-packs/nx/ng-packs/package.json

@ -11,6 +11,7 @@
"test": "ng test --detect-open-handles=true --run-in-band=true --watch-all=true", "test": "ng test --detect-open-handles=true --run-in-band=true --watch-all=true",
"test:all": "nx run-many --target=test --all", "test:all": "nx run-many --target=test --all",
"lint": "nx workspace-lint && ng lint", "lint": "nx workspace-lint && ng lint",
"lint:all": "nx run-many --target=lint --all",
"e2e": "ng e2e", "e2e": "ng e2e",
"affected:apps": "nx affected:apps", "affected:apps": "nx affected:apps",
"affected:libs": "nx affected:libs", "affected:libs": "nx affected:libs",

2
npm/ng-packs/nx/ng-packs/packages/account/src/lib/components/manage-profile/manage-profile.component.html

@ -1,6 +1,6 @@
<div id="AbpContentToolbar"></div> <div id="AbpContentToolbar"></div>
<div class="card border-0 shadow-sm min-h-400" [abpLoading]="!(profile$ | async)"> <div class="card border-0 shadow-sm min-h-400" [abpLoading]="(profile$ | async)?.userName">
<div class="card-body"> <div class="card-body">
<div class="row"> <div class="row">
<div class="col-12 col-md-3"> <div class="col-12 col-md-3">

4
npm/ng-packs/nx/ng-packs/packages/account/src/lib/models/account.ts

@ -1,12 +1,10 @@
import { TemplateRef } from '@angular/core'; /* eslint-disable @typescript-eslint/no-empty-interface */
export namespace Account { export namespace Account {
//tslint:disable
export interface TenantBoxComponentInputs {} export interface TenantBoxComponentInputs {}
export interface TenantBoxComponentOutputs {} export interface TenantBoxComponentOutputs {}
export interface PersonalSettingsComponentInputs {} export interface PersonalSettingsComponentInputs {}
export interface PersonalSettingsComponentOutputs {} export interface PersonalSettingsComponentOutputs {}
export interface ChangePasswordComponentInputs {} export interface ChangePasswordComponentInputs {}
export interface ChangePasswordComponentOutputs {} export interface ChangePasswordComponentOutputs {}
// tslint:enable
} }

19
npm/ng-packs/nx/ng-packs/packages/core/src/lib/abstracts/ng-model.component.ts

@ -1,14 +1,16 @@
import { ControlValueAccessor } from '@angular/forms';
import { ChangeDetectorRef, Component, Injector, Input } from '@angular/core'; import { ChangeDetectorRef, Component, Injector, Input } from '@angular/core';
import { ControlValueAccessor } from '@angular/forms';
// Not an abstract class on purpose. Do not change! // Not an abstract class on purpose. Do not change!
// tslint:disable-next-line: use-component-selector // tslint:disable-next-line: use-component-selector
@Component({ template: '' }) @Component({ template: '' })
export class AbstractNgModelComponent<T = any, U = T> implements ControlValueAccessor { export class AbstractNgModelComponent<T = any, U = T>
implements ControlValueAccessor
{
protected _value: T; protected _value: T;
protected cdRef: ChangeDetectorRef; protected cdRef: ChangeDetectorRef;
onChange: (value: T) => {}; onChange: (value: T) => void;
onTouched: () => {}; onTouched: () => void;
@Input() @Input()
disabled: boolean; disabled: boolean;
@ -17,16 +19,17 @@ export class AbstractNgModelComponent<T = any, U = T> implements ControlValueAcc
readonly: boolean; readonly: boolean;
@Input() @Input()
valueFn: (value: U, previousValue?: T) => T = value => (value as any) as T; valueFn: (value: U, previousValue?: T) => T = (value) => value as any as T;
@Input() @Input()
valueLimitFn: (value: T, previousValue?: T) => any = value => false; valueLimitFn: (value: T, previousValue?: T) => any = (value) => false;
@Input() @Input()
set value(value: T) { set value(value: T) {
value = this.valueFn((value as any) as U, this._value); value = this.valueFn(value as any as U, this._value);
if (this.valueLimitFn(value, this._value) !== false || this.readonly) return; if (this.valueLimitFn(value, this._value) !== false || this.readonly)
return;
this._value = value; this._value = value;
this.notifyValueChange(); this.notifyValueChange();

6
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/autofocus.directive.ts

@ -1,8 +1,8 @@
import { Directive, ElementRef, Input, AfterViewInit } from '@angular/core'; import { AfterViewInit, Directive, ElementRef, Input } from '@angular/core';
@Directive({ @Directive({
// tslint:disable-next-line: directive-selector // eslint-disable-next-line @angular-eslint/directive-selector
selector: '[autofocus]' selector: '[autofocus]',
}) })
export class AutofocusDirective implements AfterViewInit { export class AutofocusDirective implements AfterViewInit {
@Input('autofocus') @Input('autofocus')

20
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/debounce.directive.ts

@ -1,10 +1,17 @@
import { Directive, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core'; import {
Directive,
ElementRef,
EventEmitter,
Input,
OnInit,
Output,
} from '@angular/core';
import { fromEvent } from 'rxjs'; import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators'; import { debounceTime } from 'rxjs/operators';
import { SubscriptionService } from '../services/subscription.service'; import { SubscriptionService } from '../services/subscription.service';
@Directive({ @Directive({
// tslint:disable-next-line: directive-selector // eslint-disable-next-line @angular-eslint/directive-selector
selector: '[input.debounce]', selector: '[input.debounce]',
providers: [SubscriptionService], providers: [SubscriptionService],
}) })
@ -13,10 +20,15 @@ export class InputEventDebounceDirective implements OnInit {
@Output('input.debounce') readonly debounceEvent = new EventEmitter<Event>(); @Output('input.debounce') readonly debounceEvent = new EventEmitter<Event>();
constructor(private el: ElementRef, private subscription: SubscriptionService) {} constructor(
private el: ElementRef,
private subscription: SubscriptionService
) {}
ngOnInit(): void { ngOnInit(): void {
const input$ = fromEvent(this.el.nativeElement, 'input').pipe(debounceTime(this.debounce)); const input$ = fromEvent(this.el.nativeElement, 'input').pipe(
debounceTime(this.debounce)
);
this.subscription.addOne(input$, (event: Event) => { this.subscription.addOne(input$, (event: Event) => {
this.debounceEvent.emit(event); this.debounceEvent.emit(event);

85
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/for.directive.ts

@ -11,23 +11,32 @@ import {
TrackByFunction, TrackByFunction,
ViewContainerRef, ViewContainerRef,
} from '@angular/core'; } from '@angular/core';
import compare from 'just-compare';
import clone from 'just-clone'; import clone from 'just-clone';
import compare from 'just-compare';
export type CompareFn<T = any> = (value: T, comparison: T) => boolean; export type CompareFn<T = any> = (value: T, comparison: T) => boolean;
class AbpForContext { class AbpForContext {
constructor(public $implicit: any, public index: number, public count: number, public list: any[]) {} constructor(
public $implicit: any,
public index: number,
public count: number,
public list: any[]
) {}
} }
class RecordView { class RecordView {
constructor(public record: IterableChangeRecord<any>, public view: EmbeddedViewRef<AbpForContext>) {} constructor(
public record: IterableChangeRecord<any>,
public view: EmbeddedViewRef<AbpForContext>
) {}
} }
@Directive({ @Directive({
selector: '[abpFor]', selector: '[abpFor]',
}) })
export class ForDirective implements OnChanges { export class ForDirective implements OnChanges {
// eslint-disable-next-line @angular-eslint/no-input-rename
@Input('abpForOf') @Input('abpForOf')
items: any[]; items: any[];
@ -61,36 +70,46 @@ export class ForDirective implements OnChanges {
} }
get trackByFn(): TrackByFunction<any> { get trackByFn(): TrackByFunction<any> {
return this.trackBy || ((index: number, item: any) => (item as any).id || index); return (
this.trackBy || ((index: number, item: any) => (item as any).id || index)
);
} }
constructor( constructor(
private tempRef: TemplateRef<AbpForContext>, private tempRef: TemplateRef<AbpForContext>,
private vcRef: ViewContainerRef, private vcRef: ViewContainerRef,
private differs: IterableDiffers, private differs: IterableDiffers
) {} ) {}
private iterateOverAppliedOperations(changes: IterableChanges<any>) { private iterateOverAppliedOperations(changes: IterableChanges<any>) {
const rw: RecordView[] = []; const rw: RecordView[] = [];
changes.forEachOperation((record: IterableChangeRecord<any>, previousIndex: number, currentIndex: number) => { changes.forEachOperation(
if (record.previousIndex == null) { (
const view = this.vcRef.createEmbeddedView( record: IterableChangeRecord<any>,
this.tempRef, previousIndex: number,
new AbpForContext(null, -1, -1, this.items), currentIndex: number
currentIndex, ) => {
); if (record.previousIndex == null) {
const view = this.vcRef.createEmbeddedView(
rw.push(new RecordView(record, view)); this.tempRef,
} else if (currentIndex == null) { new AbpForContext(null, -1, -1, this.items),
this.vcRef.remove(previousIndex); currentIndex
} else { );
const view = this.vcRef.get(previousIndex);
this.vcRef.move(view, currentIndex); rw.push(new RecordView(record, view));
} else if (currentIndex == null) {
rw.push(new RecordView(record, view as EmbeddedViewRef<AbpForContext>)); this.vcRef.remove(previousIndex);
} else {
const view = this.vcRef.get(previousIndex);
this.vcRef.move(view, currentIndex);
rw.push(
new RecordView(record, view as EmbeddedViewRef<AbpForContext>)
);
}
} }
}); );
for (let i = 0, l = rw.length; i < l; i++) { for (let i = 0, l = rw.length; i < l; i++) {
rw[i].view.context.$implicit = rw[i].record.item; rw[i].view.context.$implicit = rw[i].record.item;
@ -106,7 +125,9 @@ export class ForDirective implements OnChanges {
} }
changes.forEachIdentityChange((record: IterableChangeRecord<any>) => { changes.forEachIdentityChange((record: IterableChangeRecord<any>) => {
const viewRef = this.vcRef.get(record.currentIndex) as EmbeddedViewRef<AbpForContext>; const viewRef = this.vcRef.get(
record.currentIndex
) as EmbeddedViewRef<AbpForContext>;
viewRef.context.$implicit = record.item; viewRef.context.$implicit = record.item;
}); });
} }
@ -143,7 +164,13 @@ export class ForDirective implements OnChanges {
private sortItems(items: any[]) { private sortItems(items: any[]) {
if (this.orderBy) { if (this.orderBy) {
items.sort((a, b) => (a[this.orderBy] > b[this.orderBy] ? 1 : a[this.orderBy] < b[this.orderBy] ? -1 : 0)); items.sort((a, b) =>
a[this.orderBy] > b[this.orderBy]
? 1
: a[this.orderBy] < b[this.orderBy]
? -1
: 0
);
} else { } else {
items.sort(); items.sort();
} }
@ -155,8 +182,14 @@ export class ForDirective implements OnChanges {
const compareFn = this.compareFn; const compareFn = this.compareFn;
if (typeof this.filterBy !== 'undefined' && typeof this.filterVal !== 'undefined' && this.filterVal !== '') { if (
items = items.filter(item => compareFn(item[this.filterBy], this.filterVal)); typeof this.filterBy !== 'undefined' &&
typeof this.filterVal !== 'undefined' &&
this.filterVal !== ''
) {
items = items.filter((item) =>
compareFn(item[this.filterBy], this.filterVal)
);
} }
switch (this.orderDir) { switch (this.orderDir) {

19
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/form-submit.directive.ts

@ -16,7 +16,7 @@ import { SubscriptionService } from '../services/subscription.service';
type Controls = { [key: string]: FormControl } | FormGroup[]; type Controls = { [key: string]: FormControl } | FormGroup[];
@Directive({ @Directive({
// tslint:disable-next-line: directive-selector // eslint-disable-next-line @angular-eslint/directive-selector
selector: 'form[ngSubmit][formGroup]', selector: 'form[ngSubmit][formGroup]',
providers: [SubscriptionService], providers: [SubscriptionService],
}) })
@ -35,7 +35,7 @@ export class FormSubmitDirective implements OnInit {
@Self() private formGroupDirective: FormGroupDirective, @Self() private formGroupDirective: FormGroupDirective,
private host: ElementRef<HTMLFormElement>, private host: ElementRef<HTMLFormElement>,
private cdRef: ChangeDetectorRef, private cdRef: ChangeDetectorRef,
private subscription: SubscriptionService, private subscription: SubscriptionService
) {} ) {}
ngOnInit() { ngOnInit() {
@ -44,16 +44,19 @@ export class FormSubmitDirective implements OnInit {
this.executedNgSubmit = true; this.executedNgSubmit = true;
}); });
const keyup$ = fromEvent(this.host.nativeElement as HTMLElement, 'keyup').pipe( const keyup$ = fromEvent(
this.host.nativeElement as HTMLElement,
'keyup'
).pipe(
debounceTime(this.debounce), debounceTime(this.debounce),
filter(event => !(event.target instanceof HTMLTextAreaElement)), filter((event) => !(event.target instanceof HTMLTextAreaElement)),
filter((event: KeyboardEvent) => event && event.key === 'Enter'), filter((event: KeyboardEvent) => event && event.key === 'Enter')
); );
this.subscription.addOne(keyup$, () => { this.subscription.addOne(keyup$, () => {
if (!this.executedNgSubmit) { if (!this.executedNgSubmit) {
this.host.nativeElement.dispatchEvent( this.host.nativeElement.dispatchEvent(
new Event('submit', { bubbles: true, cancelable: true }), new Event('submit', { bubbles: true, cancelable: true })
); );
} }
@ -73,13 +76,13 @@ export class FormSubmitDirective implements OnInit {
function setDirty(controls: Controls) { function setDirty(controls: Controls) {
if (Array.isArray(controls)) { if (Array.isArray(controls)) {
controls.forEach(group => { controls.forEach((group) => {
setDirty(group.controls as { [key: string]: FormControl }); setDirty(group.controls as { [key: string]: FormControl });
}); });
return; return;
} }
Object.keys(controls).forEach(key => { Object.keys(controls).forEach((key) => {
controls[key].markAsDirty(); controls[key].markAsDirty();
controls[key].updateValueAndValidity(); controls[key].updateValueAndValidity();
}); });

17
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/replaceable-template.directive.ts

@ -19,15 +19,18 @@ import { ReplaceableComponents } from '../models/replaceable-components';
import { ReplaceableComponentsService } from '../services/replaceable-components.service'; import { ReplaceableComponentsService } from '../services/replaceable-components.service';
import { SubscriptionService } from '../services/subscription.service'; import { SubscriptionService } from '../services/subscription.service';
@Directive({ selector: '[abpReplaceableTemplate]', providers: [SubscriptionService] }) @Directive({
selector: '[abpReplaceableTemplate]',
providers: [SubscriptionService],
})
export class ReplaceableTemplateDirective implements OnInit, OnChanges { export class ReplaceableTemplateDirective implements OnInit, OnChanges {
@Input('abpReplaceableTemplate') @Input('abpReplaceableTemplate')
data: ReplaceableComponents.ReplaceableTemplateDirectiveInput<any, any>; data: ReplaceableComponents.ReplaceableTemplateDirectiveInput<any, any>;
providedData = { inputs: {}, outputs: {} } as ReplaceableComponents.ReplaceableTemplateData< providedData = {
any, inputs: {},
any outputs: {},
>; } as ReplaceableComponents.ReplaceableTemplateData<any, any>;
context = {} as any; context = {} as any;
@ -106,7 +109,7 @@ export class ReplaceableTemplateDirective implements OnInit, OnChanges {
if (this.data.inputs) { if (this.data.inputs) {
for (const key in this.data.inputs) { for (const key in this.data.inputs) {
if (this.data.inputs.hasOwnProperty(key)) { if (Object.prototype.hasOwnProperty.call(this.data.inputs, key)) {
if (!compare(this.defaultComponentRef[key], this.data.inputs[key].value)) { if (!compare(this.defaultComponentRef[key], this.data.inputs[key].value)) {
this.defaultComponentRef[key] = this.data.inputs[key].value; this.defaultComponentRef[key] = this.data.inputs[key].value;
} }
@ -116,7 +119,7 @@ export class ReplaceableTemplateDirective implements OnInit, OnChanges {
if (this.data.outputs) { if (this.data.outputs) {
for (const key in this.data.outputs) { for (const key in this.data.outputs) {
if (this.data.outputs.hasOwnProperty(key)) { if (Object.prototype.hasOwnProperty.call(this.data.outputs, key)) {
if (!this.defaultComponentSubscriptions[key]) { if (!this.defaultComponentSubscriptions[key]) {
this.defaultComponentSubscriptions[key] = this.defaultComponentRef[key].subscribe( this.defaultComponentSubscriptions[key] = this.defaultComponentRef[key].subscribe(
value => { value => {

26
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/stop-propagation.directive.ts

@ -1,21 +1,33 @@
import { Directive, ElementRef, EventEmitter, OnInit, Output } from '@angular/core'; import {
Directive,
ElementRef,
EventEmitter,
OnInit,
Output,
} from '@angular/core';
import { fromEvent } from 'rxjs'; import { fromEvent } from 'rxjs';
import { SubscriptionService } from '../services/subscription.service'; import { SubscriptionService } from '../services/subscription.service';
@Directive({ @Directive({
// tslint:disable-next-line: directive-selector // eslint-disable-next-line @angular-eslint/directive-selector
selector: '[click.stop]', selector: '[click.stop]',
providers: [SubscriptionService], providers: [SubscriptionService],
}) })
export class StopPropagationDirective implements OnInit { export class StopPropagationDirective implements OnInit {
@Output('click.stop') readonly stopPropEvent = new EventEmitter<MouseEvent>(); @Output('click.stop') readonly stopPropEvent = new EventEmitter<MouseEvent>();
constructor(private el: ElementRef, private subscription: SubscriptionService) {} constructor(
private el: ElementRef,
private subscription: SubscriptionService
) {}
ngOnInit(): void { ngOnInit(): void {
this.subscription.addOne(fromEvent(this.el.nativeElement, 'click'), (event: MouseEvent) => { this.subscription.addOne(
event.stopPropagation(); fromEvent(this.el.nativeElement, 'click'),
this.stopPropEvent.emit(event); (event: MouseEvent) => {
}); event.stopPropagation();
this.stopPropEvent.emit(event);
}
);
} }
} }

3
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/visibility.directive.ts

@ -22,8 +22,7 @@ export class VisibilityDirective implements AfterViewInit {
this.focusedElement = this.elRef.nativeElement; this.focusedElement = this.elRef.nativeElement;
} }
let observer: MutationObserver; const observer = new MutationObserver(mutations => {
observer = new MutationObserver(mutations => {
mutations.forEach(mutation => { mutations.forEach(mutation => {
if (!mutation.target) return; if (!mutation.target) return;

29
npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/dtos.ts

@ -5,7 +5,7 @@ export class ListResultDto<T> {
constructor(initialValues: Partial<ListResultDto<T>> = {}) { constructor(initialValues: Partial<ListResultDto<T>> = {}) {
for (const key in initialValues) { for (const key in initialValues) {
if (initialValues.hasOwnProperty(key)) { if (Object.prototype.hasOwnProperty.call(initialValues, key)) {
this[key] = initialValues[key]; this[key] = initialValues[key];
} }
} }
@ -25,7 +25,10 @@ export class LimitedResultRequestDto {
constructor(initialValues: Partial<LimitedResultRequestDto> = {}) { constructor(initialValues: Partial<LimitedResultRequestDto> = {}) {
for (const key in initialValues) { for (const key in initialValues) {
if (initialValues.hasOwnProperty(key) && initialValues[key] !== undefined) { if (
Object.prototype.hasOwnProperty.call(initialValues, key) &&
initialValues[key] !== undefined
) {
this[key] = initialValues[key]; this[key] = initialValues[key];
} }
} }
@ -53,7 +56,7 @@ export class EntityDto<TKey = string> {
constructor(initialValues: Partial<EntityDto<TKey>> = {}) { constructor(initialValues: Partial<EntityDto<TKey>> = {}) {
for (const key in initialValues) { for (const key in initialValues) {
if (initialValues.hasOwnProperty(key)) { if (Object.prototype.hasOwnProperty.call(initialValues, key)) {
this[key] = initialValues[key]; this[key] = initialValues[key];
} }
} }
@ -71,7 +74,7 @@ export class CreationAuditedEntityDto<TPrimaryKey = string> extends EntityDto<TP
export class CreationAuditedEntityWithUserDto< export class CreationAuditedEntityWithUserDto<
TUserDto, TUserDto,
TPrimaryKey = string TPrimaryKey = string,
> extends CreationAuditedEntityDto<TPrimaryKey> { > extends CreationAuditedEntityDto<TPrimaryKey> {
creator?: TUserDto; creator?: TUserDto;
@ -93,7 +96,7 @@ export class AuditedEntityDto<TPrimaryKey = string> extends CreationAuditedEntit
export class AuditedEntityWithUserDto< export class AuditedEntityWithUserDto<
TUserDto, TUserDto,
TPrimaryKey = string TPrimaryKey = string,
> extends AuditedEntityDto<TPrimaryKey> { > extends AuditedEntityDto<TPrimaryKey> {
creator?: TUserDto; creator?: TUserDto;
lastModifier?: TUserDto; lastModifier?: TUserDto;
@ -115,7 +118,7 @@ export class FullAuditedEntityDto<TPrimaryKey = string> extends AuditedEntityDto
export class FullAuditedEntityWithUserDto< export class FullAuditedEntityWithUserDto<
TUserDto, TUserDto,
TPrimaryKey = string TPrimaryKey = string,
> extends FullAuditedEntityDto<TPrimaryKey> { > extends FullAuditedEntityDto<TPrimaryKey> {
creator?: TUserDto; creator?: TUserDto;
lastModifier?: TUserDto; lastModifier?: TUserDto;
@ -131,7 +134,7 @@ export class ExtensibleObject {
constructor(initialValues: Partial<ExtensibleObject> = {}) { constructor(initialValues: Partial<ExtensibleObject> = {}) {
for (const key in initialValues) { for (const key in initialValues) {
if (initialValues.hasOwnProperty(key)) { if (Object.prototype.hasOwnProperty.call(initialValues, key)) {
this[key] = initialValues[key]; this[key] = initialValues[key];
} }
} }
@ -147,7 +150,7 @@ export class ExtensibleEntityDto<TKey = string> extends ExtensibleObject {
} }
export class ExtensibleCreationAuditedEntityDto< export class ExtensibleCreationAuditedEntityDto<
TPrimaryKey = string TPrimaryKey = string,
> extends ExtensibleEntityDto<TPrimaryKey> { > extends ExtensibleEntityDto<TPrimaryKey> {
creationTime: Date | string; creationTime: Date | string;
creatorId?: string; creatorId?: string;
@ -158,7 +161,7 @@ export class ExtensibleCreationAuditedEntityDto<
} }
export class ExtensibleAuditedEntityDto< export class ExtensibleAuditedEntityDto<
TPrimaryKey = string TPrimaryKey = string,
> extends ExtensibleCreationAuditedEntityDto<TPrimaryKey> { > extends ExtensibleCreationAuditedEntityDto<TPrimaryKey> {
lastModificationTime?: Date | string; lastModificationTime?: Date | string;
lastModifierId?: string; lastModifierId?: string;
@ -170,7 +173,7 @@ export class ExtensibleAuditedEntityDto<
export class ExtensibleAuditedEntityWithUserDto< export class ExtensibleAuditedEntityWithUserDto<
TPrimaryKey = string, TPrimaryKey = string,
TUserDto = any TUserDto = any,
> extends ExtensibleAuditedEntityDto<TPrimaryKey> { > extends ExtensibleAuditedEntityDto<TPrimaryKey> {
creator: TUserDto; creator: TUserDto;
lastModifier: TUserDto; lastModifier: TUserDto;
@ -182,7 +185,7 @@ export class ExtensibleAuditedEntityWithUserDto<
export class ExtensibleCreationAuditedEntityWithUserDto< export class ExtensibleCreationAuditedEntityWithUserDto<
TPrimaryKey = string, TPrimaryKey = string,
TUserDto = any TUserDto = any,
> extends ExtensibleCreationAuditedEntityDto<TPrimaryKey> { > extends ExtensibleCreationAuditedEntityDto<TPrimaryKey> {
creator: TUserDto; creator: TUserDto;
@ -194,7 +197,7 @@ export class ExtensibleCreationAuditedEntityWithUserDto<
} }
export class ExtensibleFullAuditedEntityDto< export class ExtensibleFullAuditedEntityDto<
TPrimaryKey = string TPrimaryKey = string,
> extends ExtensibleAuditedEntityDto<TPrimaryKey> { > extends ExtensibleAuditedEntityDto<TPrimaryKey> {
isDeleted: boolean; isDeleted: boolean;
deleterId?: string; deleterId?: string;
@ -207,7 +210,7 @@ export class ExtensibleFullAuditedEntityDto<
export class ExtensibleFullAuditedEntityWithUserDto< export class ExtensibleFullAuditedEntityWithUserDto<
TPrimaryKey = string, TPrimaryKey = string,
TUserDto = any TUserDto = any,
> extends ExtensibleFullAuditedEntityDto<TPrimaryKey> { > extends ExtensibleFullAuditedEntityDto<TPrimaryKey> {
creator: TUserDto; creator: TUserDto;
lastModifier: TUserDto; lastModifier: TUserDto;

10
npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/replaceable-components.ts

@ -1,6 +1,6 @@
import { Type, EventEmitter } from '@angular/core'; import { EventEmitter, Type } from '@angular/core';
import { Subject } from 'rxjs';
import { ABP } from './common'; import { ABP } from './common';
import { Subject, BehaviorSubject } from 'rxjs';
export namespace ReplaceableComponents { export namespace ReplaceableComponents {
export interface State { export interface State {
@ -14,7 +14,7 @@ export namespace ReplaceableComponents {
export interface ReplaceableTemplateDirectiveInput< export interface ReplaceableTemplateDirectiveInput<
I, I,
O extends { [K in keyof O]: EventEmitter<any> | Subject<any> } O extends { [K in keyof O]: EventEmitter<any> | Subject<any> },
> { > {
inputs: { -readonly [K in keyof I]: { value: I[K]; twoWay?: boolean } }; inputs: { -readonly [K in keyof I]: { value: I[K]; twoWay?: boolean } };
outputs: { -readonly [K in keyof O]: (value: ABP.ExtractFromOutput<O[K]>) => void }; outputs: { -readonly [K in keyof O]: (value: ABP.ExtractFromOutput<O[K]>) => void };
@ -23,7 +23,7 @@ export namespace ReplaceableComponents {
export interface ReplaceableTemplateData< export interface ReplaceableTemplateData<
I, I,
O extends { [K in keyof O]: EventEmitter<any> | Subject<any> } O extends { [K in keyof O]: EventEmitter<any> | Subject<any> },
> { > {
inputs: ReplaceableTemplateInputs<I>; inputs: ReplaceableTemplateInputs<I>;
outputs: ReplaceableTemplateOutputs<O>; outputs: ReplaceableTemplateOutputs<O>;
@ -35,7 +35,7 @@ export namespace ReplaceableComponents {
}; };
export type ReplaceableTemplateOutputs< export type ReplaceableTemplateOutputs<
T extends { [K in keyof T]: EventEmitter<any> | Subject<any> } T extends { [K in keyof T]: EventEmitter<any> | Subject<any> },
> = { > = {
[K in keyof T]: (value: ABP.ExtractFromOutput<T[K]>) => void; [K in keyof T]: (value: ABP.ExtractFromOutput<T[K]>) => void;
}; };

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/utility.ts

@ -10,6 +10,7 @@ export type DeepPartial<T> = Partible<T> extends never
type Partible<T> = T extends Primitive | Array<any> | Node type Partible<T> = T extends Primitive | Array<any> | Node
? never ? never
: { : {
// eslint-disable-next-line @typescript-eslint/ban-types
[K in keyof T]: T[K] extends Function ? never : T[K]; [K in keyof T]: T[K] extends Function ? never : T[K];
} extends T } extends T
? T ? T

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/proxy/volo/abp/asp-net-core/mvc/application-configurations/object-extending/models.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
export interface EntityExtensionDto { export interface EntityExtensionDto {
properties: Record<string, ExtensionPropertyDto>; properties: Record<string, ExtensionPropertyDto>;

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/proxy/volo/abp/http/modeling/models.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
export interface ActionApiDescriptionModel { export interface ActionApiDescriptionModel {
uniqueName?: string; uniqueName?: string;

8
npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/list.service.ts

@ -82,6 +82,8 @@ export class ListService<QueryParamsType = ABP.PageQueryParams> implements OnDes
private destroy$ = new Subject(); private destroy$ = new Subject();
private delay: MonoTypeOperatorFunction<QueryParamsType>;
get isLoading$(): Observable<boolean> { get isLoading$(): Observable<boolean> {
return this._isLoading$.asObservable(); return this._isLoading$.asObservable();
} }
@ -95,8 +97,6 @@ export class ListService<QueryParamsType = ABP.PageQueryParams> implements OnDes
this.next(); this.next();
}; };
private delay: MonoTypeOperatorFunction<QueryParamsType>;
constructor(injector: Injector) { constructor(injector: Injector) {
const delay = injector.get(LIST_QUERY_DEBOUNCE_TIME, 300); const delay = injector.get(LIST_QUERY_DEBOUNCE_TIME, 300);
this.delay = delay ? debounceTime(delay) : tap(); this.delay = delay ? debounceTime(delay) : tap();
@ -131,12 +131,12 @@ export class ListService<QueryParamsType = ABP.PageQueryParams> implements OnDes
} }
private next() { private next() {
this._query$.next(({ this._query$.next({
filter: this._filter || undefined, filter: this._filter || undefined,
maxResultCount: this._maxResultCount, maxResultCount: this._maxResultCount,
skipCount: this._page * this._maxResultCount, skipCount: this._page * this._maxResultCount,
sorting: this._sortOrder ? `${this._sortKey} ${this._sortOrder}` : undefined, sorting: this._sortOrder ? `${this._sortKey} ${this._sortOrder}` : undefined,
} as any) as QueryParamsType); } as any as QueryParamsType);
} }
} }

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/routes.service.ts

@ -6,6 +6,7 @@ import { BaseTreeNode, createTreeFromList, TreeNode } from '../utils/tree-utils'
import { ConfigStateService } from './config-state.service'; import { ConfigStateService } from './config-state.service';
import { PermissionService } from './permission.service'; import { PermissionService } from './permission.service';
// eslint-disable-next-line @typescript-eslint/ban-types
export abstract class AbstractTreeService<T extends object> { export abstract class AbstractTreeService<T extends object> {
abstract id: string; abstract id: string;
abstract parentId: string; abstract parentId: string;

15
npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/track-by.service.ts

@ -1,11 +1,18 @@
import { Injectable, TrackByFunction } from '@angular/core'; import { Injectable, TrackByFunction } from '@angular/core';
import { O } from 'ts-toolbelt'; import { O } from 'ts-toolbelt';
export const trackBy = <T = any>(key: keyof T): TrackByFunction<T> => (_, item) => item[key]; export const trackBy =
<T = any>(key: keyof T): TrackByFunction<T> =>
(_, item) =>
item[key];
export const trackByDeep = <T = any>( export const trackByDeep =
...keys: T extends object ? O.Paths<T> : never <T = any>(
): TrackByFunction<T> => (_, item) => keys.reduce((acc, key) => acc[key], item); // eslint-disable-next-line @typescript-eslint/ban-types
...keys: T extends object ? O.Paths<T> : never
): TrackByFunction<T> =>
(_, item) =>
keys.reduce((acc, key) => acc[key], item);
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',

57
npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/config-state.service.spec.ts

@ -1,4 +1,4 @@
import { CoreTestingModule } from '@abp/ng.core/testing'; import { HttpClientTestingModule } from '@angular/common/http/testing';
import { createServiceFactory, SpectatorService } from '@ngneat/spectator/jest'; import { createServiceFactory, SpectatorService } from '@ngneat/spectator/jest';
import { Store } from '@ngxs/store'; import { Store } from '@ngxs/store';
import { import {
@ -107,7 +107,7 @@ describe('ConfigState', () => {
const createService = createServiceFactory({ const createService = createServiceFactory({
service: ConfigStateService, service: ConfigStateService,
imports: [CoreTestingModule.withConfig()], imports: [HttpClientTestingModule],
providers: [ providers: [
{ provide: CORE_OPTIONS, useValue: { skipGetAppConfiguration: true } }, { provide: CORE_OPTIONS, useValue: { skipGetAppConfiguration: true } },
{ provide: Store, useValue: {} }, { provide: Store, useValue: {} },
@ -124,35 +124,29 @@ describe('ConfigState', () => {
describe('#getAll', () => { describe('#getAll', () => {
it('should return CONFIG_STATE_DATA', () => { it('should return CONFIG_STATE_DATA', () => {
expect(configState.getAll()).toEqual(CONFIG_STATE_DATA); expect(configState.getAll()).toEqual(CONFIG_STATE_DATA);
configState configState.getAll$().subscribe(data => expect(data).toEqual(CONFIG_STATE_DATA));
.getAll$()
.subscribe((data) => expect(data).toEqual(CONFIG_STATE_DATA));
}); });
}); });
describe('#getOne', () => { describe('#getOne', () => {
it('should return one property', () => { it('should return one property', () => {
expect(configState.getOne('localization')).toEqual( expect(configState.getOne('localization')).toEqual(CONFIG_STATE_DATA.localization);
CONFIG_STATE_DATA.localization
);
configState configState
.getOne$('localization') .getOne$('localization')
.subscribe((localization) => .subscribe(localization => expect(localization).toEqual(CONFIG_STATE_DATA.localization));
expect(localization).toEqual(CONFIG_STATE_DATA.localization)
);
}); });
}); });
describe('#getDeep', () => { describe('#getDeep', () => {
it('should return deeper', () => { it('should return deeper', () => {
expect(configState.getDeep('localization.languages')).toEqual( expect(configState.getDeep('localization.languages')).toEqual(
CONFIG_STATE_DATA.localization.languages CONFIG_STATE_DATA.localization.languages,
); );
configState configState
.getDeep$('localization.languages') .getDeep$('localization.languages')
.subscribe((languages) => .subscribe(languages =>
expect(languages).toEqual(CONFIG_STATE_DATA.localization.languages) expect(languages).toEqual(CONFIG_STATE_DATA.localization.languages),
); );
expect(configState.getDeep('test')).toBeFalsy(); expect(configState.getDeep('test')).toBeFalsy();
@ -162,30 +156,22 @@ describe('ConfigState', () => {
describe('#getFeature', () => { describe('#getFeature', () => {
it('should return a setting', () => { it('should return a setting', () => {
expect(configState.getFeature('Chat.Enable')).toEqual( expect(configState.getFeature('Chat.Enable')).toEqual(
CONFIG_STATE_DATA.features.values['Chat.Enable'] CONFIG_STATE_DATA.features.values['Chat.Enable'],
); );
configState configState
.getFeature$('Chat.Enable') .getFeature$('Chat.Enable')
.subscribe((data) => .subscribe(data => expect(data).toEqual(CONFIG_STATE_DATA.features.values['Chat.Enable']));
expect(data).toEqual(CONFIG_STATE_DATA.features.values['Chat.Enable'])
);
}); });
}); });
describe('#getSetting', () => { describe('#getSetting', () => {
it('should return a setting', () => { it('should return a setting', () => {
expect( expect(configState.getSetting('Abp.Localization.DefaultLanguage')).toEqual(
configState.getSetting('Abp.Localization.DefaultLanguage') CONFIG_STATE_DATA.setting.values['Abp.Localization.DefaultLanguage'],
).toEqual(
CONFIG_STATE_DATA.setting.values['Abp.Localization.DefaultLanguage']
); );
configState configState.getSetting$('Abp.Localization.DefaultLanguage').subscribe(data => {
.getSetting$('Abp.Localization.DefaultLanguage') expect(data).toEqual(CONFIG_STATE_DATA.setting.values['Abp.Localization.DefaultLanguage']);
.subscribe((data) => { });
expect(data).toEqual(
CONFIG_STATE_DATA.setting.values['Abp.Localization.DefaultLanguage']
);
});
}); });
}); });
@ -196,14 +182,9 @@ describe('ConfigState', () => {
${'Localization'} | ${{ 'Abp.Localization.DefaultLanguage': 'en' }} ${'Localization'} | ${{ 'Abp.Localization.DefaultLanguage': 'en' }}
${'X'} | ${{}} ${'X'} | ${{}}
${'localization'} | ${{}} ${'localization'} | ${{}}
`( `('should return $expected when keyword is given as $keyword', ({ keyword, expected }) => {
'should return $expected when keyword is given as $keyword', expect(configState.getSettings(keyword)).toEqual(expected);
({ keyword, expected }) => { configState.getSettings$(keyword).subscribe(data => expect(data).toEqual(expected));
expect(configState.getSettings(keyword)).toEqual(expected); });
configState
.getSettings$(keyword)
.subscribe((data) => expect(data).toEqual(expected));
}
);
}); });
}); });

72
npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/permission.guard.spec.ts

@ -1,12 +1,8 @@
import { CoreTestingModule } from '@abp/ng.core/testing';
import { APP_BASE_HREF } from '@angular/common'; import { APP_BASE_HREF } from '@angular/common';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { RouterModule } from '@angular/router'; import { RouterModule } from '@angular/router';
import { import { createServiceFactory, SpectatorService, SpyObject } from '@ngneat/spectator/jest';
createServiceFactory,
SpectatorService,
SpyObject,
} from '@ngneat/spectator/jest';
import { Actions, Store } from '@ngxs/store'; import { Actions, Store } from '@ngxs/store';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { RestOccurError } from '../actions'; import { RestOccurError } from '../actions';
@ -30,7 +26,7 @@ describe('PermissionGuard', () => {
mocks: [PermissionService, Store], mocks: [PermissionService, Store],
declarations: [DummyComponent], declarations: [DummyComponent],
imports: [ imports: [
CoreTestingModule.withConfig(), HttpClientTestingModule,
RouterModule.forRoot( RouterModule.forRoot(
[ [
{ {
@ -41,7 +37,7 @@ describe('PermissionGuard', () => {
}, },
}, },
], ],
{ relativeLinkResolution: 'legacy' } { relativeLinkResolution: 'legacy' },
), ),
], ],
providers: [ providers: [
@ -69,34 +65,30 @@ describe('PermissionGuard', () => {
permissionService = spectator.inject(PermissionService); permissionService = spectator.inject(PermissionService);
}); });
it('should return true when the grantedPolicy is true', (done) => { it('should return true when the grantedPolicy is true', done => {
permissionService.getGrantedPolicy$.andReturn(of(true)); permissionService.getGrantedPolicy$.andReturn(of(true));
const spy = jest.spyOn(store, 'dispatch'); const spy = jest.spyOn(store, 'dispatch');
guard guard.canActivate({ data: { requiredPolicy: 'test' } } as any, null).subscribe(res => {
.canActivate({ data: { requiredPolicy: 'test' } } as any, null) expect(res).toBe(true);
.subscribe((res) => { expect(spy.mock.calls).toHaveLength(0);
expect(res).toBe(true); done();
expect(spy.mock.calls).toHaveLength(0); });
done();
});
}); });
it('should return false and dispatch RestOccurError when the grantedPolicy is false', (done) => { it('should return false and dispatch RestOccurError when the grantedPolicy is false', done => {
permissionService.getGrantedPolicy$.andReturn(of(false)); permissionService.getGrantedPolicy$.andReturn(of(false));
const spy = jest.spyOn(store, 'dispatch'); const spy = jest.spyOn(store, 'dispatch');
guard guard.canActivate({ data: { requiredPolicy: 'test' } } as any, null).subscribe(res => {
.canActivate({ data: { requiredPolicy: 'test' } } as any, null) expect(res).toBe(false);
.subscribe((res) => { expect(spy.mock.calls[0][0] instanceof RestOccurError).toBeTruthy();
expect(res).toBe(false); expect((spy.mock.calls[0][0] as RestOccurError).payload).toEqual({
expect(spy.mock.calls[0][0] instanceof RestOccurError).toBeTruthy(); status: 403,
expect((spy.mock.calls[0][0] as RestOccurError).payload).toEqual({
status: 403,
});
done();
}); });
done();
});
}); });
it('should check the requiredPolicy from RoutesService', (done) => { it('should check the requiredPolicy from RoutesService', done => {
routes.add([ routes.add([
{ {
path: '/test', path: '/test',
@ -104,29 +96,23 @@ describe('PermissionGuard', () => {
requiredPolicy: 'TestPolicy', requiredPolicy: 'TestPolicy',
}, },
]); ]);
permissionService.getGrantedPolicy$.mockImplementation((policy) => permissionService.getGrantedPolicy$.mockImplementation(policy => of(policy === 'TestPolicy'));
of(policy === 'TestPolicy') guard.canActivate({ data: {} } as any, { url: 'test' } as any).subscribe(result => {
); expect(result).toBe(true);
guard done();
.canActivate({ data: {} } as any, { url: 'test' } as any) });
.subscribe((result) => {
expect(result).toBe(true);
done();
});
}); });
it('should return Observable<true> if RoutesService does not have requiredPolicy for given URL', (done) => { it('should return Observable<true> if RoutesService does not have requiredPolicy for given URL', done => {
routes.add([ routes.add([
{ {
path: '/test', path: '/test',
name: 'Test', name: 'Test',
}, },
]); ]);
guard guard.canActivate({ data: {} } as any, { url: 'test' } as any).subscribe(result => {
.canActivate({ data: {} } as any, { url: 'test' } as any) expect(result).toBe(true);
.subscribe((result) => { done();
expect(result).toBe(true); });
done();
});
}); });
}); });

6
npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/replaceable-template.directive.spec.ts

@ -1,4 +1,4 @@
import { Component, EventEmitter, Inject, Input, OnInit, Optional, Output } from '@angular/core'; import { Component, EventEmitter, Inject, Input, Optional, Output } from '@angular/core';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { createDirectiveFactory, SpectatorDirective } from '@ngneat/spectator/jest'; import { createDirectiveFactory, SpectatorDirective } from '@ngneat/spectator/jest';
import { BehaviorSubject } from 'rxjs'; import { BehaviorSubject } from 'rxjs';
@ -11,7 +11,7 @@ import { ReplaceableComponentsService } from '../services/replaceable-components
template: ' <p>default</p> ', template: ' <p>default</p> ',
exportAs: 'abpDefaultComponent', exportAs: 'abpDefaultComponent',
}) })
class DefaultComponent implements OnInit { class DefaultComponent {
@Input() @Input()
oneWay; oneWay;
@ -24,8 +24,6 @@ class DefaultComponent implements OnInit {
@Output() @Output()
readonly someOutput = new EventEmitter<string>(); readonly someOutput = new EventEmitter<string>();
ngOnInit() {}
setTwoWay(value) { setTwoWay(value) {
this.twoWay = value; this.twoWay = value;
this.twoWayChange.emit(value); this.twoWayChange.emit(value);

2
npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/routes.service.spec.ts

@ -1,7 +1,7 @@
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { take } from 'rxjs/operators'; import { take } from 'rxjs/operators';
import { RoutesService } from '../services'; import { RoutesService } from '../services';
import { DummyInjector, mockActions } from './utils/common.utils'; import { DummyInjector } from './utils/common.utils';
import { mockPermissionService } from './utils/permission-service.spec.utils'; import { mockPermissionService } from './utils/permission-service.spec.utils';
const updateStream$ = new Subject(); const updateStream$ = new Subject();

40
npm/ng-packs/nx/ng-packs/packages/core/src/lib/utils/rxjs-utils.ts

@ -9,24 +9,24 @@ function isFunction(value) {
/** /**
* @deprecated no longer working, please use SubscriptionService (https://docs.abp.io/en/abp/latest/UI/Angular/Subscription-Service) instead. * @deprecated no longer working, please use SubscriptionService (https://docs.abp.io/en/abp/latest/UI/Angular/Subscription-Service) instead.
*/ */
export const takeUntilDestroy = (componentInstance, destroyMethodName = 'ngOnDestroy') => <T>( export const takeUntilDestroy =
source: Observable<T>, (componentInstance, destroyMethodName = 'ngOnDestroy') =>
) => { <T>(source: Observable<T>) => {
const originalDestroy = componentInstance[destroyMethodName]; const originalDestroy = componentInstance[destroyMethodName];
if (isFunction(originalDestroy) === false) { if (isFunction(originalDestroy) === false) {
throw new Error( throw new Error(
`${componentInstance.constructor.name} is using untilDestroyed but doesn't implement ${destroyMethodName}`, `${componentInstance.constructor.name} is using untilDestroyed but doesn't implement ${destroyMethodName}`,
); );
} }
if (!componentInstance['__takeUntilDestroy']) { if (!componentInstance['__takeUntilDestroy']) {
componentInstance['__takeUntilDestroy'] = new Subject(); componentInstance['__takeUntilDestroy'] = new Subject();
componentInstance[destroyMethodName] = function() { componentInstance[destroyMethodName] = function () {
// tslint:disable-next-line: no-unused-expression // eslint-disable-next-line prefer-rest-params
isFunction(originalDestroy) && originalDestroy.apply(this, arguments); isFunction(originalDestroy) && originalDestroy.apply(this, arguments);
componentInstance['__takeUntilDestroy'].next(true); componentInstance['__takeUntilDestroy'].next(true);
componentInstance['__takeUntilDestroy'].complete(); componentInstance['__takeUntilDestroy'].complete();
}; };
} }
return source.pipe(takeUntil<T>(componentInstance['__takeUntilDestroy'])); return source.pipe(takeUntil<T>(componentInstance['__takeUntilDestroy']));
}; };

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/utils/tree-utils.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
export class BaseTreeNode<T extends object> { export class BaseTreeNode<T extends object> {
children: TreeNode<T>[] = []; children: TreeNode<T>[] = [];
isLeaf = true; isLeaf = true;

3
npm/ng-packs/nx/ng-packs/packages/feature-management/src/lib/directives/free-text-input.directive.ts

@ -1,4 +1,4 @@
import { Directive, Input, HostBinding } from '@angular/core'; import { Directive, HostBinding, Input } from '@angular/core';
// TODO: improve this type // TODO: improve this type
export interface FreeTextType { export interface FreeTextType {
@ -20,6 +20,7 @@ export const INPUT_TYPES = {
}) })
export class FreeTextInputDirective { export class FreeTextInputDirective {
_feature: FreeTextType; _feature: FreeTextType;
// eslint-disable-next-line @angular-eslint/no-input-rename
@Input('abpFeatureManagementFreeText') set feature(val: FreeTextType) { @Input('abpFeatureManagementFreeText') set feature(val: FreeTextType) {
this._feature = val; this._feature = val;
this.setInputType(); this.setInputType();

1
npm/ng-packs/nx/ng-packs/packages/feature-management/src/lib/proxy/validation/string-values/models.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
export interface IStringValueType { export interface IStringValueType {
name: string; name: string;

12
npm/ng-packs/nx/ng-packs/packages/identity/src/lib/proxy/identity/models.ts

@ -1,4 +1,9 @@
import type { ExtensibleEntityDto, ExtensibleFullAuditedEntityDto, ExtensibleObject, PagedAndSortedResultRequestDto } from '@abp/ng.core'; import type {
ExtensibleEntityDto,
ExtensibleFullAuditedEntityDto,
ExtensibleObject,
PagedAndSortedResultRequestDto,
} from '@abp/ng.core';
export interface ChangePasswordInput { export interface ChangePasswordInput {
currentPassword: string; currentPassword: string;
@ -9,9 +14,8 @@ export interface GetIdentityUsersInput extends PagedAndSortedResultRequestDto {
filter: string; filter: string;
} }
// tslint:disable-next-line: no-empty-interface // eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface IdentityRoleCreateDto extends IdentityRoleCreateOrUpdateDtoBase { export interface IdentityRoleCreateDto extends IdentityRoleCreateOrUpdateDtoBase {}
}
export interface IdentityRoleCreateOrUpdateDtoBase extends ExtensibleObject { export interface IdentityRoleCreateOrUpdateDtoBase extends ExtensibleObject {
name: string; name: string;

15
npm/ng-packs/nx/ng-packs/packages/schematics/.eslintrc.json

@ -27,10 +27,23 @@
] ]
} }
}, },
{
"files": ["*.ts", "*.tsx"],
"extends": ["plugin:@nrwl/nx/typescript"],
"rules": {
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-empty-function": ["warn"]
}
},
{
"files": ["*.js", "*.jsx"],
"extends": ["plugin:@nrwl/nx/javascript"],
"rules": {}
},
{ {
"files": ["*.html"], "files": ["*.html"],
"extends": ["plugin:@nrwl/nx/angular-template"], "extends": ["plugin:@nrwl/nx/angular-template"],
"rules": {} "rules": {}
} }
] ]
} }

3
npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/api/index.ts

@ -31,7 +31,7 @@ import {
} from '../../utils'; } from '../../utils';
import * as cases from '../../utils/text'; import * as cases from '../../utils/text';
export default function(schema: GenerateProxySchema) { export default function (schema: GenerateProxySchema) {
const params = removeDefaultPlaceholders(schema); const params = removeDefaultPlaceholders(schema);
const moduleName = params.module || 'app'; const moduleName = params.module || 'app';
@ -40,6 +40,7 @@ export default function(schema: GenerateProxySchema) {
const getRootNamespace = createRootNamespaceGetter(params); const getRootNamespace = createRootNamespaceGetter(params);
const solution = await getRootNamespace(tree); const solution = await getRootNamespace(tree);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const target = await resolveProject(tree, params.target!); const target = await resolveProject(tree, params.target!);
const targetPath = buildDefaultPath(target.definition); const targetPath = buildDefaultPath(target.definition);
const readProxyConfig = createProxyConfigReader(targetPath); const readProxyConfig = createProxyConfigReader(targetPath);

3
npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/proxy-index/index.ts

@ -6,10 +6,11 @@ import {
resolveProject, resolveProject,
} from '../../utils'; } from '../../utils';
export default function(schema: { target?: string }) { export default function (schema: { target?: string }) {
const params = removeDefaultPlaceholders(schema); const params = removeDefaultPlaceholders(schema);
return async (host: Tree, _context: SchematicContext) => { return async (host: Tree, _context: SchematicContext) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const target = await resolveProject(host, params.target!); const target = await resolveProject(host, params.target!);
const targetPath = buildDefaultPath(target.definition); const targetPath = buildDefaultPath(target.definition);

3
npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/proxy-remove/index.ts

@ -13,11 +13,12 @@ import {
resolveProject, resolveProject,
} from '../../utils'; } from '../../utils';
export default function(schema: GenerateProxySchema) { export default function (schema: GenerateProxySchema) {
const params = removeDefaultPlaceholders(schema); const params = removeDefaultPlaceholders(schema);
const moduleName = params.module || 'app'; const moduleName = params.module || 'app';
return async (host: Tree, _context: SchematicContext) => { return async (host: Tree, _context: SchematicContext) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const target = await resolveProject(host, params.target!); const target = await resolveProject(host, params.target!);
const targetPath = buildDefaultPath(target.definition); const targetPath = buildDefaultPath(target.definition);

2
npm/ng-packs/nx/ng-packs/packages/schematics/src/models/method.ts

@ -3,6 +3,7 @@ import { camel } from '../utils/text';
import { ParameterInBody } from './api-definition'; import { ParameterInBody } from './api-definition';
import { Property } from './model'; import { Property } from './model';
import { Omissible } from './util'; import { Omissible } from './util';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const shouldQuote = require('should-quote'); const shouldQuote = require('should-quote');
export class Method { export class Method {
@ -60,6 +61,7 @@ export class Body {
this.body = value; this.body = value;
break; break;
case eBindingSourceId.Path: case eBindingSourceId.Path:
// eslint-disable-next-line no-case-declarations
const regex = new RegExp('{(' + paramName + '|' + camelName + '|' + name + ')}', 'g'); const regex = new RegExp('{(' + paramName + '|' + camelName + '|' + name + ')}', 'g');
this.url = this.url.replace(regex, '${' + value + '}'); this.url = this.url.replace(regex, '${' + value + '}');
break; break;

2
npm/ng-packs/nx/ng-packs/packages/schematics/src/models/util.ts

@ -9,7 +9,7 @@ type ExcludeKeys<Type, Excluded> = Exclude<
never never
>; >;
// tslint:disable-next-line: ban-types // eslint-disable-next-line @typescript-eslint/ban-types
type ExcludeMethods<Type> = Pick<Type, ExcludeKeys<Type, Function>>; type ExcludeMethods<Type> = Pick<Type, ExcludeKeys<Type, Function>>;
// Options (methods will be omitted, given keys will become optional) // Options (methods will be omitted, given keys will become optional)

247
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/ast-utils.ts

@ -8,7 +8,6 @@
import * as ts from 'typescript'; import * as ts from 'typescript';
import { Change, InsertChange, NoopChange } from './change'; import { Change, InsertChange, NoopChange } from './change';
/** /**
* Add Import `import { symbolName } from fileName` if the import doesn't exit * Add Import `import { symbolName } from fileName` if the import doesn't exit
* already. Assumes fileToEdit can be resolved and accessed. * already. Assumes fileToEdit can be resolved and accessed.
@ -18,15 +17,21 @@ import { Change, InsertChange, NoopChange } from './change';
* @param isDefault (if true, import follows style for importing default exports) * @param isDefault (if true, import follows style for importing default exports)
* @return Change * @return Change
*/ */
export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolName: string, export function insertImport(
fileName: string, isDefault = false): Change { source: ts.SourceFile,
fileToEdit: string,
symbolName: string,
fileName: string,
isDefault = false,
): Change {
const rootNode = source; const rootNode = source;
const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration); const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
// get nodes that map to import statements from the file fileName // 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). // StringLiteral of the ImportDeclaration is the import file (fileName in this case).
const importFiles = node.getChildren() const importFiles = node
.getChildren()
.filter(ts.isStringLiteral) .filter(ts.isStringLiteral)
.map(n => n.text); .map(n => n.text);
@ -64,8 +69,7 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa
} }
// no such import declaration exists // no such import declaration exists
const useStrict = findNodes(rootNode, ts.isStringLiteral) const useStrict = findNodes(rootNode, ts.isStringLiteral).filter(n => n.text === 'use strict');
.filter((n) => n.text === 'use strict');
let fallbackPos = 0; let fallbackPos = 0;
if (useStrict.length > 0) { if (useStrict.length > 0) {
fallbackPos = useStrict[0].end; fallbackPos = useStrict[0].end;
@ -75,7 +79,8 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa
// if there are no imports or 'use strict' statement, insert import at beginning of file // if there are no imports or 'use strict' statement, insert import at beginning of file
const insertAtBeginning = allImports.length === 0 && useStrict.length === 0; const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
const separator = insertAtBeginning ? '' : ';\n'; const separator = insertAtBeginning ? '' : ';\n';
const toInsert = `${separator}import ${open}${symbolName}${close}` + const toInsert =
`${separator}import ${open}${symbolName}${close}` +
` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`; ` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`;
return insertAfterLastOccurrence( return insertAfterLastOccurrence(
@ -87,7 +92,6 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa
); );
} }
/** /**
* Find all nodes from the AST in the subtree of node of SyntaxKind kind. * Find all nodes from the AST in the subtree of node of SyntaxKind kind.
* @param node * @param node
@ -97,7 +101,12 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa
* the last child even when node of kind has been found. * the last child even when node of kind has been found.
* @return all nodes of kind, or [] if none is found * @return all nodes of kind, or [] if none is found
*/ */
export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max?: number, recursive?: boolean): ts.Node[]; export function findNodes(
node: ts.Node,
kind: ts.SyntaxKind,
max?: number,
recursive?: boolean,
): ts.Node[];
/** /**
* Find all nodes from the AST in the subtree that satisfy a type guard. * Find all nodes from the AST in the subtree that satisfy a type guard.
@ -108,7 +117,12 @@ export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max?: number, recu
* the last child even when node of kind has been found. * the last child even when node of kind has been found.
* @return all nodes that satisfy the type guard, or [] if none is found * @return all nodes that satisfy the type guard, or [] if none is found
*/ */
export function findNodes<T extends ts.Node>(node: ts.Node, guard: (node: ts.Node) => node is T, max?: number, recursive?: boolean): T[]; export function findNodes<T extends ts.Node>(
node: ts.Node,
guard: (node: ts.Node) => node is T,
max?: number,
recursive?: boolean,
): T[];
export function findNodes<T extends ts.Node>( export function findNodes<T extends ts.Node>(
node: ts.Node, node: ts.Node,
@ -132,7 +146,7 @@ export function findNodes<T extends ts.Node>(
} }
if (max > 0 && (recursive || !test(node))) { if (max > 0 && (recursive || !test(node))) {
for (const child of node.getChildren()) { for (const child of node.getChildren()) {
findNodes(child, test, max).forEach((node) => { findNodes(child, test, max).forEach(node => {
if (max > 0) { if (max > 0) {
arr.push(node); arr.push(node);
} }
@ -148,7 +162,6 @@ export function findNodes<T extends ts.Node>(
return arr; return arr;
} }
/** /**
* Get all the nodes from a source. * Get all the nodes from a source.
* @param sourceFile The source file object. * @param sourceFile The source file object.
@ -186,7 +199,6 @@ export function findNode(node: ts.Node, kind: ts.SyntaxKind, text: string): ts.N
return foundNode; return foundNode;
} }
/** /**
* Helper for sorting nodes. * Helper for sorting nodes.
* @return function to sort nodes in increasing order of position in sourceFile * @return function to sort nodes in increasing order of position in sourceFile
@ -195,7 +207,6 @@ function nodesByPosition(first: ts.Node, second: ts.Node): number {
return first.getStart() - second.getStart(); return first.getStart() - second.getStart();
} }
/** /**
* Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]` * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
* or after the last of occurence of `syntaxKind` if the last occurence is a sub child * or after the last of occurence of `syntaxKind` if the last occurence is a sub child
@ -209,11 +220,13 @@ function nodesByPosition(first: ts.Node, second: ts.Node): number {
* @return Change instance * @return Change instance
* @throw Error if toInsert is first occurence but fall back is not set * @throw Error if toInsert is first occurence but fall back is not set
*/ */
export function insertAfterLastOccurrence(nodes: ts.Node[], export function insertAfterLastOccurrence(
toInsert: string, nodes: ts.Node[],
file: string, toInsert: string,
fallbackPos: number, file: string,
syntaxKind?: ts.SyntaxKind): Change { fallbackPos: number,
syntaxKind?: ts.SyntaxKind,
): Change {
let lastItem: ts.Node | undefined; let lastItem: ts.Node | undefined;
for (const node of nodes) { for (const node of nodes) {
if (!lastItem || lastItem.getStart() < node.getStart()) { if (!lastItem || lastItem.getStart() < node.getStart()) {
@ -231,7 +244,6 @@ export function insertAfterLastOccurrence(nodes: ts.Node[],
return new InsertChange(file, lastItemPosition, toInsert); return new InsertChange(file, lastItemPosition, toInsert);
} }
export function getContentOfKeyLiteral(_source: ts.SourceFile, node: ts.Node): string | null { export function getContentOfKeyLiteral(_source: ts.SourceFile, node: ts.Node): string | null {
if (node.kind == ts.SyntaxKind.Identifier) { if (node.kind == ts.SyntaxKind.Identifier) {
return (node as ts.Identifier).text; return (node as ts.Identifier).text;
@ -242,9 +254,10 @@ export function getContentOfKeyLiteral(_source: ts.SourceFile, node: ts.Node): s
} }
} }
function _angularImportsFromNode(
function _angularImportsFromNode(node: ts.ImportDeclaration, node: ts.ImportDeclaration,
_sourceFile: ts.SourceFile): {[name: string]: string} { _sourceFile: ts.SourceFile,
): { [name: string]: string } {
const ms = node.moduleSpecifier; const ms = node.moduleSpecifier;
let modulePath: string; let modulePath: string;
switch (ms.kind) { switch (ms.kind) {
@ -275,8 +288,8 @@ function _angularImportsFromNode(node: ts.ImportDeclaration,
const namedImports = nb as ts.NamedImports; const namedImports = nb as ts.NamedImports;
return namedImports.elements return namedImports.elements
.map((is: ts.ImportSpecifier) => is.propertyName ? is.propertyName.text : is.name.text) .map((is: ts.ImportSpecifier) => (is.propertyName ? is.propertyName.text : is.name.text))
.reduce((acc: {[name: string]: string}, curr: string) => { .reduce((acc: { [name: string]: string }, curr: string) => {
acc[curr] = modulePath; acc[curr] = modulePath;
return acc; return acc;
@ -291,11 +304,13 @@ function _angularImportsFromNode(node: ts.ImportDeclaration,
} }
} }
export function getDecoratorMetadata(
export function getDecoratorMetadata(source: ts.SourceFile, identifier: string, source: ts.SourceFile,
module: string): ts.Node[] { identifier: string,
module: string,
): ts.Node[] {
const angularImports = findNodes(source, ts.isImportDeclaration) const angularImports = findNodes(source, ts.isImportDeclaration)
.map((node) => _angularImportsFromNode(node, source)) .map(node => _angularImportsFromNode(node, source))
.reduce((acc, current) => { .reduce((acc, current) => {
for (const key of Object.keys(current)) { for (const key of Object.keys(current)) {
acc[key] = current[key]; acc[key] = current[key];
@ -306,8 +321,10 @@ export function getDecoratorMetadata(source: ts.SourceFile, identifier: string,
return getSourceNodes(source) return getSourceNodes(source)
.filter(node => { .filter(node => {
return node.kind == ts.SyntaxKind.Decorator return (
&& (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression; node.kind == ts.SyntaxKind.Decorator &&
(node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression
);
}) })
.map(node => (node as ts.Decorator).expression as ts.CallExpression) .map(node => (node as ts.Decorator).expression as ts.CallExpression)
.filter(expr => { .filter(expr => {
@ -326,17 +343,18 @@ export function getDecoratorMetadata(source: ts.SourceFile, identifier: string,
const id = paExpr.name.text; const id = paExpr.name.text;
const moduleId = (paExpr.expression as ts.Identifier).text; const moduleId = (paExpr.expression as ts.Identifier).text;
return id === identifier && (angularImports[moduleId + '.'] === module); return id === identifier && angularImports[moduleId + '.'] === module;
} }
return false; return false;
}) })
.filter(expr => expr.arguments[0] .filter(
&& expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression) 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 findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration|undefined { function findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration | undefined {
if (ts.isClassDeclaration(node)) { if (ts.isClassDeclaration(node)) {
return node; return node;
} }
@ -350,7 +368,7 @@ function findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration|undefine
* @param source source file containing one or more @NgModule * @param source source file containing one or more @NgModule
* @returns the name of the first @NgModule, or `undefined` if none is found * @returns the name of the first @NgModule, or `undefined` if none is found
*/ */
export function getFirstNgModuleName(source: ts.SourceFile): string|undefined { export function getFirstNgModuleName(source: ts.SourceFile): string | undefined {
// First, find the @NgModule decorators. // First, find the @NgModule decorators.
const ngModulesMetadata = getDecoratorMetadata(source, 'NgModule', '@angular/core'); const ngModulesMetadata = getDecoratorMetadata(source, 'NgModule', '@angular/core');
if (ngModulesMetadata.length === 0) { if (ngModulesMetadata.length === 0) {
@ -372,14 +390,17 @@ export function getMetadataField(
node: ts.ObjectLiteralExpression, node: ts.ObjectLiteralExpression,
metadataField: string, metadataField: string,
): ts.ObjectLiteralElement[] { ): ts.ObjectLiteralElement[] {
return node.properties return (
.filter(ts.isPropertyAssignment) node.properties
// Filter out every fields that's not "metadataField". Also handles string literals .filter(ts.isPropertyAssignment)
// (but not expressions). // Filter out every fields that's not "metadataField". Also handles string literals
.filter(({ name }) => { // (but not expressions).
return (ts.isIdentifier(name) || ts.isStringLiteral(name)) .filter(({ name }) => {
&& name.getText() === metadataField; return (
}); (ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.getText() === metadataField
);
})
);
} }
export function addSymbolToNgModuleMetadata( export function addSymbolToNgModuleMetadata(
@ -390,7 +411,7 @@ export function addSymbolToNgModuleMetadata(
importPath: string | null = null, importPath: string | null = null,
): Change[] { ): Change[] {
const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core'); const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
let node: any = nodes[0]; // tslint:disable-line:no-any let node: any = nodes[0]; // tslint:disable-line:no-any
// Find the decorator declaration. // Find the decorator declaration.
if (!node) { if (!node) {
@ -398,10 +419,7 @@ export function addSymbolToNgModuleMetadata(
} }
// Get all the children property assignment of object literals. // Get all the children property assignment of object literals.
const matchingProperties = getMetadataField( const matchingProperties = getMetadataField(node as ts.ObjectLiteralExpression, metadataField);
node as ts.ObjectLiteralExpression,
metadataField,
);
// Get the last node of the array literal. // Get the last node of the array literal.
if (!matchingProperties) { if (!matchingProperties) {
@ -459,6 +477,7 @@ export function addSymbolToNgModuleMetadata(
} }
if (Array.isArray(node)) { if (Array.isArray(node)) {
// eslint-disable-next-line @typescript-eslint/ban-types
const nodeArray = node as {} as Array<ts.Node>; const nodeArray = node as {} as Array<ts.Node>;
const symbolsArray = nodeArray.map(node => node.getText()); const symbolsArray = nodeArray.map(node => node.getText());
if (symbolsArray.includes(symbolName)) { if (symbolsArray.includes(symbolName)) {
@ -513,47 +532,66 @@ export function addSymbolToNgModuleMetadata(
* Custom function to insert a declaration (component, pipe, directive) * Custom function to insert a declaration (component, pipe, directive)
* into NgModule declarations. It also imports the component. * into NgModule declarations. It also imports the component.
*/ */
export function addDeclarationToModule(source: ts.SourceFile, export function addDeclarationToModule(
modulePath: string, classifiedName: string, source: ts.SourceFile,
importPath: string): Change[] { modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata( return addSymbolToNgModuleMetadata(
source, modulePath, 'declarations', classifiedName, importPath); source,
modulePath,
'declarations',
classifiedName,
importPath,
);
} }
/** /**
* Custom function to insert an NgModule into NgModule imports. It also imports the module. * Custom function to insert an NgModule into NgModule imports. It also imports the module.
*/ */
export function addImportToModule(source: ts.SourceFile, export function addImportToModule(
modulePath: string, classifiedName: string, source: ts.SourceFile,
importPath: string): Change[] { modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath); return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath);
} }
/** /**
* Custom function to insert a provider into NgModule. It also imports it. * Custom function to insert a provider into NgModule. It also imports it.
*/ */
export function addProviderToModule(source: ts.SourceFile, export function addProviderToModule(
modulePath: string, classifiedName: string, source: ts.SourceFile,
importPath: string): Change[] { modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath); return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath);
} }
/** /**
* Custom function to insert an export into NgModule. It also imports it. * Custom function to insert an export into NgModule. It also imports it.
*/ */
export function addExportToModule(source: ts.SourceFile, export function addExportToModule(
modulePath: string, classifiedName: string, source: ts.SourceFile,
importPath: string): Change[] { modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath); return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath);
} }
/** /**
* Custom function to insert an export into NgModule. It also imports it. * Custom function to insert an export into NgModule. It also imports it.
*/ */
export function addBootstrapToModule(source: ts.SourceFile, export function addBootstrapToModule(
modulePath: string, classifiedName: string, source: ts.SourceFile,
importPath: string): Change[] { modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath); return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath);
} }
@ -561,33 +599,41 @@ export function addBootstrapToModule(source: ts.SourceFile,
* Custom function to insert an entryComponent into NgModule. It also imports it. * Custom function to insert an entryComponent into NgModule. It also imports it.
* @deprecated - Since version 9.0.0 with Ivy, entryComponents is no longer necessary. * @deprecated - Since version 9.0.0 with Ivy, entryComponents is no longer necessary.
*/ */
export function addEntryComponentToModule(source: ts.SourceFile, export function addEntryComponentToModule(
modulePath: string, classifiedName: string, source: ts.SourceFile,
importPath: string): Change[] { modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata( return addSymbolToNgModuleMetadata(
source, modulePath, source,
'entryComponents', classifiedName, importPath, modulePath,
'entryComponents',
classifiedName,
importPath,
); );
} }
/** /**
* Determine if an import already exists. * Determine if an import already exists.
*/ */
export function isImported(source: ts.SourceFile, export function isImported(
classifiedName: string, source: ts.SourceFile,
importPath: string): boolean { classifiedName: string,
importPath: string,
): boolean {
const allNodes = getSourceNodes(source); const allNodes = getSourceNodes(source);
const matchingNodes = allNodes const matchingNodes = allNodes
.filter(ts.isImportDeclaration) .filter(ts.isImportDeclaration)
.filter( .filter(
(imp) => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath, imp => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath,
) )
.filter((imp) => { .filter(imp => {
if (!imp.importClause) { if (!imp.importClause) {
return false; return false;
} }
const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter( const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter(
(n) => n.getText() === classifiedName, n => n.getText() === classifiedName,
); );
return nodes.length > 0; return nodes.length > 0;
@ -611,11 +657,11 @@ export function getEnvironmentExportName(source: ts.SourceFile): string | null {
allNodes allNodes
.filter(ts.isImportDeclaration) .filter(ts.isImportDeclaration)
.filter( .filter(
(declaration) => declaration =>
declaration.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral && declaration.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral &&
declaration.importClause !== undefined, declaration.importClause !== undefined,
) )
.map((declaration) => .map(declaration =>
// If `importClause` property is defined then the first // If `importClause` property is defined then the first
// child will be `NamedImports` object (or `namedBindings`). // child will be `NamedImports` object (or `namedBindings`).
(declaration.importClause as ts.ImportClause).getChildAt(0), (declaration.importClause as ts.ImportClause).getChildAt(0),
@ -623,8 +669,8 @@ export function getEnvironmentExportName(source: ts.SourceFile): string | null {
// Find those `NamedImports` object that contains `environment` keyword // Find those `NamedImports` object that contains `environment` keyword
// in its text. E.g. `{ environment as env }`. // in its text. E.g. `{ environment as env }`.
.filter(ts.isNamedImports) .filter(ts.isNamedImports)
.filter((namedImports) => namedImports.getText().includes('environment')) .filter(namedImports => namedImports.getText().includes('environment'))
.forEach((namedImports) => { .forEach(namedImports => {
for (const specifier of namedImports.elements) { for (const specifier of namedImports.elements) {
// `propertyName` is defined if the specifier // `propertyName` is defined if the specifier
// has an aliased import. // has an aliased import.
@ -682,8 +728,7 @@ export function addRouteDeclarationToModule(
if (!scopeConfigMethodArgs.length) { if (!scopeConfigMethodArgs.length) {
const { line } = source.getLineAndCharacterOfPosition(routerModuleExpr.getStart()); const { line } = source.getLineAndCharacterOfPosition(routerModuleExpr.getStart());
throw new Error( throw new Error(
`The router module method doesn't have arguments ` + `The router module method doesn't have arguments ` + `at line ${line} in ${fileToAdd}`,
`at line ${line} in ${fileToAdd}`,
); );
} }
@ -698,22 +743,24 @@ export function addRouteDeclarationToModule(
const routesVarName = routesArg.getText(); const routesVarName = routesArg.getText();
let routesVar; let routesVar;
if (routesArg.kind === ts.SyntaxKind.Identifier) { if (routesArg.kind === ts.SyntaxKind.Identifier) {
routesVar = source.statements routesVar = source.statements.filter(ts.isVariableStatement).find(v => {
.filter(ts.isVariableStatement) return v.declarationList.declarations[0].name.getText() === routesVarName;
.find((v) => { });
return v.declarationList.declarations[0].name.getText() === routesVarName;
});
} }
if (!routesVar) { if (!routesVar) {
const { line } = source.getLineAndCharacterOfPosition(routesArg.getStart()); const { line } = source.getLineAndCharacterOfPosition(routesArg.getStart());
throw new Error( throw new Error(
`No route declaration array was found that corresponds ` + `No route declaration array was found that corresponds ` +
`to router module at line ${line} in ${fileToAdd}`, `to router module at line ${line} in ${fileToAdd}`,
); );
} }
routesArr = findNodes(routesVar, ts.SyntaxKind.ArrayLiteralExpression, 1)[0] as ts.ArrayLiteralExpression; routesArr = findNodes(
routesVar,
ts.SyntaxKind.ArrayLiteralExpression,
1,
)[0] as ts.ArrayLiteralExpression;
} }
const occurrencesCount = routesArr.elements.length; const occurrencesCount = routesArr.elements.length;
@ -724,16 +771,16 @@ export function addRouteDeclarationToModule(
if (occurrencesCount > 0) { if (occurrencesCount > 0) {
const lastRouteLiteral = [...routesArr.elements].pop() as ts.Expression; const lastRouteLiteral = [...routesArr.elements].pop() as ts.Expression;
const lastRouteIsWildcard = ts.isObjectLiteralExpression(lastRouteLiteral) const lastRouteIsWildcard =
&& lastRouteLiteral ts.isObjectLiteralExpression(lastRouteLiteral) &&
.properties lastRouteLiteral.properties.some(
.some(n => ( n =>
ts.isPropertyAssignment(n) ts.isPropertyAssignment(n) &&
&& ts.isIdentifier(n.name) ts.isIdentifier(n.name) &&
&& n.name.text === 'path' n.name.text === 'path' &&
&& ts.isStringLiteral(n.initializer) ts.isStringLiteral(n.initializer) &&
&& n.initializer.text === '**' n.initializer.text === '**',
)); );
const indentation = text.match(/\r?\n(\r?)\s*/) || []; const indentation = text.match(/\r?\n(\r?)\s*/) || [];
const routeText = `${indentation[0] || ' '}${routeLiteral}`; const routeText = `${indentation[0] || ' '}${routeLiteral}`;

571
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/config.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
/** /**
* @license * @license
* Copyright Google Inc. All Rights Reserved. * Copyright Google Inc. All Rights Reserved.
@ -31,20 +32,23 @@ export interface AppConfig {
/** /**
* List of application assets. * List of application assets.
*/ */
assets?: (string | { assets?: (
/** | string
* The pattern to match. | {
*/ /**
glob?: string; * The pattern to match.
/** */
* The dir to search within. glob?: string;
*/ /**
input?: string; * The dir to search within.
/** */
* The output path (relative to the outDir). input?: string;
*/ /**
output?: string; * The output path (relative to the outDir).
})[]; */
output?: string;
}
)[];
/** /**
* URL where files will be deployed. * URL where files will be deployed.
*/ */
@ -56,7 +60,7 @@ export interface AppConfig {
/** /**
* The runtime platform of the app. * The runtime platform of the app.
*/ */
platform?: ('browser' | 'server'); platform?: 'browser' | 'server';
/** /**
* The name of the start HTML file. * The name of the start HTML file.
*/ */
@ -92,26 +96,32 @@ export interface AppConfig {
/** /**
* Global styles to be included in the build. * Global styles to be included in the build.
*/ */
styles?: (string | { styles?: (
input?: string; | string
[name: string]: any; // tslint:disable-line:no-any | {
})[]; input?: string;
[name: string]: any; // tslint:disable-line:no-any
}
)[];
/** /**
* Options to pass to style preprocessors * Options to pass to style preprocessors
*/ */
stylePreprocessorOptions?: { stylePreprocessorOptions?: {
/** /**
* Paths to include. Paths will be resolved to project root. * Paths to include. Paths will be resolved to project root.
*/ */
includePaths?: string[]; includePaths?: string[];
}; };
/** /**
* Global scripts to be included in the build. * Global scripts to be included in the build.
*/ */
scripts?: (string | { scripts?: (
input: string; | string
[name: string]: any; // tslint:disable-line:no-any | {
})[]; input: string;
[name: string]: any; // tslint:disable-line:no-any
}
)[];
/** /**
* Source file for environment config. * Source file for environment config.
*/ */
@ -120,7 +130,7 @@ export interface AppConfig {
* Name and corresponding file for environment config. * Name and corresponding file for environment config.
*/ */
environments?: { environments?: {
[name: string]: any; // tslint:disable-line:no-any [name: string]: any; // tslint:disable-line:no-any
}; };
appShell?: { appShell?: {
app: string; app: string;
@ -130,7 +140,7 @@ export interface AppConfig {
/** /**
* The type of budget * The type of budget
*/ */
type?: ('bundle' | 'initial' | 'allScript' | 'all' | 'anyScript' | 'any' | 'anyComponentStyle'); type?: 'bundle' | 'initial' | 'allScript' | 'all' | 'anyScript' | 'any' | 'anyComponentStyle';
/** /**
* The name of the bundle * The name of the bundle
*/ */
@ -172,14 +182,14 @@ export interface CliConfig {
* The global configuration of the project. * The global configuration of the project.
*/ */
project?: { project?: {
/** /**
* The name of the project. * The name of the project.
*/ */
name?: string; name?: string;
/** /**
* Whether or not this project was ejected. * Whether or not this project was ejected.
*/ */
ejected?: boolean; ejected?: boolean;
}; };
/** /**
* Properties of the different applications in this project. * Properties of the different applications in this project.
@ -189,278 +199,278 @@ export interface CliConfig {
* Configuration for end-to-end tests. * Configuration for end-to-end tests.
*/ */
e2e?: { e2e?: {
protractor?: { protractor?: {
/** /**
* Path to the config file. * Path to the config file.
*/ */
config?: string; config?: string;
}; };
}; };
/** /**
* Properties to be passed to TSLint. * Properties to be passed to TSLint.
*/ */
lint?: { lint?: {
/** /**
* File glob(s) to lint. * File glob(s) to lint.
*/ */
files?: (string | string[]); files?: string | string[];
/** /**
* Location of the tsconfig.json project file. * Location of the tsconfig.json project file.
* Will also use as files to lint if 'files' property not present. * Will also use as files to lint if 'files' property not present.
*/ */
project: string; project: string;
/** /**
* Location of the tslint.json configuration. * Location of the tslint.json configuration.
*/ */
tslintConfig?: string; tslintConfig?: string;
/** /**
* File glob(s) to ignore. * File glob(s) to ignore.
*/ */
exclude?: (string | string[]); exclude?: string | string[];
}[]; }[];
/** /**
* Configuration for unit tests. * Configuration for unit tests.
*/ */
test?: { test?: {
karma?: { karma?: {
/** /**
* Path to the karma config file. * Path to the karma config file.
*/ */
config?: string; config?: string;
}; };
codeCoverage?: { codeCoverage?: {
/** /**
* Globs to exclude from code coverage. * Globs to exclude from code coverage.
*/ */
exclude?: string[]; exclude?: string[];
}; };
}; };
/** /**
* Specify the default values for generating. * Specify the default values for generating.
*/ */
defaults?: { defaults?: {
/**
* The file extension to be used for style files.
*/
styleExt?: string;
/**
* How often to check for file updates.
*/
poll?: number;
/**
* Use lint to fix files after generation
*/
lintFix?: boolean;
/**
* Options for generating a class.
*/
class?: {
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a component.
*/
component?: {
/** /**
* The file extension to be used for style files. * Flag to indicate if a directory is created.
*/ */
styleExt?: string; flat?: boolean;
/** /**
* How often to check for file updates. * Specifies if a spec file is generated.
*/
spec?: boolean;
/**
* Specifies if the style will be in the ts file.
*/
inlineStyle?: boolean;
/**
* Specifies if the template will be in the ts file.
*/
inlineTemplate?: boolean;
/**
* Specifies the view encapsulation strategy.
*/
viewEncapsulation?: 'Emulated' | 'Native' | 'None';
/**
* Specifies the change detection strategy.
*/
changeDetection?: 'Default' | 'OnPush';
};
/**
* Options for generating a directive.
*/
directive?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a guard.
*/
guard?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating an interface.
*/
interface?: {
/**
* Prefix to apply to interface names. (i.e. I)
*/
prefix?: string;
};
/**
* Options for generating a module.
*/
module?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a pipe.
*/
pipe?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a service.
*/
service?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Properties to be passed to the build command.
*/
build?: {
/**
* Output sourcemaps.
*/
sourcemaps?: boolean;
/**
* Base url for the application being built.
*/
baseHref?: string;
/**
* The ssl key used by the server.
*/
progress?: boolean;
/**
* Enable and define the file watching poll time period (milliseconds).
*/ */
poll?: number; poll?: number;
/** /**
* Use lint to fix files after generation * Delete output path before build.
*/ */
lintFix?: boolean; deleteOutputPath?: boolean;
/** /**
* Options for generating a class. * Do not use the real path when resolving modules.
*/ */
class?: { preserveSymlinks?: boolean;
/** /**
* Specifies if a spec file is generated. * Show circular dependency warnings on builds.
*/ */
spec?: boolean; showCircularDependencies?: boolean;
}; /**
/** * Use a separate bundle containing code used across multiple bundles.
* Options for generating a component. */
*/ commonChunk?: boolean;
component?: { /**
/** * Use file name for lazy loaded chunks.
* Flag to indicate if a directory is created. */
*/ namedChunks?: boolean;
flat?: boolean; };
/** /**
* Specifies if a spec file is generated. * Properties to be passed to the serve command.
*/ */
spec?: boolean; serve?: {
/** /**
* Specifies if the style will be in the ts file. * The port the application will be served on.
*/ */
inlineStyle?: boolean; port?: number;
/** /**
* Specifies if the template will be in the ts file. * The host the application will be served on.
*/ */
inlineTemplate?: boolean; host?: string;
/** /**
* Specifies the view encapsulation strategy. * Enables ssl for the application.
*/ */
viewEncapsulation?: ('Emulated' | 'Native' | 'None'); ssl?: boolean;
/** /**
* Specifies the change detection strategy. * The ssl key used by the server.
*/ */
changeDetection?: ('Default' | 'OnPush'); sslKey?: string;
}; /**
/** * The ssl certificate used by the server.
* Options for generating a directive. */
*/ sslCert?: string;
directive?: { /**
/** * Proxy configuration file.
* Flag to indicate if a directory is created. */
*/ proxyConfig?: string;
flat?: boolean; };
/** /**
* Specifies if a spec file is generated. * Properties about schematics.
*/ */
spec?: boolean; schematics?: {
}; /**
/** * The schematics collection to use.
* Options for generating a guard. */
*/ collection?: string;
guard?: { /**
/** * The new app schematic.
* Flag to indicate if a directory is created. */
*/ newApp?: string;
flat?: boolean; };
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating an interface.
*/
interface?: {
/**
* Prefix to apply to interface names. (i.e. I)
*/
prefix?: string;
};
/**
* Options for generating a module.
*/
module?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a pipe.
*/
pipe?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a service.
*/
service?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Properties to be passed to the build command.
*/
build?: {
/**
* Output sourcemaps.
*/
sourcemaps?: boolean;
/**
* Base url for the application being built.
*/
baseHref?: string;
/**
* The ssl key used by the server.
*/
progress?: boolean;
/**
* Enable and define the file watching poll time period (milliseconds).
*/
poll?: number;
/**
* Delete output path before build.
*/
deleteOutputPath?: boolean;
/**
* Do not use the real path when resolving modules.
*/
preserveSymlinks?: boolean;
/**
* Show circular dependency warnings on builds.
*/
showCircularDependencies?: boolean;
/**
* Use a separate bundle containing code used across multiple bundles.
*/
commonChunk?: boolean;
/**
* Use file name for lazy loaded chunks.
*/
namedChunks?: boolean;
};
/**
* Properties to be passed to the serve command.
*/
serve?: {
/**
* The port the application will be served on.
*/
port?: number;
/**
* The host the application will be served on.
*/
host?: string;
/**
* Enables ssl for the application.
*/
ssl?: boolean;
/**
* The ssl key used by the server.
*/
sslKey?: string;
/**
* The ssl certificate used by the server.
*/
sslCert?: string;
/**
* Proxy configuration file.
*/
proxyConfig?: string;
};
/**
* Properties about schematics.
*/
schematics?: {
/**
* The schematics collection to use.
*/
collection?: string;
/**
* The new app schematic.
*/
newApp?: string;
};
}; };
/** /**
* Specify which package manager tool to use. * Specify which package manager tool to use.
*/ */
packageManager?: ('npm' | 'cnpm' | 'yarn' | 'default'); packageManager?: 'npm' | 'cnpm' | 'yarn' | 'default';
/** /**
* Allow people to disable console warnings. * Allow people to disable console warnings.
*/ */
warnings?: { warnings?: {
versionMismatch?: boolean; versionMismatch?: boolean;
}; };
} }
export function getWorkspacePath(host: Tree): string { export function getWorkspacePath(host: Tree): string {
const possibleFiles = [ '/angular.json', '/.angular.json' ]; const possibleFiles = ['/angular.json', '/.angular.json'];
const path = possibleFiles.filter(path => host.exists(path))[0]; const path = possibleFiles.filter(path => host.exists(path))[0];
return path; return path;
@ -483,7 +493,6 @@ export function addProjectToWorkspace<TProjectType extends ProjectType = Project
project: WorkspaceProject<TProjectType>, project: WorkspaceProject<TProjectType>,
): Rule { ): Rule {
return (_host: Tree, _context: SchematicContext) => { return (_host: Tree, _context: SchematicContext) => {
if (workspace.projects[name]) { if (workspace.projects[name]) {
throw new Error(`Project '${name}' already exists in workspace.`); throw new Error(`Project '${name}' already exists in workspace.`);
} }
@ -501,9 +510,9 @@ export function addProjectToWorkspace<TProjectType extends ProjectType = Project
} }
export function updateWorkspaceSchema(workspace: WorkspaceSchema): Rule { export function updateWorkspaceSchema(workspace: WorkspaceSchema): Rule {
return (host: Tree, _context: SchematicContext) => { return (host: Tree, _context: SchematicContext) => {
host.overwrite(getWorkspacePath(host), JSON.stringify(workspace, null, 2)); host.overwrite(getWorkspacePath(host), JSON.stringify(workspace, null, 2));
}; };
} }
export const configPath = '/.angular-cli.json'; export const configPath = '/.angular-cli.json';
@ -528,5 +537,5 @@ export function getAppFromConfig(config: CliConfig, appIndexOrName: string): App
return config.apps[parseInt(appIndexOrName)]; return config.apps[parseInt(appIndexOrName)];
} }
return config.apps.filter((app) => app.name === appIndexOrName)[0]; return config.apps.filter(app => app.name === appIndexOrName)[0];
} }

58
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/find-module.ts

@ -5,23 +5,16 @@
* Use of this source code is governed by an MIT-style license that can be * Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import { import { dirname, join, normalize, NormalizedRoot, Path, relative } from '@angular-devkit/core';
dirname,
join,
normalize, NormalizedRoot,
Path,
relative
} from '@angular-devkit/core';
import { DirEntry, Tree } from '@angular-devkit/schematics'; import { DirEntry, Tree } from '@angular-devkit/schematics';
export interface ModuleOptions { export interface ModuleOptions {
project?: string; // added this project?: string; // added this
module?: string; module?: string;
name: string; name: string;
flat?: boolean; flat?: boolean;
path?: string; path?: string;
route?: string; // added this route?: string; // added this
selector?: string; // added this selector?: string; // added this
skipImport?: boolean; skipImport?: boolean;
moduleExt?: string; moduleExt?: string;
@ -35,7 +28,7 @@ export const ROUTING_MODULE_EXT = '-routing.module.ts';
* Find the module referred by a set of options passed to the schematics. * Find the module referred by a set of options passed to the schematics.
*/ */
export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path | undefined { export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path | undefined {
if (options.hasOwnProperty('skipImport') && options.skipImport) { if (Object.prototype.hasOwnProperty.call(options, 'skipImport') && options.skipImport) {
return undefined; return undefined;
} }
@ -51,9 +44,7 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path
const componentPath = normalize(`/${options.path}/${options.name}`); const componentPath = normalize(`/${options.path}/${options.name}`);
const moduleBaseName = normalize(modulePath).split('/').pop(); const moduleBaseName = normalize(modulePath).split('/').pop();
const candidateSet = new Set<Path>([ const candidateSet = new Set<Path>([normalize(options.path || '/')]);
normalize(options.path || '/'),
]);
for (let dir = modulePath; dir != NormalizedRoot; dir = dirname(dir)) { for (let dir = modulePath; dir != NormalizedRoot; dir = dirname(dir)) {
candidateSet.add(dir); candidateSet.add(dir);
@ -64,11 +55,9 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path
const candidatesDirs = [...candidateSet].sort((a, b) => b.length - a.length); const candidatesDirs = [...candidateSet].sort((a, b) => b.length - a.length);
for (const c of candidatesDirs) { for (const c of candidatesDirs) {
const candidateFiles = [ const candidateFiles = ['', `${moduleBaseName}.ts`, `${moduleBaseName}${moduleExt}`].map(x =>
'', join(c, x),
`${moduleBaseName}.ts`, );
`${moduleBaseName}${moduleExt}`,
].map(x => join(c, x));
for (const sc of candidateFiles) { for (const sc of candidateFiles) {
if (host.exists(sc)) { if (host.exists(sc)) {
@ -78,8 +67,8 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path
} }
throw new Error( throw new Error(
`Specified module '${options.module}' does not exist.\n` `Specified module '${options.module}' does not exist.\n` +
+ `Looked in the following directories:\n ${candidatesDirs.join('\n ')}`, `Looked in the following directories:\n ${candidatesDirs.join('\n ')}`,
); );
} }
} }
@ -87,9 +76,12 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path
/** /**
* Function to find the "closest" module to a generated file's path. * Function to find the "closest" module to a generated file's path.
*/ */
export function findModule(host: Tree, generateDir: string, export function findModule(
moduleExt = MODULE_EXT, routingModuleExt = ROUTING_MODULE_EXT): Path { host: Tree,
generateDir: string,
moduleExt = MODULE_EXT,
routingModuleExt = ROUTING_MODULE_EXT,
): Path {
let dir: DirEntry | null = host.getDir('/' + generateDir); let dir: DirEntry | null = host.getDir('/' + generateDir);
let foundRoutingModule = false; let foundRoutingModule = false;
@ -103,16 +95,18 @@ export function findModule(host: Tree, generateDir: string,
return join(dir.path, filteredMatches[0]); return join(dir.path, filteredMatches[0]);
} else if (filteredMatches.length > 1) { } else if (filteredMatches.length > 1) {
throw new Error( throw new Error(
'More than one module matches. Use the skip-import option to skip importing ' + 'More than one module matches. Use the skip-import option to skip importing ' +
'the component into the closest module or use the module option to specify a module.'); 'the component into the closest module or use the module option to specify a module.',
);
} }
dir = dir.parent; dir = dir.parent;
} }
const errorMsg = foundRoutingModule ? 'Could not find a non Routing NgModule.' const errorMsg = foundRoutingModule
+ `\nModules with suffix '${routingModuleExt}' are strictly reserved for routing.` ? 'Could not find a non Routing NgModule.' +
+ '\nUse the skip-import option to skip importing in NgModule.' `\nModules with suffix '${routingModuleExt}' are strictly reserved for routing.` +
'\nUse the skip-import option to skip importing in NgModule.'
: 'Could not find an NgModule. Use the skip-import option to skip importing in NgModule.'; : 'Could not find an NgModule. Use the skip-import option to skip importing in NgModule.';
throw new Error(errorMsg); throw new Error(errorMsg);
@ -133,8 +127,10 @@ export function buildRelativePath(from: string, to: string): string {
fromParts.pop(); fromParts.pop();
const toFileName = toParts.pop(); const toFileName = toParts.pop();
const relativePath = relative(normalize(fromParts.join('/') || '/'), const relativePath = relative(
normalize(toParts.join('/') || '/')); normalize(fromParts.join('/') || '/'),
normalize(toParts.join('/') || '/'),
);
let pathPrefix = ''; let pathPrefix = '';
// Set the path prefix for same dir or child dir, parent dir starts with `..` // Set the path prefix for same dir or child dir, parent dir starts with `..`

1
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/workspace-models.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
/** /**
* @license * @license
* Copyright Google Inc. All Rights Reserved. * Copyright Google Inc. All Rights Reserved.

4
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/enum.ts

@ -3,6 +3,7 @@ import { Exception } from '../enums';
import { Type } from '../models'; import { Type } from '../models';
import { interpolate } from './common'; import { interpolate } from './common';
import { parseNamespace } from './namespace'; import { parseNamespace } from './namespace';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const shouldQuote = require('should-quote'); const shouldQuote = require('should-quote');
export interface EnumGeneratorParams { export interface EnumGeneratorParams {
@ -33,13 +34,14 @@ export function createImportRefToEnumMapper({ solution, types }: EnumGeneratorPa
throw new SchematicsException(interpolate(Exception.NoTypeDefinition, ref)); throw new SchematicsException(interpolate(Exception.NoTypeDefinition, ref));
const namespace = parseNamespace(solution, ref); const namespace = parseNamespace(solution, ref);
const members = enumNames!.map((key, i) => ({ const members = enumNames.map((key, i) => ({
key: shouldQuote(key) ? `'${key}'` : key, key: shouldQuote(key) ? `'${key}'` : key,
value: enumValues[i], value: enumValues[i],
})); }));
return { return {
namespace, namespace,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
name: ref.split('.').pop()!, name: ref.split('.').pop()!,
members, members,
}; };

2
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/generics.ts

@ -58,9 +58,9 @@ export class GenericsCollector {
} }
export function generateRefWithPlaceholders(sourceType: string) { export function generateRefWithPlaceholders(sourceType: string) {
// eslint-disable-next-line prefer-const
let { identifier, generics } = extractGenerics(sourceType); let { identifier, generics } = extractGenerics(sourceType);
identifier = identifier;
generics = generics.map((_, i) => `T${i}`); generics = generics.map((_, i) => `T${i}`);
return generics.length ? `${identifier}<${generics}>` : identifier; return generics.length ? `${identifier}<${generics}>` : identifier;

1
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/model.ts

@ -17,6 +17,7 @@ import {
extendsSelf, extendsSelf,
removeTypeModifiers, removeTypeModifiers,
} from './type'; } from './type';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const shouldQuote = require('should-quote'); const shouldQuote = require('should-quote');
export interface ModelGeneratorParams { export interface ModelGeneratorParams {

1
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/source.ts

@ -1,3 +1,4 @@
/* eslint-disable no-empty */
import { SchematicsException, Tree } from '@angular-devkit/schematics'; import { SchematicsException, Tree } from '@angular-devkit/schematics';
import got from 'got'; import got from 'got';
import { import {

3
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/text.ts

@ -1,3 +1,4 @@
/* eslint-disable no-useless-escape */
import { strings } from '@angular-devkit/core'; import { strings } from '@angular-devkit/core';
export const lower = (text: string) => text.toLowerCase(); export const lower = (text: string) => text.toLowerCase();
@ -11,7 +12,7 @@ export const dir = (text: string) =>
strings.dasherize(text.replace(/\./g, '/').replace(/\/\//g, '/')); strings.dasherize(text.replace(/\./g, '/').replace(/\/\//g, '/'));
export const quote = (value: number | string) => export const quote = (value: number | string) =>
typeof value === 'string' ? `'${value.replace(/'/g, '\\\'')}'` : value; typeof value === 'string' ? `'${value.replace(/'/g, "\\'")}'` : value;
function _(text: string): string { function _(text: string): string {
return text.replace(/\./g, '_'); return text.replace(/\./g, '_');

1
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/workspace.ts

@ -1,3 +1,4 @@
/* eslint-disable no-empty */
import { strings, workspaces } from '@angular-devkit/core'; import { strings, workspaces } from '@angular-devkit/core';
import { SchematicsException, Tree } from '@angular-devkit/schematics'; import { SchematicsException, Tree } from '@angular-devkit/schematics';
import { Exception } from '../enums'; import { Exception } from '../enums';

11
npm/ng-packs/nx/ng-packs/packages/tenant-management/src/lib/proxy/models.ts

@ -1,4 +1,8 @@
import type { ExtensibleEntityDto, ExtensibleObject, PagedAndSortedResultRequestDto } from '@abp/ng.core'; import type {
ExtensibleEntityDto,
ExtensibleObject,
PagedAndSortedResultRequestDto,
} from '@abp/ng.core';
export interface GetTenantsInput extends PagedAndSortedResultRequestDto { export interface GetTenantsInput extends PagedAndSortedResultRequestDto {
filter: string; filter: string;
@ -17,6 +21,5 @@ export interface TenantDto extends ExtensibleEntityDto<string> {
name: string; name: string;
} }
// tslint:disable-next-line: no-empty-interface // eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface TenantUpdateDto extends TenantCreateOrUpdateDtoBase { export interface TenantUpdateDto extends TenantCreateOrUpdateDtoBase {}
}

6
npm/ng-packs/nx/ng-packs/packages/theme-basic/src/lib/components/account-layout/auth-wrapper/auth-wrapper.component.ts

@ -1,13 +1,11 @@
import { Component, OnInit } from '@angular/core';
import { AuthWrapperService } from '@abp/ng.account.core'; import { AuthWrapperService } from '@abp/ng.account.core';
import { Component } from '@angular/core';
@Component({ @Component({
selector: 'abp-auth-wrapper', selector: 'abp-auth-wrapper',
templateUrl: './auth-wrapper.component.html', templateUrl: './auth-wrapper.component.html',
providers: [AuthWrapperService], providers: [AuthWrapperService],
}) })
export class AuthWrapperComponent implements OnInit { export class AuthWrapperComponent {
constructor(public service: AuthWrapperService) {} constructor(public service: AuthWrapperService) {}
ngOnInit(): void {}
} }

6
npm/ng-packs/nx/ng-packs/packages/theme-basic/src/lib/components/account-layout/tenant-box/tenant-box.component.ts

@ -1,13 +1,11 @@
import { Component, OnInit } from '@angular/core';
import { TenantBoxService } from '@abp/ng.account.core'; import { TenantBoxService } from '@abp/ng.account.core';
import { Component } from '@angular/core';
@Component({ @Component({
selector: 'abp-tenant-box', selector: 'abp-tenant-box',
templateUrl: './tenant-box.component.html', templateUrl: './tenant-box.component.html',
providers: [TenantBoxService], providers: [TenantBoxService],
}) })
export class TenantBoxComponent implements OnInit { export class TenantBoxComponent {
constructor(public service: TenantBoxService) {} constructor(public service: TenantBoxService) {}
ngOnInit(): void {}
} }

11
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/button/button.component.ts

@ -1,14 +1,15 @@
/* eslint-disable @angular-eslint/no-output-native */
import { ABP } from '@abp/ng.core';
import { import {
Component, Component,
ElementRef,
EventEmitter, EventEmitter,
Input, Input,
OnInit,
Output, Output,
ViewChild,
ElementRef,
Renderer2, Renderer2,
OnInit, ViewChild,
} from '@angular/core'; } from '@angular/core';
import { ABP } from '@abp/ng.core';
@Component({ @Component({
selector: 'abp-button', selector: 'abp-button',
@ -49,13 +50,11 @@ export class ButtonComponent implements OnInit {
@Input() @Input()
attributes: ABP.Dictionary<string>; attributes: ABP.Dictionary<string>;
// tslint:disable
@Output() readonly click = new EventEmitter<MouseEvent>(); @Output() readonly click = new EventEmitter<MouseEvent>();
@Output() readonly focus = new EventEmitter<FocusEvent>(); @Output() readonly focus = new EventEmitter<FocusEvent>();
@Output() readonly blur = new EventEmitter<FocusEvent>(); @Output() readonly blur = new EventEmitter<FocusEvent>();
// tslint:enable
@Output() readonly abpClick = new EventEmitter<MouseEvent>(); @Output() readonly abpClick = new EventEmitter<MouseEvent>();

4
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/chart/chart.component.ts

@ -1,12 +1,12 @@
import { import {
AfterViewInit, AfterViewInit,
ChangeDetectorRef,
Component, Component,
ElementRef, ElementRef,
EventEmitter, EventEmitter,
Input, Input,
OnDestroy, OnDestroy,
Output, Output,
ChangeDetectorRef,
} from '@angular/core'; } from '@angular/core';
import { BehaviorSubject } from 'rxjs'; import { BehaviorSubject } from 'rxjs';
import { chartJsLoaded$ } from '../../utils/widget-utils'; import { chartJsLoaded$ } from '../../utils/widget-utils';
@ -29,7 +29,7 @@ export class ChartComponent implements AfterViewInit, OnDestroy {
@Input() responsive = true; @Input() responsive = true;
// tslint:disable-next-line: no-output-on-prefix // eslint-disable-next-line @angular-eslint/no-output-on-prefix
@Output() readonly onDataSelect: EventEmitter<any> = new EventEmitter(); @Output() readonly onDataSelect: EventEmitter<any> = new EventEmitter();
@Output() readonly initialized = new BehaviorSubject(this); @Output() readonly initialized = new BehaviorSubject(this);

8
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/loading/loading.component.ts

@ -1,4 +1,4 @@
import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { Component, ViewEncapsulation } from '@angular/core';
@Component({ @Component({
selector: 'abp-loading', selector: 'abp-loading',
@ -33,8 +33,4 @@ import { Component, OnInit, ViewEncapsulation } from '@angular/core';
`, `,
], ],
}) })
export class LoadingComponent implements OnInit { export class LoadingComponent {}
constructor() {}
ngOnInit() {}
}

6
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/table-empty-message/table-empty-message.component.ts

@ -1,13 +1,13 @@
import { Component, OnInit, Input } from '@angular/core'; import { Component, Input } from '@angular/core';
@Component({ @Component({
// tslint:disable-next-line: component-selector // eslint-disable-next-line @angular-eslint/component-selector
selector: '[abp-table-empty-message]', selector: '[abp-table-empty-message]',
template: ` template: `
<td class="text-center" [attr.colspan]="colspan"> <td class="text-center" [attr.colspan]="colspan">
{{ emptyMessage | abpLocalization }} {{ emptyMessage | abpLocalization }}
</td> </td>
` `,
}) })
export class TableEmptyMessageComponent { export class TableEmptyMessageComponent {
@Input() @Input()

2
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/directives/ngx-datatable-default.directive.ts

@ -5,7 +5,7 @@ import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators'; import { debounceTime } from 'rxjs/operators';
@Directive({ @Directive({
// tslint:disable-next-line // eslint-disable-next-line @angular-eslint/directive-selector
selector: 'ngx-datatable[default]', selector: 'ngx-datatable[default]',
exportAs: 'ngxDatatableDefault', exportAs: 'ngxDatatableDefault',
}) })

2
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/directives/ngx-datatable-list.directive.ts

@ -19,7 +19,7 @@ import {
} from '../tokens/ngx-datatable-messages.token'; } from '../tokens/ngx-datatable-messages.token';
@Directive({ @Directive({
// tslint:disable-next-line // eslint-disable-next-line @angular-eslint/directive-selector
selector: 'ngx-datatable[list]', selector: 'ngx-datatable[list]',
exportAs: 'ngxDatatableList', exportAs: 'ngxDatatableList',
}) })

63
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts

@ -1,9 +1,4 @@
import { import { AuthService, LocalizationParam, RestOccurError, RouterEvents } from '@abp/ng.core';
AuthService,
LocalizationParam,
RestOccurError,
RouterEvents,
} from '@abp/ng.core';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { import {
ApplicationRef, ApplicationRef,
@ -32,8 +27,7 @@ export const DEFAULT_ERROR_MESSAGES = {
}, },
defaultError401: { defaultError401: {
title: 'You are not authenticated!', title: 'You are not authenticated!',
details: details: 'You should be authenticated (sign in) in order to perform this operation.',
'You should be authenticated (sign in) in order to perform this operation.',
}, },
defaultError403: { defaultError403: {
title: 'You are not authorized!', title: 'You are not authorized!',
@ -76,9 +70,8 @@ export const DEFAULT_ERROR_LOCALIZATIONS = {
export class ErrorHandler { export class ErrorHandler {
componentRef: ComponentRef<HttpErrorWrapperComponent>; componentRef: ComponentRef<HttpErrorWrapperComponent>;
protected httpErrorHandler = this.injector.get( protected httpErrorHandler = this.injector.get(HTTP_ERROR_HANDLER, (_, err: HttpErrorResponse) =>
HTTP_ERROR_HANDLER, throwError(err),
(_, err: HttpErrorResponse) => throwError(err)
); );
constructor( constructor(
@ -88,7 +81,7 @@ export class ErrorHandler {
protected cfRes: ComponentFactoryResolver, protected cfRes: ComponentFactoryResolver,
protected rendererFactory: RendererFactory2, protected rendererFactory: RendererFactory2,
protected injector: Injector, protected injector: Injector,
@Inject('HTTP_ERROR_CONFIG') protected httpErrorConfig: HttpErrorConfig @Inject('HTTP_ERROR_CONFIG') protected httpErrorConfig: HttpErrorConfig,
) { ) {
this.listenToRestError(); this.listenToRestError();
this.listenToRouterError(); this.listenToRouterError();
@ -116,21 +109,21 @@ export class ErrorHandler {
this.actions this.actions
.pipe( .pipe(
ofActionSuccessful(RestOccurError), ofActionSuccessful(RestOccurError),
map((action) => action.payload), map(action => action.payload),
filter(this.filterRestErrors), filter(this.filterRestErrors),
switchMap(this.executeErrorHandler) switchMap(this.executeErrorHandler),
) )
.subscribe(); .subscribe();
} }
private executeErrorHandler = (error) => { private executeErrorHandler = error => {
const returnValue = this.httpErrorHandler(this.injector, error); const returnValue = this.httpErrorHandler(this.injector, error);
return (returnValue instanceof Observable ? returnValue : of(null)).pipe( return (returnValue instanceof Observable ? returnValue : of(null)).pipe(
catchError((err) => { catchError(err => {
this.handleError(err); this.handleError(err);
return of(null); return of(null);
}) }),
); );
}; };
@ -140,10 +133,7 @@ export class ErrorHandler {
defaultValue: DEFAULT_ERROR_MESSAGES.defaultError.title, defaultValue: DEFAULT_ERROR_MESSAGES.defaultError.title,
}; };
if ( if (err instanceof HttpErrorResponse && err.headers.get('_AbpErrorFormat')) {
err instanceof HttpErrorResponse &&
err.headers.get('_AbpErrorFormat')
) {
const confirmation$ = this.showError(null, null, body); const confirmation$ = this.showError(null, null, body);
if (err.status === 401) { if (err.status === 401) {
@ -164,7 +154,7 @@ export class ErrorHandler {
{ {
key: DEFAULT_ERROR_LOCALIZATIONS.defaultError401.details, key: DEFAULT_ERROR_LOCALIZATIONS.defaultError401.details,
defaultValue: DEFAULT_ERROR_MESSAGES.defaultError401.details, defaultValue: DEFAULT_ERROR_MESSAGES.defaultError401.details,
} },
).subscribe(() => this.navigateToLogin()); ).subscribe(() => this.navigateToLogin());
break; break;
case 403: case 403:
@ -191,7 +181,7 @@ export class ErrorHandler {
{ {
key: DEFAULT_ERROR_LOCALIZATIONS.defaultError404.title, key: DEFAULT_ERROR_LOCALIZATIONS.defaultError404.title,
defaultValue: DEFAULT_ERROR_MESSAGES.defaultError404.title, defaultValue: DEFAULT_ERROR_MESSAGES.defaultError404.title,
} },
); );
break; break;
case 500: case 500:
@ -228,7 +218,7 @@ export class ErrorHandler {
{ {
key: DEFAULT_ERROR_LOCALIZATIONS.defaultError.title, key: DEFAULT_ERROR_LOCALIZATIONS.defaultError.title,
defaultValue: DEFAULT_ERROR_MESSAGES.defaultError.title, defaultValue: DEFAULT_ERROR_MESSAGES.defaultError.title,
} },
); );
break; break;
} }
@ -258,7 +248,7 @@ export class ErrorHandler {
protected showError( protected showError(
message?: LocalizationParam, message?: LocalizationParam,
title?: LocalizationParam, title?: LocalizationParam,
body?: any body?: any,
): Observable<Confirmation.Status> { ): Observable<Confirmation.Status> {
if (body) { if (body) {
if (body.details) { if (body.details) {
@ -298,28 +288,23 @@ export class ErrorHandler {
for (const key in instance) { for (const key in instance) {
/* istanbul ignore else */ /* istanbul ignore else */
if (this.componentRef.instance.hasOwnProperty(key)) { if (Object.prototype.hasOwnProperty.call(this.componentRef.instance, key)) {
this.componentRef.instance[key] = instance[key]; this.componentRef.instance[key] = instance[key];
} }
} }
this.componentRef.instance.hideCloseIcon = this.componentRef.instance.hideCloseIcon = this.httpErrorConfig.errorScreen.hideCloseIcon;
this.httpErrorConfig.errorScreen.hideCloseIcon;
const appRef = this.injector.get(ApplicationRef); const appRef = this.injector.get(ApplicationRef);
if (this.canCreateCustomError(instance.status as ErrorScreenErrorCodes)) { if (this.canCreateCustomError(instance.status as ErrorScreenErrorCodes)) {
this.componentRef.instance.cfRes = this.cfRes; this.componentRef.instance.cfRes = this.cfRes;
this.componentRef.instance.appRef = appRef; this.componentRef.instance.appRef = appRef;
this.componentRef.instance.injector = this.injector; this.componentRef.instance.injector = this.injector;
this.componentRef.instance.customComponent = this.componentRef.instance.customComponent = this.httpErrorConfig.errorScreen.component;
this.httpErrorConfig.errorScreen.component;
} }
appRef.attachView(this.componentRef.hostView); appRef.attachView(this.componentRef.hostView);
renderer.appendChild( renderer.appendChild(host, (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]);
host,
(this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]
);
const destroy$ = new Subject<void>(); const destroy$ = new Subject<void>();
this.componentRef.instance.destroy$ = destroy$; this.componentRef.instance.destroy$ = destroy$;
@ -339,19 +324,13 @@ export class ErrorHandler {
protected filterRestErrors = ({ status }: HttpErrorResponse): boolean => { protected filterRestErrors = ({ status }: HttpErrorResponse): boolean => {
if (typeof status !== 'number') return false; if (typeof status !== 'number') return false;
return ( return this.httpErrorConfig.skipHandledErrorCodes.findIndex(code => code === status) < 0;
this.httpErrorConfig.skipHandledErrorCodes.findIndex(
(code) => code === status
) < 0
);
}; };
protected filterRouteErrors = (navigationError: NavigationError): boolean => { protected filterRouteErrors = (navigationError: NavigationError): boolean => {
return ( return (
navigationError.error?.message?.indexOf('Cannot match') > -1 && navigationError.error?.message?.indexOf('Cannot match') > -1 &&
this.httpErrorConfig.skipHandledErrorCodes.findIndex( this.httpErrorConfig.skipHandledErrorCodes.findIndex(code => code === 404) < 0
(code) => code === 404
) < 0
); );
}; };
} }

1
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/tests/breadcrumb.component.spec.ts

@ -9,6 +9,7 @@ import { HttpClient } from '@angular/common/http';
import { RouterModule } from '@angular/router'; import { RouterModule } from '@angular/router';
import { createRoutingFactory, SpectatorRouting, SpyObject } from '@ngneat/spectator/jest'; import { createRoutingFactory, SpectatorRouting, SpyObject } from '@ngneat/spectator/jest';
import { Store } from '@ngxs/store'; import { Store } from '@ngxs/store';
// eslint-disable-next-line @nrwl/nx/enforce-module-boundaries
import { mockRoutesService } from '../../../../core/src/lib/tests/routes.service.spec'; import { mockRoutesService } from '../../../../core/src/lib/tests/routes.service.spec';
import { BreadcrumbComponent } from '../components/breadcrumb/breadcrumb.component'; import { BreadcrumbComponent } from '../components/breadcrumb/breadcrumb.component';

Loading…
Cancel
Save