id
stringlengths 6
6
| text
stringlengths 20
17.2k
| title
stringclasses 1
value |
|---|---|---|
014102
|
Angular Router
=========
Managing state transitions is one of the hardest parts of building applications. This is especially true on the web, where you also need to ensure that the state is reflected in the URL. In addition, we often want to split applications into multiple bundles and load them on demand. Doing this transparently isn’t trivial.
The Angular router is designed to solve these problems. Using the router, you can declaratively specify application state, manage state transitions while taking care of the URL, and load components on demand.
## Guide
Read the dev guide [here](https://angular.io/guide/routing/common-router-tasks).
| |
014103
|
Implements the Angular Router service , which enables navigation from one view to the next as users perform application tasks.
Defines the `Route` object that maps a URL path to a component, and the `RouterOutlet` directive
that you use to place a routed view in a template, as well as a complete API for configuring, querying, and controlling the router state.
Import `RouterModule` to use the Router service in your app.
For more usage information, see the [Routing and Navigation](guide/routing/common-router-tasks) guide.
| |
014121
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Injectable, NgModule} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {provideRoutes, Router, RouterModule, ROUTES} from '@angular/router';
@Component({template: '<div>simple standalone</div>', standalone: true})
export class SimpleStandaloneComponent {}
@Component({template: '<div>not standalone</div>', standalone: false})
export class NotStandaloneComponent {}
@Component({
template: '<router-outlet></router-outlet>',
standalone: true,
imports: [RouterModule],
})
export class RootCmp {}
describe('standalone in Router API', () => {
describe('loadChildren => routes', () => {
it('can navigate to and render standalone component', fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'lazy',
component: RootCmp,
loadChildren: () => [{path: '', component: SimpleStandaloneComponent}],
},
]),
],
});
const root = TestBed.createComponent(RootCmp);
const router = TestBed.inject(Router);
router.navigateByUrl('/lazy');
advance(root);
expect(root.nativeElement.innerHTML).toContain('simple standalone');
}));
it('throws an error when loadChildren=>routes has a component that is not standalone', fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'lazy',
component: RootCmp,
loadChildren: () => [{path: 'notstandalone', component: NotStandaloneComponent}],
},
]),
],
});
const root = TestBed.createComponent(RootCmp);
const router = TestBed.inject(Router);
router.navigateByUrl('/lazy/notstandalone');
expect(() => advance(root)).toThrowError(
/.*lazy\/notstandalone.*component must be standalone/,
);
}));
});
describe('route providers', () => {
it('can provide a guard on a route', fakeAsync(() => {
@Injectable()
class ConfigurableGuard {
static canActivateValue = false;
canActivate() {
return ConfigurableGuard.canActivateValue;
}
}
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'simple',
providers: [ConfigurableGuard],
canActivate: [ConfigurableGuard],
component: SimpleStandaloneComponent,
},
]),
],
});
const root = TestBed.createComponent(RootCmp);
ConfigurableGuard.canActivateValue = false;
const router = TestBed.inject(Router);
router.navigateByUrl('/simple');
advance(root);
expect(root.nativeElement.innerHTML).not.toContain('simple standalone');
expect(router.url).not.toContain('simple');
ConfigurableGuard.canActivateValue = true;
router.navigateByUrl('/simple');
advance(root);
expect(root.nativeElement.innerHTML).toContain('simple standalone');
expect(router.url).toContain('simple');
}));
it('can inject provider on a route into component', fakeAsync(() => {
@Injectable()
class Service {
value = 'my service';
}
@Component({
template: `{{service.value}}`,
standalone: false,
})
class MyComponent {
constructor(readonly service: Service) {}
}
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([{path: 'home', providers: [Service], component: MyComponent}]),
],
declarations: [MyComponent],
});
const root = TestBed.createComponent(RootCmp);
const router = TestBed.inject(Router);
router.navigateByUrl('/home');
advance(root);
expect(root.nativeElement.innerHTML).toContain('my service');
expect(router.url).toContain('home');
}));
it('can not inject provider in lazy loaded ngModule from component on same level', fakeAsync(() => {
@Injectable()
class Service {
value = 'my service';
}
@NgModule({providers: [Service]})
class LazyModule {}
@Component({
template: `{{service.value}}`,
standalone: false,
})
class MyComponent {
constructor(readonly service: Service) {}
}
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{path: 'home', loadChildren: () => LazyModule, component: MyComponent},
]),
],
declarations: [MyComponent],
});
const root = TestBed.createComponent(RootCmp);
const router = TestBed.inject(Router);
router.navigateByUrl('/home');
expect(() => advance(root)).toThrowError();
}));
it('component from lazy module can inject provider from parent route', fakeAsync(() => {
@Injectable()
class Service {
value = 'my service';
}
@Component({
template: `{{service.value}}`,
standalone: false,
})
class MyComponent {
constructor(readonly service: Service) {}
}
@NgModule({
providers: [Service],
declarations: [MyComponent],
imports: [RouterModule.forChild([{path: '', component: MyComponent}])],
})
class LazyModule {}
TestBed.configureTestingModule({
imports: [RouterModule.forRoot([{path: 'home', loadChildren: () => LazyModule}])],
});
const root = TestBed.createComponent(RootCmp);
const router = TestBed.inject(Router);
router.navigateByUrl('/home');
advance(root);
expect(root.nativeElement.innerHTML).toContain('my service');
}));
it('gets the correct injector for guards and components when combining lazy modules and route providers', fakeAsync(() => {
const canActivateLog: string[] = [];
abstract class ServiceBase {
abstract name: string;
canActivate() {
canActivateLog.push(this.name);
return true;
}
}
@Injectable()
class Service1 extends ServiceBase {
override name = 'service1';
}
@Injectable()
class Service2 extends ServiceBase {
override name = 'service2';
}
@Injectable()
class Service3 extends ServiceBase {
override name = 'service3';
}
@Component({
template: `parent<router-outlet></router-outlet>`,
standalone: false,
})
class ParentCmp {
constructor(readonly service: ServiceBase) {}
}
@Component({
template: `child`,
standalone: false,
})
class ChildCmp {
constructor(readonly service: ServiceBase) {}
}
@Component({
template: `child2`,
standalone: false,
})
class ChildCmp2 {
constructor(readonly service: ServiceBase) {}
}
@NgModule({
providers: [{provide: ServiceBase, useClass: Service2}],
declarations: [ChildCmp, ChildCmp2],
imports: [
RouterModule.forChild([
{
path: '',
// This component and guard should get Service2 since it's provided in this module
component: ChildCmp,
canActivate: [ServiceBase],
},
{
path: 'child2',
providers: [{provide: ServiceBase, useFactory: () => new Service3()}],
// This component and guard should get Service3 since it's provided on this route
component: ChildCmp2,
canActivate: [ServiceBase],
},
]),
],
})
class LazyModule {}
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
// This component and guard should get Service1 since it's provided on this route
component: ParentCmp,
canActivate: [ServiceBase],
providers: [{provide: ServiceBase, useFactory: () => new Service1()}],
loadChildren: () => LazyModule,
},
]),
],
declarations: [ParentCmp],
});
const root = TestBed.createComponent(RootCmp);
const router = TestBed.inject(Router);
router.navigateByUrl('/home');
advance(root);
expect(canActivateLog).toEqual(['service1', 'service2']);
expect(
root.debugElement.query(By.directive(ParentCmp)).componentInstance.service.name,
).toEqual('service1');
expect(
root.debugElement.query(By.directive(ChildCmp)).componentInstance.service.name,
).toEqual('service2');
router.navigateByUrl('/home/child2');
advance(root);
expect(canActivateLog).toEqual(['service1', 'service2', 'service3']);
expect(
root.debugElement.query(By.directive(ChildCmp2)).componentInstance.service.name,
).toEqual('service3');
}));
});
| |
014122
|
describe('loadComponent', () => {
it('does not load component when canActivate returns false', fakeAsync(() => {
const loadComponentSpy = jasmine.createSpy();
@Injectable({providedIn: 'root'})
class Guard {
canActivate() {
return false;
}
}
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
loadComponent: loadComponentSpy,
canActivate: [Guard],
},
]),
],
});
TestBed.inject(Router).navigateByUrl('/home');
tick();
expect(loadComponentSpy).not.toHaveBeenCalled();
}));
it('loads and renders lazy component', fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
loadComponent: () => SimpleStandaloneComponent,
},
]),
],
});
const root = TestBed.createComponent(RootCmp);
TestBed.inject(Router).navigateByUrl('/home');
advance(root);
expect(root.nativeElement.innerHTML).toContain('simple standalone');
}));
it('throws error when loadComponent is not standalone', fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
loadComponent: () => NotStandaloneComponent,
},
]),
],
});
const root = TestBed.createComponent(RootCmp);
TestBed.inject(Router).navigateByUrl('/home');
expect(() => advance(root)).toThrowError(/.*home.*component must be standalone/);
}));
it('throws error when loadComponent is used with a module', fakeAsync(() => {
@NgModule()
class LazyModule {}
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
loadComponent: () => LazyModule,
},
]),
],
});
const root = TestBed.createComponent(RootCmp);
TestBed.inject(Router).navigateByUrl('/home');
expect(() => advance(root)).toThrowError(/.*home.*Use 'loadChildren' instead/);
}));
});
describe('default export unwrapping', () => {
it('should work for loadComponent', async () => {
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
loadComponent: () => import('./default_export_component'),
},
]),
],
});
const root = TestBed.createComponent(RootCmp);
await TestBed.inject(Router).navigateByUrl('/home');
root.detectChanges();
expect(root.nativeElement.innerHTML).toContain('default exported');
});
it('should work for loadChildren', async () => {
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
loadChildren: () => import('./default_export_routes'),
},
]),
],
});
const root = TestBed.createComponent(RootCmp);
await TestBed.inject(Router).navigateByUrl('/home');
root.detectChanges();
expect(root.nativeElement.innerHTML).toContain('default exported');
});
});
});
describe('provideRoutes', () => {
it('warns if provideRoutes is used without provideRouter, RouterModule, or RouterModule.forRoot', () => {
spyOn(console, 'warn');
TestBed.configureTestingModule({providers: [provideRoutes([])]});
TestBed.inject(ROUTES);
expect(console.warn).toHaveBeenCalled();
});
});
function advance(fixture: ComponentFixture<unknown>) {
tick();
fixture.detectChanges();
}
| |
014132
|
describe('data', async () => {
it('should set static data', async () => {
const s = await recognize([{path: 'a', data: {one: 1}, component: ComponentA}], 'a');
const r: ActivatedRouteSnapshot = s.root.firstChild!;
expect(r.data).toEqual({one: 1});
});
it("should inherit componentless route's data", async () => {
const s = await recognize(
[
{
path: 'a',
data: {one: 1},
children: [{path: 'b', data: {two: 2}, component: ComponentB}],
},
],
'a/b',
);
const r: ActivatedRouteSnapshot = s.root.firstChild!.firstChild!;
expect(r.data).toEqual({one: 1, two: 2});
});
it("should not inherit route's data if it has component", async () => {
const s = await recognize(
[
{
path: 'a',
component: ComponentA,
data: {one: 1},
children: [{path: 'b', data: {two: 2}, component: ComponentB}],
},
],
'a/b',
);
const r: ActivatedRouteSnapshot = s.root.firstChild!.firstChild!;
expect(r.data).toEqual({two: 2});
});
it("should not inherit route's data if it has loadComponent", async () => {
const s = await recognize(
[
{
path: 'a',
loadComponent: () => ComponentA,
data: {one: 1},
children: [{path: 'b', data: {two: 2}, component: ComponentB}],
},
],
'a/b',
);
const r: ActivatedRouteSnapshot = s.root.firstChild!.firstChild!;
expect(r.data).toEqual({two: 2});
});
it("should inherit route's data if paramsInheritanceStrategy is 'always'", async () => {
const s = await recognize(
[
{
path: 'a',
component: ComponentA,
data: {one: 1},
children: [{path: 'b', data: {two: 2}, component: ComponentB}],
},
],
'a/b',
'always',
);
const r: ActivatedRouteSnapshot = s.root.firstChild!.firstChild!;
expect(r.data).toEqual({one: 1, two: 2});
});
it('should set resolved data', async () => {
const s = await recognize(
[{path: 'a', resolve: {one: 'some-token'}, component: ComponentA}],
'a',
);
const r: any = s.root.firstChild!;
expect(r._resolve).toEqual({one: 'some-token'});
});
});
| |
014140
|
it('with overlapping loads from navigation and the preloader', fakeAsync(() => {
const preloader = TestBed.inject(RouterPreloader);
const router = TestBed.inject(Router);
router.events.subscribe((e) => {
if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) {
events.push(e);
}
});
lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1));
subLoadChildrenSpy.and.returnValue(of(LoadedModule2).pipe(delay(5)));
preloader.preload().subscribe((x) => {});
tick();
// Load the out modules at start of test and ensure it and only
// it is loaded
delayLoadUnPaused.next(['lazymodule']);
tick();
expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1);
expect(events.map((e) => e.toString())).toEqual([
'RouteConfigLoadStart(path: lazy)',
'RouteConfigLoadEnd(path: lazy)',
]);
// Cause the load from router to start (has 5 tick delay)
router.navigateByUrl('/lazy/sub/LoadedModule2');
tick(); // T1
// Cause the load from preloader to start
delayLoadUnPaused.next(['lazymodule', 'submodule']);
tick(); // T2
expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1);
expect(subLoadChildrenSpy).toHaveBeenCalledTimes(1);
tick(5); // T2 to T7 enough time for mutiple loads to finish
expect(subLoadChildrenSpy).toHaveBeenCalledTimes(1);
expect(events.map((e) => e.toString())).toEqual([
'RouteConfigLoadStart(path: lazy)',
'RouteConfigLoadEnd(path: lazy)',
'RouteConfigLoadStart(path: sub)',
'RouteConfigLoadEnd(path: sub)',
]);
}));
it('cope with factory fail from broken modules', fakeAsync(() => {
const preloader = TestBed.inject(RouterPreloader);
const router = TestBed.inject(Router);
router.events.subscribe((e) => {
if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) {
events.push(e);
}
});
class BrokenModuleFactory extends NgModuleFactory<unknown> {
override moduleType: Type<unknown> = LoadedModule1;
constructor() {
super();
}
override create(_parentInjector: Injector | null): NgModuleRef<unknown> {
throw 'Error: Broken module';
}
}
lazyLoadChildrenSpy.and.returnValue(of(new BrokenModuleFactory()));
preloader.preload().subscribe((x) => {});
tick();
expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(0);
router.navigateByUrl('/lazy/LoadedModule1').catch((reason) => {
expect(reason).toEqual('Error: Broken module');
});
tick();
expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1);
lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1));
router.navigateByUrl('/lazy/LoadedModule1').catch(() => {
fail('navigation should not throw');
});
tick();
expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(2);
expect(subLoadChildrenSpy).toHaveBeenCalledTimes(0);
expect(events.map((e) => e.toString())).toEqual([
'RouteConfigLoadStart(path: lazy)',
'RouteConfigLoadEnd(path: lazy)',
'RouteConfigLoadStart(path: lazy)',
'RouteConfigLoadEnd(path: lazy)',
]);
}));
});
describe('should ignore errors', () => {
@NgModule({
declarations: [LazyLoadedCmp],
imports: [RouterModule.forChild([{path: 'LoadedModule1', component: LazyLoadedCmp}])],
})
class LoadedModule {}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: ROUTES,
multi: true,
useValue: [
{path: 'lazy1', loadChildren: jasmine.createSpy('expected1')},
{path: 'lazy2', loadChildren: () => LoadedModule},
],
},
{provide: PreloadingStrategy, useExisting: PreloadAllModules},
],
});
});
it('should work', fakeAsync(
inject([RouterPreloader, Router], (preloader: RouterPreloader, router: Router) => {
preloader.preload().subscribe(() => {});
tick();
const c = router.config;
expect(getLoadedRoutes(c[0])).not.toBeDefined();
expect(getLoadedRoutes(c[1])).toBeDefined();
}),
));
});
describe('should copy loaded configs', () => {
const configs = [{path: 'LoadedModule1', component: LazyLoadedCmp}];
@NgModule({
declarations: [LazyLoadedCmp],
providers: [{provide: ROUTES, multi: true, useValue: configs}],
})
class LoadedModule {}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideLocationMocks(),
provideRouter(
[{path: 'lazy1', loadChildren: () => LoadedModule}],
withPreloading(PreloadAllModules),
),
],
});
});
it('should work', fakeAsync(
inject([RouterPreloader, Router], (preloader: RouterPreloader, router: Router) => {
preloader.preload().subscribe(() => {});
tick();
const c = router.config;
expect(getLoadedRoutes(c[0])).toBeDefined();
expect(getLoadedRoutes(c[0])).not.toBe(configs);
expect(getLoadedRoutes(c[0])![0]).not.toBe(configs[0]);
expect(getLoadedRoutes(c[0])![0].component).toBe(configs[0].component);
}),
));
});
describe("should work with lazy loaded modules that don't provide RouterModule.forChild()", () => {
@NgModule({
declarations: [LazyLoadedCmp],
providers: [
{
provide: ROUTES,
multi: true,
useValue: [{path: 'LoadedModule1', component: LazyLoadedCmp}],
},
],
})
class LoadedModule {}
@NgModule({})
class EmptyModule {}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideLocationMocks(),
provideRouter(
[{path: 'lazyEmptyModule', loadChildren: () => EmptyModule}],
withPreloading(PreloadAllModules),
),
],
});
});
it('should work', fakeAsync(
inject([RouterPreloader], (preloader: RouterPreloader) => {
preloader.preload().subscribe();
}),
));
});
| |
014176
|
ribe('guards', () => {
describe('CanActivate', () => {
describe('should not activate a route when CanActivate returns false', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}],
});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
const recordedEvents: Event[] = [];
router.events.forEach((e) => recordedEvents.push(e));
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canActivate: ['alwaysFalse']},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('');
expectEvents(recordedEvents, [
[NavigationStart, '/team/22'],
[RoutesRecognized, '/team/22'],
[GuardsCheckStart, '/team/22'],
[ChildActivationStart],
[ActivationStart],
[GuardsCheckEnd, '/team/22'],
[NavigationCancel, '/team/22'],
]);
expect((recordedEvents[5] as GuardsCheckEnd).shouldActivate).toBe(false);
}),
));
});
describe('should not activate a route when CanActivate returns false (componentless route)', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}],
});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'parent',
canActivate: ['alwaysFalse'],
children: [{path: 'team/:id', component: TeamCmp}],
},
]);
router.navigateByUrl('parent/team/22');
advance(fixture);
expect(location.path()).toEqual('');
}),
));
});
describe('should activate a route when CanActivate returns true', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: 'alwaysTrue',
useValue: (a: ActivatedRouteSnapshot, s: RouterStateSnapshot) => true,
},
],
});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canActivate: ['alwaysTrue']},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
}),
));
});
describe('should work when given a class', () => {
class AlwaysTrue {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return true;
}
}
beforeEach(() => {
TestBed.configureTestingModule({providers: [AlwaysTrue]});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canActivate: [AlwaysTrue]},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
}),
));
});
describe('should work when returns an observable', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: 'CanActivate',
useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return new Observable<boolean>((observer) => {
observer.next(false);
});
},
},
],
});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('');
}),
));
});
describe('should work when returns a promise', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: 'CanActivate',
useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
if (a.params['id'] === '22') {
return Promise.resolve(true);
} else {
return Promise.resolve(false);
}
},
},
],
});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/22');
}),
));
});
describe('should reset the location when cancelling a navigation', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: 'alwaysFalse',
useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return false;
},
},
{provide: LocationStrategy, useClass: HashLocationStrategy},
],
});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'one', component: SimpleCmp},
{path: 'two', component: SimpleCmp, canActivate: ['alwaysFalse']},
]);
router.navigateByUrl('/one');
advance(fixture);
expect(location.path()).toEqual('/one');
location.go('/two');
location.historyGo(0);
advance(fixture);
expect(location.path()).toEqual('/one');
}),
));
});
describe('should redirect to / when guard returns false', () => {
beforeEach(() =>
TestBed.configureTestingModule({
providers: [
{
provide: 'returnFalseAndNavigate',
useFactory: (router: Router) => () => {
router.navigate(['/']);
return false;
},
deps: [Router],
},
],
}),
);
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
router.resetConfig([
{
path: '',
component: SimpleCmp,
},
{path: 'one', component: RouteCmp, canActivate: ['returnFalseAndNavigate']},
]);
const fixture = TestBed.createComponent(RootCmp);
router.navigateByUrl('/one');
advance(fixture);
expect(location.path()).toEqual('');
expect(fixture.nativeElement).toHaveText('simple');
}),
));
});
| |
014180
|
ribe('CanDeactivate', () => {
let log: any;
beforeEach(() => {
log = [];
TestBed.configureTestingModule({
providers: [
{
provide: 'CanDeactivateParent',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return a.params['id'] === '22';
},
},
{
provide: 'CanDeactivateTeam',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return c.route.snapshot.params['id'] === '22';
},
},
{
provide: 'CanDeactivateUser',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return a.params['name'] === 'victor';
},
},
{
provide: 'RecordingDeactivate',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
log.push({path: a.routeConfig!.path, component: c});
return true;
},
},
{
provide: 'alwaysFalse',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return false;
},
},
{
provide: 'alwaysFalseAndLogging',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
log.push('called');
return false;
},
},
{
provide: 'alwaysFalseWithDelayAndLogging',
useValue: () => {
log.push('called');
let resolve: (result: boolean) => void;
const promise = new Promise((res) => (resolve = res));
setTimeout(() => resolve(false), 0);
return promise;
},
},
{
provide: 'canActivate_alwaysTrueAndLogging',
useValue: () => {
log.push('canActivate called');
return true;
},
},
],
});
});
describe('should not deactivate a route when CanDeactivate returns false', () => {
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivateTeam']},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
let successStatus: boolean = false;
router.navigateByUrl('/team/33')!.then((res) => (successStatus = res));
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(successStatus).toEqual(true);
let canceledStatus: boolean = false;
router.navigateByUrl('/team/44')!.then((res) => (canceledStatus = res));
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(canceledStatus).toEqual(false);
}),
));
it('works with componentless routes', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'grandparent',
canDeactivate: ['RecordingDeactivate'],
children: [
{
path: 'parent',
canDeactivate: ['RecordingDeactivate'],
children: [
{
path: 'child',
canDeactivate: ['RecordingDeactivate'],
children: [
{
path: 'simple',
component: SimpleCmp,
canDeactivate: ['RecordingDeactivate'],
},
],
},
],
},
],
},
{path: 'simple', component: SimpleCmp},
]);
router.navigateByUrl('/grandparent/parent/child/simple');
advance(fixture);
expect(location.path()).toEqual('/grandparent/parent/child/simple');
router.navigateByUrl('/simple');
advance(fixture);
const child = fixture.debugElement.children[1].componentInstance;
expect(log.map((a: any) => a.path)).toEqual([
'simple',
'child',
'parent',
'grandparent',
]);
expect(log[0].component instanceof SimpleCmp).toBeTruthy();
[1, 2, 3].forEach((i) => expect(log[i].component).toBeNull());
expect(child instanceof SimpleCmp).toBeTruthy();
expect(child).not.toBe(log[0].component);
}),
));
it('works with aux routes', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'two-outlets',
component: TwoOutletsCmp,
children: [
{path: 'a', component: BlankCmp},
{
path: 'b',
canDeactivate: ['RecordingDeactivate'],
component: SimpleCmp,
outlet: 'aux',
},
],
},
]);
router.navigateByUrl('/two-outlets/(a//aux:b)');
advance(fixture);
expect(location.path()).toEqual('/two-outlets/(a//aux:b)');
router.navigate(['two-outlets', {outlets: {aux: null}}]);
advance(fixture);
expect(log.map((a: any) => a.path)).toEqual(['b']);
expect(location.path()).toEqual('/two-outlets/a');
}),
));
it('works with a nested route', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'team/:id',
component: TeamCmp,
children: [
{path: '', pathMatch: 'full', component: SimpleCmp},
{path: 'user/:name', component: UserCmp, canDeactivate: ['CanDeactivateUser']},
],
},
]);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
// this works because we can deactivate victor
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
router.navigateByUrl('/team/33/user/fedor');
advance(fixture);
// this doesn't work cause we cannot deactivate fedor
router.navigateByUrl('/team/44');
advance(fixture);
expect(location.path()).toEqual('/team/33/user/fedor');
}),
));
});
it('should use correct component to deactivate forChild route', fakeAsync(
inject([Router], (router: Router) => {
@Component({
selector: 'admin',
template: '',
standalone: false,
})
class AdminComponent {}
@NgModule({
declarations: [AdminComponent],
imports: [
RouterModule.forChild([
{
path: '',
component: AdminComponent,
canDeactivate: ['RecordingDeactivate'],
},
]),
],
})
class LazyLoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'a',
component: WrapperCmp,
children: [{path: '', pathMatch: 'full', loadChildren: () => LazyLoadedModule}],
},
{path: 'b', component: SimpleCmp},
]);
router.navigateByUrl('/a');
advance(fixture);
router.navigateByUrl('/b');
advance(fixture);
expect(log[0].component).toBeInstanceOf(AdminComponent);
}),
));
it('should not create a route state if navigation is canceled', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'main',
component: TeamCmp,
children: [
{path: 'component1', component: SimpleCmp, canDeactivate: ['alwaysFalse']},
{path: 'component2', component: SimpleCmp},
],
},
]);
router.navigateByUrl('/main/component1');
advance(fixture);
router.navigateByUrl('/main/component2');
advance(fixture);
const teamCmp = fixture.debugElement.children[1].componentInstance;
expect(teamCmp.route.firstChild.url.value[0].path).toEqual('component1');
expect(location.path()).toEqual('/main/component1');
}),
));
| |
014181
|
should not run CanActivate when CanDeactivate returns false', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'main',
component: TeamCmp,
children: [
{
path: 'component1',
component: SimpleCmp,
canDeactivate: ['alwaysFalseWithDelayAndLogging'],
},
{
path: 'component2',
component: SimpleCmp,
canActivate: ['canActivate_alwaysTrueAndLogging'],
},
],
},
]);
router.navigateByUrl('/main/component1');
advance(fixture);
expect(location.path()).toEqual('/main/component1');
router.navigateByUrl('/main/component2');
advance(fixture);
expect(location.path()).toEqual('/main/component1');
expect(log).toEqual(['called']);
}),
));
it('should call guards every time when navigating to the same url over and over again', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'simple', component: SimpleCmp, canDeactivate: ['alwaysFalseAndLogging']},
{path: 'blank', component: BlankCmp},
]);
router.navigateByUrl('/simple');
advance(fixture);
router.navigateByUrl('/blank');
advance(fixture);
expect(log).toEqual(['called']);
expect(location.path()).toEqual('/simple');
router.navigateByUrl('/blank');
advance(fixture);
expect(log).toEqual(['called', 'called']);
expect(location.path()).toEqual('/simple');
}),
));
describe('next state', () => {
let log: string[];
class ClassWithNextState {
canDeactivate(
component: TeamCmp,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot,
): boolean {
log.push(currentState.url, nextState.url);
return true;
}
}
beforeEach(() => {
log = [];
TestBed.configureTestingModule({
providers: [
ClassWithNextState,
{
provide: 'FunctionWithNextState',
useValue: (
cmp: any,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot,
) => {
log.push(currentState.url, nextState.url);
return true;
},
},
],
});
});
it('should pass next state as the 4 argument when guard is a class', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'team/:id',
component: TeamCmp,
canDeactivate: [
(
component: TeamCmp,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot,
) =>
coreInject(ClassWithNextState).canDeactivate(
component,
currentRoute,
currentState,
nextState,
),
],
},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(log).toEqual(['/team/22', '/team/33']);
}),
));
it('should pass next state as the 4 argument when guard is a function', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canDeactivate: ['FunctionWithNextState']},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(log).toEqual(['/team/22', '/team/33']);
}),
));
});
describe('should work when given a class', () => {
class AlwaysTrue {
canDeactivate(): boolean {
return true;
}
}
beforeEach(() => {
TestBed.configureTestingModule({providers: [AlwaysTrue]});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'team/:id',
component: TeamCmp,
canDeactivate: [() => coreInject(AlwaysTrue).canDeactivate()],
},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
}),
));
});
describe('should work when returns an observable', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: 'CanDeactivate',
useValue: (c: TeamCmp, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return new Observable<boolean>((observer) => {
observer.next(false);
});
},
},
],
});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivate']},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/22');
}),
));
});
});
describe('CanActivateChild', () => {
describe('should be invoked when activating a child', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: 'alwaysFalse',
useValue: (a: any, b: any) => a.paramMap.get('id') === '22',
},
],
});
});
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: '',
canActivateChild: ['alwaysFalse'],
children: [{path: 'team/:id', component: TeamCmp}],
},
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33')!.catch(() => {});
advance(fixture);
expect(location.path()).toEqual('/team/22');
}),
));
});
it('should find the guard provided in lazy loaded module', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'admin',
template: '<router-outlet></router-outlet>',
standalone: false,
})
class AdminComponent {}
@Component({
selector: 'lazy',
template: 'lazy-loaded',
standalone: false,
})
class LazyLoadedComponent {}
@NgModule({
declarations: [AdminComponent, LazyLoadedComponent],
imports: [
RouterModule.forChild([
{
path: '',
component: AdminComponent,
children: [
{
path: '',
canActivateChild: ['alwaysTrue'],
children: [{path: '', component: LazyLoadedComponent}],
},
],
},
]),
],
providers: [{provide: 'alwaysTrue', useValue: () => true}],
})
class LazyLoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'admin', loadChildren: () => LazyLoadedModule}]);
router.navigateByUrl('/admin');
advance(fixture);
expect(location.path()).toEqual('/admin');
expect(fixture.nativeElement).toHaveText('lazy-loaded');
}),
));
});
| |
014187
|
ribe('lazy loading', () => {
it('works', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded-parent [<router-outlet></router-outlet>]',
standalone: false,
})
class ParentLazyLoadedComponent {}
@Component({
selector: 'lazy',
template: 'lazy-loaded-child',
standalone: false,
})
class ChildLazyLoadedComponent {}
@NgModule({
declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent],
imports: [
RouterModule.forChild([
{
path: 'loaded',
component: ParentLazyLoadedComponent,
children: [{path: 'child', component: ChildLazyLoadedComponent}],
},
]),
],
})
class LoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]);
router.navigateByUrl('/lazy/loaded/child');
advance(fixture);
expect(location.path()).toEqual('/lazy/loaded/child');
expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]');
}),
));
it('should have 2 injector trees: module and element', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'parent[<router-outlet></router-outlet>]',
viewProviders: [{provide: 'shadow', useValue: 'from parent component'}],
standalone: false,
})
class Parent {}
@Component({
selector: 'lazy',
template: 'child',
standalone: false,
})
class Child {}
@NgModule({
declarations: [Parent],
imports: [
RouterModule.forChild([
{
path: 'parent',
component: Parent,
children: [{path: 'child', loadChildren: () => ChildModule}],
},
]),
],
providers: [
{provide: 'moduleName', useValue: 'parent'},
{provide: 'fromParent', useValue: 'from parent'},
],
})
class ParentModule {}
@NgModule({
declarations: [Child],
imports: [RouterModule.forChild([{path: '', component: Child}])],
providers: [
{provide: 'moduleName', useValue: 'child'},
{provide: 'fromChild', useValue: 'from child'},
{provide: 'shadow', useValue: 'from child module'},
],
})
class ChildModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => ParentModule}]);
router.navigateByUrl('/lazy/parent/child');
advance(fixture);
expect(location.path()).toEqual('/lazy/parent/child');
expect(fixture.nativeElement).toHaveText('parent[child]');
const pInj = fixture.debugElement.query(By.directive(Parent)).injector!;
const cInj = fixture.debugElement.query(By.directive(Child)).injector!;
expect(pInj.get('moduleName')).toEqual('parent');
expect(pInj.get('fromParent')).toEqual('from parent');
expect(pInj.get(Parent)).toBeInstanceOf(Parent);
expect(pInj.get('fromChild', null)).toEqual(null);
expect(pInj.get(Child, null)).toEqual(null);
expect(cInj.get('moduleName')).toEqual('child');
expect(cInj.get('fromParent')).toEqual('from parent');
expect(cInj.get('fromChild')).toEqual('from child');
expect(cInj.get(Parent)).toBeInstanceOf(Parent);
expect(cInj.get(Child)).toBeInstanceOf(Child);
// The child module can not shadow the parent component
expect(cInj.get('shadow')).toEqual('from parent component');
const pmInj = pInj.get(NgModuleRef).injector;
const cmInj = cInj.get(NgModuleRef).injector;
expect(pmInj.get('moduleName')).toEqual('parent');
expect(cmInj.get('moduleName')).toEqual('child');
expect(pmInj.get(Parent, '-')).toEqual('-');
expect(cmInj.get(Parent, '-')).toEqual('-');
expect(pmInj.get(Child, '-')).toEqual('-');
expect(cmInj.get(Child, '-')).toEqual('-');
}),
));
// https://github.com/angular/angular/issues/12889
it('should create a single instance of lazy-loaded modules', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded-parent [<router-outlet></router-outlet>]',
standalone: false,
})
class ParentLazyLoadedComponent {}
@Component({
selector: 'lazy',
template: 'lazy-loaded-child',
standalone: false,
})
class ChildLazyLoadedComponent {}
@NgModule({
declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent],
imports: [
RouterModule.forChild([
{
path: 'loaded',
component: ParentLazyLoadedComponent,
children: [{path: 'child', component: ChildLazyLoadedComponent}],
},
]),
],
})
class LoadedModule {
static instances = 0;
constructor() {
LoadedModule.instances++;
}
}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]);
router.navigateByUrl('/lazy/loaded/child');
advance(fixture);
expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]');
expect(LoadedModule.instances).toEqual(1);
}),
));
// https://github.com/angular/angular/issues/13870
it('should create a single instance of guards for lazy-loaded modules', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Injectable()
class Service {}
@Injectable()
class Resolver {
constructor(public service: Service) {}
resolve() {
return this.service;
}
}
@Component({
selector: 'lazy',
template: 'lazy',
standalone: false,
})
class LazyLoadedComponent {
resolvedService: Service;
constructor(
public injectedService: Service,
route: ActivatedRoute,
) {
this.resolvedService = route.snapshot.data['service'];
}
}
@NgModule({
declarations: [LazyLoadedComponent],
providers: [Service, Resolver],
imports: [
RouterModule.forChild([
{
path: 'loaded',
component: LazyLoadedComponent,
resolve: {'service': () => coreInject(Resolver).resolve()},
},
]),
],
})
class LoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]);
router.navigateByUrl('/lazy/loaded');
advance(fixture);
expect(fixture.nativeElement).toHaveText('lazy');
const lzc = fixture.debugElement.query(
By.directive(LazyLoadedComponent),
).componentInstance;
expect(lzc.injectedService).toBe(lzc.resolvedService);
}),
));
it('should emit RouteConfigLoadStart and RouteConfigLoadEnd event when route is lazy loaded', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded-parent [<router-outlet></router-outlet>]',
standalone: false,
})
class ParentLazyLoadedComponent {}
@Component({
selector: 'lazy',
template: 'lazy-loaded-child',
standalone: false,
})
class ChildLazyLoadedComponent {}
@NgModule({
declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent],
imports: [
RouterModule.forChild([
{
path: 'loaded',
component: ParentLazyLoadedComponent,
children: [{path: 'child', component: ChildLazyLoadedComponent}],
},
]),
],
})
class LoadedModule {}
const events: Array<RouteConfigLoadStart | RouteConfigLoadEnd> = [];
router.events.subscribe((e) => {
if (e instanceof RouteConfigLoadStart || e instanceof RouteConfigLoadEnd) {
events.push(e);
}
});
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]);
router.navigateByUrl('/lazy/loaded/child');
advance(fixture);
expect(events.length).toEqual(2);
expect(events[0].toString()).toEqual('RouteConfigLoadStart(path: lazy)');
expect(events[1].toString()).toEqual('RouteConfigLoadEnd(path: lazy)');
}),
));
| |
014188
|
throws an error when forRoot() is used in a lazy context', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'should not show',
standalone: false,
})
class LazyLoadedComponent {}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forRoot([{path: 'loaded', component: LazyLoadedComponent}])],
})
class LoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]);
let recordedError: any = null;
router.navigateByUrl('/lazy/loaded')!.catch((err) => (recordedError = err));
advance(fixture);
expect(recordedError.message).toContain(`NG04007`);
}),
));
it('should combine routes from multiple modules into a single configuration', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded-2',
standalone: false,
})
class LazyComponent2 {}
@NgModule({
declarations: [LazyComponent2],
imports: [RouterModule.forChild([{path: 'loaded', component: LazyComponent2}])],
})
class SiblingOfLoadedModule {}
@Component({
selector: 'lazy',
template: 'lazy-loaded-1',
standalone: false,
})
class LazyComponent1 {}
@NgModule({
declarations: [LazyComponent1],
imports: [
RouterModule.forChild([{path: 'loaded', component: LazyComponent1}]),
SiblingOfLoadedModule,
],
})
class LoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'lazy1', loadChildren: () => LoadedModule},
{path: 'lazy2', loadChildren: () => SiblingOfLoadedModule},
]);
router.navigateByUrl('/lazy1/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy1/loaded');
router.navigateByUrl('/lazy2/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy2/loaded');
}),
));
it('should allow lazy loaded module in named outlet', fakeAsync(
inject([Router], (router: Router) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded',
standalone: false,
})
class LazyComponent {}
@NgModule({
declarations: [LazyComponent],
imports: [RouterModule.forChild([{path: '', component: LazyComponent}])],
})
class LazyLoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{path: 'lazy', loadChildren: () => LazyLoadedModule, outlet: 'right'},
],
},
]);
router.navigateByUrl('/team/22/user/john');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: ]');
router.navigateByUrl('/team/22/(user/john//right:lazy)');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: lazy-loaded ]');
}),
));
it('should allow componentless named outlet to render children', fakeAsync(
inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{path: 'simple', outlet: 'right', children: [{path: '', component: SimpleCmp}]},
],
},
]);
router.navigateByUrl('/team/22/user/john');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: ]');
router.navigateByUrl('/team/22/(user/john//right:simple)');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: simple ]');
}),
));
it('should render loadComponent named outlet with children', fakeAsync(() => {
const router = TestBed.inject(Router);
const fixture = createRoot(router, RootCmp);
@Component({
standalone: true,
imports: [RouterModule],
template: '[right outlet component: <router-outlet></router-outlet>]',
})
class RightComponent {
constructor(readonly route: ActivatedRoute) {}
}
const loadSpy = jasmine.createSpy();
loadSpy.and.returnValue(RightComponent);
router.resetConfig([
{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{
path: 'simple',
loadComponent: loadSpy,
outlet: 'right',
children: [{path: '', component: SimpleCmp}],
},
],
},
{path: '', component: SimpleCmp},
]);
router.navigateByUrl('/team/22/(user/john//right:simple)');
advance(fixture);
expect(fixture.nativeElement).toHaveText(
'team 22 [ user john, right: [right outlet component: simple] ]',
);
const rightCmp: RightComponent = fixture.debugElement.query(
By.directive(RightComponent),
).componentInstance;
// Ensure we don't accidentally add `EmptyOutletComponent` via `standardizeConfig`
expect(rightCmp.route.routeConfig?.component).not.toBeDefined();
// Ensure we can navigate away and come back
router.navigateByUrl('/');
advance(fixture);
router.navigateByUrl('/team/22/(user/john//right:simple)');
advance(fixture);
expect(fixture.nativeElement).toHaveText(
'team 22 [ user john, right: [right outlet component: simple] ]',
);
expect(loadSpy.calls.count()).toEqual(1);
}));
describe('should use the injector of the lazily-loaded configuration', () => {
class LazyLoadedServiceDefinedInModule {}
@Component({
selector: 'eager-parent',
template: 'eager-parent <router-outlet></router-outlet>',
standalone: false,
})
class EagerParentComponent {}
@Component({
selector: 'lazy-parent',
template: 'lazy-parent <router-outlet></router-outlet>',
standalone: false,
})
class LazyParentComponent {}
@Component({
selector: 'lazy-child',
template: 'lazy-child',
standalone: false,
})
class LazyChildComponent {
constructor(
lazy: LazyParentComponent, // should be able to inject lazy/direct parent
lazyService: LazyLoadedServiceDefinedInModule, // should be able to inject lazy service
eager: EagerParentComponent, // should use the injector of the location to create a
// parent
) {}
}
@NgModule({
declarations: [LazyParentComponent, LazyChildComponent],
imports: [
RouterModule.forChild([
{
path: '',
children: [
{
path: 'lazy-parent',
component: LazyParentComponent,
children: [{path: 'lazy-child', component: LazyChildComponent}],
},
],
},
]),
],
providers: [LazyLoadedServiceDefinedInModule],
})
class LoadedModule {}
@NgModule({declarations: [EagerParentComponent], imports: [RouterModule.forRoot([])]})
class TestModule {}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TestModule],
});
});
it('should use the injector of the lazily-loaded configuration', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'eager-parent',
component: EagerParentComponent,
children: [{path: 'lazy', loadChildren: () => LoadedModule}],
},
]);
router.navigateByUrl('/eager-parent/lazy/lazy-parent/lazy-child');
advance(fixture);
expect(location.path()).toEqual('/eager-parent/lazy/lazy-parent/lazy-child');
expect(fixture.nativeElement).toHaveText('eager-parent lazy-parent lazy-child');
}),
));
});
| |
014189
|
works when given a callback', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded',
standalone: false,
})
class LazyLoadedComponent {}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])],
})
class LoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]);
router.navigateByUrl('/lazy/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy/loaded');
expect(fixture.nativeElement).toHaveText('lazy-loaded');
}),
));
it('error emit an error when cannot load a config', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'lazy',
loadChildren: () => {
throw new Error('invalid');
},
},
]);
const recordedEvents: Event[] = [];
router.events.forEach((e) => recordedEvents.push(e));
router.navigateByUrl('/lazy/loaded')!.catch((s) => {});
advance(fixture);
expect(location.path()).toEqual('');
expectEvents(recordedEvents, [
[NavigationStart, '/lazy/loaded'],
[RouteConfigLoadStart],
[NavigationError, '/lazy/loaded'],
]);
}),
));
it('should emit an error when the lazily-loaded config is not valid', fakeAsync(() => {
const router = TestBed.inject(Router);
@NgModule({imports: [RouterModule.forChild([{path: 'loaded'}])]})
class LoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]);
let recordedError: any = null;
router.navigateByUrl('/lazy/loaded').catch((err) => (recordedError = err));
advance(fixture);
expect(recordedError.message).toContain(
`Invalid configuration of route 'lazy/loaded'. One of the following must be provided: component, loadComponent, redirectTo, children or loadChildren`,
);
}));
it('should work with complex redirect rules', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded',
standalone: false,
})
class LazyLoadedComponent {}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])],
})
class LoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'lazy', loadChildren: () => LoadedModule},
{path: '**', redirectTo: 'lazy'},
]);
router.navigateByUrl('/lazy/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy/loaded');
}),
));
it('should work with wildcard route', fakeAsync(
inject([Router, Location], (router: Router, location: Location) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded',
standalone: false,
})
class LazyLoadedComponent {}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forChild([{path: '', component: LazyLoadedComponent}])],
})
class LazyLoadedModule {}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: '**', loadChildren: () => LazyLoadedModule}]);
router.navigateByUrl('/lazy');
advance(fixture);
expect(location.path()).toEqual('/lazy');
expect(fixture.nativeElement).toHaveText('lazy-loaded');
}),
));
describe('preloading', () => {
let log: string[] = [];
@Component({
selector: 'lazy',
template: 'should not show',
standalone: false,
})
class LazyLoadedComponent {}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [
RouterModule.forChild([{path: 'LoadedModule2', component: LazyLoadedComponent}]),
],
})
class LoadedModule2 {}
@NgModule({
imports: [
RouterModule.forChild([{path: 'LoadedModule1', loadChildren: () => LoadedModule2}]),
],
})
class LoadedModule1 {}
@NgModule({})
class EmptyModule {}
beforeEach(() => {
log.length = 0;
TestBed.configureTestingModule({
providers: [
{provide: PreloadingStrategy, useExisting: PreloadAllModules},
{
provide: 'loggingReturnsTrue',
useValue: () => {
log.push('loggingReturnsTrue');
return true;
},
},
],
});
const preloader = TestBed.inject(RouterPreloader);
preloader.setUpPreloading();
});
it('should work', fakeAsync(() => {
const router = TestBed.inject(Router);
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'blank', component: BlankCmp},
{path: 'lazy', loadChildren: () => LoadedModule1},
]);
router.navigateByUrl('/blank');
advance(fixture);
const config = router.config;
const firstRoutes = getLoadedRoutes(config[1])!;
expect(firstRoutes).toBeDefined();
expect(firstRoutes[0].path).toEqual('LoadedModule1');
const secondRoutes = getLoadedRoutes(firstRoutes[0])!;
expect(secondRoutes).toBeDefined();
expect(secondRoutes[0].path).toEqual('LoadedModule2');
}));
it('should not preload when canLoad is present and does not execute guard', fakeAsync(() => {
const router = TestBed.inject(Router);
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'blank', component: BlankCmp},
{path: 'lazy', loadChildren: () => LoadedModule1, canLoad: ['loggingReturnsTrue']},
]);
router.navigateByUrl('/blank');
advance(fixture);
const config = router.config;
const firstRoutes = getLoadedRoutes(config[1])!;
expect(firstRoutes).toBeUndefined();
expect(log.length).toBe(0);
}));
it('should allow navigation to modules with no routes', fakeAsync(() => {
const router = TestBed.inject(Router);
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => EmptyModule}]);
router.navigateByUrl('/lazy');
advance(fixture);
}));
});
| |
014212
|
describe('component input binding', () => {
it('sets component inputs from matching query params', async () => {
@Component({
template: '',
standalone: false,
})
class MyComponent {
@Input() language?: string;
}
TestBed.configureTestingModule({
providers: [
provideRouter([{path: '**', component: MyComponent}], withComponentInputBinding()),
],
});
const harness = await RouterTestingHarness.create();
const instance = await harness.navigateByUrl('/?language=english', MyComponent);
expect(instance.language).toEqual('english');
await harness.navigateByUrl('/?language=french');
expect(instance.language).toEqual('french');
// Should set the input to undefined when the matching router data is removed
await harness.navigateByUrl('/');
expect(instance.language).toEqual(undefined);
await harness.navigateByUrl('/?notlanguage=doubletalk');
expect(instance.language).toEqual(undefined);
});
it('sets component inputs from resolved and static data', async () => {
@Component({
template: '',
standalone: false,
})
class MyComponent {
@Input() resolveA?: string;
@Input() dataA?: string;
}
TestBed.configureTestingModule({
providers: [
provideRouter(
[
{
path: '**',
component: MyComponent,
data: {'dataA': 'My static data'},
resolve: {'resolveA': () => 'My resolved data'},
},
],
withComponentInputBinding(),
),
],
});
const harness = await RouterTestingHarness.create();
const instance = await harness.navigateByUrl('/', MyComponent);
expect(instance.resolveA).toEqual('My resolved data');
expect(instance.dataA).toEqual('My static data');
});
it('sets component inputs from path params', async () => {
@Component({
template: '',
standalone: false,
})
class MyComponent {
@Input() language?: string;
}
TestBed.configureTestingModule({
providers: [
provideRouter([{path: '**', component: MyComponent}], withComponentInputBinding()),
],
});
const harness = await RouterTestingHarness.create();
const instance = await harness.navigateByUrl('/x;language=english', MyComponent);
expect(instance.language).toEqual('english');
});
it('when keys conflict, sets inputs based on priority: data > path params > query params', async () => {
@Component({
template: '',
standalone: false,
})
class MyComponent {
@Input() result?: string;
}
TestBed.configureTestingModule({
providers: [
provideRouter(
[
{
path: 'withData',
component: MyComponent,
data: {'result': 'from data'},
},
{
path: 'withoutData',
component: MyComponent,
},
],
withComponentInputBinding(),
),
],
});
const harness = await RouterTestingHarness.create();
let instance = await harness.navigateByUrl(
'/withData;result=from path param?result=from query params',
MyComponent,
);
expect(instance.result).toEqual('from data');
// Same component, different instance because it's a different route
instance = await harness.navigateByUrl(
'/withoutData;result=from path param?result=from query params',
MyComponent,
);
expect(instance.result).toEqual('from path param');
instance = await harness.navigateByUrl('/withoutData?result=from query params', MyComponent);
expect(instance.result).toEqual('from query params');
});
it('does not write multiple times if two sources of conflicting keys both update', async () => {
let resultLog: Array<string | undefined> = [];
@Component({
template: '',
standalone: false,
})
class MyComponent {
@Input()
set result(v: string | undefined) {
resultLog.push(v);
}
}
TestBed.configureTestingModule({
providers: [
provideRouter([{path: '**', component: MyComponent}], withComponentInputBinding()),
],
});
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/x', MyComponent);
expect(resultLog).toEqual([undefined]);
await harness.navigateByUrl('/x;result=from path param?result=from query params', MyComponent);
expect(resultLog).toEqual([undefined, 'from path param']);
});
it('Should have inputs available to all outlets after navigation', async () => {
@Component({
template: '{{myInput}}',
standalone: true,
})
class MyComponent {
@Input() myInput?: string;
}
@Component({
template: '<router-outlet/>',
imports: [RouterOutlet],
standalone: true,
})
class OutletWrapper {}
TestBed.configureTestingModule({
providers: [
provideRouter(
[
{
path: 'root',
component: OutletWrapper,
children: [{path: '**', component: MyComponent}],
},
],
withComponentInputBinding(),
),
],
});
const harness = await RouterTestingHarness.create('/root/child?myInput=1');
expect(harness.routeNativeElement!.innerText).toBe('1');
await harness.navigateByUrl('/root/child?myInput=2');
expect(harness.routeNativeElement!.innerText).toBe('2');
});
});
describe('injectors', () => {
it('should always use environment injector from route hierarchy and not inherit from outlet', async () => {
let childTokenValue: any = null;
const TOKEN = new InjectionToken<any>('');
@Component({
template: '',
standalone: true,
})
class Child {
constructor() {
childTokenValue = inject(TOKEN as any, {optional: true});
}
}
@NgModule({
providers: [{provide: TOKEN, useValue: 'some value'}],
})
class ModWithProviders {}
@Component({
template: '<router-outlet/>',
imports: [RouterOutlet, ModWithProviders],
standalone: true,
})
class App {}
TestBed.configureTestingModule({
providers: [provideRouter([{path: 'a', component: Child}])],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl('/a');
fixture.detectChanges();
expect(childTokenValue).toEqual(null);
});
it('should not get sibling providers', async () => {
let childTokenValue: any = null;
const TOKEN = new InjectionToken<any>('');
@Component({
template: '',
standalone: true,
})
class Child {
constructor() {
childTokenValue = inject(TOKEN, {optional: true});
}
}
@Component({
template: '<router-outlet/>',
imports: [RouterOutlet],
standalone: true,
})
class App {}
TestBed.configureTestingModule({
providers: [
provideRouter([
{path: 'a', providers: [{provide: TOKEN, useValue: 'a value'}], component: Child},
{path: 'b', component: Child},
]),
],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl('/a');
fixture.detectChanges();
expect(childTokenValue).toEqual('a value');
await TestBed.inject(Router).navigateByUrl('/b');
fixture.detectChanges();
expect(childTokenValue).toEqual(null);
});
});
| |
014245
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Compiler,
createEnvironmentInjector,
EnvironmentInjector,
Injectable,
OnDestroy,
} from '@angular/core';
import {from, Observable, of, Subscription} from 'rxjs';
import {catchError, concatMap, filter, mergeAll, mergeMap} from 'rxjs/operators';
import {Event, NavigationEnd} from './events';
import {LoadedRouterConfig, Route, Routes} from './models';
import {Router} from './router';
import {RouterConfigLoader} from './router_config_loader';
/**
* @description
*
* Provides a preloading strategy.
*
* @publicApi
*/
export abstract class PreloadingStrategy {
abstract preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
/**
* @description
*
* Provides a preloading strategy that preloads all modules as quickly as possible.
*
* ```
* RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
* ```
*
* @publicApi
*/
@Injectable({providedIn: 'root'})
export class PreloadAllModules implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any> {
return fn().pipe(catchError(() => of(null)));
}
}
/**
* @description
*
* Provides a preloading strategy that does not preload any modules.
*
* This strategy is enabled by default.
*
* @publicApi
*/
@Injectable({providedIn: 'root'})
export class NoPreloading implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any> {
return of(null);
}
}
/**
* The preloader optimistically loads all router configurations to
* make navigations into lazily-loaded sections of the application faster.
*
* The preloader runs in the background. When the router bootstraps, the preloader
* starts listening to all navigation events. After every such event, the preloader
* will check if any configurations can be loaded lazily.
*
* If a route is protected by `canLoad` guards, the preloaded will not load it.
*
* @publicApi
*/
@Injectable({providedIn: 'root'})
export class RouterPreloader implements OnDestroy {
private subscription?: Subscription;
constructor(
private router: Router,
compiler: Compiler,
private injector: EnvironmentInjector,
private preloadingStrategy: PreloadingStrategy,
private loader: RouterConfigLoader,
) {}
setUpPreloading(): void {
this.subscription = this.router.events
.pipe(
filter((e: Event) => e instanceof NavigationEnd),
concatMap(() => this.preload()),
)
.subscribe(() => {});
}
preload(): Observable<any> {
return this.processRoutes(this.injector, this.router.config);
}
/** @nodoc */
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
private processRoutes(injector: EnvironmentInjector, routes: Routes): Observable<void> {
const res: Observable<any>[] = [];
for (const route of routes) {
if (route.providers && !route._injector) {
route._injector = createEnvironmentInjector(
route.providers,
injector,
`Route: ${route.path}`,
);
}
const injectorForCurrentRoute = route._injector ?? injector;
const injectorForChildren = route._loadedInjector ?? injectorForCurrentRoute;
// Note that `canLoad` is only checked as a condition that prevents `loadChildren` and not
// `loadComponent`. `canLoad` guards only block loading of child routes by design. This
// happens as a consequence of needing to descend into children for route matching immediately
// while component loading is deferred until route activation. Because `canLoad` guards can
// have side effects, we cannot execute them here so we instead skip preloading altogether
// when present. Lastly, it remains to be decided whether `canLoad` should behave this way
// at all. Code splitting and lazy loading is separate from client-side authorization checks
// and should not be used as a security measure to prevent loading of code.
if (
(route.loadChildren && !route._loadedRoutes && route.canLoad === undefined) ||
(route.loadComponent && !route._loadedComponent)
) {
res.push(this.preloadConfig(injectorForCurrentRoute, route));
}
if (route.children || route._loadedRoutes) {
res.push(this.processRoutes(injectorForChildren, (route.children ?? route._loadedRoutes)!));
}
}
return from(res).pipe(mergeAll());
}
private preloadConfig(injector: EnvironmentInjector, route: Route): Observable<void> {
return this.preloadingStrategy.preload(route, () => {
let loadedChildren$: Observable<LoadedRouterConfig | null>;
if (route.loadChildren && route.canLoad === undefined) {
loadedChildren$ = this.loader.loadChildren(injector, route);
} else {
loadedChildren$ = of(null);
}
const recursiveLoadChildren$ = loadedChildren$.pipe(
mergeMap((config: LoadedRouterConfig | null) => {
if (config === null) {
return of(void 0);
}
route._loadedRoutes = config.routes;
route._loadedInjector = config.injector;
// If the loaded config was a module, use that as the module/module injector going
// forward. Otherwise, continue using the current module/module injector.
return this.processRoutes(config.injector ?? injector, config.routes);
}),
);
if (route.loadComponent && !route._loadedComponent) {
const loadComponent$ = this.loader.loadComponent(route);
return from([recursiveLoadChildren$, loadComponent$]).pipe(mergeAll());
} else {
return recursiveLoadChildren$;
}
});
}
}
| |
014251
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Compiler,
EnvironmentInjector,
inject,
Injectable,
InjectionToken,
Injector,
NgModuleFactory,
Type,
} from '@angular/core';
import {ConnectableObservable, from, Observable, of, Subject} from 'rxjs';
import {finalize, map, mergeMap, refCount, tap} from 'rxjs/operators';
import {DefaultExport, LoadedRouterConfig, Route, Routes} from './models';
import {wrapIntoObservable} from './utils/collection';
import {assertStandalone, validateConfig} from './utils/config';
import {standardizeConfig} from './components/empty_outlet';
/**
* The DI token for a router configuration.
*
* `ROUTES` is a low level API for router configuration via dependency injection.
*
* We recommend that in almost all cases to use higher level APIs such as `RouterModule.forRoot()`,
* `provideRouter`, or `Router.resetConfig()`.
*
* @publicApi
*/
export const ROUTES = new InjectionToken<Route[][]>(ngDevMode ? 'ROUTES' : '');
type ComponentLoader = Observable<Type<unknown>>;
@Injectable({providedIn: 'root'})
export class RouterConfigLoader {
private componentLoaders = new WeakMap<Route, ComponentLoader>();
private childrenLoaders = new WeakMap<Route, Observable<LoadedRouterConfig>>();
onLoadStartListener?: (r: Route) => void;
onLoadEndListener?: (r: Route) => void;
private readonly compiler = inject(Compiler);
loadComponent(route: Route): Observable<Type<unknown>> {
if (this.componentLoaders.get(route)) {
return this.componentLoaders.get(route)!;
} else if (route._loadedComponent) {
return of(route._loadedComponent);
}
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
const loadRunner = wrapIntoObservable(route.loadComponent!()).pipe(
map(maybeUnwrapDefaultExport),
tap((component) => {
if (this.onLoadEndListener) {
this.onLoadEndListener(route);
}
(typeof ngDevMode === 'undefined' || ngDevMode) &&
assertStandalone(route.path ?? '', component);
route._loadedComponent = component;
}),
finalize(() => {
this.componentLoaders.delete(route);
}),
);
// Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
const loader = new ConnectableObservable(loadRunner, () => new Subject<Type<unknown>>()).pipe(
refCount(),
);
this.componentLoaders.set(route, loader);
return loader;
}
loadChildren(parentInjector: Injector, route: Route): Observable<LoadedRouterConfig> {
if (this.childrenLoaders.get(route)) {
return this.childrenLoaders.get(route)!;
} else if (route._loadedRoutes) {
return of({routes: route._loadedRoutes, injector: route._loadedInjector});
}
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
const moduleFactoryOrRoutes$ = loadChildren(
route,
this.compiler,
parentInjector,
this.onLoadEndListener,
);
const loadRunner = moduleFactoryOrRoutes$.pipe(
finalize(() => {
this.childrenLoaders.delete(route);
}),
);
// Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
const loader = new ConnectableObservable(
loadRunner,
() => new Subject<LoadedRouterConfig>(),
).pipe(refCount());
this.childrenLoaders.set(route, loader);
return loader;
}
}
/**
* Executes a `route.loadChildren` callback and converts the result to an array of child routes and
* an injector if that callback returned a module.
*
* This function is used for the route discovery during prerendering
* in @angular-devkit/build-angular. If there are any updates to the contract here, it will require
* an update to the extractor.
*/
export function loadChildren(
route: Route,
compiler: Compiler,
parentInjector: Injector,
onLoadEndListener?: (r: Route) => void,
): Observable<LoadedRouterConfig> {
return wrapIntoObservable(route.loadChildren!()).pipe(
map(maybeUnwrapDefaultExport),
mergeMap((t) => {
if (t instanceof NgModuleFactory || Array.isArray(t)) {
return of(t);
} else {
return from(compiler.compileModuleAsync(t));
}
}),
map((factoryOrRoutes: NgModuleFactory<any> | Routes) => {
if (onLoadEndListener) {
onLoadEndListener(route);
}
// This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is
// no injector associated with lazy loading a `Route` array.
let injector: EnvironmentInjector | undefined;
let rawRoutes: Route[];
let requireStandaloneComponents = false;
if (Array.isArray(factoryOrRoutes)) {
rawRoutes = factoryOrRoutes;
requireStandaloneComponents = true;
} else {
injector = factoryOrRoutes.create(parentInjector).injector;
// When loading a module that doesn't provide `RouterModule.forChild()` preloader
// will get stuck in an infinite loop. The child module's Injector will look to
// its parent `Injector` when it doesn't find any ROUTES so it will return routes
// for it's parent module instead.
rawRoutes = injector.get(ROUTES, [], {optional: true, self: true}).flat();
}
const routes = rawRoutes.map(standardizeConfig);
(typeof ngDevMode === 'undefined' || ngDevMode) &&
validateConfig(routes, route.path, requireStandaloneComponents);
return {routes, injector};
}),
);
}
function isWrappedDefaultExport<T>(value: T | DefaultExport<T>): value is DefaultExport<T> {
// We use `in` here with a string key `'default'`, because we expect `DefaultExport` objects to be
// dynamically imported ES modules with a spec-mandated `default` key. Thus we don't expect that
// `default` will be a renamed property.
return value && typeof value === 'object' && 'default' in value;
}
function maybeUnwrapDefaultExport<T>(input: T | DefaultExport<T>): T {
// As per `isWrappedDefaultExport`, the `default` key here is generated by the browser and not
// subject to property renaming, so we reference it with bracket access.
return isWrappedDefaultExport(input) ? input['default'] : input;
}
| |
014257
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
HashLocationStrategy,
LOCATION_INITIALIZED,
LocationStrategy,
ViewportScroller,
} from '@angular/common';
import {
APP_BOOTSTRAP_LISTENER,
APP_INITIALIZER,
ApplicationRef,
ComponentRef,
ENVIRONMENT_INITIALIZER,
EnvironmentProviders,
inject,
InjectFlags,
InjectionToken,
Injector,
makeEnvironmentProviders,
NgZone,
Provider,
runInInjectionContext,
Type,
} from '@angular/core';
import {of, Subject} from 'rxjs';
import {INPUT_BINDER, RoutedComponentInputBinder} from './directives/router_outlet';
import {Event, NavigationError, stringifyEvent} from './events';
import {RedirectCommand, Routes} from './models';
import {NAVIGATION_ERROR_HANDLER, NavigationTransitions} from './navigation_transition';
import {Router} from './router';
import {InMemoryScrollingOptions, ROUTER_CONFIGURATION, RouterConfigOptions} from './router_config';
import {ROUTES} from './router_config_loader';
import {PreloadingStrategy, RouterPreloader} from './router_preloader';
import {ROUTER_SCROLLER, RouterScroller} from './router_scroller';
import {ActivatedRoute} from './router_state';
import {UrlSerializer} from './url_tree';
import {afterNextNavigation} from './utils/navigations';
import {
CREATE_VIEW_TRANSITION,
createViewTransition,
VIEW_TRANSITION_OPTIONS,
ViewTransitionsFeatureOptions,
} from './utils/view_transition';
/**
* Sets up providers necessary to enable `Router` functionality for the application.
* Allows to configure a set of routes as well as extra features that should be enabled.
*
* @usageNotes
*
* Basic example of how you can add a Router to your application:
* ```
* const appRoutes: Routes = [];
* bootstrapApplication(AppComponent, {
* providers: [provideRouter(appRoutes)]
* });
* ```
*
* You can also enable optional features in the Router by adding functions from the `RouterFeatures`
* type:
* ```
* const appRoutes: Routes = [];
* bootstrapApplication(AppComponent,
* {
* providers: [
* provideRouter(appRoutes,
* withDebugTracing(),
* withRouterConfig({paramsInheritanceStrategy: 'always'}))
* ]
* }
* );
* ```
*
* @see {@link RouterFeatures}
*
* @publicApi
* @param routes A set of `Route`s to use for the application routing table.
* @param features Optional features to configure additional router behaviors.
* @returns A set of providers to setup a Router.
*/
export function provideRouter(routes: Routes, ...features: RouterFeatures[]): EnvironmentProviders {
return makeEnvironmentProviders([
{provide: ROUTES, multi: true, useValue: routes},
typeof ngDevMode === 'undefined' || ngDevMode
? {provide: ROUTER_IS_PROVIDED, useValue: true}
: [],
{provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]},
{provide: APP_BOOTSTRAP_LISTENER, multi: true, useFactory: getBootstrapListener},
features.map((feature) => feature.ɵproviders),
]);
}
export function rootRoute(router: Router): ActivatedRoute {
return router.routerState.root;
}
/**
* Helper type to represent a Router feature.
*
* @publicApi
*/
export interface RouterFeature<FeatureKind extends RouterFeatureKind> {
ɵkind: FeatureKind;
ɵproviders: Provider[];
}
/**
* Helper function to create an object that represents a Router feature.
*/
function routerFeature<FeatureKind extends RouterFeatureKind>(
kind: FeatureKind,
providers: Provider[],
): RouterFeature<FeatureKind> {
return {ɵkind: kind, ɵproviders: providers};
}
/**
* An Injection token used to indicate whether `provideRouter` or `RouterModule.forRoot` was ever
* called.
*/
export const ROUTER_IS_PROVIDED = new InjectionToken<boolean>('', {
providedIn: 'root',
factory: () => false,
});
const routerIsProvidedDevModeCheck = {
provide: ENVIRONMENT_INITIALIZER,
multi: true,
useFactory() {
return () => {
if (!inject(ROUTER_IS_PROVIDED)) {
console.warn(
'`provideRoutes` was called without `provideRouter` or `RouterModule.forRoot`. ' +
'This is likely a mistake.',
);
}
};
},
};
/**
* Registers a DI provider for a set of routes.
* @param routes The route configuration to provide.
*
* @usageNotes
*
* ```
* @NgModule({
* providers: [provideRoutes(ROUTES)]
* })
* class LazyLoadedChildModule {}
* ```
*
* @deprecated If necessary, provide routes using the `ROUTES` `InjectionToken`.
* @see {@link ROUTES}
* @publicApi
*/
export function provideRoutes(routes: Routes): Provider[] {
return [
{provide: ROUTES, multi: true, useValue: routes},
typeof ngDevMode === 'undefined' || ngDevMode ? routerIsProvidedDevModeCheck : [],
];
}
/**
* A type alias for providers returned by `withInMemoryScrolling` for use with `provideRouter`.
*
* @see {@link withInMemoryScrolling}
* @see {@link provideRouter}
*
* @publicApi
*/
export type InMemoryScrollingFeature = RouterFeature<RouterFeatureKind.InMemoryScrollingFeature>;
/**
* Enables customizable scrolling behavior for router navigations.
*
* @usageNotes
*
* Basic example of how you can enable scrolling feature:
* ```
* const appRoutes: Routes = [];
* bootstrapApplication(AppComponent,
* {
* providers: [
* provideRouter(appRoutes, withInMemoryScrolling())
* ]
* }
* );
* ```
*
* @see {@link provideRouter}
* @see {@link ViewportScroller}
*
* @publicApi
* @param options Set of configuration parameters to customize scrolling behavior, see
* `InMemoryScrollingOptions` for additional information.
* @returns A set of providers for use with `provideRouter`.
*/
export function withInMemoryScrolling(
options: InMemoryScrollingOptions = {},
): InMemoryScrollingFeature {
const providers = [
{
provide: ROUTER_SCROLLER,
useFactory: () => {
const viewportScroller = inject(ViewportScroller);
const zone = inject(NgZone);
const transitions = inject(NavigationTransitions);
const urlSerializer = inject(UrlSerializer);
return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, options);
},
},
];
return routerFeature(RouterFeatureKind.InMemoryScrollingFeature, providers);
}
export function getBootstrapListener() {
const injector = inject(Injector);
return (bootstrappedComponentRef: ComponentRef<unknown>) => {
const ref = injector.get(ApplicationRef);
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
const router = injector.get(Router);
const bootstrapDone = injector.get(BOOTSTRAP_DONE);
if (injector.get(INITIAL_NAVIGATION) === InitialNavigation.EnabledNonBlocking) {
router.initialNavigation();
}
injector.get(ROUTER_PRELOADER, null, InjectFlags.Optional)?.setUpPreloading();
injector.get(ROUTER_SCROLLER, null, InjectFlags.Optional)?.init();
router.resetRootComponentType(ref.componentTypes[0]);
if (!bootstrapDone.closed) {
bootstrapDone.next();
bootstrapDone.complete();
bootstrapDone.unsubscribe();
}
};
}
/**
* A subject used to indicate that the bootstrapping phase is done. When initial navigation is
* `enabledBlocking`, the first navigation waits until bootstrapping is finished before continuing
* to the activation phase.
*/
const BOOTSTRAP_DONE = new InjectionToken<Subject<void>>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'bootstrap done indicator' : '',
{
factory: () => {
return new Subject<void>();
},
},
);
/**
* This and the INITIAL_NAVIGATION token are used internally only. The public API side of this is
* configured through the `ExtraOptions`.
*
* When set to `EnabledBlocking`, the initial navigation starts before the root
* component is created. The bootstrap is blocked until the initial navigation is complete. This
* value should be set in case you use [server-side rendering](guide/ssr), but do not enable
* [hydration](guide/hydration) for your application.
*
* When set to `EnabledNonBlocking`, the initial navigation starts after the root component has been
* created. The bootstrap is not blocked on the completion of the initial navigation.
*
* When set to `Disabled`, the initial navigation is not performed. The location listener is set up
* before the root component gets created. Use if there is a reason to have more control over when
* the router starts its initial navigation due to some complex initialization logic.
*
* @see {@link ExtraOptions}
*/
const enum InitialNavigation {
EnabledBlocking,
EnabledNonBlocking,
Disabled,
}
con
| |
014259
|
* Provides the location strategy that uses the URL fragment instead of the history API.
*
* @usageNotes
*
* Basic example of how you can use the hash location option:
* ```
* const appRoutes: Routes = [];
* bootstrapApplication(AppComponent,
* {
* providers: [
* provideRouter(appRoutes, withHashLocation())
* ]
* }
* );
* ```
*
* @see {@link provideRouter}
* @see {@link HashLocationStrategy}
*
* @returns A set of providers for use with `provideRouter`.
*
* @publicApi
*/
export function withHashLocation(): RouterHashLocationFeature {
const providers = [{provide: LocationStrategy, useClass: HashLocationStrategy}];
return routerFeature(RouterFeatureKind.RouterHashLocationFeature, providers);
}
/**
* A type alias for providers returned by `withNavigationErrorHandler` for use with `provideRouter`.
*
* @see {@link withNavigationErrorHandler}
* @see {@link provideRouter}
*
* @publicApi
*/
export type NavigationErrorHandlerFeature =
RouterFeature<RouterFeatureKind.NavigationErrorHandlerFeature>;
/**
* Provides a function which is called when a navigation error occurs.
*
* This function is run inside application's [injection context](guide/di/dependency-injection-context)
* so you can use the [`inject`](api/core/inject) function.
*
* This function can return a `RedirectCommand` to convert the error to a redirect, similar to returning
* a `UrlTree` or `RedirectCommand` from a guard. This will also prevent the `Router` from emitting
* `NavigationError`; it will instead emit `NavigationCancel` with code NavigationCancellationCode.Redirect.
* Return values other than `RedirectCommand` are ignored and do not change any behavior with respect to
* how the `Router` handles the error.
*
* @usageNotes
*
* Basic example of how you can use the error handler option:
* ```
* const appRoutes: Routes = [];
* bootstrapApplication(AppComponent,
* {
* providers: [
* provideRouter(appRoutes, withNavigationErrorHandler((e: NavigationError) =>
* inject(MyErrorTracker).trackError(e)))
* ]
* }
* );
* ```
*
* @see {@link NavigationError}
* @see {@link core/inject}
* @see {@link runInInjectionContext}
*
* @returns A set of providers for use with `provideRouter`.
*
* @publicApi
*/
export function withNavigationErrorHandler(
handler: (error: NavigationError) => unknown | RedirectCommand,
): NavigationErrorHandlerFeature {
const providers = [
{
provide: NAVIGATION_ERROR_HANDLER,
useValue: handler,
},
];
return routerFeature(RouterFeatureKind.NavigationErrorHandlerFeature, providers);
}
/**
* A type alias for providers returned by `withComponentInputBinding` for use with `provideRouter`.
*
* @see {@link withComponentInputBinding}
* @see {@link provideRouter}
*
* @publicApi
*/
export type ComponentInputBindingFeature =
RouterFeature<RouterFeatureKind.ComponentInputBindingFeature>;
/**
* A type alias for providers returned by `withViewTransitions` for use with `provideRouter`.
*
* @see {@link withViewTransitions}
* @see {@link provideRouter}
*
* @publicApi
*/
export type ViewTransitionsFeature = RouterFeature<RouterFeatureKind.ViewTransitionsFeature>;
/**
* Enables binding information from the `Router` state directly to the inputs of the component in
* `Route` configurations.
*
* @usageNotes
*
* Basic example of how you can enable the feature:
* ```
* const appRoutes: Routes = [];
* bootstrapApplication(AppComponent,
* {
* providers: [
* provideRouter(appRoutes, withComponentInputBinding())
* ]
* }
* );
* ```
*
* The router bindings information from any of the following sources:
*
* - query parameters
* - path and matrix parameters
* - static route data
* - data from resolvers
*
* Duplicate keys are resolved in the same order from above, from least to greatest,
* meaning that resolvers have the highest precedence and override any of the other information
* from the route.
*
* Importantly, when an input does not have an item in the route data with a matching key, this
* input is set to `undefined`. This prevents previous information from being
* retained if the data got removed from the route (i.e. if a query parameter is removed).
* Default values can be provided with a resolver on the route to ensure the value is always present
* or an input and use an input transform in the component.
*
* @see {@link guide/components/inputs#input-transforms input transforms}
* @returns A set of providers for use with `provideRouter`.
*/
export function withComponentInputBinding(): ComponentInputBindingFeature {
const providers = [
RoutedComponentInputBinder,
{provide: INPUT_BINDER, useExisting: RoutedComponentInputBinder},
];
return routerFeature(RouterFeatureKind.ComponentInputBindingFeature, providers);
}
/**
* Enables view transitions in the Router by running the route activation and deactivation inside of
* `document.startViewTransition`.
*
* Note: The View Transitions API is not available in all browsers. If the browser does not support
* view transitions, the Router will not attempt to start a view transition and continue processing
* the navigation as usual.
*
* @usageNotes
*
* Basic example of how you can enable the feature:
* ```
* const appRoutes: Routes = [];
* bootstrapApplication(AppComponent,
* {
* providers: [
* provideRouter(appRoutes, withViewTransitions())
* ]
* }
* );
* ```
*
* @returns A set of providers for use with `provideRouter`.
* @see https://developer.chrome.com/docs/web-platform/view-transitions/
* @see https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API
* @developerPreview
*/
export function withViewTransitions(
options?: ViewTransitionsFeatureOptions,
): ViewTransitionsFeature {
const providers = [
{provide: CREATE_VIEW_TRANSITION, useValue: createViewTransition},
{
provide: VIEW_TRANSITION_OPTIONS,
useValue: {skipNextTransition: !!options?.skipInitialTransition, ...options},
},
];
return routerFeature(RouterFeatureKind.ViewTransitionsFeature, providers);
}
/**
* A type alias that represents all Router features available for use with `provideRouter`.
* Features can be enabled by adding special functions to the `provideRouter` call.
* See documentation for each symbol to find corresponding function name. See also `provideRouter`
* documentation on how to use those functions.
*
* @see {@link provideRouter}
*
* @publicApi
*/
export type RouterFeatures =
| PreloadingFeature
| DebugTracingFeature
| InitialNavigationFeature
| InMemoryScrollingFeature
| RouterConfigurationFeature
| NavigationErrorHandlerFeature
| ComponentInputBindingFeature
| ViewTransitionsFeature
| RouterHashLocationFeature;
/**
* The list of features as an enum to uniquely type each feature.
*/
export const enum RouterFeatureKind {
PreloadingFeature,
DebugTracingFeature,
EnabledBlockingInitialNavigationFeature,
DisabledInitialNavigationFeature,
InMemoryScrollingFeature,
RouterConfigurationFeature,
RouterHashLocationFeature,
NavigationErrorHandlerFeature,
ComponentInputBindingFeature,
ViewTransitionsFeature,
}
| |
014266
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NavigationBehaviorOptions, Route} from './models';
import {ActivatedRouteSnapshot, RouterStateSnapshot} from './router_state';
import {UrlTree} from './url_tree';
/**
* Identifies the call or event that triggered a navigation.
*
* * 'imperative': Triggered by `router.navigateByUrl()` or `router.navigate()`.
* * 'popstate' : Triggered by a `popstate` event.
* * 'hashchange'-: Triggered by a `hashchange` event.
*
* @publicApi
*/
export type NavigationTrigger = 'imperative' | 'popstate' | 'hashchange';
export const IMPERATIVE_NAVIGATION = 'imperative';
/**
* Identifies the type of a router event.
*
* @publicApi
*/
export enum EventType {
NavigationStart,
NavigationEnd,
NavigationCancel,
NavigationError,
RoutesRecognized,
ResolveStart,
ResolveEnd,
GuardsCheckStart,
GuardsCheckEnd,
RouteConfigLoadStart,
RouteConfigLoadEnd,
ChildActivationStart,
ChildActivationEnd,
ActivationStart,
ActivationEnd,
Scroll,
NavigationSkipped,
}
/**
* Base for events the router goes through, as opposed to events tied to a specific
* route. Fired one time for any given navigation.
*
* The following code shows how a class subscribes to router events.
*
* ```ts
* import {Event, RouterEvent, Router} from '@angular/router';
*
* class MyService {
* constructor(public router: Router) {
* router.events.pipe(
* filter((e: Event | RouterEvent): e is RouterEvent => e instanceof RouterEvent)
* ).subscribe((e: RouterEvent) => {
* // Do something
* });
* }
* }
* ```
*
* @see {@link Event}
* @see [Router events summary](guide/routing/router-reference#router-events)
* @publicApi
*/
export class RouterEvent {
constructor(
/** A unique ID that the router assigns to every router navigation. */
public id: number,
/** The URL that is the destination for this navigation. */
public url: string,
) {}
}
/**
* An event triggered when a navigation starts.
*
* @publicApi
*/
export class NavigationStart extends RouterEvent {
readonly type = EventType.NavigationStart;
/**
* Identifies the call or event that triggered the navigation.
* An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`.
*
* @see {@link NavigationEnd}
* @see {@link NavigationCancel}
* @see {@link NavigationError}
*/
navigationTrigger?: NavigationTrigger;
/**
* The navigation state that was previously supplied to the `pushState` call,
* when the navigation is triggered by a `popstate` event. Otherwise null.
*
* The state object is defined by `NavigationExtras`, and contains any
* developer-defined state value, as well as a unique ID that
* the router assigns to every router transition/navigation.
*
* From the perspective of the router, the router never "goes back".
* When the user clicks on the back button in the browser,
* a new navigation ID is created.
*
* Use the ID in this previous-state object to differentiate between a newly created
* state and one returned to by a `popstate` event, so that you can restore some
* remembered state, such as scroll position.
*
*/
restoredState?: {[k: string]: any; navigationId: number} | null;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
navigationTrigger: NavigationTrigger = 'imperative',
/** @docsNotRequired */
restoredState: {[k: string]: any; navigationId: number} | null = null,
) {
super(id, url);
this.navigationTrigger = navigationTrigger;
this.restoredState = restoredState;
}
/** @docsNotRequired */
override toString(): string {
return `NavigationStart(id: ${this.id}, url: '${this.url}')`;
}
}
/**
* An event triggered when a navigation ends successfully.
*
* @see {@link NavigationStart}
* @see {@link NavigationCancel}
* @see {@link NavigationError}
*
* @publicApi
*/
export class NavigationEnd extends RouterEvent {
readonly type = EventType.NavigationEnd;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
public urlAfterRedirects: string,
) {
super(id, url);
}
/** @docsNotRequired */
override toString(): string {
return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`;
}
}
/**
* A code for the `NavigationCancel` event of the `Router` to indicate the
* reason a navigation failed.
*
* @publicApi
*/
export enum NavigationCancellationCode {
/**
* A navigation failed because a guard returned a `UrlTree` to redirect.
*/
Redirect,
/**
* A navigation failed because a more recent navigation started.
*/
SupersededByNewNavigation,
/**
* A navigation failed because one of the resolvers completed without emitting a value.
*/
NoDataFromResolver,
/**
* A navigation failed because a guard returned `false`.
*/
GuardRejected,
}
/**
* A code for the `NavigationSkipped` event of the `Router` to indicate the
* reason a navigation was skipped.
*
* @publicApi
*/
export enum NavigationSkippedCode {
/**
* A navigation was skipped because the navigation URL was the same as the current Router URL.
*/
IgnoredSameUrlNavigation,
/**
* A navigation was skipped because the configured `UrlHandlingStrategy` return `false` for both
* the current Router URL and the target of the navigation.
*
* @see {@link UrlHandlingStrategy}
*/
IgnoredByUrlHandlingStrategy,
}
/**
* An event triggered when a navigation is canceled, directly or indirectly.
* This can happen for several reasons including when a route guard
* returns `false` or initiates a redirect by returning a `UrlTree`.
*
* @see {@link NavigationStart}
* @see {@link NavigationEnd}
* @see {@link NavigationError}
*
* @publicApi
*/
export class NavigationCancel extends RouterEvent {
readonly type = EventType.NavigationCancel;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/**
* A description of why the navigation was cancelled. For debug purposes only. Use `code`
* instead for a stable cancellation reason that can be used in production.
*/
public reason: string,
/**
* A code to indicate why the navigation was canceled. This cancellation code is stable for
* the reason and can be relied on whereas the `reason` string could change and should not be
* used in production.
*/
readonly code?: NavigationCancellationCode,
) {
super(id, url);
}
/** @docsNotRequired */
override toString(): string {
return `NavigationCancel(id: ${this.id}, url: '${this.url}')`;
}
}
/**
* An event triggered when a navigation is skipped.
* This can happen for a couple reasons including onSameUrlHandling
* is set to `ignore` and the navigation URL is not different than the
* current state.
*
* @publicApi
*/
export class NavigationSkipped extends RouterEvent {
readonly type = EventType.NavigationSkipped;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/**
* A description of why the navigation was skipped. For debug purposes only. Use `code`
* instead for a stable skipped reason that can be used in production.
*/
public reason: string,
/**
* A code to indicate why the navigation was skipped. This code is stable for
* the reason and can be relied on whereas the `reason` string could change and should not be
* used in production.
*/
readonly code?: NavigationSkippedCode,
) {
super(id, url);
}
}
/**
* An event triggered when a navigation fails due to an unexpected error.
*
* @see {@link NavigationStart}
* @see {@link NavigationEnd}
* @see {@link NavigationCancel}
*
* @publicApi
*/
| |
014268
|
/**
* Router events that allow you to track the lifecycle of the router.
*
* The events occur in the following sequence:
*
* * [NavigationStart](api/router/NavigationStart): Navigation starts.
* * [RouteConfigLoadStart](api/router/RouteConfigLoadStart): Before
* the router [lazy loads](guide/routing/common-router-tasks#lazy-loading) a route configuration.
* * [RouteConfigLoadEnd](api/router/RouteConfigLoadEnd): After a route has been lazy loaded.
* * [RoutesRecognized](api/router/RoutesRecognized): When the router parses the URL
* and the routes are recognized.
* * [GuardsCheckStart](api/router/GuardsCheckStart): When the router begins the *guards*
* phase of routing.
* * [ChildActivationStart](api/router/ChildActivationStart): When the router
* begins activating a route's children.
* * [ActivationStart](api/router/ActivationStart): When the router begins activating a route.
* * [GuardsCheckEnd](api/router/GuardsCheckEnd): When the router finishes the *guards*
* phase of routing successfully.
* * [ResolveStart](api/router/ResolveStart): When the router begins the *resolve*
* phase of routing.
* * [ResolveEnd](api/router/ResolveEnd): When the router finishes the *resolve*
* phase of routing successfully.
* * [ChildActivationEnd](api/router/ChildActivationEnd): When the router finishes
* activating a route's children.
* * [ActivationEnd](api/router/ActivationEnd): When the router finishes activating a route.
* * [NavigationEnd](api/router/NavigationEnd): When navigation ends successfully.
* * [NavigationCancel](api/router/NavigationCancel): When navigation is canceled.
* * [NavigationError](api/router/NavigationError): When navigation fails
* due to an unexpected error.
* * [Scroll](api/router/Scroll): When the user scrolls.
*
* @publicApi
*/
export type Event =
| NavigationStart
| NavigationEnd
| NavigationCancel
| NavigationError
| RoutesRecognized
| GuardsCheckStart
| GuardsCheckEnd
| RouteConfigLoadStart
| RouteConfigLoadEnd
| ChildActivationStart
| ChildActivationEnd
| ActivationStart
| ActivationEnd
| Scroll
| ResolveStart
| ResolveEnd
| NavigationSkipped;
export function stringifyEvent(routerEvent: Event): string {
switch (routerEvent.type) {
case EventType.ActivationEnd:
return `ActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
case EventType.ActivationStart:
return `ActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
case EventType.ChildActivationEnd:
return `ChildActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
case EventType.ChildActivationStart:
return `ChildActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
case EventType.GuardsCheckEnd:
return `GuardsCheckEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state}, shouldActivate: ${routerEvent.shouldActivate})`;
case EventType.GuardsCheckStart:
return `GuardsCheckStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
case EventType.NavigationCancel:
return `NavigationCancel(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
case EventType.NavigationSkipped:
return `NavigationSkipped(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
case EventType.NavigationEnd:
return `NavigationEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}')`;
case EventType.NavigationError:
return `NavigationError(id: ${routerEvent.id}, url: '${routerEvent.url}', error: ${routerEvent.error})`;
case EventType.NavigationStart:
return `NavigationStart(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
case EventType.ResolveEnd:
return `ResolveEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
case EventType.ResolveStart:
return `ResolveStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
case EventType.RouteConfigLoadEnd:
return `RouteConfigLoadEnd(path: ${routerEvent.route.path})`;
case EventType.RouteConfigLoadStart:
return `RouteConfigLoadStart(path: ${routerEvent.route.path})`;
case EventType.RoutesRecognized:
return `RoutesRecognized(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
case EventType.Scroll:
const pos = routerEvent.position
? `${routerEvent.position[0]}, ${routerEvent.position[1]}`
: null;
return `Scroll(anchor: '${routerEvent.anchor}', position: '${pos}')`;
}
}
| |
014271
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
EnvironmentInjector,
EnvironmentProviders,
NgModuleFactory,
Provider,
ProviderToken,
Type,
} from '@angular/core';
import {Observable} from 'rxjs';
import {ActivatedRouteSnapshot, RouterStateSnapshot} from './router_state';
import {UrlSegment, UrlSegmentGroup, UrlTree} from './url_tree';
/**
* How to handle a navigation request to the current URL. One of:
*
* - `'ignore'` : The router ignores the request it is the same as the current state.
* - `'reload'` : The router processes the URL even if it is not different from the current state.
* One example of when you might want this option is if a `canMatch` guard depends on
* application state and initially rejects navigation to a route. After fixing the state, you want
* to re-navigate to the same URL so the route with the `canMatch` guard can activate.
*
* Note that this only configures whether the Route reprocesses the URL and triggers related
* action and events like redirects, guards, and resolvers. By default, the router re-uses a
* component instance when it re-navigates to the same component type without visiting a different
* component first. This behavior is configured by the `RouteReuseStrategy`. In order to reload
* routed components on same url navigation, you need to set `onSameUrlNavigation` to `'reload'`
* _and_ provide a `RouteReuseStrategy` which returns `false` for `shouldReuseRoute`. Additionally,
* resolvers and most guards for routes do not run unless the path or path params changed
* (configured by `runGuardsAndResolvers`).
*
* @publicApi
* @see {@link RouteReuseStrategy}
* @see {@link RunGuardsAndResolvers}
* @see {@link NavigationBehaviorOptions}
* @see {@link RouterConfigOptions}
*/
export type OnSameUrlNavigation = 'reload' | 'ignore';
/**
* The `InjectionToken` and `@Injectable` classes for guards and resolvers are deprecated in favor
* of plain JavaScript functions instead.. Dependency injection can still be achieved using the
* [`inject`](api/core/inject) function from `@angular/core` and an injectable class can be used as
* a functional guard using [`inject`](api/core/inject): `canActivate: [() =>
* inject(myGuard).canActivate()]`.
*
* @deprecated
* @see {@link CanMatchFn}
* @see {@link CanLoadFn}
* @see {@link CanActivateFn}
* @see {@link CanActivateChildFn}
* @see {@link CanDeactivateFn}
* @see {@link ResolveFn}
* @see {@link core/inject}
* @publicApi
*/
export type DeprecatedGuard = ProviderToken<any> | any;
/**
* The supported types that can be returned from a `Router` guard.
*
* @see [Routing guide](guide/routing/common-router-tasks#preventing-unauthorized-access)
* @publicApi
*/
export type GuardResult = boolean | UrlTree | RedirectCommand;
/**
* Can be returned by a `Router` guard to instruct the `Router` to redirect rather than continue
* processing the path of the in-flight navigation. The `redirectTo` indicates _where_ the new
* navigation should go to and the optional `navigationBehaviorOptions` can provide more information
* about _how_ to perform the navigation.
*
* ```ts
* const route: Route = {
* path: "user/:userId",
* component: User,
* canActivate: [
* () => {
* const router = inject(Router);
* const authService = inject(AuthenticationService);
*
* if (!authService.isLoggedIn()) {
* const loginPath = router.parseUrl("/login");
* return new RedirectCommand(loginPath, {
* skipLocationChange: "true",
* });
* }
*
* return true;
* },
* ],
* };
* ```
* @see [Routing guide](guide/routing/common-router-tasks#preventing-unauthorized-access)
*
* @publicApi
*/
export class RedirectCommand {
constructor(
readonly redirectTo: UrlTree,
readonly navigationBehaviorOptions?: NavigationBehaviorOptions,
) {}
}
/**
* Type used to represent a value which may be synchronous or async.
*
* @publicApi
*/
export type MaybeAsync<T> = T | Observable<T> | Promise<T>;
/**
* Represents a route configuration for the Router service.
* An array of `Route` objects, used in `Router.config` and for nested route configurations
* in `Route.children`.
*
* @see {@link Route}
* @see {@link Router}
* @see [Router configuration guide](guide/routing/router-reference#configuration)
* @publicApi
*/
export type Routes = Route[];
/**
* Represents the result of matching URLs with a custom matching function.
*
* * `consumed` is an array of the consumed URL segments.
* * `posParams` is a map of positional parameters.
*
* @see {@link UrlMatcher}
* @publicApi
*/
export type UrlMatchResult = {
consumed: UrlSegment[];
posParams?: {[name: string]: UrlSegment};
};
/**
* A function for matching a route against URLs. Implement a custom URL matcher
* for `Route.matcher` when a combination of `path` and `pathMatch`
* is not expressive enough. Cannot be used together with `path` and `pathMatch`.
*
* The function takes the following arguments and returns a `UrlMatchResult` object.
* * *segments* : An array of URL segments.
* * *group* : A segment group.
* * *route* : The route to match against.
*
* The following example implementation matches HTML files.
*
* ```
* export function htmlFiles(url: UrlSegment[]) {
* return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null;
* }
*
* export const routes = [{ matcher: htmlFiles, component: AnyComponent }];
* ```
*
* @publicApi
*/
export type UrlMatcher = (
segments: UrlSegment[],
group: UrlSegmentGroup,
route: Route,
) => UrlMatchResult | null;
/**
*
* Represents static data associated with a particular route.
*
* @see {@link Route#data}
*
* @publicApi
*/
export type Data = {
[key: string | symbol]: any;
};
/**
*
* Represents the resolved data associated with a particular route.
*
* Returning a `RedirectCommand` directs the router to cancel the current navigation and redirect to
* the location provided in the `RedirectCommand`. Note that there are no ordering guarantees when
* resolvers execute. If multiple resolvers would return a `RedirectCommand`, only the first one
* returned will be used.
*
* @see {@link Route#resolve}
*
* @publicApi
*/
export type ResolveData = {
[key: string | symbol]: ResolveFn<unknown> | DeprecatedGuard;
};
/**
* An ES Module object with a default export of the given type.
*
* @see {@link Route#loadComponent}
* @see {@link LoadChildrenCallback}
*
* @publicApi
*/
export interface DefaultExport<T> {
/**
* Default exports are bound under the name `"default"`, per the ES Module spec:
* https://tc39.es/ecma262/#table-export-forms-mapping-to-exportentry-records
*/
default: T;
}
/**
*
* A function that is called to resolve a collection of lazy-loaded routes.
* Must be an arrow function of the following form:
* `() => import('...').then(mod => mod.MODULE)`
* or
* `() => import('...').then(mod => mod.ROUTES)`
*
* For example:
*
* ```
* [{
* path: 'lazy',
* loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule),
* }];
* ```
* or
* ```
* [{
* path: 'lazy',
* loadChildren: () => import('./lazy-route/lazy.routes').then(mod => mod.ROUTES),
* }];
* ```
*
* If the lazy-loaded routes are exported via a `default` export, the `.then` can be omitted:
* ```
* [{
* path: 'lazy',
* loadChildren: () => import('./lazy-route/lazy.routes'),
* }];
* ```
*
* @see {@link Route#loadChildren}
* @publicApi
*/
export type LoadChildrenCallback = () =>
| Type<any>
| NgModuleFactory<any>
| Routes
| Observable<Type<any> | Routes | DefaultExport<Type<any>> | DefaultExport<Routes>>
| Promise<
NgModuleFactory<any> | Type<any> | Routes | DefaultExport<Type<any>> | DefaultExport<Routes>
>;
/**
*
* A function that returns a set of routes to load.
*
* @see {@link LoadChildrenCallback}
* @publicApi
*/
export type LoadChildren = LoadChildrenCallback;
| |
014273
|
/**
* A configuration object that defines a single route.
* A set of routes are collected in a `Routes` array to define a `Router` configuration.
* The router attempts to match segments of a given URL against each route,
* using the configuration options defined in this object.
*
* Supports static, parameterized, redirect, and wildcard routes, as well as
* custom route data and resolve methods.
*
* For detailed usage information, see the [Routing Guide](guide/routing/common-router-tasks).
*
* @usageNotes
*
* ### Simple Configuration
*
* The following route specifies that when navigating to, for example,
* `/team/11/user/bob`, the router creates the 'Team' component
* with the 'User' child component in it.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* ### Multiple Outlets
*
* The following route creates sibling components with multiple outlets.
* When navigating to `/team/11(aux:chat/jim)`, the router creates the 'Team' component next to
* the 'Chat' component. The 'Chat' component is placed into the 'aux' outlet.
*
* ```
* [{
* path: 'team/:id',
* component: Team
* }, {
* path: 'chat/:user',
* component: Chat
* outlet: 'aux'
* }]
* ```
*
* ### Wild Cards
*
* The following route uses wild-card notation to specify a component
* that is always instantiated regardless of where you navigate to.
*
* ```
* [{
* path: '**',
* component: WildcardComponent
* }]
* ```
*
* ### Redirects
*
* The following route uses the `redirectTo` property to ignore a segment of
* a given URL when looking for a child path.
*
* When navigating to '/team/11/legacy/user/jim', the router changes the URL segment
* '/team/11/legacy/user/jim' to '/team/11/user/jim', and then instantiates
* the Team component with the User child component in it.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: 'legacy/user/:name',
* redirectTo: 'user/:name'
* }, {
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* The redirect path can be relative, as shown in this example, or absolute.
* If we change the `redirectTo` value in the example to the absolute URL segment '/user/:name',
* the result URL is also absolute, '/user/jim'.
* ### Empty Path
*
* Empty-path route configurations can be used to instantiate components that do not 'consume'
* any URL segments.
*
* In the following configuration, when navigating to
* `/team/11`, the router instantiates the 'AllUsers' component.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: '',
* component: AllUsers
* }, {
* path: 'user/:name',
* component: User
* }]
* }]
* ```
*
* Empty-path routes can have children. In the following example, when navigating
* to `/team/11/user/jim`, the router instantiates the wrapper component with
* the user component in it.
*
* Note that an empty path route inherits its parent's parameters and data.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* children: [{
* path: '',
* component: WrapperCmp,
* children: [{
* path: 'user/:name',
* component: User
* }]
* }]
* }]
* ```
*
* ### Matching Strategy
*
* The default path-match strategy is 'prefix', which means that the router
* checks URL elements from the left to see if the URL matches a specified path.
* For example, '/team/11/user' matches 'team/:id'.
*
* ```
* [{
* path: '',
* pathMatch: 'prefix', //default
* redirectTo: 'main'
* }, {
* path: 'main',
* component: Main
* }]
* ```
*
* You can specify the path-match strategy 'full' to make sure that the path
* covers the whole unconsumed URL. It is important to do this when redirecting
* empty-path routes. Otherwise, because an empty path is a prefix of any URL,
* the router would apply the redirect even when navigating to the redirect destination,
* creating an endless loop.
*
* In the following example, supplying the 'full' `pathMatch` strategy ensures
* that the router applies the redirect if and only if navigating to '/'.
*
* ```
* [{
* path: '',
* pathMatch: 'full',
* redirectTo: 'main'
* }, {
* path: 'main',
* component: Main
* }]
* ```
*
* ### Componentless Routes
*
* You can share parameters between sibling components.
* For example, suppose that two sibling components should go next to each other,
* and both of them require an ID parameter. You can accomplish this using a route
* that does not specify a component at the top level.
*
* In the following example, 'MainChild' and 'AuxChild' are siblings.
* When navigating to 'parent/10/(a//aux:b)', the route instantiates
* the main child and aux child components next to each other.
* For this to work, the application component must have the primary and aux outlets defined.
*
* ```
* [{
* path: 'parent/:id',
* children: [
* { path: 'a', component: MainChild },
* { path: 'b', component: AuxChild, outlet: 'aux' }
* ]
* }]
* ```
*
* The router merges the parameters, data, and resolve of the componentless
* parent into the parameters, data, and resolve of the children.
*
* This is especially useful when child components are defined
* with an empty path string, as in the following example.
* With this configuration, navigating to '/parent/10' creates
* the main child and aux components.
*
* ```
* [{
* path: 'parent/:id',
* children: [
* { path: '', component: MainChild },
* { path: '', component: AuxChild, outlet: 'aux' }
* ]
* }]
* ```
*
* ### Lazy Loading
*
* Lazy loading speeds up application load time by splitting the application
* into multiple bundles and loading them on demand.
* To use lazy loading, provide the `loadChildren` property in the `Route` object,
* instead of the `children` property.
*
* Given the following example route, the router will lazy load
* the associated module on demand using the browser native import system.
*
* ```
* [{
* path: 'lazy',
* loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule),
* }];
* ```
*
* @publicApi
*/
| |
014274
|
export interface Route {
/**
* Used to define a page title for the route. This can be a static string or an `Injectable` that
* implements `Resolve`.
*
* @see {@link TitleStrategy}
*/
title?: string | Type<Resolve<string>> | ResolveFn<string>;
/**
* The path to match against. Cannot be used together with a custom `matcher` function.
* A URL string that uses router matching notation.
* Can be a wild card (`**`) that matches any URL (see Usage Notes below).
* Default is "/" (the root path).
*
*/
path?: string;
/**
* The path-matching strategy, one of 'prefix' or 'full'.
* Default is 'prefix'.
*
* By default, the router checks URL elements from the left to see if the URL
* matches a given path and stops when there is a config match. Importantly there must still be a
* config match for each segment of the URL. For example, '/team/11/user' matches the prefix
* 'team/:id' if one of the route's children matches the segment 'user'. That is, the URL
* '/team/11/user' matches the config
* `{path: 'team/:id', children: [{path: ':user', component: User}]}`
* but does not match when there are no children as in `{path: 'team/:id', component: Team}`.
*
* The path-match strategy 'full' matches against the entire URL.
* It is important to do this when redirecting empty-path routes.
* Otherwise, because an empty path is a prefix of any URL,
* the router would apply the redirect even when navigating
* to the redirect destination, creating an endless loop.
*
*/
pathMatch?: 'prefix' | 'full';
/**
* A custom URL-matching function. Cannot be used together with `path`.
*/
matcher?: UrlMatcher;
/**
* The component to instantiate when the path matches.
* Can be empty if child routes specify components.
*/
component?: Type<any>;
/**
* An object specifying a lazy-loaded component.
*/
loadComponent?: () =>
| Type<unknown>
| Observable<Type<unknown> | DefaultExport<Type<unknown>>>
| Promise<Type<unknown> | DefaultExport<Type<unknown>>>;
/**
* Filled for routes `loadComponent` once the component is loaded.
* @internal
*/
_loadedComponent?: Type<unknown>;
/**
* A URL or function that returns a URL to redirect to when the path matches.
*
* Absolute if the URL begins with a slash (/) or the function returns a `UrlTree`, otherwise
* relative to the path URL.
*
* The `RedirectFunction` is run in an injection context so it can call `inject` to get any
* required dependencies.
*
* When not present, router does not redirect.
*/
redirectTo?: string | RedirectFunction;
/**
* Name of a `RouterOutlet` object where the component can be placed
* when the path matches.
*/
outlet?: string;
/**
* An array of `CanActivateFn` or DI tokens used to look up `CanActivate()`
* handlers, in order to determine if the current user is allowed to
* activate the component. By default, any user can activate.
*
* When using a function rather than DI tokens, the function can call `inject` to get any required
* dependencies. This `inject` call must be done in a synchronous context.
*/
canActivate?: Array<CanActivateFn | DeprecatedGuard>;
/**
* An array of `CanMatchFn` or DI tokens used to look up `CanMatch()`
* handlers, in order to determine if the current user is allowed to
* match the `Route`. By default, any route can match.
*
* When using a function rather than DI tokens, the function can call `inject` to get any required
* dependencies. This `inject` call must be done in a synchronous context.
*/
canMatch?: Array<CanMatchFn | DeprecatedGuard>;
/**
* An array of `CanActivateChildFn` or DI tokens used to look up `CanActivateChild()` handlers,
* in order to determine if the current user is allowed to activate
* a child of the component. By default, any user can activate a child.
*
* When using a function rather than DI tokens, the function can call `inject` to get any required
* dependencies. This `inject` call must be done in a synchronous context.
*/
canActivateChild?: Array<CanActivateChildFn | DeprecatedGuard>;
/**
* An array of `CanDeactivateFn` or DI tokens used to look up `CanDeactivate()`
* handlers, in order to determine if the current user is allowed to
* deactivate the component. By default, any user can deactivate.
*
* When using a function rather than DI tokens, the function can call `inject` to get any required
* dependencies. This `inject` call must be done in a synchronous context.
*/
canDeactivate?: Array<CanDeactivateFn<any> | DeprecatedGuard>;
/**
* An array of `CanLoadFn` or DI tokens used to look up `CanLoad()`
* handlers, in order to determine if the current user is allowed to
* load the component. By default, any user can load.
*
* When using a function rather than DI tokens, the function can call `inject` to get any required
* dependencies. This `inject` call must be done in a synchronous context.
* @deprecated Use `canMatch` instead
*/
canLoad?: Array<CanLoadFn | DeprecatedGuard>;
/**
* Additional developer-defined data provided to the component via
* `ActivatedRoute`. By default, no additional data is passed.
*/
data?: Data;
/**
* A map of DI tokens used to look up data resolvers. See `Resolve`.
*/
resolve?: ResolveData;
/**
* An array of child `Route` objects that specifies a nested route
* configuration.
*/
children?: Routes;
/**
* An object specifying lazy-loaded child routes.
*/
loadChildren?: LoadChildren;
/**
* A policy for when to run guards and resolvers on a route.
*
* Guards and/or resolvers will always run when a route is activated or deactivated. When a route
* is unchanged, the default behavior is the same as `paramsChange`.
*
* `paramsChange` : Rerun the guards and resolvers when path or
* path param changes. This does not include query parameters. This option is the default.
* - `always` : Run on every execution.
* - `pathParamsChange` : Rerun guards and resolvers when the path params
* change. This does not compare matrix or query parameters.
* - `paramsOrQueryParamsChange` : Run when path, matrix, or query parameters change.
* - `pathParamsOrQueryParamsChange` : Rerun guards and resolvers when the path params
* change or query params have changed. This does not include matrix parameters.
*
* @see {@link RunGuardsAndResolvers}
*/
runGuardsAndResolvers?: RunGuardsAndResolvers;
/**
* A `Provider` array to use for this `Route` and its `children`.
*
* The `Router` will create a new `EnvironmentInjector` for this
* `Route` and use it for this `Route` and its `children`. If this
* route also has a `loadChildren` function which returns an `NgModuleRef`, this injector will be
* used as the parent of the lazy loaded module.
*/
providers?: Array<Provider | EnvironmentProviders>;
/**
* Injector created from the static route providers
* @internal
*/
_injector?: EnvironmentInjector;
/**
* Filled for routes with `loadChildren` once the routes are loaded.
* @internal
*/
_loadedRoutes?: Route[];
/**
* Filled for routes with `loadChildren` once the routes are loaded
* @internal
*/
_loadedInjector?: EnvironmentInjector;
}
export interface LoadedRouterConfig {
routes: Route[];
injector: EnvironmentInjector | undefined;
}
| |
014275
|
/**
* @description
*
* Interface that a class can implement to be a guard deciding if a route can be activated.
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, the current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements a `CanActivate` function that checks whether the
* current user has permission to activate the requested route.
*
* ```
* class UserToken {}
* class Permissions {
* canActivate(): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanActivateTeam implements CanActivate {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canActivate(
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot
* ): MaybeAsync<GuardResult> {
* return this.permissions.canActivate(this.currentUser, route.params.id);
* }
* }
* ```
*
* Here, the defined guard function is provided as part of the `Route` object
* in the router configuration:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamComponent,
* canActivate: [CanActivateTeam]
* }
* ])
* ],
* providers: [CanActivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* @publicApi
*/
export interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): MaybeAsync<GuardResult>;
}
/**
* The signature of a function used as a `canActivate` guard on a `Route`.
*
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, the current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements and uses a `CanActivateFn` that checks whether the
* current user has permission to activate the requested route.
*
* ```ts
* @Injectable()
* class UserToken {}
*
* @Injectable()
* class PermissionsService {
* canActivate(currentUser: UserToken, userId: string): boolean {
* return true;
* }
* canMatch(currentUser: UserToken): boolean {
* return true;
* }
* }
*
* const canActivateTeam: CanActivateFn = (
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot,
* ) => {
* return inject(PermissionsService).canActivate(inject(UserToken), route.params['id']);
* };
* ```
*
* Here, the defined guard function is provided as part of the `Route` object
* in the router configuration:
*
* ```ts
* bootstrapApplication(App, {
* providers: [
* provideRouter([
* {
* path: 'team/:id',
* component: TeamComponent,
* canActivate: [canActivateTeam],
* },
* ]),
* ],
* });
* ```
*
* @publicApi
* @see {@link Route}
*/
export type CanActivateFn = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
) => MaybeAsync<GuardResult>;
/**
* @description
*
* Interface that a class can implement to be a guard deciding if a child route can be activated.
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements a `CanActivateChild` function that checks whether the
* current user has permission to activate the requested child route.
*
* ```
* class UserToken {}
* class Permissions {
* canActivate(user: UserToken, id: string): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanActivateTeam implements CanActivateChild {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canActivateChild(
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot
* ): MaybeAsync<GuardResult> {
* return this.permissions.canActivate(this.currentUser, route.params.id);
* }
* }
* ```
*
* Here, the defined guard function is provided as part of the `Route` object
* in the router configuration:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'root',
* canActivateChild: [CanActivateTeam],
* children: [
* {
* path: 'team/:id',
* component: TeamComponent
* }
* ]
* }
* ])
* ],
* providers: [CanActivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* @publicApi
*/
export interface CanActivateChild {
canActivateChild(
childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): MaybeAsync<GuardResult>;
}
/**
* The signature of a function used as a `canActivateChild` guard on a `Route`.
*
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, the current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements a `canActivate` function that checks whether the
* current user has permission to activate the requested route.
*
* {@example router/route_functional_guards.ts region="CanActivateChildFn"}
*
* @publicApi
* @see {@link Route}
*/
export type CanActivateChildFn = (
childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
) => MaybeAsync<GuardResult>;
/**
* @description
*
* Interface that a class can implement to be a guard deciding if a route can be deactivated.
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements a `CanDeactivate` function that checks whether the
* current user has permission to deactivate the requested route.
*
* ```
* class UserToken {}
* class Permissions {
* canDeactivate(user: UserToken, id: string): boolean {
* return true;
* }
* }
* ```
*
* Here, the defined guard function is provided as part of the `Route` object
* in the router configuration:
*
* ```
*
* @Injectable()
* class CanDeactivateTeam implements CanDeactivate<TeamComponent> {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canDeactivate(
* component: TeamComponent,
* currentRoute: ActivatedRouteSnapshot,
* currentState: RouterStateSnapshot,
* nextState: RouterStateSnapshot
* ): MaybeAsync<GuardResult> {
* return this.permissions.canDeactivate(this.currentUser, route.params.id);
* }
* }
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamComponent,
* canDeactivate: [CanDeactivateTeam]
* }
* ])
* ],
* providers: [CanDeactivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* @publicApi
*/
export interface CanDeactivate<T> {
canDeactivate(
component: T,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot,
): MaybeAsync<GuardResult>;
}
/**
* The signature of a function used as a `canDeactivate` guard on a `Route`.
*
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, the current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements and uses a `CanDeactivateFn` that checks whether the
* user component has unsaved changes before navigating away from the route.
*
* {@example router/route_functional_guards.ts region="CanDeactivateFn"}
*
* @publicApi
* @see {@link Route}
*/
export type CanDeactivateFn<T> = (
component: T,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot,
) => MaybeAsync<GuardResult>;
| |
014280
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
HashLocationStrategy,
Location,
LocationStrategy,
PathLocationStrategy,
ViewportScroller,
} from '@angular/common';
import {
APP_BOOTSTRAP_LISTENER,
ComponentRef,
inject,
Inject,
InjectionToken,
ModuleWithProviders,
NgModule,
NgZone,
Optional,
Provider,
SkipSelf,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {EmptyOutletComponent} from './components/empty_outlet';
import {RouterLink} from './directives/router_link';
import {RouterLinkActive} from './directives/router_link_active';
import {RouterOutlet} from './directives/router_outlet';
import {RuntimeErrorCode} from './errors';
import {Routes} from './models';
import {NAVIGATION_ERROR_HANDLER, NavigationTransitions} from './navigation_transition';
import {
getBootstrapListener,
rootRoute,
ROUTER_IS_PROVIDED,
withComponentInputBinding,
withDebugTracing,
withDisabledInitialNavigation,
withEnabledBlockingInitialNavigation,
withPreloading,
withViewTransitions,
} from './provide_router';
import {Router} from './router';
import {ExtraOptions, ROUTER_CONFIGURATION} from './router_config';
import {RouterConfigLoader, ROUTES} from './router_config_loader';
import {ChildrenOutletContexts} from './router_outlet_context';
import {ROUTER_SCROLLER, RouterScroller} from './router_scroller';
import {ActivatedRoute} from './router_state';
import {DefaultUrlSerializer, UrlSerializer} from './url_tree';
/**
* The directives defined in the `RouterModule`.
*/
const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkActive, EmptyOutletComponent];
/**
* @docsNotRequired
*/
export const ROUTER_FORROOT_GUARD = new InjectionToken<void>(
typeof ngDevMode === 'undefined' || ngDevMode
? 'router duplicate forRoot guard'
: 'ROUTER_FORROOT_GUARD',
);
// TODO(atscott): All of these except `ActivatedRoute` are `providedIn: 'root'`. They are only kept
// here to avoid a breaking change whereby the provider order matters based on where the
// `RouterModule`/`RouterTestingModule` is imported. These can/should be removed as a "breaking"
// change in a major version.
export const ROUTER_PROVIDERS: Provider[] = [
Location,
{provide: UrlSerializer, useClass: DefaultUrlSerializer},
Router,
ChildrenOutletContexts,
{provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]},
RouterConfigLoader,
// Only used to warn when `provideRoutes` is used without `RouterModule` or `provideRouter`. Can
// be removed when `provideRoutes` is removed.
typeof ngDevMode === 'undefined' || ngDevMode
? {provide: ROUTER_IS_PROVIDED, useValue: true}
: [],
];
/**
* @description
*
* Adds directives and providers for in-app navigation among views defined in an application.
* Use the Angular `Router` service to declaratively specify application states and manage state
* transitions.
*
* You can import this NgModule multiple times, once for each lazy-loaded bundle.
* However, only one `Router` service can be active.
* To ensure this, there are two ways to register routes when importing this module:
*
* * The `forRoot()` method creates an `NgModule` that contains all the directives, the given
* routes, and the `Router` service itself.
* * The `forChild()` method creates an `NgModule` that contains all the directives and the given
* routes, but does not include the `Router` service.
*
* @see [Routing and Navigation guide](guide/routing/common-router-tasks) for an
* overview of how the `Router` service should be used.
*
* @publicApi
*/
@NgModule({
imports: ROUTER_DIRECTIVES,
exports: ROUTER_DIRECTIVES,
})
export class RouterModule {
constructor(@Optional() @Inject(ROUTER_FORROOT_GUARD) guard: any) {}
/**
* Creates and configures a module with all the router providers and directives.
* Optionally sets up an application listener to perform an initial navigation.
*
* When registering the NgModule at the root, import as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @param routes An array of `Route` objects that define the navigation paths for the application.
* @param config An `ExtraOptions` configuration object that controls how navigation is performed.
* @return The new `NgModule`.
*
*/
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule> {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
typeof ngDevMode === 'undefined' || ngDevMode
? config?.enableTracing
? withDebugTracing().ɵproviders
: []
: [],
{provide: ROUTES, multi: true, useValue: routes},
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new Optional(), new SkipSelf()]],
},
config?.errorHandler
? {
provide: NAVIGATION_ERROR_HANDLER,
useValue: config.errorHandler,
}
: [],
{provide: ROUTER_CONFIGURATION, useValue: config ? config : {}},
config?.useHash ? provideHashLocationStrategy() : providePathLocationStrategy(),
provideRouterScroller(),
config?.preloadingStrategy ? withPreloading(config.preloadingStrategy).ɵproviders : [],
config?.initialNavigation ? provideInitialNavigation(config) : [],
config?.bindToComponentInputs ? withComponentInputBinding().ɵproviders : [],
config?.enableViewTransitions ? withViewTransitions().ɵproviders : [],
provideRouterInitializer(),
],
};
}
/**
* Creates a module with all the router directives and a provider registering routes,
* without creating a new Router service.
* When registering for submodules and lazy-loaded submodules, create the NgModule as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @param routes An array of `Route` objects that define the navigation paths for the submodule.
* @return The new NgModule.
*
*/
static forChild(routes: Routes): ModuleWithProviders<RouterModule> {
return {
ngModule: RouterModule,
providers: [{provide: ROUTES, multi: true, useValue: routes}],
};
}
}
/**
* For internal use by `RouterModule` only. Note that this differs from `withInMemoryRouterScroller`
* because it reads from the `ExtraOptions` which should not be used in the standalone world.
*/
export function provideRouterScroller(): Provider {
return {
provide: ROUTER_SCROLLER,
useFactory: () => {
const viewportScroller = inject(ViewportScroller);
const zone = inject(NgZone);
const config: ExtraOptions = inject(ROUTER_CONFIGURATION);
const transitions = inject(NavigationTransitions);
const urlSerializer = inject(UrlSerializer);
if (config.scrollOffset) {
viewportScroller.setOffset(config.scrollOffset);
}
return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, config);
},
};
}
// Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` should
// provide hash location directly via `{provide: LocationStrategy, useClass: HashLocationStrategy}`.
function provideHashLocationStrategy(): Provider {
return {provide: LocationStrategy, useClass: HashLocationStrategy};
}
// Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` does not
// need this at all because `PathLocationStrategy` is the default factory for `LocationStrategy`.
function providePathLocationStrategy(): Provider {
return {provide: LocationStrategy, useClass: PathLocationStrategy};
}
export function provideForRootGuard(router: Router): any {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && router) {
throw new RuntimeError(
RuntimeErrorCode.FOR_ROOT_CALLED_TWICE,
`The Router was provided more than once. This can happen if 'forRoot' is used outside of the root injector.` +
` Lazy loaded modules should use RouterModule.forChild() instead.`,
);
}
return 'guarded';
}
// Note: For internal use only with `RouterModule`. Standalone router setup with `provideRouter`
// users call `withXInitialNavigation` directly.
function provideInitialNavigation(config: Pick<ExtraOptions, 'initialNavigation'>): Provider[] {
return [
config.initialNavigation === 'disabled' ? withDisabledInitialNavigation().ɵproviders : [],
config.initialNavigation === 'enabledBlocking'
? withEnabledBlockingInitialNavigation().ɵproviders
: [],
];
}
// TO
| |
014296
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {EnvironmentInjector, ProviderToken, runInInjectionContext} from '@angular/core';
import {
concat,
defer,
from,
MonoTypeOperatorFunction,
Observable,
of,
OperatorFunction,
pipe,
} from 'rxjs';
import {concatMap, first, map, mergeMap, tap} from 'rxjs/operators';
import {ActivationStart, ChildActivationStart, Event} from '../events';
import {
CanActivateChildFn,
CanActivateFn,
CanDeactivateFn,
GuardResult,
CanLoadFn,
CanMatchFn,
Route,
} from '../models';
import {navigationCancelingError, redirectingNavigationError} from '../navigation_canceling_error';
import {NavigationTransition} from '../navigation_transition';
import {ActivatedRouteSnapshot, RouterStateSnapshot} from '../router_state';
import {isUrlTree, UrlSegment, UrlSerializer, UrlTree} from '../url_tree';
import {wrapIntoObservable} from '../utils/collection';
import {getClosestRouteInjector} from '../utils/config';
import {
CanActivate,
CanDeactivate,
getCanActivateChild,
getTokenOrFunctionIdentity,
} from '../utils/preactivation';
import {
isBoolean,
isCanActivate,
isCanActivateChild,
isCanDeactivate,
isCanLoad,
isCanMatch,
} from '../utils/type_guards';
import {prioritizedGuardValue} from './prioritized_guard_value';
export function checkGuards(
injector: EnvironmentInjector,
forwardEvent?: (evt: Event) => void,
): MonoTypeOperatorFunction<NavigationTransition> {
return mergeMap((t) => {
const {
targetSnapshot,
currentSnapshot,
guards: {canActivateChecks, canDeactivateChecks},
} = t;
if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) {
return of({...t, guardsResult: true});
}
return runCanDeactivateChecks(
canDeactivateChecks,
targetSnapshot!,
currentSnapshot,
injector,
).pipe(
mergeMap((canDeactivate) => {
return canDeactivate && isBoolean(canDeactivate)
? runCanActivateChecks(targetSnapshot!, canActivateChecks, injector, forwardEvent)
: of(canDeactivate);
}),
map((guardsResult) => ({...t, guardsResult})),
);
});
}
function runCanDeactivateChecks(
checks: CanDeactivate[],
futureRSS: RouterStateSnapshot,
currRSS: RouterStateSnapshot,
injector: EnvironmentInjector,
) {
return from(checks).pipe(
mergeMap((check) =>
runCanDeactivate(check.component, check.route, currRSS, futureRSS, injector),
),
first((result) => {
return result !== true;
}, true),
);
}
function runCanActivateChecks(
futureSnapshot: RouterStateSnapshot,
checks: CanActivate[],
injector: EnvironmentInjector,
forwardEvent?: (evt: Event) => void,
) {
return from(checks).pipe(
concatMap((check: CanActivate) => {
return concat(
fireChildActivationStart(check.route.parent, forwardEvent),
fireActivationStart(check.route, forwardEvent),
runCanActivateChild(futureSnapshot, check.path, injector),
runCanActivate(futureSnapshot, check.route, injector),
);
}),
first((result) => {
return result !== true;
}, true),
);
}
/**
* This should fire off `ActivationStart` events for each route being activated at this
* level.
* In other words, if you're activating `a` and `b` below, `path` will contain the
* `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
* return
* `true` so checks continue to run.
*/
function fireActivationStart(
snapshot: ActivatedRouteSnapshot | null,
forwardEvent?: (evt: Event) => void,
): Observable<boolean> {
if (snapshot !== null && forwardEvent) {
forwardEvent(new ActivationStart(snapshot));
}
return of(true);
}
/**
* This should fire off `ChildActivationStart` events for each route being activated at this
* level.
* In other words, if you're activating `a` and `b` below, `path` will contain the
* `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
* return
* `true` so checks continue to run.
*/
function fireChildActivationStart(
snapshot: ActivatedRouteSnapshot | null,
forwardEvent?: (evt: Event) => void,
): Observable<boolean> {
if (snapshot !== null && forwardEvent) {
forwardEvent(new ChildActivationStart(snapshot));
}
return of(true);
}
function runCanActivate(
futureRSS: RouterStateSnapshot,
futureARS: ActivatedRouteSnapshot,
injector: EnvironmentInjector,
): Observable<GuardResult> {
const canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null;
if (!canActivate || canActivate.length === 0) return of(true);
const canActivateObservables = canActivate.map(
(canActivate: CanActivateFn | ProviderToken<unknown>) => {
return defer(() => {
const closestInjector = getClosestRouteInjector(futureARS) ?? injector;
const guard = getTokenOrFunctionIdentity<CanActivate>(canActivate, closestInjector);
const guardVal = isCanActivate(guard)
? guard.canActivate(futureARS, futureRSS)
: runInInjectionContext(closestInjector, () =>
(guard as CanActivateFn)(futureARS, futureRSS),
);
return wrapIntoObservable(guardVal).pipe(first());
});
},
);
return of(canActivateObservables).pipe(prioritizedGuardValue());
}
function runCanActivateChild(
futureRSS: RouterStateSnapshot,
path: ActivatedRouteSnapshot[],
injector: EnvironmentInjector,
): Observable<GuardResult> {
const futureARS = path[path.length - 1];
const canActivateChildGuards = path
.slice(0, path.length - 1)
.reverse()
.map((p) => getCanActivateChild(p))
.filter((_) => _ !== null);
const canActivateChildGuardsMapped = canActivateChildGuards.map((d: any) => {
return defer(() => {
const guardsMapped = d.guards.map(
(canActivateChild: CanActivateChildFn | ProviderToken<unknown>) => {
const closestInjector = getClosestRouteInjector(d.node) ?? injector;
const guard = getTokenOrFunctionIdentity<{canActivateChild: CanActivateChildFn}>(
canActivateChild,
closestInjector,
);
const guardVal = isCanActivateChild(guard)
? guard.canActivateChild(futureARS, futureRSS)
: runInInjectionContext(closestInjector, () =>
(guard as CanActivateChildFn)(futureARS, futureRSS),
);
return wrapIntoObservable(guardVal).pipe(first());
},
);
return of(guardsMapped).pipe(prioritizedGuardValue());
});
});
return of(canActivateChildGuardsMapped).pipe(prioritizedGuardValue());
}
function runCanDeactivate(
component: Object | null,
currARS: ActivatedRouteSnapshot,
currRSS: RouterStateSnapshot,
futureRSS: RouterStateSnapshot,
injector: EnvironmentInjector,
): Observable<GuardResult> {
const canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null;
if (!canDeactivate || canDeactivate.length === 0) return of(true);
const canDeactivateObservables = canDeactivate.map((c: any) => {
const closestInjector = getClosestRouteInjector(currARS) ?? injector;
const guard = getTokenOrFunctionIdentity<any>(c, closestInjector);
const guardVal = isCanDeactivate(guard)
? guard.canDeactivate(component, currARS, currRSS, futureRSS)
: runInInjectionContext(closestInjector, () =>
(guard as CanDeactivateFn<any>)(component, currARS, currRSS, futureRSS),
);
return wrapIntoObservable(guardVal).pipe(first());
});
return of(canDeactivateObservables).pipe(prioritizedGuardValue());
}
| |
014304
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable} from 'rxjs';
import {filter, map, take} from 'rxjs/operators';
import {
Event,
NavigationCancel,
NavigationCancellationCode,
NavigationEnd,
NavigationError,
NavigationSkipped,
} from '../events';
enum NavigationResult {
COMPLETE,
FAILED,
REDIRECTING,
}
/**
* Performs the given action once the router finishes its next/current navigation.
*
* The navigation is considered complete under the following conditions:
* - `NavigationCancel` event emits and the code is not `NavigationCancellationCode.Redirect` or
* `NavigationCancellationCode.SupersededByNewNavigation`. In these cases, the
* redirecting/superseding navigation must finish.
* - `NavigationError`, `NavigationEnd`, or `NavigationSkipped` event emits
*/
export function afterNextNavigation(router: {events: Observable<Event>}, action: () => void) {
router.events
.pipe(
filter(
(e): e is NavigationEnd | NavigationCancel | NavigationError | NavigationSkipped =>
e instanceof NavigationEnd ||
e instanceof NavigationCancel ||
e instanceof NavigationError ||
e instanceof NavigationSkipped,
),
map((e) => {
if (e instanceof NavigationEnd || e instanceof NavigationSkipped) {
return NavigationResult.COMPLETE;
}
const redirecting =
e instanceof NavigationCancel
? e.code === NavigationCancellationCode.Redirect ||
e.code === NavigationCancellationCode.SupersededByNewNavigation
: false;
return redirecting ? NavigationResult.REDIRECTING : NavigationResult.FAILED;
}),
filter(
(result): result is NavigationResult.COMPLETE | NavigationResult.FAILED =>
result !== NavigationResult.REDIRECTING,
),
take(1),
)
.subscribe(() => {
action();
});
}
| |
014322
|
# Saved Responses for Angular's Issue Tracker
This doc collects canned responses that the Angular team can use to close issues that fall into the
listed resolution categories.
Since GitHub currently doesn't allow us to have a repository-wide or organization-wide list
of [saved replies](https://help.github.com/articles/working-with-saved-replies/), these replies need
to be maintained by individual team members. Since the responses can be modified in the future, all
responses are versioned to simplify the process of keeping the responses up to date.
## Angular: Already Fixed (v3)
```
Thanks for reporting this issue. Luckily it has already been fixed in one of the recent releases. Please update to the most recent version to resolve the problem.
If after upgrade the problem still exists in your application please [open a new issue](https://github.com/angular/angular/issues/new/choose) and follow the instructions in the issue template.
```
## Angular: Don't Understand (v3)
```
I'm sorry but we don't understand the problem you are reporting.
If the problem still exists in your application, please [open a new issue](https://github.com/angular/angular/issues/new/choose) and follow the instructions in the issue template.
```
## Angular: Can't reproduce (v2)
```
I'm sorry but we can't reproduce the problem you are reporting. We require that reported issues have a minimal reproduction that showcases the problem.
If the problem still exists in your application, please [open a new issue](https://github.com/angular/angular/issues/new/choose) and follow the instructions in the issue template that include info on how to create a reproduction using our template.
```
## Angular: Duplicate (v2)
```
Thanks for reporting this issue. However this issue is a duplicate of an existing issue #ISSUE_NUMBER. Please subscribe to that issue for future updates.
```
## Angular: Insufficient Information Provided (v2)
```
Thanks for reporting this issue. However, you didn't provide sufficient information for us to understand and reproduce the problem. Please check out [our submission guidelines](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#submit-issue) to understand why we can't act on issues that are lacking important information.
If the problem still exists in your application, please [open a new issue](https://github.com/angular/angular/issues/new/choose) and follow the instructions in the issue template.
```
## Angular: Issue Outside of Angular (v2)
```
I'm sorry but this issue is not caused by Angular. Please contact the author(s) of project PROJECT_NAME or file issue on their issue tracker.
```
## Angular: Behaving as Expected (v1)
```
It appears this behaves as expected. If you still feel there is an issue, please provide further details in a new issue.
```
## Angular: Non-reproducible (v2)
```
I'm sorry but we can't reproduce the problem following the instructions you provided.
If the problem still exists in your application please [open a new issue](https://github.com/angular/angular/issues/new/choose) and follow the instructions in the issue template.
```
## Angular: Obsolete (v2)
```
Thanks for reporting this issue. This issue is now obsolete due to changes in the recent releases. Please update to the most recent Angular version.
If the problem still exists in your application, please [open a new issue](https://github.com/angular/angular/issues/new/choose) and follow the instructions in the issue template.
```
## Angular: Support Request (v1)
```
Hello, we reviewed this issue and determined that it doesn't fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on [StackOverflow](https://stackoverflow.com/) using tag `angular`.
If you are wondering why we don't resolve support issues via the issue tracker, please [check out this explanation](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#question).
```
## Angular: Commit Header
```
It looks like you need to update your commit header to match our requirements. This is different from the PR title. To update the commit header, use the command `git commit --amend` and update the header there.
Once you've finished that update, you will need to force push using `git push [origin name] [branch name] --force`. That should address this.
```
## Angular: Rebase and Squash
```
Please rebase and squash your commits. To do this, make sure to `git fetch upstream` to get the latest changes from the angular repository. Then in your branch run `git rebase upstream/main -i` to do an interactive rebase. This should allow you to fixup or drop any unnecessary commits. After you finish the rebase, force push using `git push [origin name] [branch name] --force`.
```
| |
014325
|
## Releasing APIs before they're fully stable
The Angular team may occasionally seek to release a feature or API without immediately
including this API in Angular's normal support and deprecation category. You can use
one of two labels on such APIs: Developer Preview and Experimental. APIs tagged this way
are not subject to Angular's breaking change and deprecation policy.
Use the sections below to decide whether a pre-stable tag makes sense.
### Developer Preview
Use "Developer Preview" when:
* The team has relatively high confidence the API will ship as stable.
* The team needs additional community feedback before fully committing to an exact API shape.
* The API may undergo only minor, superficial changes. This can include changes like renaming
or reordering parameters, but should not include significant conceptual or structural changes.
### Experimental
Use "Experimental" when:
* The team has low-to-medium confidence that the API should exist at all.
* The team needs additional community feedback before deciding to move forward with the API at all.
* The API may undergo significant conceptual or structural changes.
* The API relies on a not-yet-standardized platform feature.
| |
014327
|
# Angular Branching and Versioning: A Practical Guide
This guide explains how the Angular team manages branches and how those branches relate to
merging PRs and publishing releases. Before reading, you should understand
[Semantic Versioning](https://semver.org/#semantic-versioning-200).
## Distribution tags on npm
Angular's branching relates directly to versions published on npm. We will reference these [npm
distribution tags](https://docs.npmjs.com/cli/v6/commands/npm-dist-tag#purpose) throughout:
| Tag | Description |
|--------|-----------------------------------------------------------------------------------|
| latest | The most recent stable version. |
| next | The most recent pre-release version of Angular for testing. May not always exist. |
| v*-lts | The most recent LTS release for the specified version, such as `v9-lts`. |
## Branch naming
Angular's main branch is `main`. This branch always represents the absolute latest changes. The
code on `main` always represents a pre-release version, often published with the `next` tag on npm.
For each minor and major version increment, a new branch is created. These branches use a naming
scheme matching `\d+\.\d+\.x` and receive subsequent patch changes for that version range. For
example, the `10.2.x` branch represents the latest patch changes for subsequent releases starting
with `10.2.`. The version tagged on npm as `latest` will always correspond to such a branch,
referred to as the **active patch branch**.
## Major releases lifecycle
Angular releases a major version roughly every six months. Following a major release, we move
through a consistent lifecycle to the next major release, and repeat. At a high level, this
process proceeds as follows:
* A major release occurs. The `main` branch now represents the next minor version.
* Six weeks later, a minor release occurs. The `main` branch now represents the next minor
version.
* Six weeks later, a second minor release occurs. The `main` branch now represents the next major
version.
* Three months later, a major release occurs and the process repeats.
### Example
* Angular publishes `11.0.0`. At this point in time, the `main` branch represents `11.1.0`.
* Six weeks later, we publish `11.1.0` and `main` represents `11.2.0`.
* Six weeks later, we publish `11.2.0` and `main` represents `12.0.0`.
* Three months later, this cycle repeats with the publication of `12.0.0`.
### Feature freeze and release candidates
Before publishing minor and major versions as `latest` on npm, they go through a feature freeze and
a release candidate (RC) phase.
**Feature freeze** means that `main` is forked into a branch for a specific version, with no
additional features permitted before releasing as `latest` to npm. This branch becomes the **active
RC branch**. Upon branching, the `main` branch increments to the next minor or major pre-release
version. One week after feature freeze, the first RC is published with the `next` tag on npm from
the active RC branch. Patch bug fixes continue to merge into `main`, the active RC branch, and
the active patch branch during this entire period.
One to three weeks after publishing the first RC, the active RC branch is published as `latest` on
npm and the branch becomes the active patch branch. At this point there is no active RC branch until
the next minor or major release.
## Targeting pull requests
Every pull request has a **base branch**:

This base branch represents the latest branch that will receive the change. Most pull requests
should specify `main`. However, some changes will explicitly use an earlier branch, such as
`11.1.x`, in order to patch an older version. Specific GitHub labels, described below, control the
additional branches into which a pull request will be cherry-picked.
### Labelling pull requests
There are five labels that target PRs to versions:
| Label | Description |
|---------------|-----------------------------------------------------------------------------|
| target: major | A change that includes a backwards-incompatible behavior or API change. |
| target: minor | A change that introduces a new, backwards-compatible functionality. |
| target: patch | A backwards-compatible bug fix. |
| target: rc | A change that should be explicitly included in an active release candidate. |
| target: lts | A critical security or browser compatibility fix for LTS releases. |
Every PR must have exactly one `target: *` label. Angular's dev tooling will merge the pull request
into its base branch and then cherry-pick the commits to the appropriate branches based on the
specified target label.
The vast majority of pull requests will target `major`, `minor`, or `patch` based on the contents of
the code change. In rare cases, a pull request will specify `target: rc` or `target: lts` to
explicitly target a special branch.
Breaking changes, marked with `target: major`, can only be merged when `main` represents the next
major version.
### Pull request examples
| I want to... | Target branch | Target label | Your change will land in... |
| ----------------------------------------------------------- | ----------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------- |
| Make a non-breaking bug fix | `main` | `patch` | `main`, the active patch branch, and the active RC branch if there is one |
| Introduce a new feature | `main` | `minor` | `main` (any time) |
| Make a breaking change | `main` | `major` | `main` (only when `main` represents the next major version) |
| Make a critical security fix | `main` | `lts` | `main`, the active patch branch, the active RC branch if there is one, and all branches for versions within the LTS window |
| Bump the version of an RC | the active RC branch | `rc` | The active RC branch |
| Fix an RC bug for a major release feature | `main` | `rc` | `main` and the active RC branch |
| Backport a bug fix to the `latest` npm version during an RC | the active patch branch | `patch` | the active patch branch only |
| |
014328
|
# Building and Testing Angular
This document describes how to set up your development environment to build and test Angular.
It also explains the basic mechanics of using `git`, `node`, and `yarn`.
* [Prerequisite Software](#prerequisite-software)
* [Getting the Sources](#getting-the-sources)
* [Installing NPM Modules](#installing-npm-modules)
* [Building](#building)
* [Running Tests Locally](#running-tests-locally)
* [Formatting your Source Code](#formatting-your-source-code)
* [Linting/verifying your Source Code](#lintingverifying-your-source-code)
* [Publishing Snapshot Builds](#publishing-snapshot-builds)
* [Bazel Support](#bazel-support)
See the [contribution guidelines](https://github.com/angular/angular/blob/main/CONTRIBUTING.md)
if you'd like to contribute to Angular.
## Prerequisite Software
Before you can build and test Angular, you must install and configure the
following on your development machine:
* [Git](https://git-scm.com/) and/or the [**GitHub app**](https://desktop.github.com/) (for Mac and
Windows);
[GitHub's Guide to Installing Git](https://help.github.com/articles/set-up-git) is a good source
of information.\
**Windows Users**: Git Bash or an equivalent shell is required\
*Windows Powershell and cmd shells are not
supported [#46780](https://github.com/angular/angular/issues/46780) so some commands might fail*
* [Node.js](https://nodejs.org), (version specified in [`.nvmrc`](../.nvmrc)) which is used to run a
development web server,
run tests, and generate distributable files.
`.nvmrc` is read by [nvm](https://github.com/nvm-sh/nvm) commands like `nvm install`
and `nvm use`.
* [Yarn](https://yarnpkg.com) (version specified in the engines field
of [`package.json`](../package.json)) which is used to install dependencies.
* On Windows: [MSYS2](https://www.msys2.org/) which is used by Bazel. Follow
the [instructions](https://bazel.build/install/windows#installing-compilers-and-language-runtimes)
## Getting the Sources
Fork and clone the Angular repository:
1. Login to your GitHub account or create one by following the instructions given
[here](https://github.com/signup/free).
2. [Fork](https://help.github.com/forking) the [main Angular
repository](https://github.com/angular/angular).
3. Clone your fork of the Angular repository and define an `upstream` remote pointing back to
the Angular repository that you forked in the first place.
```shell
# Clone your GitHub repository:
git clone [email protected]:<github username>/angular.git
# Go to the Angular directory:
cd angular
# Add the main Angular repository as an upstream remote to your repository:
git remote add upstream https://github.com/angular/angular.git
```
## Installing NPM Modules
Next, install the JavaScript modules needed to build and test Angular:
```shell
# Install Angular project dependencies (package.json)
yarn install
```
## Building
To build Angular run:
```shell
yarn build
```
* Results are put in the `dist/packages-dist` folder.
## Running Tests Locally
Bazel is used as the primary tool for building and testing Angular.
To see how to run and debug Angular tests locally please refer to the
Bazel [Testing Angular](./building-with-bazel.md#testing-angular) section.
Note that you should execute all test suites before submitting a PR to
GitHub (`yarn test //packages/...`).
However, affected tests will be executed on our CI infrastructure. So if you forgot to run some
affected tests which would fail, GitHub will indicate the error state and present you the failures.
PRs can only be merged if the code is formatted properly and all tests are passing.
<a name="formatting-your-source-code"></a>
<a name="clang-format"></a>
<a name="prettier"></a>
### Testing changes against a local library/project
Often for developers the best way to ensure the changes they have made work as expected is to run
use changes in another library or project. To do this developers can build Angular locally, and
using `yarn link` build a local project with the created artifacts.
This can be done by running:
```sh
yarn ng-dev misc build-and-link <path-to-local-project-root>
```
### Building and serving a project
#### Cache
When making changes to Angular packages and testing in a local library/project you need to
run `ng cache disable` to disable the Angular CLI disk cache. If you are making changes that are not
reflected in your locally served library/project, verify if you
have [CLI Cache](https://angular.io/guide/workspace-config#cache-options) disabled.
#### Invoking the Angular CLI
The Angular CLI needs to be invoked using
Node.js [`--preserve-symlinks`](https://nodejs.org/api/cli.html#--preserve-symlinks) flag. Otherwise
the symbolic links will be resolved using their real path which causes node module resolution to
fail.
```sh
node --preserve-symlinks --preserve-symlinks-main node_modules/@angular/cli/lib/init.js serve
```
## Formatting your source code
Angular uses [prettier](https://clang.llvm.org/docs/ClangFormat.html) to format the source code.
If the source code is not properly formatted, the CI will fail and the PR cannot be merged.
You can automatically format your code by running:
- `yarn ng-dev format changed [shaOrRef]`: format only files changed since the provided
sha/ref. `shaOrRef` defaults to `main`.
- `yarn ng-dev format all`: format _all_ source code
- `yarn ng-dev format files <files..>`: format only provided files
## Linting/verifying your Source Code
You can check that your code is properly formatted and adheres to coding style by running:
``` shell
$ yarn lint
```
## Publishing Snapshot Builds
When a build of any branch on the upstream fork angular/angular is green on CI, it
automatically publishes build artifacts to repositories in the Angular org. For example,
the `@angular/core` package is published to https://github.com/angular/core-builds.
You may find that your un-merged change needs some validation from external participants.
Rather than requiring them to pull your Pull Request and build Angular locally, they can depend on
snapshots of the Angular packages created based on the code in the Pull Request.
### Publishing to GitHub Repos
You can also manually publish `*-builds` snapshots just like our CI build does for upstream
builds. Before being able to publish the packages, you need to build them locally by running the
`yarn build` command.
First time, you need to create the GitHub repositories:
``` shell
$ export TOKEN=[get one from https://github.com/settings/tokens]
$ CREATE_REPOS=1 ./scripts/ci/publish-build-artifacts.sh [GitHub username]
```
For subsequent snapshots, just run:
``` shell
$ ./scripts/ci/publish-build-artifacts.sh [GitHub username]
```
The script will publish the build snapshot to a branch with the same name as your current branch,
and create it if it doesn't exist.
## Bazel Support
### IDEs
#### VS Code
1. Install [Bazel](https://marketplace.visualstudio.com/items?itemName=BazelBuild.vscode-bazel)
extension for VS Code.
#### WebStorm / IntelliJ
1. Install the [Bazel](https://plugins.jetbrains.com/plugin/8609-bazel) plugin
2. You can find the settings under `Preferences->Other Settings->Bazel Settings`
It will automatically recognize `*.bazel` and `*.bzl` files.
### Remote Build Execution and Remote Caching
Bazel builds in the Angular repository use a shared cache. When a build occurs, a hash of the inputs
is computed
and checked against available outputs in the shared cache. If an output is found, it is used as the
output for the
build action rather than performing the build locally.
> Remote Build Execution requires authentication as a google.com account.
#### --config=remote flag
The `--config=remote` flag can be added to enable remote execution of builds.
| |
014339
|
import { AfterViewInit } from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
import { ElementRef } from '@angular/core';
import { EventEmitter } from '@angular/core';
import * as i0 from '@angular/core';
import { InjectionToken } from '@angular/core';
import { Injector } from '@angular/core';
import { ModuleWithProviders } from '@angular/core';
import { Observable } from 'rxjs';
import { OnChanges } from '@angular/core';
import { OnDestroy } from '@angular/core';
import { OnInit } from '@angular/core';
import { Renderer2 } from '@angular/core';
import { SimpleChanges } from '@angular/core';
import { Version } from '@angular/core';
// @public
export abstract class AbstractControl<TValue = any, TRawValue extends TValue = TValue> {
constructor(validators: ValidatorFn | ValidatorFn[] | null, asyncValidators: AsyncValidatorFn | AsyncValidatorFn[] | null);
addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void;
addValidators(validators: ValidatorFn | ValidatorFn[]): void;
get asyncValidator(): AsyncValidatorFn | null;
set asyncValidator(asyncValidatorFn: AsyncValidatorFn | null);
clearAsyncValidators(): void;
clearValidators(): void;
get dirty(): boolean;
disable(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
get disabled(): boolean;
enable(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
get enabled(): boolean;
readonly errors: ValidationErrors | null;
readonly events: Observable<ControlEvent<TValue>>;
get<P extends string | readonly (string | number)[]>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null;
get<P extends string | Array<string | number>>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null;
getError(errorCode: string, path?: Array<string | number> | string): any;
getRawValue(): any;
hasAsyncValidator(validator: AsyncValidatorFn): boolean;
hasError(errorCode: string, path?: Array<string | number> | string): boolean;
hasValidator(validator: ValidatorFn): boolean;
get invalid(): boolean;
markAllAsTouched(opts?: {
emitEvent?: boolean;
}): void;
markAsDirty(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
markAsPending(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
markAsPristine(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
markAsTouched(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
markAsUntouched(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
get parent(): FormGroup | FormArray | null;
abstract patchValue(value: TValue, options?: Object): void;
get pending(): boolean;
get pristine(): boolean;
removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void;
removeValidators(validators: ValidatorFn | ValidatorFn[]): void;
abstract reset(value?: TValue, options?: Object): void;
get root(): AbstractControl;
setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[] | null): void;
setErrors(errors: ValidationErrors | null, opts?: {
emitEvent?: boolean;
}): void;
setParent(parent: FormGroup | FormArray | null): void;
setValidators(validators: ValidatorFn | ValidatorFn[] | null): void;
abstract setValue(value: TRawValue, options?: Object): void;
get status(): FormControlStatus;
readonly statusChanges: Observable<FormControlStatus>;
get touched(): boolean;
get untouched(): boolean;
get updateOn(): FormHooks;
updateValueAndValidity(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
get valid(): boolean;
get validator(): ValidatorFn | null;
set validator(validatorFn: ValidatorFn | null);
readonly value: TValue;
readonly valueChanges: Observable<TValue>;
}
// @public
export abstract class AbstractControlDirective {
get asyncValidator(): AsyncValidatorFn | null;
abstract get control(): AbstractControl | null;
get dirty(): boolean | null;
get disabled(): boolean | null;
get enabled(): boolean | null;
get errors(): ValidationErrors | null;
getError(errorCode: string, path?: Array<string | number> | string): any;
hasError(errorCode: string, path?: Array<string | number> | string): boolean;
get invalid(): boolean | null;
get path(): string[] | null;
get pending(): boolean | null;
get pristine(): boolean | null;
reset(value?: any): void;
get status(): string | null;
get statusChanges(): Observable<any> | null;
get touched(): boolean | null;
get untouched(): boolean | null;
get valid(): boolean | null;
get validator(): ValidatorFn | null;
get value(): any;
get valueChanges(): Observable<any> | null;
}
// @public
export interface AbstractControlOptions {
asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null;
updateOn?: 'change' | 'blur' | 'submit';
validators?: ValidatorFn | ValidatorFn[] | null;
}
// @public
export class AbstractFormGroupDirective extends ControlContainer implements OnInit, OnDestroy {
get control(): FormGroup;
get formDirective(): Form | null;
// (undocumented)
ngOnDestroy(): void;
// (undocumented)
ngOnInit(): void;
get path(): string[];
// (undocumented)
static ɵdir: i0.ɵɵDirectiveDeclaration<AbstractFormGroupDirective, never, never, {}, {}, never, never, false, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<AbstractFormGroupDirective, never>;
}
// @public
export interface AsyncValidator extends Validator {
validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
// @public
export interface AsyncValidatorFn {
// (undocumented)
(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
// @public
export class CheckboxControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor {
writeValue(value: any): void;
// (undocumented)
static ɵdir: i0.ɵɵDirectiveDeclaration<CheckboxControlValueAccessor, "input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]", never, {}, {}, never, never, false, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxControlValueAccessor, never>;
}
// @public
export class CheckboxRequiredValidator extends RequiredValidator {
// (undocumented)
static ɵdir: i0.ɵɵDirectiveDeclaration<CheckboxRequiredValidator, "input[type=checkbox][required][formControlName],input[type=checkbox][required][formControl],input[type=checkbox][required][ngModel]", never, {}, {}, never, never, false, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<CheckboxRequiredValidator, never>;
}
// @public
export const COMPOSITION_BUFFER_MODE: InjectionToken<boolean>;
// @public
export type ControlConfig<T> = [
T | FormControlState<T>,
(ValidatorFn | ValidatorFn[])?,
(AsyncValidatorFn | AsyncValidatorFn[])?
];
// @public
export abstract class ControlContainer extends AbstractControlDirective {
get formDirective(): Form | null;
name: string | number | null;
get path(): string[] | null;
}
// @public
export abstract class ControlEvent<T = any> {
abstract readonly source: AbstractControl<unknown>;
}
// @public
export interface ControlValueAccessor {
registerOnChange(fn: any): void;
registerOnTouched(fn: any): void;
setDisabledState?(isDisabled: boolean): void;
writeValue(obj: any): void;
}
// @public
export class DefaultValueAccessor extends BaseControlValueAccessor implements ControlValueAccessor {
constructor(renderer: Renderer2, elementRef: ElementRef, _compositionMode: boolean);
writeValue(value: any): void;
// (undocumented)
static ɵdir: i0.ɵɵDirectiveDeclaration<DefaultValueAccessor, "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]", never, {}, {}, never, never, false, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<DefaultValueAccessor, [null, null, { optional: true; }]>;
}
// @public
export class EmailValidator extends AbstractValidatorDirective {
email: boolean | string;
// (undocumented)
enabled(input: boolean): boolean;
//
| |
014359
|
## API Report File for "@angular/core_rxjs-interop"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { DestroyRef } from '@angular/core';
import { Injector } from '@angular/core';
import { MonoTypeOperatorFunction } from 'rxjs';
import { Observable } from 'rxjs';
import { OutputOptions } from '@angular/core';
import { OutputRef } from '@angular/core';
import { ResourceLoaderParams } from '@angular/core';
import { ResourceOptions } from '@angular/core';
import { ResourceRef } from '@angular/core';
import { Signal } from '@angular/core';
import { Subscribable } from 'rxjs';
import { ValueEqualityFn } from '@angular/core/primitives/signals';
// @public
export function outputFromObservable<T>(observable: Observable<T>, opts?: OutputOptions): OutputRef<T>;
// @public
export function outputToObservable<T>(ref: OutputRef<T>): Observable<T>;
// @public
export function pendingUntilEvent<T>(injector?: Injector): MonoTypeOperatorFunction<T>;
// @public
export function rxResource<T, R>(opts: RxResourceOptions<T, R>): ResourceRef<T>;
// @public
export interface RxResourceOptions<T, R> extends Omit<ResourceOptions<T, R>, 'loader'> {
// (undocumented)
loader: (params: ResourceLoaderParams<R>) => Observable<T>;
}
// @public
export function takeUntilDestroyed<T>(destroyRef?: DestroyRef): MonoTypeOperatorFunction<T>;
// @public
export function toObservable<T>(source: Signal<T>, options?: ToObservableOptions): Observable<T>;
// @public
export interface ToObservableOptions {
injector?: Injector;
}
// @public (undocumented)
export function toSignal<T>(source: Observable<T> | Subscribable<T>): Signal<T | undefined>;
// @public (undocumented)
export function toSignal<T>(source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | undefined>> & {
initialValue?: undefined;
requireSync?: false;
}): Signal<T | undefined>;
// @public (undocumented)
export function toSignal<T>(source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | null>> & {
initialValue?: null;
requireSync?: false;
}): Signal<T | null>;
// @public (undocumented)
export function toSignal<T>(source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T>> & {
initialValue?: undefined;
requireSync: true;
}): Signal<T>;
// @public (undocumented)
export function toSignal<T, const U extends T>(source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | U>> & {
initialValue: U;
requireSync?: false;
}): Signal<T | U>;
// @public
export interface ToSignalOptions<T> {
equal?: ValueEqualityFn<T>;
initialValue?: unknown;
injector?: Injector;
manualCleanup?: boolean;
rejectErrors?: boolean;
requireSync?: boolean;
}
// (No @packageDocumentation comment for this package)
```
| |
014382
|
d: string, url: string, options: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
reportProgress?: boolean;
observe: 'events';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
responseType?: 'json';
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<HttpEvent<any>>;
request<R>(method: string, url: string, options: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
reportProgress?: boolean;
observe: 'events';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
responseType?: 'json';
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<HttpEvent<R>>;
request(method: string, url: string, options: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'response';
context?: HttpContext;
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<HttpResponse<ArrayBuffer>>;
request(method: string, url: string, options: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'response';
context?: HttpContext;
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType: 'blob';
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<HttpResponse<Blob>>;
request(method: string, url: string, options: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'response';
context?: HttpContext;
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType: 'text';
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<HttpResponse<string>>;
request(method: string, url: string, options: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
reportProgress?: boolean;
observe: 'response';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpResponse<Object>>;
request<R>(method: string, url: string, options: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
reportProgress?: boolean;
observe: 'response';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
responseType?: 'json';
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<HttpResponse<R>>;
request(method: string, url: string, options?: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
observe?: 'body';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
responseType?: 'json';
reportProgress?: boolean;
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<Object>;
request<R>(method: string, url: string, options?: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
observe?: 'body';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
responseType?: 'json';
reportProgress?: boolean;
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<R>;
request(method: string, url: string, options?: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
observe?: 'body' | 'events' | 'response';
reportProgress?: boolean;
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
withCredentials?: boolean;
transferCache?: {
includeHeaders?: string[];
} | boolean;
}): Observable<any>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<HttpClient, never>;
// (undocumented)
static ɵprov: i0.ɵɵInjectableDeclaration<HttpClient>;
}
// @public @deprecated
export class HttpClientJsonpModule {
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<HttpClientJsonpModule, never>;
// (undocumented)
static ɵinj: i0.ɵɵInjectorDeclaration<HttpClientJsonpModule>;
// (undocumented)
static ɵmod: i0.ɵɵNgModuleDeclaration<HttpClientJsonpModule, never, never, never>;
}
// @public @deprecated
export class HttpClientModule {
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<HttpClientModule, never>;
// (undocumented)
static ɵinj: i0.ɵɵInjectorDeclaration<HttpClientModule>;
// (undocumented)
static ɵmod: i0.ɵɵNgModuleDeclaration<HttpClientModule, never, never, never>;
}
// @public @deprecated
export class HttpClientXsrfModule {
static disable(): ModuleWithProviders<HttpClientXsrfModule>;
static withOptions(options?: {
cookieName?: string;
headerName?: string;
}): ModuleWithProviders<HttpClientXsrfModule>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<HttpClientXsrfModule, never>;
// (undocumented)
static ɵinj: i0.ɵɵInjectorDeclaration<HttpClientXsrfModule>;
// (undocumented)
static ɵmod: i0.ɵɵNgModuleDeclaration<HttpClientXsrfModule, never, never, never>;
}
// @public
export class HttpContext {
delete(token: HttpContextToken<unknown>): HttpContext;
get<T>(token: HttpContextToken<T>): T;
has(token: HttpContextToken<unknown>): boolean;
// (undocumented)
keys(): IterableIterator<HttpContextToken<unknown>>;
set<T>(token: HttpContextToken<T>, value: T): HttpContext;
}
// @public
export class HttpContextToken<T> {
constructor(defaultValue: () => T);
// (undocumented)
readonly defaultValue: () => T;
}
// @public
export interface HttpDownloadProgressEvent extends HttpProgressEvent {
partialText?: string;
// (undocumented)
type: HttpEventType.DownloadProgress;
}
// @public
export class HttpErrorResponse extends HttpResponseBase implements Error {
constructor(init: {
error?: any;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
});
// (undocumented)
readonly error: any | null;
// (undocumented)
readonly message: string;
// (undocumented)
readonly name = "HttpErrorResponse";
readonly ok = false;
}
// @public
export type HttpEvent<T> = HttpSentEvent | HttpHeaderResponse | HttpResponse<T> | HttpProgressEvent | HttpUserEvent<T>;
// @public
export enum HttpEventType {
DownloadProgress = 3,
Response = 4,
ResponseHeader = 2,
Sent = 0,
UploadProgress = 1,
User = 5
}
// @public
export interface HttpFeature<KindT extends HttpFeatureKind> {
// (undocumented)
ɵkind: KindT;
// (undocumented)
ɵproviders: Provider[];
}
// @public
export enum HttpFeatureKind {
// (undocumented)
CustomXsrfConfiguration = 2,
// (undocumented)
Fetch = 6,
// (undocumented)
| |
014399
|
## API Report File for "@angular/platform-browser_animations"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { ANIMATION_MODULE_TYPE } from '@angular/core';
import * as i0 from '@angular/core';
import * as i1 from '@angular/platform-browser';
import { ModuleWithProviders } from '@angular/core';
import { Provider } from '@angular/core';
export { ANIMATION_MODULE_TYPE }
// @public
export class BrowserAnimationsModule {
static withConfig(config: BrowserAnimationsModuleConfig): ModuleWithProviders<BrowserAnimationsModule>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<BrowserAnimationsModule, never>;
// (undocumented)
static ɵinj: i0.ɵɵInjectorDeclaration<BrowserAnimationsModule>;
// (undocumented)
static ɵmod: i0.ɵɵNgModuleDeclaration<BrowserAnimationsModule, never, never, [typeof i1.BrowserModule]>;
}
// @public
export interface BrowserAnimationsModuleConfig {
disableAnimations?: boolean;
}
// @public
export class NoopAnimationsModule {
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<NoopAnimationsModule, never>;
// (undocumented)
static ɵinj: i0.ɵɵInjectorDeclaration<NoopAnimationsModule>;
// (undocumented)
static ɵmod: i0.ɵɵNgModuleDeclaration<NoopAnimationsModule, never, never, [typeof i1.BrowserModule]>;
}
// @public
export function provideAnimations(): Provider[];
// @public
export function provideNoopAnimations(): Provider[];
// (No @packageDocumentation comment for this package)
```
| |
014452
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AnimateApp} from './app/animate-app';
@NgModule({declarations: [AnimateApp], bootstrap: [AnimateApp], imports: [BrowserAnimationsModule]})
export class ExampleModule {}
platformBrowserDynamic().bootstrapModule(ExampleModule);
| |
014464
|
<!DOCTYPE html>
<html>
<head>
<title>Order Management</title>
<style>
.warning {
background-color: yellow;
}
</style>
</head>
<body>
<order-management-app> Loading... </order-management-app>
<script src="/angular/packages/zone.js/bundles/zone.umd.js"></script>
<script src="/app_bundle.js"></script>
</body>
</html>
| |
014472
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
@Component({
selector: 'async-app',
template: `
<div id="increment">
<span class="val">{{ val1 }}</span>
<button class="action" (click)="increment()">Increment</button>
</div>
<div id="delayedIncrement">
<span class="val">{{ val2 }}</span>
<button class="action" (click)="delayedIncrement()">Delayed Increment</button>
<button class="cancel" *ngIf="timeoutId != null" (click)="cancelDelayedIncrement()">
Cancel
</button>
</div>
<div id="multiDelayedIncrements">
<span class="val">{{ val3 }}</span>
<button class="action" (click)="multiDelayedIncrements(10)">10 Delayed Increments</button>
<button
class="cancel"
*ngIf="multiTimeoutId != null"
(click)="cancelMultiDelayedIncrements()"
>
Cancel
</button>
</div>
<div id="periodicIncrement">
<span class="val">{{ val4 }}</span>
<button class="action" (click)="periodicIncrement()">Periodic Increment</button>
<button class="cancel" *ngIf="intervalId != null" (click)="cancelPeriodicIncrement()">
Cancel
</button>
</div>
`,
standalone: false,
})
class AsyncApplication {
val1: number = 0;
val2: number = 0;
val3: number = 0;
val4: number = 0;
timeoutId: any = null;
multiTimeoutId: any = null;
intervalId: any = null;
increment(): void {
this.val1++;
}
delayedIncrement(): void {
this.cancelDelayedIncrement();
this.timeoutId = setTimeout(() => {
this.val2++;
this.timeoutId = null;
}, 2000);
}
multiDelayedIncrements(i: number): void {
this.cancelMultiDelayedIncrements();
const self = this;
function helper(_i: number) {
if (_i <= 0) {
self.multiTimeoutId = null;
return;
}
self.multiTimeoutId = setTimeout(() => {
self.val3++;
helper(_i - 1);
}, 500);
}
helper(i);
}
periodicIncrement(): void {
this.cancelPeriodicIncrement();
this.intervalId = setInterval(() => this.val4++, 2000);
}
cancelDelayedIncrement(): void {
if (this.timeoutId != null) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
}
cancelMultiDelayedIncrements(): void {
if (this.multiTimeoutId != null) {
clearTimeout(this.multiTimeoutId);
this.multiTimeoutId = null;
}
}
cancelPeriodicIncrement(): void {
if (this.intervalId != null) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
}
@NgModule({
declarations: [AsyncApplication],
bootstrap: [AsyncApplication],
imports: [BrowserModule],
})
class ExampleModule {}
platformBrowserDynamic().bootstrapModule(ExampleModule);
| |
014478
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Injectable, NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
/**
* You can find the AngularJS implementation of this example here:
* https://github.com/wardbell/ng1DataBinding
*/
// ---- model
let _nextId = 1;
class Person {
personId: number;
mom: Person;
dad: Person;
friends: Person[];
constructor(
public firstName: string,
public lastName: string,
public yearOfBirth: number,
) {
this.personId = _nextId++;
this.firstName = firstName;
this.lastName = lastName;
this.mom = null;
this.dad = null;
this.friends = [];
this.personId = _nextId++;
}
get age(): number {
return 2015 - this.yearOfBirth;
}
get fullName(): string {
return `${this.firstName} ${this.lastName}`;
}
get friendNames(): string {
return this.friends.map((f) => f.fullName).join(', ');
}
}
// ---- services
@Injectable()
export class DataService {
currentPerson: Person;
persons: Person[];
constructor() {
this.persons = [
new Person('Victor', 'Savkin', 1930),
new Person('Igor', 'Minar', 1920),
new Person('John', 'Papa', 1910),
new Person('Nancy', 'Duarte', 1910),
new Person('Jack', 'Papa', 1910),
new Person('Jill', 'Papa', 1910),
new Person('Ward', 'Bell', 1910),
new Person('Robert', 'Bell', 1910),
new Person('Tracy', 'Ward', 1910),
new Person('Dan', 'Wahlin', 1910),
];
this.persons[0].friends = [0, 1, 2, 6, 9].map((_) => this.persons[_]);
this.persons[1].friends = [0, 2, 6, 9].map((_) => this.persons[_]);
this.persons[2].friends = [0, 1, 6, 9].map((_) => this.persons[_]);
this.persons[6].friends = [0, 1, 2, 9].map((_) => this.persons[_]);
this.persons[9].friends = [0, 1, 2, 6].map((_) => this.persons[_]);
this.persons[2].mom = this.persons[5];
this.persons[2].dad = this.persons[4];
this.persons[6].mom = this.persons[8];
this.persons[6].dad = this.persons[7];
this.currentPerson = this.persons[0];
}
}
// ---- components
@Component({
selector: 'full-name-cmp',
template: `
<h1>Edit Full Name</h1>
<div>
<form>
<div>
<label>
First:
<input
[(ngModel)]="person.firstName"
type="text"
placeholder="First name"
name="firstName"
/>
</label>
</div>
<div>
<label>
Last:
<input
[(ngModel)]="person.lastName"
type="text"
placeholder="Last name"
name="lastName"
/>
</label>
</div>
<div>
<label>{{ person.fullName }}</label>
</div>
</form>
</div>
`,
standalone: false,
})
export class FullNameComponent {
constructor(private _service: DataService) {}
get person(): Person {
return this._service.currentPerson;
}
}
@Component({
selector: 'person-detail-cmp',
template: `
<h2>{{ person.fullName }}</h2>
<div>
<form>
<div>
<label
>First:
<input
[(ngModel)]="person.firstName"
type="text"
placeholder="First name"
name="firstName"
/></label>
</div>
<div>
<label
>Last:
<input
[(ngModel)]="person.lastName"
type="text"
placeholder="Last name"
name="lastName"
/></label>
</div>
<div>
<label
>Year of birth:
<input
[(ngModel)]="person.yearOfBirth"
type="number"
placeholder="Year of birth"
name="yearOfBirth"
/></label>
Age: {{ person.age }}
</div>
<div *ngIf="person.mom != null">
<label>Mom:</label>
<input
[(ngModel)]="person.mom.firstName"
type="text"
placeholder="Mom's first name"
name="momFirstName"
/>
<input
[(ngModel)]="person.mom.lastName"
type="text"
placeholder="Mom's last name"
name="momLastName"
/>
{{ person.mom.fullName }}
</div>
<div *ngIf="person.dad != null">
<label>Dad:</label>
<input
[(ngModel)]="person.dad.firstName"
type="text"
placeholder="Dad's first name"
name="dasFirstName"
/>
<input
[(ngModel)]="person.dad.lastName"
type="text"
placeholder="Dad's last name"
name="dadLastName"
/>
{{ person.dad.fullName }}
</div>
<div *ngIf="person.friends.length > 0">
<label>Friends:</label>
{{ person.friendNames }}
</div>
</form>
</div>
`,
standalone: false,
})
export class PersonsDetailComponent {
constructor(private _service: DataService) {}
get person(): Person {
return this._service.currentPerson;
}
}
@Component({
selector: 'persons-cmp',
template: `
<h1>FullName Demo</h1>
<div>
<ul>
<li *ngFor="let person of persons">
<label (click)="select(person)">{{ person.fullName }}</label>
</li>
</ul>
<person-detail-cmp></person-detail-cmp>
</div>
`,
standalone: false,
})
export class PersonsComponent {
persons: Person[];
constructor(private _service: DataService) {
this.persons = _service.persons;
}
select(person: Person): void {
this._service.currentPerson = person;
}
}
@Component({
selector: 'person-management-app',
viewProviders: [DataService],
template: `
<button (click)="switchToEditName()">Edit Full Name</button>
<button (click)="switchToPersonList()">Person Array</button>
<full-name-cmp *ngIf="mode == 'editName'"></full-name-cmp>
<persons-cmp *ngIf="mode == 'personList'"></persons-cmp>
`,
standalone: false,
})
export class PersonManagementApplication {
mode: string;
switchToEditName(): void {
this.mode = 'editName';
}
switchToPersonList(): void {
this.mode = 'personList';
}
}
@NgModule({
bootstrap: [PersonManagementApplication],
declarations: [
PersonManagementApplication,
FullNameComponent,
PersonsComponent,
PersonsDetailComponent,
],
imports: [BrowserModule, FormsModule],
})
export class ExampleModule {}
platformBrowserDynamic().bootstrapModule(ExampleModule);
| |
014494
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {HttpClientModule} from '@angular/common/http';
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {HttpCmp} from './app/http_comp';
@NgModule({
declarations: [HttpCmp],
bootstrap: [HttpCmp],
imports: [BrowserModule, HttpClientModule],
})
export class ExampleModule {}
platformBrowserDynamic().bootstrapModule(ExampleModule);
| |
014509
|
<!DOCTYPE html>
<html>
<title>Routing Example</title>
<link rel="stylesheet" type="text/css" href="./css/gumby.css" />
<link rel="stylesheet" type="text/css" href="./css/app.css" />
<base href="/" />
<body>
<inbox-app> Loading... </inbox-app>
</body>
<script src="/angular/packages/zone.js/bundles/zone.umd.js"></script>
<script type="module" src="bundles/main.js"></script>
</html>
| |
014650
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {mergeApplicationConfig, ApplicationConfig} from '@angular/core';
import {provideServerRendering} from '@angular/platform-server';
import {appConfig} from './app.config';
const serverConfig: ApplicationConfig = {
providers: [provideServerRendering()],
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
| |
014651
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component} from '@angular/core';
import {testData} from '../../test-data';
@Component({
selector: 'app-root',
standalone: true,
template: `
<table>
<tbody>
@for(entry of data; track $index) {
<tr (click)="onClick()">
<td>{{ entry.id }}</td>
<td>{{ entry.name }}</td>
</tr>
}
</tbody>
</table>
`,
})
export class AppComponent {
data = testData();
onClick() {}
}
| |
014716
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Input} from '@angular/core';
import {DomSanitizer, SafeStyle} from '@angular/platform-browser';
import {TableCell} from '../util';
let trustedEmptyColor: SafeStyle;
let trustedGreyColor: SafeStyle;
@Component({
standalone: true,
selector: 'app',
template: `
<table>
<tbody>
@for (row of data; track $index) {
<tr>
@for (cell of row; track $index) {
<td [style.backgroundColor]="getColor(cell.row)">
@if (condition) {
<!--
Use static text in cells to avoid the need
to run a new change detection cycle.
-->
Cell }
</td>
}
</tr>
}
</tbody>
</table>
`,
})
export class AppComponent {
@Input() data: TableCell[][] = [];
condition = true;
constructor(sanitizer: DomSanitizer) {
trustedEmptyColor = sanitizer.bypassSecurityTrustStyle('white');
trustedGreyColor = sanitizer.bypassSecurityTrustStyle('grey');
}
getColor(row: number) {
return row % 2 ? trustedEmptyColor : trustedGreyColor;
}
}
| |
014720
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Input} from '@angular/core';
import {DomSanitizer, SafeStyle} from '@angular/platform-browser';
import {TableCell} from '../util';
let trustedEmptyColor: SafeStyle;
let trustedGreyColor: SafeStyle;
@Component({
standalone: true,
selector: 'app',
template: `
<table>
<tbody>
@for (row of data; track $index) {
<tr>
@for (cell of row; track $index) {
<td [style.backgroundColor]="getColor(cell.row)">
@defer (when condition; on immediate) {
<!--
Use static text in cells to avoid the need
to run a new change detection cycle.
-->
Cell }
</td>
}
</tr>
}
</tbody>
</table>
`,
})
export class AppComponent {
@Input() data: TableCell[][] = [];
condition = true;
constructor(sanitizer: DomSanitizer) {
trustedEmptyColor = sanitizer.bypassSecurityTrustStyle('white');
trustedGreyColor = sanitizer.bypassSecurityTrustStyle('grey');
}
getColor(row: number) {
return row % 2 ? trustedEmptyColor : trustedGreyColor;
}
}
| |
014795
|
<!DOCTYPE html>
<html>
<head>
<!-- Prevent the browser from requesting any favicon. -->
<link rel="icon" href="data:," />
</head>
<body>
<div>
<app-component>Loading...</app-component>
</div>
<script src="/angular/packages/zone.js/bundles/zone.umd.js"></script>
<script src="/bundle.debug.min.js"></script>
</body>
</html>
| |
020857
|
/// <reference path='fourslash.ts' />
// @noImplicitAny: true
// @Filename: /a.ts
////import fs = require("fs");
////fs;
verify.codeFixAvailable([{
description: "Install '@types/node'",
commands: [{
type: "install package",
file: "/a.ts",
packageName: "@types/node",
}],
}]);
| |
023343
|
// @target: es2017
export async function get(): Promise<[]> {
let emails = [];
return emails;
}
| |
024555
|
export interface ReactSelectProps<TValue = OptionValues> extends React.Props<ReactSelectClass<TValue>> {
/**
* text to display when `allowCreate` is true.
* @default 'Add "{label}"?'
*/
addLabelText?: string;
/**
* renders a custom drop-down arrow to be shown in the right-hand side of the select.
* @default undefined
*/
arrowRenderer?: ArrowRendererHandler | null;
/**
* blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices.
* @default false
*/
autoBlur?: boolean;
/**
* autofocus the component on mount
* @deprecated. Use autoFocus instead
* @default false
*/
autofocus?: boolean;
/**
* autofocus the component on mount
* @default false
*/
autoFocus?: boolean;
/**
* If enabled, the input will expand as the length of its value increases
*/
autosize?: boolean;
/**
* whether pressing backspace removes the last item when there is no input value
* @default true
*/
backspaceRemoves?: boolean;
/**
* Message to use for screenreaders to press backspace to remove the current item
* {label} is replaced with the item label
* @default "Press backspace to remove..."
*/
backspaceToRemoveMessage?: string;
/**
* CSS className for the outer element
*/
className?: string;
/**
* Prefix prepended to element default className if no className is defined
*/
classNamePrefix?: string;
/**
* title for the "clear" control when `multi` is true
* @default "Clear all"
*/
clearAllText?: string;
/**
* Renders a custom clear to be shown in the right-hand side of the select when clearable true
* @default undefined
*/
clearRenderer?: ClearRendererHandler;
/**
* title for the "clear" control
* @default "Clear value"
*/
clearValueText?: string;
/**
* whether to close the menu when a value is selected
* @default true
*/
closeOnSelect?: boolean;
/**
* whether it is possible to reset value. if enabled, an X button will appear at the right side.
* @default true
*/
clearable?: boolean;
/**
* whether backspace removes an item if there is no text input
* @default true
*/
deleteRemoves?: boolean;
/**
* delimiter to use to join multiple values
* @default ","
*/
delimiter?: string;
/**
* whether the Select is disabled or not
* @default false
*/
disabled?: boolean;
/**
* whether escape clears the value when the menu is closed
* @default true
*/
escapeClearsValue?: boolean;
/**
* method to filter a single option
*/
filterOption?: FilterOptionHandler<TValue>;
/**
* method to filter the options array
*/
filterOptions?: FilterOptionsHandler<TValue>;
/**
* id for the underlying HTML input element
* @default undefined
*/
id?: string;
/**
* whether to strip diacritics when filtering
* @default true
*/
ignoreAccents?: boolean;
/**
* whether to perform case-insensitive filtering
* @default true
*/
ignoreCase?: boolean;
/**
* custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'}
* @default {}
*/
inputProps?: { [key: string]: any };
/**
* renders a custom input
*/
inputRenderer?: InputRendererHandler;
/**
* allows for synchronization of component id's on server and client.
* @see https://github.com/JedWatson/react-select/pull/1105
*/
instanceId?: string;
/**
* whether the Select is loading externally or not (such as options being loaded).
* if true, a loading spinner will be shown at the right side.
* @default false
*/
isLoading?: boolean;
/**
* (legacy mode) joins multiple values into a single form field with the delimiter
* @default false
*/
joinValues?: boolean;
/**
* the option property to use for the label
* @default "label"
*/
labelKey?: string;
/**
* (any, start) match the start or entire string when filtering
* @default "any"
*/
matchPos?: string;
/**
* (any, label, value) which option property to filter on
* @default "any"
*/
matchProp?: string;
/**
* buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport
* @default 0
*/
menuBuffer?: number;
/**
* optional style to apply to the menu container
*/
menuContainerStyle?: React.CSSProperties;
/**
* renders a custom menu with options
*/
menuRenderer?: MenuRendererHandler<TValue>;
/**
* optional style to apply to the menu
*/
menuStyle?: React.CSSProperties;
/**
* multi-value input
* @default false
*/
multi?: boolean;
/**
* field name, for hidden `<input>` tag
*/
name?: string;
/**
* placeholder displayed when there are no matching search results or a falsy value to hide it
* @default "No results found"
*/
noResultsText?: string | JSX.Element;
/**
* onBlur handler: function (event) {}
*/
onBlur?: OnBlurHandler;
/**
* whether to clear input on blur or not
* @default true
*/
onBlurResetsInput?: boolean;
/**
* whether the input value should be reset when options are selected.
* Also input value will be set to empty if 'onSelectResetsInput=true' and
* Select will get new value that not equal previous value.
* @default true
*/
onSelectResetsInput?: boolean;
/**
* whether to clear input when closing the menu through the arrow
* @default true
*/
onCloseResetsInput?: boolean;
/**
* onChange handler: function (newValue) {}
*/
onChange?: OnChangeHandler<TValue>;
/**
* fires when the menu is closed
*/
onClose?: OnCloseHandler;
/**
* onFocus handler: function (event) {}
*/
onFocus?: OnFocusHandler;
/**
* onInputChange handler: function (inputValue) {}
*/
onInputChange?: OnInputChangeHandler;
/**
* onInputKeyDown handler: function (keyboardEvent) {}
*/
onInputKeyDown?: OnInputKeyDownHandler;
/**
* fires when the menu is scrolled to the bottom; can be used to paginate options
*/
onMenuScrollToBottom?: OnMenuScrollToBottomHandler;
/**
* fires when the menu is opened
*/
onOpen?: OnOpenHandler;
/**
* boolean to enable opening dropdown when focused
* @default false
*/
openOnClick?: boolean;
/**
* open the options menu when the input gets focus (requires searchable = true)
* @default true
*/
openOnFocus?: boolean;
/**
* className to add to each option component
*/
optionClassName?: string;
/**
* option component to render in dropdown
*/
optionComponent?: OptionComponentType<TValue>;
/**
* function which returns a custom way to render the options in the menu
*/
optionRenderer?: OptionRendererHandler<TValue>;
/**
* array of Select options
* @default false
*/
options?: Options<TValue>;
/**
* number of options to jump when using page up/down keys
* @default 5
*/
pageSize?: number;
/**
* field placeholder, displayed when there's no value
* @default "Select..."
*/
placeholder?: string | JSX.Element;
/**
* whether the selected option is removed from the dropdown on multi selects
* @default true
*/
removeSelected?: boolean;
/**
* applies HTML5 required attribute when needed
* @default false
*/
required?: boolean;
/**
* value to use when you clear the control
*/
resetValue?: any;
/**
* use react-select in right-to-left direction
* @default false
*/
rtl?: boolean;
/**
* whether the viewport will shift to display the entire menu when engaged
* @default true
*/
scrollMenuIntoView?: boolean;
/**
* whether to enable searching feature or not
* @default true;
*/
searchable?: boolean;
/**
* whether to select the currently focused value when the [tab] key is pressed
*/
tabSelectsValue?: boolean;
/**
* initial field value
*/
value?: Option<TValue> | Options<TValue> | string | string[] | number | number[] | boolean;
/**
* the option property to use for the value
* @default "value"
| |
025027
|
declare let cond: any;
// OK: One or other operand is possibly nullish
const test1 = (cond ? undefined : 32) ?? "possibly reached";
// Not OK: Both operands nullish
const test2 = (cond ? undefined : null) ?? "always reached";
// Not OK: Both operands non-nullish
const test3 = (cond ? 132 : 17) ?? "unreachable";
// Parens
const test4 = (cond ? (undefined) : (17)) ?? 42;
// Should be OK (special case)
if (!!true) {
}
// Should be OK (special cases)
while (0) { }
while (1) { }
while (true) { }
while (false) { }
const p5 = {} ?? null;
const p6 = 0 > 1 ?? null;
const p7 = null ?? null;
const p8 = (class foo { }) && null;
const p9 = (class foo { }) || null;
// Outer expression tests
while ({} as any) { }
while ({} satisfies unknown) { }
while ((<any>({}))) { }
while ((({}))) { }
// Should be OK
console.log((cond || undefined) && 1 / cond);
function foo(this: Object | undefined) {
// Should be OK
return this ?? 0;
}
| |
026824
|
// @noImplicitAny: true
let additional = [];
for (const subcomponent of [1, 2, 3]) {
additional = [...additional, subcomponent];
}
| |
027688
|
// @strict: true
export interface Predicate<A> {
(a: A): boolean
}
interface Left<E> {
readonly _tag: 'Left'
readonly left: E
}
interface Right<A> {
readonly _tag: 'Right'
readonly right: A
}
type Either<E, A> = Left<E> | Right<A>;
interface Refinement<A, B extends A> {
(a: A): a is B
}
declare const filter: {
<A, B extends A>(refinement: Refinement<A, B>): (as: ReadonlyArray<A>) => ReadonlyArray<B>
<A>(predicate: Predicate<A>): <B extends A>(bs: ReadonlyArray<B>) => ReadonlyArray<B>
<A>(predicate: Predicate<A>): (as: ReadonlyArray<A>) => ReadonlyArray<A>
};
declare function pipe<A, B>(a: A, ab: (a: A) => B): B;
declare function exists<A>(predicate: Predicate<A>): <E>(ma: Either<E, A>) => boolean;
declare const es: Either<string, number>[];
const x = pipe(es, filter(exists((n) => n > 0)))
| |
033103
|
// @strict: true
declare const o1: undefined | { b: string };
o1?.b;
declare const o2: undefined | { b: { c: string } };
o2?.b.c;
declare const o3: { b: undefined | { c: string } };
o3.b?.c;
declare const o4: { b?: { c: { d?: { e: string } } } };
o4.b?.c.d?.e;
declare const o5: { b?(): { c: { d?: { e: string } } } };
o5.b?.().c.d?.e;
// GH#33744
declare const o6: <T>() => undefined | ({ x: number });
o6<number>()?.x;
// GH#34109
o1?.b ? 1 : 0;
// GH#36031
o2?.b!.c;
o2?.b!.c!;
| |
036169
|
Promise.resolve().then(v => null);
>Promise.resolve().then(v => null) : Promise<any>
> : ^^^^^^^^^^^^
>Promise.resolve().then : <TResult1 = void, TResult2 = never>(onfulfilled?: (value: void) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>
> : ^ ^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>Promise.resolve() : Promise<void>
> : ^^^^^^^^^^^^^
>Promise.resolve : { (): Promise<void>; <T>(value: T): Promise<Awaited<T>>; <T>(value: T | PromiseLike<T>): Promise<Awaited<T>>; }
> : ^^^^^^ ^^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^^ ^^^
>Promise : PromiseConstructor
> : ^^^^^^^^^^^^^^^^^^
>resolve : { (): Promise<void>; <T>(value: T): Promise<Awaited<T>>; <T>(value: T | PromiseLike<T>): Promise<Awaited<T>>; }
> : ^^^^^^ ^^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^^ ^^^
>then : <TResult1 = void, TResult2 = never>(onfulfilled?: (value: void) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>
> : ^ ^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>v => null : (v: void) => any
> : ^ ^^^^^^^^^^^^^^
>v : void
> : ^^^^
| |
039347
|
privateNameJsPrototype.js(3,3): error TS18016: Private identifiers are not allowed outside class bodies.
privateNameJsPrototype.js(4,3): error TS18016: Private identifiers are not allowed outside class bodies.
privateNameJsPrototype.js(5,7): error TS18016: Private identifiers are not allowed outside class bodies.
privateNameJsPrototype.js(5,7): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameJsPrototype.js(9,3): error TS18016: Private identifiers are not allowed outside class bodies.
privateNameJsPrototype.js(10,3): error TS18016: Private identifiers are not allowed outside class bodies.
privateNameJsPrototype.js(11,7): error TS18016: Private identifiers are not allowed outside class bodies.
privateNameJsPrototype.js(11,7): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameJsPrototype.js(15,10): error TS2339: Property '#z' does not exist on type 'C'.
==== privateNameJsPrototype.js (9 errors) ====
function A() { }
A.prototype = {
#x: 1, // Error
~~
!!! error TS18016: Private identifiers are not allowed outside class bodies.
#m() {}, // Error
~~
!!! error TS18016: Private identifiers are not allowed outside class bodies.
get #p() { return "" } // Error
~~
!!! error TS18016: Private identifiers are not allowed outside class bodies.
~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
}
class B { }
B.prototype = {
#y: 2, // Error
~~
!!! error TS18016: Private identifiers are not allowed outside class bodies.
#m() {}, // Error
~~
!!! error TS18016: Private identifiers are not allowed outside class bodies.
get #p() { return "" } // Error
~~
!!! error TS18016: Private identifiers are not allowed outside class bodies.
~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
}
class C {
constructor() {
this.#z = 3;
~~
!!! error TS2339: Property '#z' does not exist on type 'C'.
}
}
| |
042644
|
void;
}
export interface ArrowRendererProps {
/**
* Arrow mouse down event handler.
*/
onMouseDown: React.MouseEventHandler<any>;
/**
* whether the Select is open or not.
*/
isOpen: boolean;
}
export interface ValueComponentProps<TValue = OptionValues> {
disabled: ReactSelectProps<TValue>['disabled'];
id: string;
instancePrefix: string;
onClick: OnValueClickHandler<TValue> | null;
onRemove?: SelectValueHandler<TValue>;
placeholder: ReactSelectProps<TValue>['placeholder'];
value: Option<TValue>;
values?: Array<Option<TValue>>;
}
export interface ReactSelectProps<TValue = OptionValues> extends React.Props<ReactSelectClass<TValue>> {
/**
* text to display when `allowCreate` is true.
* @default 'Add "{label}"?'
*/
addLabelText?: string;
/**
* renders a custom drop-down arrow to be shown in the right-hand side of the select.
* @default undefined
*/
arrowRenderer?: ArrowRendererHandler | null;
/**
* blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices.
* @default false
*/
autoBlur?: boolean;
/**
* autofocus the component on mount
* @deprecated. Use autoFocus instead
* @default false
*/
autofocus?: boolean;
/**
* autofocus the component on mount
* @default false
*/
autoFocus?: boolean;
/**
* If enabled, the input will expand as the length of its value increases
*/
autosize?: boolean;
/**
* whether pressing backspace removes the last item when there is no input value
* @default true
*/
backspaceRemoves?: boolean;
/**
* Message to use for screenreaders to press backspace to remove the current item
* {label} is replaced with the item label
* @default "Press backspace to remove..."
*/
backspaceToRemoveMessage?: string;
/**
* CSS className for the outer element
*/
className?: string;
/**
* Prefix prepended to element default className if no className is defined
*/
classNamePrefix?: string;
/**
* title for the "clear" control when `multi` is true
* @default "Clear all"
*/
clearAllText?: string;
/**
* Renders a custom clear to be shown in the right-hand side of the select when clearable true
* @default undefined
*/
clearRenderer?: ClearRendererHandler;
/**
* title for the "clear" control
* @default "Clear value"
*/
clearValueText?: string;
/**
* whether to close the menu when a value is selected
* @default true
*/
closeOnSelect?: boolean;
/**
* whether it is possible to reset value. if enabled, an X button will appear at the right side.
* @default true
*/
clearable?: boolean;
/**
* whether backspace removes an item if there is no text input
* @default true
*/
deleteRemoves?: boolean;
/**
* delimiter to use to join multiple values
* @default ","
*/
delimiter?: string;
/**
* whether the Select is disabled or not
* @default false
*/
disabled?: boolean;
/**
* whether escape clears the value when the menu is closed
* @default true
*/
escapeClearsValue?: boolean;
/**
* method to filter a single option
*/
filterOption?: FilterOptionHandler<TValue>;
/**
* method to filter the options array
*/
filterOptions?: FilterOptionsHandler<TValue>;
/**
* id for the underlying HTML input element
* @default undefined
*/
id?: string;
/**
* whether to strip diacritics when filtering
* @default true
*/
ignoreAccents?: boolean;
/**
* whether to perform case-insensitive filtering
* @default true
*/
ignoreCase?: boolean;
/**
* custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'}
* @default {}
*/
inputProps?: { [key: string]: any };
/**
* renders a custom input
*/
inputRenderer?: InputRendererHandler;
/**
* allows for synchronization of component id's on server and client.
* @see https://github.com/JedWatson/react-select/pull/1105
*/
instanceId?: string;
/**
* whether the Select is loading externally or not (such as options being loaded).
* if true, a loading spinner will be shown at the right side.
* @default false
*/
isLoading?: boolean;
/**
* (legacy mode) joins multiple values into a single form field with the delimiter
* @default false
*/
joinValues?: boolean;
/**
* the option property to use for the label
* @default "label"
*/
labelKey?: string;
/**
* (any, start) match the start or entire string when filtering
* @default "any"
*/
matchPos?: string;
/**
* (any, label, value) which option property to filter on
* @default "any"
*/
matchProp?: string;
/**
* buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport
* @default 0
*/
menuBuffer?: number;
/**
* optional style to apply to the menu container
*/
menuContainerStyle?: React.CSSProperties;
/**
* renders a custom menu with options
*/
menuRenderer?: MenuRendererHandler<TValue>;
/**
* optional style to apply to the menu
*/
menuStyle?: React.CSSProperties;
/**
* multi-value input
* @default false
*/
multi?: boolean;
/**
* field name, for hidden `<input>` tag
*/
name?: string;
/**
* placeholder displayed when there are no matching search results or a falsy value to hide it
* @default "No results found"
*/
noResultsText?: string | JSX.Element;
/**
* onBlur handler: function (event) {}
*/
onBlur?: OnBlurHandler;
/**
* whether to clear input on blur or not
* @default true
*/
onBlurResetsInput?: boolean;
/**
* whether the input value should be reset when options are selected.
* Also input value will be set to empty if 'onSelectResetsInput=true' and
* Select will get new value that not equal previous value.
* @default true
*/
onSelectResetsInput?: boolean;
/**
* whether to clear input when closing the menu through the arrow
* @default true
*/
onCloseResetsInput?: boolean;
/**
* onChange handler: function (newValue) {}
*/
onChange?: OnChangeHandler<TValue>;
/**
* fires when the menu is closed
*/
onClose?: OnCloseHandler;
/**
* onFocus handler: function (event) {}
*/
onFocus?: OnFocusHandler;
/**
* onInputChange handler: function (inputValue) {}
*/
onInputChange?: OnInputChangeHandler;
/**
* onInputKeyDown handler: function (keyboardEvent) {}
*/
onInputKeyDown?: OnInputKeyDownHandler;
/**
* fires when the menu is scrolled to the bottom; can be used to paginate options
*/
onMenuScrollToBottom?: OnMenuScrollToBottomHandler;
/**
* fires when the menu is opened
*/
onOpen?: OnOpenHandler;
/**
* boolean to enable opening dropdown when focused
* @default false
*/
openOnClick?: boolean;
/**
* open the options menu when the input gets focus (requires searchable = true)
* @default true
*/
openOnFocus?: boolean;
/**
* className to add to each option component
*/
optionClassName?: string;
/**
* option component to render in dropdown
*/
optionComponent?: OptionComponentType<TValue>;
/**
* function which returns a custom way to render the options in the menu
*/
optionRenderer?: OptionRendererHandler<TValue>;
/**
* array of Select options
* @default false
*/
options?: Options<TValue>;
/**
* number of options to jump when using page up/down keys
* @default 5
*/
pageSize?: number;
/**
* field placeholder, displayed when there's no value
* @default "Select..."
*/
placeholder?: string | JSX.Element;
/**
* whether the selected option is removed from the dropdown on multi selects
* @default true
*/
removeSelected?: boolean;
| |
043350
|
parser509534.ts(2,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
parser509534.ts(3,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
==== parser509534.ts (2 errors) ====
"use strict";
var config = require("../config");
~~~~~~~
!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
module.exports.route = function (server) {
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
// General Login Page
server.get(config.env.siteRoot + "/auth/login", function (req, res, next) {
// TODO Should render login page that shows auth options
req.redirect("/auth/live");
});
}
| |
044691
|
privateNameInObjectLiteral-3.ts(2,9): error TS18016: Private identifiers are not allowed outside class bodies.
privateNameInObjectLiteral-3.ts(2,9): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
==== privateNameInObjectLiteral-3.ts (2 errors) ====
const obj = {
get #foo() {
~~~~
!!! error TS18016: Private identifiers are not allowed outside class bodies.
~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
return ""
}
};
| |
045456
|
//// [tests/cases/conformance/expressions/optionalChaining/propertyAccessChain/propertyAccessChain.ts] ////
//// [propertyAccessChain.ts]
declare const o1: undefined | { b: string };
o1?.b;
declare const o2: undefined | { b: { c: string } };
o2?.b.c;
declare const o3: { b: undefined | { c: string } };
o3.b?.c;
declare const o4: { b?: { c: { d?: { e: string } } } };
o4.b?.c.d?.e;
declare const o5: { b?(): { c: { d?: { e: string } } } };
o5.b?.().c.d?.e;
// GH#33744
declare const o6: <T>() => undefined | ({ x: number });
o6<number>()?.x;
// GH#34109
o1?.b ? 1 : 0;
// GH#36031
o2?.b!.c;
o2?.b!.c!;
//// [propertyAccessChain.js]
"use strict";
var _a, _b, _c, _d, _e, _f;
o1 === null || o1 === void 0 ? void 0 : o1.b;
o2 === null || o2 === void 0 ? void 0 : o2.b.c;
(_a = o3.b) === null || _a === void 0 ? void 0 : _a.c;
(_c = (_b = o4.b) === null || _b === void 0 ? void 0 : _b.c.d) === null || _c === void 0 ? void 0 : _c.e;
(_e = (_d = o5.b) === null || _d === void 0 ? void 0 : _d.call(o5).c.d) === null || _e === void 0 ? void 0 : _e.e;
(_f = o6()) === null || _f === void 0 ? void 0 : _f.x;
// GH#34109
(o1 === null || o1 === void 0 ? void 0 : o1.b) ? 1 : 0;
// GH#36031
o2 === null || o2 === void 0 ? void 0 : o2.b.c;
o2 === null || o2 === void 0 ? void 0 : o2.b.c;
| |
046569
|
a.ts(1,1): error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.
==== tsconfig.json (0 errors) ====
{ "compilerOptions": {"types": []} }
==== a.ts (1 errors) ====
module.exports = 1;
~~~~~~
!!! error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.
| |
046657
|
/a.js(2,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
/f.cts(1,1): error TS1286: ESM syntax is not allowed in a CommonJS module when 'verbatimModuleSyntax' is enabled.
/main1.ts(1,13): error TS2305: Module '"./a"' has no exported member 'y'.
/main1.ts(3,12): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
/main1.ts(19,4): error TS2339: Property 'default' does not exist on type '() => void'.
/main1.ts(23,8): error TS1192: Module '"/e"' has no default export.
/main2.mts(1,13): error TS2305: Module '"./a"' has no exported member 'y'.
/main2.mts(4,4): error TS2339: Property 'default' does not exist on type 'typeof import("/a")'.
/main2.mts(5,12): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
/main2.mts(14,8): error TS1192: Module '"/e"' has no default export.
/main3.cjs(1,10): error TS1293: ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'.
/main3.cjs(1,13): error TS2305: Module '"./a"' has no exported member 'y'.
/main3.cjs(2,1): error TS8002: 'import ... =' can only be used in TypeScript files.
/main3.cjs(5,8): error TS1293: ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'.
/main3.cjs(8,8): error TS1293: ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'.
/main3.cjs(10,8): error TS1293: ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'.
/main3.cjs(12,8): error TS1293: ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'.
/main3.cjs(14,8): error TS1293: ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'.
/main3.cjs(17,8): error TS1293: ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'.
| |
050156
|
bug24934.js(2,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
==== bug24934.js (1 errors) ====
export function abc(a, b, c) { return 5; }
module.exports = { abc };
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
==== use.js (0 errors) ====
import { abc } from './bug24934';
abc(1, 2, 3);
| |
050174
|
/a.ts(1,22): error TS7016: Could not find a declaration file for module '@foo/bar'. '/node_modules/@foo/bar/index.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/foo__bar` if it exists or add a new declaration (.d.ts) file containing `declare module '@foo/bar';`
==== /a.ts (1 errors) ====
import * as foo from "@foo/bar";
~~~~~~~~~~
!!! error TS7016: Could not find a declaration file for module '@foo/bar'. '/node_modules/@foo/bar/index.js' implicitly has an 'any' type.
!!! error TS7016: Try `npm i --save-dev @types/foo__bar` if it exists or add a new declaration (.d.ts) file containing `declare module '@foo/bar';`
==== /node_modules/@foo/bar/package.json (0 errors) ====
{ "name": "@foo/bar", "version": "1.2.3" }
==== /node_modules/@foo/bar/index.js (0 errors) ====
This file is not processed.
| |
050181
|
didYouMeanSuggestionErrors.ts(1,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
didYouMeanSuggestionErrors.ts(2,5): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
didYouMeanSuggestionErrors.ts(3,19): error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`.
didYouMeanSuggestionErrors.ts(7,1): error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
didYouMeanSuggestionErrors.ts(8,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
didYouMeanSuggestionErrors.ts(9,9): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.
didYouMeanSuggestionErrors.ts(9,21): error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
didYouMeanSuggestionErrors.ts(10,9): error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.
didYouMeanSuggestionErrors.ts(12,19): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
didYouMeanSuggestionErrors.ts(13,19): error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
didYouMeanSuggestionErrors.ts(14,19): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
didYouMeanSuggestionErrors.ts(16,23): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
didYouMeanSuggestionErrors.ts(17,23): error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
didYouMeanSuggestionErrors.ts(18,23): error TS2583: Cannot find name 'WeakMap'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
didYouMeanSuggestionErrors.ts(19,23): error TS2583: Cannot find name 'WeakSet'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
didYouMeanSuggestionErrors.ts(20,19): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later.
didYouMeanSuggestionErrors.ts(21,19): error TS2585: 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later.
didYouMeanSuggestionErrors.ts(23,18): error TS2583: Cannot find name 'Iterator'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
didYouMeanSuggestionErrors.ts(24,18): error TS2583: Cannot find name 'AsyncIterator'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
==== didYouMeanSuggestionErrors.ts (19 errors) ====
describe("my test suite", () => {
~~~~~~~~
!!! error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
it("should run", () => {
~~
!!! error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
const a = $(".thing");
~
!!! error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`.
});
});
suite("another suite", () => {
~~~~~
!!! error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
test("everything else", () => {
~~~~
!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
console.log(process.env);
~~~~~~~
!!! error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.
~~~~~~~
!!! error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
document.createElement("div");
~~~~~~~~
!!! error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.
const x = require("fs");
~~~~~~~
!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
const y = Buffer.from([]);
~~~~~~
!!! error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
const z = module.exports;
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
const a = new Map();
~~~
!!! error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
const b = new Set();
~~~
!!! error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
const c = new WeakMap();
~~~~~~~
!!! error TS2583: Cannot find name 'WeakMap'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
const d = new WeakSet();
~~~~~~~
!!! error TS2583: Cannot find name 'WeakSet'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
const e = Symbol();
~~~~~~
!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later.
const f = Promise.resolve(0);
~~~~~~~
!!! error TS2585: 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later.
const i: Iterator<any> = null as any;
~~~~~~~~
!!! error TS2583: Cannot find name 'Iterator'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
const j: AsyncIterator<any> = null as any;
~~~~~~~~~~~~~
!!! error TS2583: Cannot find name 'AsyncIterator'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2015' or later.
const k: Symbol = null as any;
const l: Promise<any> = null as any;
});
});
| |
054459
|
.map((arr) => arr.list)
>map : <U>(callbackfn: (value: { list?: MyObj[]; }, index: number, array: { list?: MyObj[]; }[]) => U, thisArg?: any) => U[]
> : ^ ^^ ^^^ ^^^^^^^^^^^ ^^^^^ ^^ ^^ ^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^ ^^^^^^^^
>(arr) => arr.list : (arr: { list?: MyObj[]; }) => MyObj[] | undefined
> : ^ ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
>arr : { list?: MyObj[]; }
> : ^^^^^^^^^ ^^^
>arr.list : MyObj[] | undefined
> : ^^^^^^^^^^^^^^^^^^^
>arr : { list?: MyObj[]; }
> : ^^^^^^^^^ ^^^
>list : MyObj[] | undefined
> : ^^^^^^^^^^^^^^^^^^^
.filter((arr) => arr && arr.length)
>filter : { <S extends MyObj[] | undefined>(predicate: (value: MyObj[] | undefined, index: number, array: (MyObj[] | undefined)[]) => value is S, thisArg?: any): S[]; (predicate: (value: MyObj[] | undefined, index: number, array: (MyObj[] | undefined)[]) => unknown, thisArg?: any): (MyObj[] | undefined)[]; }
> : ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>(arr) => arr && arr.length : (arr: MyObj[] | undefined) => number | undefined
> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>arr : MyObj[] | undefined
> : ^^^^^^^^^^^^^^^^^^^
>arr && arr.length : number | undefined
> : ^^^^^^^^^^^^^^^^^^
>arr : MyObj[] | undefined
> : ^^^^^^^^^^^^^^^^^^^
>arr.length : number
> : ^^^^^^
>arr : MyObj[]
> : ^^^^^^^
>length : number
> : ^^^^^^
.map((arr) => arr // should error
>map : <U>(callbackfn: (value: MyObj[] | undefined, index: number, array: (MyObj[] | undefined)[]) => U, thisArg?: any) => U[]
> : ^ ^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^
>(arr) => arr // should error .filter((obj) => obj && obj.data) .map(obj => JSON.parse(obj.data)) : (arr: MyObj[] | undefined) => any[]
> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>arr : MyObj[] | undefined
> : ^^^^^^^^^^^^^^^^^^^
>arr // should error .filter((obj) => obj && obj.data) .map(obj => JSON.parse(obj.data)) : any[]
> : ^^^^^
>arr // should error .filter((obj) => obj && obj.data) .map : <U>(callbackfn: (value: MyObj, index: number, array: MyObj[]) => U, thisArg?: any) => U[]
> : ^ ^^ ^^^ ^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^
>arr // should error .filter((obj) => obj && obj.data) : MyObj[]
> : ^^^^^^^
>arr // should error .filter : { <S extends MyObj>(predicate: (value: MyObj, index: number, array: MyObj[]) => value is S, thisArg?: any): S[]; (predicate: (value: MyObj, index: number, array: MyObj[]) => unknown, thisArg?: any): MyObj[]; }
> : ^^^ ^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^^ ^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^ ^^ ^^^ ^^^^^^^^^^^^^
>arr : MyObj[] | undefined
> : ^^^^^^^^^^^^^^^^^^^
.filter((obj) => obj && obj.data)
>filter : { <S extends MyObj>(predicate: (value: MyObj, index: number, array: MyObj[]) => value is S, thisArg?: any): S[]; (predicate: (value: MyObj, index: number, array: MyObj[]) => unknown, thisArg?: any): MyObj[]; }
> : ^^^ ^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^^ ^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^ ^^ ^^^ ^^^^^^^^^^^^^
>(obj) => obj && obj.data : (obj: MyObj) => string | undefined
> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>obj : MyObj
> : ^^^^^
>obj && obj.data : string | undefined
> : ^^^^^^^^^^^^^^^^^^
>obj : MyObj
> : ^^^^^
>obj.data : string | undefined
> : ^^^^^^^^^^^^^^^^^^
>obj : MyObj
> : ^^^^^
>data : string | undefined
> : ^^^^^^^^^^^^^^^^^^
.map(obj => JSON.parse(obj.data)) // should error
>map : <U>(callbackfn: (value: MyObj, index: number, array: MyObj[]) => U, thisArg?: any) => U[]
> : ^ ^^ ^^^ ^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^
>obj => JSON.parse(obj.data) : (obj: MyObj) => any
> : ^ ^^^^^^^^^^^^^^^
>obj : MyObj
> : ^^^^^
>JSON.parse(obj.data) : any
> : ^^^
>JSON.parse : (text: string, reviver?: (this: any, key: string, value: any) => any) => any
> : ^ ^^ ^^ ^^^ ^^^^^
>JSON : JSON
> : ^^^^
>parse : (text: string, reviver?: (this: any, key: string, value: any) => any) => any
> : ^ ^^ ^^ ^^^ ^^^^^
>obj.data : string | undefined
> : ^^^^^^^^^^^^^^^^^^
>obj : MyObj
> : ^^^^^
>data : string | undefined
> : ^^^^^^^^^^^^^^^^^^
);
| |
057064
|
o2?.f(x);
>o2?.f(x) : boolean
> : ^^^^^^^
>o2?.f : (x: any) => x is number
> : ^ ^^ ^^^^^
>o2 : { f(x: any): x is number; }
> : ^^^^ ^^ ^^^ ^^^
>f : (x: any) => x is number
> : ^ ^^ ^^^^^
>x : number
> : ^^^^^^
}
else {
x;
>x : string | number
> : ^^^^^^^^^^^^^^^
o2;
>o2 : { f(x: any): x is number; } | undefined
> : ^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^
o2?.f;
>o2?.f : ((x: any) => x is number) | undefined
> : ^^ ^^ ^^^^^ ^^^^^^^^^^^^^
>o2 : { f(x: any): x is number; } | undefined
> : ^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^
>f : ((x: any) => x is number) | undefined
> : ^^ ^^ ^^^^^ ^^^^^^^^^^^^^
o2.f;
>o2.f : (x: any) => x is number
> : ^ ^^ ^^^^^
>o2 : { f(x: any): x is number; } | undefined
> : ^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^
>f : (x: any) => x is number
> : ^ ^^ ^^^^^
}
x;
>x : string | number
> : ^^^^^^^^^^^^^^^
o2;
>o2 : { f(x: any): x is number; } | undefined
> : ^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^
o2?.f;
>o2?.f : ((x: any) => x is number) | undefined
> : ^^ ^^ ^^^^^ ^^^^^^^^^^^^^
>o2 : { f(x: any): x is number; } | undefined
> : ^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^
>f : ((x: any) => x is number) | undefined
> : ^^ ^^ ^^^^^ ^^^^^^^^^^^^^
o2.f;
>o2.f : (x: any) => x is number
> : ^ ^^ ^^^^^
>o2 : { f(x: any): x is number; } | undefined
> : ^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^
>f : (x: any) => x is number
> : ^ ^^ ^^^^^
declare const o3: { x: 1, y: string } | { x: 2, y: number } | undefined;
>o3 : { x: 1; y: string; } | { x: 2; y: number; } | undefined
> : ^^^^^ ^^^^^ ^^^^^^^^^^^ ^^^^^ ^^^^^^^^^^^^^^^
>x : 1
> : ^
>y : string
> : ^^^^^^
>x : 2
> : ^
>y : number
> : ^^^^^^
if (o3?.x === 1) {
>o3?.x === 1 : boolean
> : ^^^^^^^
>o3?.x : 1 | 2 | undefined
> : ^^^^^^^^^^^^^^^^^
>o3 : { x: 1; y: string; } | { x: 2; y: number; } | undefined
> : ^^^^^ ^^^^^ ^^^^^^^^^^^ ^^^^^ ^^^^^^^^^^^^^^^
>x : 1 | 2 | undefined
> : ^^^^^^^^^^^^^^^^^
>1 : 1
> : ^
o3;
>o3 : { x: 1; y: string; }
> : ^^^^^ ^^^^^ ^^^
o3.x;
>o3.x : 1
> : ^
>o3 : { x: 1; y: string; }
> : ^^^^^ ^^^^^ ^^^
>x : 1
> : ^
o3?.x;
>o3?.x : 1
> : ^
>o3 : { x: 1; y: string; }
> : ^^^^^ ^^^^^ ^^^
>x : 1
> : ^
}
else {
o3;
>o3 : { x: 2; y: number; } | undefined
> : ^^^^^ ^^^^^ ^^^^^^^^^^^^^^^
o3?.x;
>o3?.x : 2 | undefined
> : ^^^^^^^^^^^^^
>o3 : { x: 2; y: number; } | undefined
> : ^^^^^ ^^^^^ ^^^^^^^^^^^^^^^
>x : 2 | undefined
> : ^^^^^^^^^^^^^
o3.x;
>o3.x : 2
> : ^
>o3 : { x: 2; y: number; } | undefined
> : ^^^^^ ^^^^^ ^^^^^^^^^^^^^^^
>x : 2
> : ^
}
o3;
>o3 : { x: 1; y: string; } | { x: 2; y: number; } | undefined
> : ^^^^^ ^^^^^ ^^^^^^^^^^^ ^^^^^ ^^^^^^^^^^^^^^^
o3?.x;
>o3?.x : 1 | 2 | undefined
> : ^^^^^^^^^^^^^^^^^
>o3 : { x: 1; y: string; } | { x: 2; y: number; } | undefined
> : ^^^^^ ^^^^^ ^^^^^^^^^^^ ^^^^^ ^^^^^^^^^^^^^^^
>x : 1 | 2 | undefined
> : ^^^^^^^^^^^^^^^^^
o3.x;
>o3.x : 1 | 2
> : ^^^^^
>o3 : { x: 1; y: string; } | { x: 2; y: number; } | undefined
> : ^^^^^ ^^^^^ ^^^^^^^^^^^ ^^^^^ ^^^^^^^^^^^^^^^
>x : 1 | 2
> : ^^^^^
declare const o4: { x?: { y: boolean } };
>o4 : { x?: { y: boolean; }; }
> : ^^^^^^ ^^^
>x : { y: boolean; } | undefined
> : ^^^^^ ^^^^^^^^^^^^^^^
>y : boolean
> : ^^^^^^^
if (o4.x?.y) {
>o4.x?.y : boolean | undefined
> : ^^^^^^^^^^^^^^^^^^^
>o4.x : { y: boolean; } | undefined
> : ^^^^^ ^^^^^^^^^^^^^^^
>o4 : { x?: { y: boolean; }; }
> : ^^^^^^ ^^^
>x : { y: boolean; } | undefined
> : ^^^^^ ^^^^^^^^^^^^^^^
>y : boolean | undefined
> : ^^^^^^^^^^^^^^^^^^^
o4.x; // { y: boolean }
>o4.x : { y: boolean; }
> : ^^^^^ ^^^
>o4 : { x?: { y: boolean; }; }
> : ^^^^^^ ^^^
>x : { y: boolean; }
> : ^^^^^ ^^^
o4.x.y; // true
>o4.x.y : true
> : ^^^^
>o4.x : { y: boolean; }
> : ^^^^^ ^^^
>o4 : { x?: { y: boolean; }; }
> : ^^^^^^ ^^^
>x : { y: boolean; }
> : ^^^^^ ^^^
>y : true
> : ^^^^
o4.x?.y; // true
>o4.x?.y : true
> : ^^^^
>o4.x : { y: boolean; }
> : ^^^^^ ^^^
>o4 : { x?: { y: boolean; }; }
> : ^^^^^^ ^^^
>x : { y: boolean; }
> : ^^^^^ ^^^
>y : true
> : ^^^^
}
else {
o4.x;
>o4.x : { y: boolean; } | undefined
> : ^^^^^ ^^^^^^^^^^^^^^^
>o4 : { x?: { y: boolean; }; }
> : ^^^^^^ ^^^
>x : { y: boolean; } | undefined
> : ^^^^^ ^^^^^^^^^^^^^^^
| |
058540
|
privateNamesNotAllowedInVariableDeclarations.ts(1,7): error TS18029: Private identifiers are not allowed in variable declarations.
==== privateNamesNotAllowedInVariableDeclarations.ts (1 errors) ====
const #foo = 3;
~~~~
!!! error TS18029: Private identifiers are not allowed in variable declarations.
| |
059221
|
><U>(u: U, update: (u: U) => T) => { const set = (newU: U) => Object.is(u, newU) ? t : update(newU); return Object.assign( <K extends Key<U>>(key: K) => reduce<Value<K, U>>(u[key as keyof U] as Value<K, U>, (v: Value<K, U>) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }); } : <U>(u: U, update: (u: U) => T) => (<K extends Key<U>>(key: K) => (<K_1 extends keyof Value<K, U>>(key: K_1) => (<K_2 extends keyof Value<K_1, Value<K, U>>>(key: K_2) => (<K_3 extends keyof Value<K_2, Value<K_1, Value<K, U>>>>(key: K_3) => (<K_4 extends keyof Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>(key: K_4) => (<K_5 extends keyof Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>(key: K_5) => (<K_6 extends keyof Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>(key: K_6) => (<K_7 extends keyof Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>(key: K_7) => (<K_8 extends keyof Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>(key: K_8) => (<K_9 extends keyof Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>>(key: K_9) => (<K_10 extends keyof Value<K_9, Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value<K_10, Value<K_9, Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>>>) => Value<K_10, Value<K_9, Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>>>) => T; set: (newU: Value<K_10, Value<K_9, Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value<K_9, Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>>) => Value<K_9, Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>>) => T; set: (newU: Value<K_9, Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>>) => T; }) & { map: (updater: (u: Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>) => Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>) => T; set: (newU: Value<K_8, Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>>) => T; }) & { map: (updater: (u: Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>) => Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>) => T; set: (newU: Value<K_7, Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>>) => T; }) & { map: (updater: (u: Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>) => Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>) => T; set: (newU: Value<K_6, Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>>) => T; }) & { map: (updater: (u: Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>) => Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>) => T; set: (newU: Value<K_5, Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>>) => T; }) & { map: (updater: (u: Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>) => Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>) => T; set: (newU: Value<K_4, Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>>) => T; }) & { map: (updater: (u: Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>) => Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>) => T; set: (newU: Value<K_3, Value<K_2, Value<K_1, Value<K, U>>>>) => T; }) & { map: (updater: (u: Value<K_2, Value<K_1, Value<K, U>>>) => Value<K_2, Value<K_1, Value<K, U>>>) => T; set: (newU: Value<K_2, Value<K_1, Value<K, U>>>) => T; }) & { map: (updater: (u: Value<K_1, Value<K, U>>) => Value<K_1, Value<K, U>>) => T; set: (newU: Value<K_1, Value<K, U>>) => T; }) & { map: (updater: (u: Value<K, U>) => Value<K, U>) => T; set: (newU: Value<K, U>) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; }
| |
061198
|
//// [tests/cases/compiler/mappedTypeWithAsClauseAndLateBoundProperty2.ts] ////
//// [mappedTypeWithAsClauseAndLateBoundProperty2.ts]
export const thing = (null! as { [K in keyof number[] as Exclude<K, "length">]: (number[])[K] }) satisfies any;
//// [mappedTypeWithAsClauseAndLateBoundProperty2.js]
export const thing = null;
//// [mappedTypeWithAsClauseAndLateBoundProperty2.d.ts]
export declare const thing: {
[x: number]: number;
toString: () => string;
toLocaleString: {
(): string;
(locales: string | string[], options?: Intl.NumberFormatOptions & Intl.DateTimeFormatOptions): string;
};
pop: () => number;
push: (...items: number[]) => number;
concat: {
(...items: ConcatArray<number>[]): number[];
(...items: (number | ConcatArray<number>)[]): number[];
};
join: (separator?: string) => string;
reverse: () => number[];
shift: () => number;
slice: (start?: number, end?: number) => number[];
sort: (compareFn?: (a: number, b: number) => number) => number[];
splice: {
(start: number, deleteCount?: number): number[];
(start: number, deleteCount: number, ...items: number[]): number[];
};
unshift: (...items: number[]) => number;
indexOf: (searchElement: number, fromIndex?: number) => number;
lastIndexOf: (searchElement: number, fromIndex?: number) => number;
every: {
<S extends number>(predicate: (value: number, index: number, array: number[]) => value is S, thisArg?: any): this is S[];
(predicate: (value: number, index: number, array: number[]) => unknown, thisArg?: any): boolean;
};
some: (predicate: (value: number, index: number, array: number[]) => unknown, thisArg?: any) => boolean;
forEach: (callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any) => void;
map: <U>(callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any) => U[];
filter: {
<S extends number>(predicate: (value: number, index: number, array: number[]) => value is S, thisArg?: any): S[];
(predicate: (value: number, index: number, array: number[]) => unknown, thisArg?: any): number[];
};
reduce: {
(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[]) => number): number;
(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[]) => number, initialValue: number): number;
<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: number[]) => U, initialValue: U): U;
};
reduceRight: {
(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[]) => number): number;
(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[]) => number, initialValue: number): number;
<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: number[]) => U, initialValue: U): U;
};
find: {
<S extends number>(predicate: (value: number, index: number, obj: number[]) => value is S, thisArg?: any): S;
(predicate: (value: number, index: number, obj: number[]) => unknown, thisArg?: any): number;
};
findIndex: (predicate: (value: number, index: number, obj: number[]) => unknown, thisArg?: any) => number;
fill: (value: number, start?: number, end?: number) => number[];
copyWithin: (target: number, start: number, end?: number) => number[];
entries: () => ArrayIterator<[number, number]>;
keys: () => ArrayIterator<number>;
values: () => ArrayIterator<number>;
includes: (searchElement: number, fromIndex?: number) => boolean;
flatMap: <U, This = undefined>(callback: (this: This, value: number, index: number, array: number[]) => U | readonly U[], thisArg?: This) => U[];
flat: <A, D extends number = 1>(this: A, depth?: D) => FlatArray<A, D>[];
[Symbol.iterator]: () => ArrayIterator<number>;
readonly [Symbol.unscopables]: {
[x: number]: boolean;
length?: boolean;
toString?: boolean;
toLocaleString?: boolean;
pop?: boolean;
push?: boolean;
concat?: boolean;
join?: boolean;
reverse?: boolean;
shift?: boolean;
slice?: boolean;
sort?: boolean;
splice?: boolean;
unshift?: boolean;
indexOf?: boolean;
lastIndexOf?: boolean;
every?: boolean;
some?: boolean;
forEach?: boolean;
map?: boolean;
filter?: boolean;
reduce?: boolean;
reduceRight?: boolean;
find?: boolean;
findIndex?: boolean;
fill?: boolean;
copyWithin?: boolean;
entries?: boolean;
keys?: boolean;
values?: boolean;
includes?: boolean;
flatMap?: boolean;
flat?: boolean;
[Symbol.iterator]?: boolean;
readonly [Symbol.unscopables]?: boolean;
};
};
| |
063797
|
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
>forEach : (callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any) => void
> : ^ ^^ ^^ ^^^ ^^^^^
>callbackfn : (value: T, index: number, array: T[]) => void
> : ^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>value : T
> : ^
>index : number
> : ^^^^^^
>array : T[]
> : ^^^
>thisArg : any
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
>map : <U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any) => U[]
> : ^ ^^ ^^ ^^ ^^^ ^^^^^
>callbackfn : (value: T, index: number, array: T[]) => U
> : ^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>value : T
> : ^
>index : number
> : ^^^^^^
>array : T[]
> : ^^^
>thisArg : any
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[];
>filter : (callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any) => T[]
> : ^ ^^ ^^ ^^^ ^^^^^
>callbackfn : (value: T, index: number, array: T[]) => boolean
> : ^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>value : T
> : ^
>index : number
> : ^^^^^^
>array : T[]
> : ^^^
>thisArg : any
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T;
>reduce : { (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; <U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; }
> : ^^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>callbackfn : (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T
> : ^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>previousValue : T
> : ^
>currentValue : T
> : ^
>currentIndex : number
> : ^^^^^^
>array : T[]
> : ^^^
>initialValue : T
> : ^
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
>reduce : { (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; <U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; }
> : ^^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>callbackfn : (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U
> : ^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>previousValue : U
> : ^
>currentValue : T
> : ^
>currentIndex : number
> : ^^^^^^
>array : T[]
> : ^^^
>initialValue : U
> : ^
/**
* Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T;
>reduceRight : { (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; <U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; }
> : ^^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>callbackfn : (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T
> : ^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>previousValue : T
> : ^
>currentValue : T
> : ^
>currentIndex : number
> : ^^^^^^
>array : T[]
> : ^^^
>initialValue : T
> : ^
| |
073389
|
privateNameES5Ban.ts(3,5): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameES5Ban.ts(4,5): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameES5Ban.ts(5,12): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameES5Ban.ts(6,12): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameES5Ban.ts(7,9): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameES5Ban.ts(8,9): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameES5Ban.ts(9,16): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateNameES5Ban.ts(10,16): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
==== privateNameES5Ban.ts (8 errors) ====
class A {
constructor() {}
#field = 123;
~~~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
#method() {}
~~~~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
static #sField = "hello world";
~~~~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
static #sMethod() {}
~~~~~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
get #acc() { return ""; }
~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
set #acc(x: string) {}
~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
static get #sAcc() { return 0; }
~~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
static set #sAcc(x: number) {}
~~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
}
| |
073655
|
//// [tests/cases/compiler/indexedAccessAndNullableNarrowing.ts] ////
=== indexedAccessAndNullableNarrowing.ts ===
function f1<T extends Record<string, any>, K extends keyof T>(x: T[K] | undefined) {
>f1 : <T extends Record<string, any>, K extends keyof T>(x: T[K] | undefined) => void
> : ^ ^^^^^^^^^ ^^ ^^^^^^^^^ ^^ ^^ ^^^^^^^^^
>x : T[K] | undefined
> : ^^^^^^^^^^^^^^^^
if (x === undefined) return;
>x === undefined : boolean
> : ^^^^^^^
>x : T[K] | undefined
> : ^^^^^^^^^^^^^^^^
>undefined : undefined
> : ^^^^^^^^^
x; // T[K] & ({} | null)
>x : T[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^
if (x === undefined) return;
>x === undefined : boolean
> : ^^^^^^^
>x : T[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^
>undefined : undefined
> : ^^^^^^^^^
x; // T[K] & ({} | null)
>x : T[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^
}
function f2<T extends Record<string, any>, K extends keyof T>(x: T[K] | null) {
>f2 : <T extends Record<string, any>, K extends keyof T>(x: T[K] | null) => void
> : ^ ^^^^^^^^^ ^^ ^^^^^^^^^ ^^ ^^ ^^^^^^^^^
>x : T[K] | null
> : ^^^^^^^^^^^
if (x === null) return;
>x === null : boolean
> : ^^^^^^^
>x : T[K] | null
> : ^^^^^^^^^^^
x; // T[K] & ({} | undefined)
>x : T[K] & ({} | undefined)
> : ^^^^^^^^^^^^^^^^^^^^^^^
if (x === null) return;
>x === null : boolean
> : ^^^^^^^
>x : T[K] & ({} | undefined)
> : ^^^^^^^^^^^^^^^^^^^^^^^
x; // T[K] & ({} | undefined)
>x : T[K] & ({} | undefined)
> : ^^^^^^^^^^^^^^^^^^^^^^^
}
function f3<T, K extends keyof T>(t: T[K], p1: Partial<T>[K] & {}, p2: Partial<T>[K] & ({} | null)) {
>f3 : <T, K extends keyof T>(t: T[K], p1: Partial<T>[K] & {}, p2: Partial<T>[K] & ({} | null)) => void
> : ^ ^^ ^^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^^^^^^^
>t : T[K]
> : ^^^^
>p1 : Partial<T>[K] & {}
> : ^^^^^^^^^^^^^^^^^^
>p2 : Partial<T>[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^
t = p1;
>t = p1 : Partial<T>[K] & {}
> : ^^^^^^^^^^^^^^^^^^
>t : T[K]
> : ^^^^
>p1 : Partial<T>[K] & {}
> : ^^^^^^^^^^^^^^^^^^
t = p2;
>t = p2 : Partial<T>[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^
>t : T[K]
> : ^^^^
>p2 : Partial<T>[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
// https://github.com/microsoft/TypeScript/issues/57693
type AnyObject = Record<string, any>;
>AnyObject : AnyObject
> : ^^^^^^^^^
type State = AnyObject;
>State : AnyObject
> : ^^^^^^^^^
declare function hasOwnProperty<T extends AnyObject>(
>hasOwnProperty : <T extends AnyObject>(object: T, prop: PropertyKey) => prop is keyof T
> : ^ ^^^^^^^^^ ^^ ^^ ^^ ^^ ^^^^^
object: T,
>object : T
> : ^
prop: PropertyKey,
>prop : PropertyKey
> : ^^^^^^^^^^^
): prop is keyof T;
interface Store<S = State> {
setState<K extends keyof S>(key: K, value: S[K]): void;
>setState : <K extends keyof S>(key: K, value: S[K]) => void
> : ^ ^^^^^^^^^ ^^ ^^ ^^ ^^ ^^^^^
>key : K
> : ^
>value : S[K]
> : ^^^^
}
export function syncStoreProp<
>syncStoreProp : <S extends State, P extends Partial<S>, K extends keyof S>(store: Store<S>, props: P, key: K) => void
> : ^ ^^^^^^^^^ ^^ ^^^^^^^^^ ^^ ^^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^^^^^^^
S extends State,
P extends Partial<S>,
K extends keyof S,
>(store: Store<S>, props: P, key: K) {
>store : Store<S>
> : ^^^^^^^^
>props : P
> : ^
>key : K
> : ^
const value = hasOwnProperty(props, key) ? props[key] : undefined;
>value : P[K] | undefined
> : ^^^^^^^^^^^^^^^^
>hasOwnProperty(props, key) ? props[key] : undefined : P[K] | undefined
> : ^^^^^^^^^^^^^^^^
>hasOwnProperty(props, key) : boolean
> : ^^^^^^^
>hasOwnProperty : <T extends AnyObject>(object: T, prop: PropertyKey) => prop is keyof T
> : ^ ^^^^^^^^^ ^^ ^^ ^^ ^^ ^^^^^
>props : P
> : ^
>key : string | number | symbol
> : ^^^^^^^^^^^^^^^^^^^^^^^^
>props[key] : P[K]
> : ^^^^
>props : P
> : ^
>key : K
> : ^
>undefined : undefined
> : ^^^^^^^^^
if (value === undefined) return;
>value === undefined : boolean
> : ^^^^^^^
>value : P[K] | undefined
> : ^^^^^^^^^^^^^^^^
>undefined : undefined
> : ^^^^^^^^^
store.setState(key, value);
>store.setState(key, value) : void
> : ^^^^
>store.setState : <K_1 extends keyof S>(key: K_1, value: S[K_1]) => void
> : ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^ ^^^^^^^^^^^^^
>store : Store<S>
> : ^^^^^^^^
>setState : <K_1 extends keyof S>(key: K_1, value: S[K_1]) => void
> : ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^ ^^^^^^^^^^^^^
>key : K
> : ^
>value : P[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^
if (value === undefined) return;
>value === undefined : boolean
> : ^^^^^^^
>value : P[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^
>undefined : undefined
> : ^^^^^^^^^
store.setState(key, value);
>store.setState(key, value) : void
> : ^^^^
>store.setState : <K_1 extends keyof S>(key: K_1, value: S[K_1]) => void
> : ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^ ^^^^^^^^^^^^^
>store : Store<S>
> : ^^^^^^^^
>setState : <K_1 extends keyof S>(key: K_1, value: S[K_1]) => void
> : ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^ ^^^^^^^^^^^^^
>key : K
> : ^
>value : P[K] & ({} | null)
> : ^^^^^^^^^^^^^^^^^^
}
| |
074467
|
a.ts(2,1): error TS1203: Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead.
main.ts(1,20): error TS2497: This module can only be referenced with ECMAScript imports/exports by turning on the 'allowSyntheticDefaultImports' flag and referencing its default export.
==== a.ts (1 errors) ====
class a { }
export = a;
~~~~~~~~~~~
!!! error TS1203: Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead.
==== main.ts (1 errors) ====
import * as a from "./a";
~~~~~
!!! error TS2497: This module can only be referenced with ECMAScript imports/exports by turning on the 'allowSyntheticDefaultImports' flag and referencing its default export.
a;
| |
076015
|
eyJ2ZXJzaW9uIjozLCJmaWxlIjoic291cmNlTWFwVmFsaWRhdGlvbkRlc3RydWN0dXJpbmdGb3JBcnJheUJpbmRpbmdQYXR0ZXJuRGVmYXVsdFZhbHVlcy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInNvdXJjZU1hcFZhbGlkYXRpb25EZXN0cnVjdHVyaW5nRm9yQXJyYXlCaW5kaW5nUGF0dGVybkRlZmF1bHRWYWx1ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBTUEsSUFBSSxNQUFNLEdBQVUsQ0FBQyxDQUFDLEVBQUUsT0FBTyxFQUFFLFFBQVEsQ0FBQyxDQUFDO0FBQzNDLFNBQVMsUUFBUTtJQUNiLE9BQU8sTUFBTSxDQUFDO0FBQ2xCLENBQUM7QUFFRCxJQUFJLFdBQVcsR0FBc0IsQ0FBQyxPQUFPLEVBQUUsQ0FBQyxRQUFRLEVBQUUsRUFBRSxDQUFDLENBQUMsQ0FBQztBQUMvRCxJQUFJLFdBQVcsR0FBc0IsQ0FBQyxTQUFTLEVBQUUsQ0FBQyxVQUFVLEVBQUUsUUFBUSxDQUFDLENBQUMsQ0FBQztBQUN6RSxTQUFTLGFBQWE7SUFDbEIsT0FBTyxXQUFXLENBQUM7QUFDdkIsQ0FBQztBQUVELEtBQVksSUFBQSxLQUFpQixNQUFNLEdBQVYsRUFBYixLQUFLLG1CQUFFLE1BQU0sS0FBQSxFQUFZLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRSxDQUFDO0lBQ3JELE9BQU8sQ0FBQyxHQUFHLENBQUMsS0FBSyxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQUNELEtBQVMsSUFBQSxLQUFxQixRQUFRLEVBQUUsRUFBNUIsVUFBYyxFQUFkLEtBQUssbUJBQUcsTUFBTSxLQUFBLEVBQWdCLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRSxDQUFDO0lBQzFELE9BQU8sQ0FBQyxHQUFHLENBQUMsS0FBSyxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQUNELEtBQVMsSUFBQSxLQUFxQixDQUFDLENBQUMsRUFBRSxTQUFTLEVBQUUsVUFBVSxDQUFDLEVBQTVDLFVBQWMsRUFBZCxLQUFLLG1CQUFHLE1BQU0sS0FBQSxFQUFnQyxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxFQUFFLEVBQUUsQ0FBQztJQUMxRSxPQUFPLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxDQUFDO0FBQ3ZCLENBQUM7QUFDRCxLQUFZLElBQUEsS0FHWSxXQUFXLEdBQWYsRUFIUixxQkFHUixDQUFDLE1BQU0sRUFBRSxNQUFNLENBQUMsS0FBQSxFQUZoQixVQUF5QixFQUF6QixhQUFhLG1CQUFHLFNBQVMsS0FBQSxFQUN6QixVQUE2QixFQUE3QixlQUFlLG1CQUFHLFdBQVcsS0FBQSxFQUNJLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRSxDQUFDO0lBQ3JELE9BQU8sQ0FBQyxHQUFHLENBQUMsYUFBYSxDQUFDLENBQUM7QUFDL0IsQ0FBQztBQUNELEtBQVMsSUFBQSxLQUdlLGFBQWEsRUFBRSxFQUgzQixVQUdRLEVBSFIscUJBR1IsQ0FBQyxNQUFNLEVBQUUsTUFBTSxDQUFDLEtBQUEsRUFGaEIsVUFBeUIsRUFBekIsYUFBYSxtQkFBRyxTQUFTLEtBQUEsRUFDekIsVUFBNkIsRUFBN0IsZUFBZSxtQkFBRyxXQUFXLEtBQUEsRUFDUSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxFQUFFLEVBQUUsQ0FBQztJQUN6RCxPQUFPLENBQUMsR0FBRyxDQUFDLGFBQWEsQ0FBQyxDQUFDO0FBQy9CLENBQUM7QUFDRCxLQUFTLElBQUEsS0FHZSxDQUFDLFNBQVMsRUFBRSxDQUFDLFVBQVUsRUFBRSxRQUFRLENBQUMsQ0FBQyxFQUgvQyxVQUdRLEVBSFIscUJBR1IsQ0FBQyxNQUFNLEVBQUUsTUFBTSxDQUFDLEtBQUEsRUFGaEIsVUFBeUIsRUFBekIsYUFBYSxtQkFBRyxTQUFTLEtBQUEsRUFDekIsVUFBNkIsRUFBN0IsZUFBZSxtQkFBRyxXQUFXLEtBQUEsRUFDNEIsQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsRUFBRSxFQUFFLENBQUM7SUFDN0UsT0FBTyxDQUFDLEdBQUcsQ0FBQyxhQUFhLENBQUMsQ0FBQztBQUMvQixDQUFDO0FBRUQsS0FBVSxJQUFBLEtBQWdCLE1BQU0sR0FBVixFQUFaLE9BQU8sbUJBQUcsQ0FBQyxDQUFDLEtBQUEsRUFBWSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxFQUFFLEVBQUUsQ0FBQztJQUNsRCxPQUFPLENBQUMsR0FBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDO0FBQ3pCLENBQUM7QUFDRCxLQUFVLElBQUEsS0FBZ0IsUUFBUSxFQUFFLEdBQWQsRUFBWixPQUFPLG1CQUFHLENBQUMsQ0FBQyxLQUFBLEVBQWdCLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRSxDQUFDO0lBQ3RELE9BQU8sQ0FBQyxHQUFHLENBQUMsT0FBTyxDQUFDLENBQUM7QUFDekIsQ0FBQztBQUNELEtBQVUsSUFBQSxLQUFnQixDQUFDLENBQUMsRUFBRSxTQUFTLEVBQUUsVUFBVSxDQUFDLEdBQTlCLEVBQVosT0FBTy
| |
078277
|
static filter<R>(dit: typeof Promise, values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
>filter : { <R_1>(dit: typeof Promise, values: Promise.Thenable<Promise.Thenable<R_1>[]>, filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<Promise.Thenable<R_1>[]>, filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R>(dit: typeof Promise, values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1[]>, filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1>[], filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1>[], filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: R_1[], filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: R_1[], filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; }
> : ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>dit : typeof Promise
> : ^^^^^^^^^^^^^^
>Promise : typeof Promise
> : ^^^^^^^^^^^^^^
>values : Promise.Thenable<R[]>
> : ^^^^^^^^^^^^^^^^^^^^^
>Promise : any
> : ^^^
>filterer : (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>
> : ^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>item : R
> : ^
>index : number
> : ^^^^^^
>arrayLength : number
> : ^^^^^^
>Promise : any
> : ^^^
static filter<R>(dit: typeof Promise, values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
>filter : { <R_1>(dit: typeof Promise, values: Promise.Thenable<Promise.Thenable<R_1>[]>, filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<Promise.Thenable<R_1>[]>, filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1[]>, filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R>(dit: typeof Promise, values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1>[], filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1>[], filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: R_1[], filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: R_1[], filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; }
> : ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>dit : typeof Promise
> : ^^^^^^^^^^^^^^
>Promise : typeof Promise
> : ^^^^^^^^^^^^^^
>values : Promise.Thenable<R[]>
> : ^^^^^^^^^^^^^^^^^^^^^
>Promise : any
> : ^^^
>filterer : (item: R, index: number, arrayLength: number) => boolean
> : ^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>item : R
> : ^
>index : number
> : ^^^^^^
>arrayLength : number
> : ^^^^^^
| |
078278
|
static filter<R>(dit: typeof Promise, values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
>filter : { <R_1>(dit: typeof Promise, values: Promise.Thenable<Promise.Thenable<R_1>[]>, filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<Promise.Thenable<R_1>[]>, filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1[]>, filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1[]>, filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R>(dit: typeof Promise, values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1>[], filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: R_1[], filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: R_1[], filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; }
> : ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>dit : typeof Promise
> : ^^^^^^^^^^^^^^
>Promise : typeof Promise
> : ^^^^^^^^^^^^^^
>values : Promise.Thenable<R>[]
> : ^^^^^^^^^^^^^^^^^^^^^
>Promise : any
> : ^^^
>filterer : (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>
> : ^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>item : R
> : ^
>index : number
> : ^^^^^^
>arrayLength : number
> : ^^^^^^
>Promise : any
> : ^^^
static filter<R>(dit: typeof Promise, values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
>filter : { <R_1>(dit: typeof Promise, values: Promise.Thenable<Promise.Thenable<R_1>[]>, filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<Promise.Thenable<R_1>[]>, filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1[]>, filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1[]>, filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: Promise.Thenable<R_1>[], filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R>(dit: typeof Promise, values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>; <R_1>(dit: typeof Promise, values: R_1[], filterer: (item: R_1, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R_1[]>; <R_1>(dit: typeof Promise, values: R_1[], filterer: (item: R_1, index: number, arrayLength: number) => boolean): Promise<R_1[]>; }
> : ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^^^^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>dit : typeof Promise
> : ^^^^^^^^^^^^^^
>Promise : typeof Promise
> : ^^^^^^^^^^^^^^
>values : Promise.Thenable<R>[]
> : ^^^^^^^^^^^^^^^^^^^^^
>Promise : any
> : ^^^
>filterer : (item: R, index: number, arrayLength: number) => boolean
> : ^ ^^ ^^ ^^ ^^ ^^ ^^^^^
>item : R
> : ^
>index : number
> : ^^^^^^
>arrayLength : number
> : ^^^^^^
| |
079199
|
function f15a(o: Thing | undefined, value: unknown) {
if (o?.foo === value) {
o.foo; // Error
}
else {
o.foo; // Error
}
if (o?.foo !== value) {
o.foo; // Error
}
else {
o.foo; // Error
}
if (o?.foo == value) {
o.foo; // Error
}
else {
o.foo; // Error
}
if (o?.foo != value) {
o.foo; // Error
}
else {
o.foo; // Error
}
}
function f16(o: Thing | undefined) {
if (o?.foo === undefined) {
o.foo; // Error
}
else {
o.foo;
}
if (o?.foo !== undefined) {
o.foo;
}
else {
o.foo; // Error
}
if (o?.foo == undefined) {
o.foo; // Error
}
else {
o.foo;
}
if (o?.foo != undefined) {
o.foo;
}
else {
o.foo; // Error
}
}
function f20(o: Thing | undefined) {
if (typeof o?.foo === "number") {
o.foo;
}
if (typeof o?.["foo"] === "number") {
o["foo"];
}
if (typeof o?.bar() === "number") {
o.bar;
}
if (o?.baz instanceof Error) {
o.baz;
}
}
function f21(o: Thing | null) {
if (typeof o?.foo === "number") {
o.foo;
}
if (typeof o?.["foo"] === "number") {
o["foo"];
}
if (typeof o?.bar() === "number") {
o.bar;
}
if (o?.baz instanceof Error) {
o.baz;
}
}
function f22(o: Thing | undefined) {
if (typeof o?.foo === "number") {
o.foo;
}
else {
o.foo; // Error
}
if (typeof o?.foo !== "number") {
o.foo; // Error
}
else {
o.foo;
}
if (typeof o?.foo == "number") {
o.foo;
}
else {
o.foo; // Error
}
if (typeof o?.foo != "number") {
o.foo; // Error
}
else {
o.foo;
}
}
function f23(o: Thing | undefined) {
if (typeof o?.foo === "undefined") {
o.foo; // Error
}
else {
o.foo;
}
if (typeof o?.foo !== "undefined") {
o.foo;
}
else {
o.foo; // Error
}
if (typeof o?.foo == "undefined") {
o.foo; // Error
}
else {
o.foo;
}
if (typeof o?.foo != "undefined") {
o.foo;
}
else {
o.foo; // Error
}
}
declare function assert(x: unknown): asserts x;
declare function assertNonNull<T>(x: T): asserts x is NonNullable<T>;
function f30(o: Thing | undefined) {
if (!!true) {
assert(o?.foo);
o.foo;
}
if (!!true) {
assert(o?.foo === 42);
o.foo;
}
if (!!true) {
assert(typeof o?.foo === "number");
o.foo;
}
if (!!true) {
assertNonNull(o?.foo);
o.foo;
}
}
function f40(o: Thing | undefined) {
switch (o?.foo) {
case "abc":
o.foo;
break;
case 42:
o.foo;
break;
case undefined:
o.foo; // Error
break;
default:
o.foo; // Error
break;
}
}
function f41(o: Thing | undefined) {
switch (typeof o?.foo) {
case "string":
o.foo;
break;
case "number":
o.foo;
break;
case "undefined":
o.foo; // Error
break;
default:
o.foo; // Error
break;
}
}
// Repros from #34570
type Shape =
| { type: 'rectangle', width: number, height: number }
| { type: 'circle', radius: number }
function getArea(shape?: Shape) {
switch (shape?.type) {
case 'circle':
return Math.PI * shape.radius ** 2
case 'rectangle':
return shape.width * shape.height
default:
return 0
}
}
type Feature = {
id: string;
geometry?: {
type: string;
coordinates: number[];
};
};
function extractCoordinates(f: Feature): number[] {
if (f.geometry?.type !== 'test') {
return [];
}
return f.geometry.coordinates;
}
// Repro from #35842
interface SomeObject {
someProperty: unknown;
}
let lastSomeProperty: unknown | undefined;
function someFunction(someOptionalObject: SomeObject | undefined): void {
if (someOptionalObject?.someProperty !== lastSomeProperty) {
console.log(someOptionalObject);
console.log(someOptionalObject.someProperty); // Error
lastSomeProperty = someOptionalObject?.someProperty;
}
}
const someObject: SomeObject = {
someProperty: 42
};
someFunction(someObject);
someFunction(undefined);
// Repro from #35970
let i = 0;
declare const arr: { tag: ("left" | "right") }[];
while (arr[i]?.tag === "left") {
i += 1;
if (arr[i]?.tag === "right") {
console.log("I should ALSO be reachable");
}
}
// Repro from #51941
type Test5 = {
main?: {
childs: Record<string, Test5>;
};
};
function f50(obj: Test5) {
for (const key in obj.main?.childs) {
if (obj.main.childs[key] === obj) {
return obj;
}
}
return null;
}
//// [controlFlowOptionalChain.js]
"use strict";
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
var a;
| |
079250
|
privateFieldAssignabilityFromUnknown.ts(2,3): error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
privateFieldAssignabilityFromUnknown.ts(5,7): error TS2741: Property '#field' is missing in type '{}' but required in type 'Class'.
==== privateFieldAssignabilityFromUnknown.ts (2 errors) ====
export class Class {
#field: any
~~~~~~
!!! error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.
}
const task: Class = {} as unknown;
~~~~
!!! error TS2741: Property '#field' is missing in type '{}' but required in type 'Class'.
!!! related TS2728 privateFieldAssignabilityFromUnknown.ts:2:3: '#field' is declared here.
| |
079599
|
return Promise.resolve<TObj[K]>(obj[key]);
>Promise.resolve<TObj[K]>(obj[key]) : Promise<Awaited<TObj[K]>>
> : ^^^^^^^^^^^^^^^^^^^^^^^^^
>Promise.resolve : { (): Promise<void>; <T>(value: T): Promise<Awaited<T>>; <T>(value: T | PromiseLike<T>): Promise<Awaited<T>>; }
> : ^^^^^^ ^^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^^ ^^^
>Promise : PromiseConstructor
> : ^^^^^^^^^^^^^^^^^^
>resolve : { (): Promise<void>; <T>(value: T): Promise<Awaited<T>>; <T>(value: T | PromiseLike<T>): Promise<Awaited<T>>; }
> : ^^^^^^ ^^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^^ ^^^
>obj[key] : TObj[K]
> : ^^^^^^^
>obj : TObj
> : ^^^^
>key : K
> : ^
}
| |
080348
|
metadataImportType.ts(2,6): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
metadataImportType.ts(3,15): error TS2307: Cannot find module './b' or its corresponding type declarations.
==== metadataImportType.ts (2 errors) ====
export class A {
@test
~~~~
!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`.
b: import('./b').B
~~~~~
!!! error TS2307: Cannot find module './b' or its corresponding type declarations.
}
| |
080414
|
a.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
==== tsconfig.json (0 errors) ====
{ "compilerOptions": {} }
==== a.ts (1 errors) ====
module.exports = 1;
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
| |
082607
|
fixSignatureCaching.ts(9,10): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(284,10): error TS2339: Property 'detectMobileBrowsers' does not exist on type '{}'.
fixSignatureCaching.ts(293,10): error TS2339: Property 'FALLBACK_PHONE' does not exist on type '{}'.
fixSignatureCaching.ts(294,10): error TS2339: Property 'FALLBACK_TABLET' does not exist on type '{}'.
fixSignatureCaching.ts(295,10): error TS2339: Property 'FALLBACK_MOBILE' does not exist on type '{}'.
fixSignatureCaching.ts(301,17): error TS2339: Property 'isArray' does not exist on type 'never'.
fixSignatureCaching.ts(330,74): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(369,10): error TS2339: Property 'findMatch' does not exist on type '{}'.
fixSignatureCaching.ts(387,10): error TS2339: Property 'findMatches' does not exist on type '{}'.
fixSignatureCaching.ts(407,10): error TS2339: Property 'getVersionStr' does not exist on type '{}'.
fixSignatureCaching.ts(408,26): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(431,10): error TS2339: Property 'getVersion' does not exist on type '{}'.
fixSignatureCaching.ts(432,28): error TS2339: Property 'getVersionStr' does not exist on type '{}'.
fixSignatureCaching.ts(433,31): error TS2339: Property 'prepareVersionNo' does not exist on type '{}'.
fixSignatureCaching.ts(443,10): error TS2339: Property 'prepareVersionNo' does not exist on type '{}'.
fixSignatureCaching.ts(458,10): error TS2339: Property 'isMobileFallback' does not exist on type '{}'.
fixSignatureCaching.ts(459,21): error TS2339: Property 'detectMobileBrowsers' does not exist on type '{}'.
fixSignatureCaching.ts(460,18): error TS2339: Property 'detectMobileBrowsers' does not exist on type '{}'.
fixSignatureCaching.ts(463,10): error TS2339: Property 'isTabletFallback' does not exist on type '{}'.
fixSignatureCaching.ts(464,21): error TS2339: Property 'detectMobileBrowsers' does not exist on type '{}'.
fixSignatureCaching.ts(467,10): error TS2339: Property 'prepareDetectionCache' does not exist on type '{}'.
fixSignatureCaching.ts(474,23): error TS2339: Property 'findMatch' does not exist on type '{}'.
fixSignatureCaching.ts(474,38): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(481,22): error TS2339: Property 'findMatch' does not exist on type '{}'.
fixSignatureCaching.ts(481,37): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(489,18): error TS2339: Property 'isMobileFallback' does not exist on type '{}'.
fixSignatureCaching.ts(492,37): error TS2339: Property 'FALLBACK_MOBILE' does not exist on type '{}'.
fixSignatureCaching.ts(495,51): error TS2339: Property 'FALLBACK_PHONE' does not exist on type '{}'.
fixSignatureCaching.ts(498,52): error TS2339: Property 'FALLBACK_TABLET' does not exist on type '{}'.
fixSignatureCaching.ts(501,25): error TS2339: Property 'isTabletFallback' does not exist on type '{}'.
fixSignatureCaching.ts(502,48): error TS2339: Property 'FALLBACK_TABLET' does not exist on type '{}'.
fixSignatureCaching.ts(511,10): error TS2339: Property 'mobileGrade' does not exist on type '{}'.
fixSignatureCaching.ts(636,10): error TS2339: Property 'detectOS' does not exist on type '{}'.
fixSignatureCaching.ts(637,21): error TS2339: Property 'findMatch' does not exist on type '{}'.
fixSignatureCaching.ts(637,36): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(638,18): error TS2339: Property 'findMatch' does not exist on type '{}'.
fixSignatureCaching.ts(638,33): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(641,10): error TS2339: Property 'getDeviceSmallerSide' does not exist on type '{}'.
fixSignatureCaching.ts(707,18): error TS2339: Property 'prepareDetectionCache' does not exist on type '{}'.
fixSignatureCaching.ts(737,18): error TS2339: Property 'prepareDetectionCache' does not exist on type '{}'.
fixSignatureCaching.ts(786,18): error TS2339: Property 'prepareDetectionCache' does not exist on type '{}'.
fixSignatureCaching.ts(808,46): error TS2339: Property 'findMatch' does not exist on type '{}'.
fixSignatureCaching.ts(808,61): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(831,47): error TS2339: Property 'findMatches' does not exist on type '{}'.
fixSignatureCaching.ts(831,64): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(848,39): error TS2339: Property 'detectOS' does not exist on type '{}'.
fixSignatureCaching.ts(872,25): error TS2339: Property 'getVersion' does not exist on type '{}'.
fixSignatureCaching.ts(893,25): error TS2339: Property 'getVersionStr' does not exist on type '{}'.
fixSignatureCaching.ts(915,36): error TS2339: Property 'findMatches' does not exist on type '{}'.
fixSignatureCaching.ts(915,53): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'.
fixSignatureCaching.ts(955,42): error TS2339: Property 'mobileGrade' does not exist on type '{}'.
fixSignatureCaching.ts(964,57): error TS2339: Property 'getDeviceSmallerSide' does not exist on type '{}'.
fixSignatureCaching.ts(978,16): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
fixSignatureCaching.ts(978,42): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
fixSignatureCaching.ts(979,37): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
fixSignatureCaching.ts(980,23): error TS2304: Cannot find name 'define'.
fixSignatureCaching.ts(980,48): error TS2304: Cannot find name 'define'.
fixSignatureCaching.ts(981,16): error TS2304: Cannot find name 'define'.
fixSignatureCaching.ts(983,44): error TS2339: Property 'MobileDetect' does not exist on type 'Window & typeof globalThis'.
| |
083876
|
var flat = _.reduceRight(list, (a, b) => a.concat(b), []);
>flat : number[]
> : ^^^^^^^^
>_.reduceRight(list, (a, b) => a.concat(b), []) : number[]
> : ^^^^^^^^
>_.reduceRight : { <T>(list: T[], iterator: Reducer<T, T>, initialValue?: T, context?: any): T; <T, U>(list: T[], iterator: Reducer<T, U>, initialValue: U, context?: any): U; <T>(list: Dictionary<T>, iterator: Reducer<T, T>, initialValue?: T, context?: any): T; <T, U>(list: Dictionary<T>, iterator: Reducer<T, U>, initialValue: U, context?: any): U; }
> : ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^
>_ : Underscore.Static
> : ^^^^^^^^^^^^^^^^^
>reduceRight : { <T>(list: T[], iterator: Reducer<T, T>, initialValue?: T, context?: any): T; <T, U>(list: T[], iterator: Reducer<T, U>, initialValue: U, context?: any): U; <T>(list: Dictionary<T>, iterator: Reducer<T, T>, initialValue?: T, context?: any): T; <T, U>(list: Dictionary<T>, iterator: Reducer<T, U>, initialValue: U, context?: any): U; }
> : ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^
>list : number[][]
> : ^^^^^^^^^^
>(a, b) => a.concat(b) : (a: number[], b: number[]) => number[]
> : ^ ^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
>a : number[]
> : ^^^^^^^^
>b : number[]
> : ^^^^^^^^
>a.concat(b) : number[]
> : ^^^^^^^^
>a.concat : { (...items: ConcatArray<number>[]): number[]; (...items: (number | ConcatArray<number>)[]): number[]; }
> : ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>a : number[]
> : ^^^^^^^^
>concat : { (...items: ConcatArray<number>[]): number[]; (...items: (number | ConcatArray<number>)[]): number[]; }
> : ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>b : number[]
> : ^^^^^^^^
>[] : undefined[]
> : ^^^^^^^^^^^
var even = _.find([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0);
>even : number
> : ^^^^^^
>_.find([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0) : number
> : ^^^^^^
>_.find : { <T>(list: T[], iterator: Iterator_<T, boolean>, context?: any): T; <T>(list: Dictionary<T>, iterator: Iterator_<T, boolean>, context?: any): T; }
> : ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^
>_ : Underscore.Static
> : ^^^^^^^^^^^^^^^^^
>find : { <T>(list: T[], iterator: Iterator_<T, boolean>, context?: any): T; <T>(list: Dictionary<T>, iterator: Iterator_<T, boolean>, context?: any): T; }
> : ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^
>[1, 2, 3, 4, 5, 6] : number[]
> : ^^^^^^^^
>1 : 1
> : ^
>2 : 2
> : ^
>3 : 3
> : ^
>4 : 4
> : ^
>5 : 5
> : ^
>6 : 6
> : ^
>(num) => num % 2 == 0 : (num: number) => boolean
> : ^ ^^^^^^^^^^^^^^^^^^^^
>num : number
> : ^^^^^^
>num % 2 == 0 : boolean
> : ^^^^^^^
>num % 2 : number
> : ^^^^^^
>num : number
> : ^^^^^^
>2 : 2
> : ^
>0 : 0
> : ^
var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0);
>evens : number[]
> : ^^^^^^^^
>_.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0) : number[]
> : ^^^^^^^^
>_.filter : { <T>(list: T[], iterator: Iterator_<T, boolean>, context?: any): T[]; <T>(list: Dictionary<T>, iterator: Iterator_<T, boolean>, context?: any): T[]; }
> : ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^
>_ : Underscore.Static
> : ^^^^^^^^^^^^^^^^^
>filter : { <T>(list: T[], iterator: Iterator_<T, boolean>, context?: any): T[]; <T>(list: Dictionary<T>, iterator: Iterator_<T, boolean>, context?: any): T[]; }
> : ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^^
>[1, 2, 3, 4, 5, 6] : number[]
> : ^^^^^^^^
>1 : 1
> : ^
>2 : 2
> : ^
>3 : 3
> : ^
>4 : 4
> : ^
>5 : 5
> : ^
>6 : 6
> : ^
>(num) => num % 2 == 0 : (num: number) => boolean
> : ^ ^^^^^^^^^^^^^^^^^^^^
>num : number
> : ^^^^^^
>num % 2 == 0 : boolean
> : ^^^^^^^
>num % 2 : number
> : ^^^^^^
>num : number
> : ^^^^^^
>2 : 2
> : ^
>0 : 0
> : ^
| |
083878
|
_.any([null, 0, 'yes', false]);
>_.any([null, 0, 'yes', false]) : boolean
> : ^^^^^^^
>_.any : { <T>(list: T[], iterator?: Iterator_<T, boolean>, context?: any): boolean; <T>(list: Dictionary<T>, iterator?: Iterator_<T, boolean>, context?: any): boolean; }
> : ^^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^
>_ : Underscore.Static
> : ^^^^^^^^^^^^^^^^^
>any : { <T>(list: T[], iterator?: Iterator_<T, boolean>, context?: any): boolean; <T>(list: Dictionary<T>, iterator?: Iterator_<T, boolean>, context?: any): boolean; }
> : ^^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^
>[null, 0, 'yes', false] : (string | number | false)[]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^
>0 : 0
> : ^
>'yes' : "yes"
> : ^^^^^
>false : false
> : ^^^^^
_.contains([1, 2, 3], 3);
>_.contains([1, 2, 3], 3) : boolean
> : ^^^^^^^
>_.contains : { <T>(list: T[], value: T): boolean; <T>(list: Dictionary<T>, value: T): boolean; }
> : ^^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>_ : Underscore.Static
> : ^^^^^^^^^^^^^^^^^
>contains : { <T>(list: T[], value: T): boolean; <T>(list: Dictionary<T>, value: T): boolean; }
> : ^^^ ^^ ^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^ ^^^ ^^^
>[1, 2, 3] : number[]
> : ^^^^^^^^
>1 : 1
> : ^
>2 : 2
> : ^
>3 : 3
> : ^
>3 : 3
> : ^
_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
>_.invoke([[5, 1, 7], [3, 2, 1]], 'sort') : any[]
> : ^^^^^
>_.invoke : { (list: any[], methodName: string, ...args: any[]): any[]; (list: Dictionary<any>, methodName: string, ...args: any[]): any[]; }
> : ^^^ ^^ ^^ ^^ ^^^^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^^^^ ^^ ^^^ ^^^
>_ : Underscore.Static
> : ^^^^^^^^^^^^^^^^^
>invoke : { (list: any[], methodName: string, ...args: any[]): any[]; (list: Dictionary<any>, methodName: string, ...args: any[]): any[]; }
> : ^^^ ^^ ^^ ^^ ^^^^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^^^^ ^^ ^^^ ^^^
>[[5, 1, 7], [3, 2, 1]] : number[][]
> : ^^^^^^^^^^
>[5, 1, 7] : number[]
> : ^^^^^^^^
>5 : 5
> : ^
>1 : 1
> : ^
>7 : 7
> : ^
>[3, 2, 1] : number[]
> : ^^^^^^^^
>3 : 3
> : ^
>2 : 2
> : ^
>1 : 1
> : ^
>'sort' : "sort"
> : ^^^^^^
var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }];
>stooges : { name: string; age: number; }[]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>[{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }] : { name: string; age: number; }[]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>{ name: 'moe', age: 40 } : { name: string; age: number; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>name : string
> : ^^^^^^
>'moe' : "moe"
> : ^^^^^
>age : number
> : ^^^^^^
>40 : 40
> : ^^
>{ name: 'larry', age: 50 } : { name: string; age: number; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>name : string
> : ^^^^^^
>'larry' : "larry"
> : ^^^^^^^
>age : number
> : ^^^^^^
>50 : 50
> : ^^
>{ name: 'curly', age: 60 } : { name: string; age: number; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>name : string
> : ^^^^^^
>'curly' : "curly"
> : ^^^^^^^
>age : number
> : ^^^^^^
>60 : 60
> : ^^
_.pluck(stooges, 'name');
>_.pluck(stooges, 'name') : any[]
> : ^^^^^
>_.pluck : { (list: any[], propertyName: string): any[]; (list: Dictionary<any>, propertyName: string): any[]; }
> : ^^^ ^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^^ ^^^
>_ : Underscore.Static
> : ^^^^^^^^^^^^^^^^^
>pluck : { (list: any[], propertyName: string): any[]; (list: Dictionary<any>, propertyName: string): any[]; }
> : ^^^ ^^ ^^ ^^ ^^^ ^^^ ^^ ^^ ^^ ^^^ ^^^
>stooges : { name: string; age: number; }[]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>'name' : "name"
> : ^^^^^^
_.max(stooges, (stooge) => stooge.age);
>_.max(stooges, (stooge) => stooge.age) : { name: string; age: number; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>_.max : { <T>(list: T[], iterator?: Iterator_<T, any>, context?: any): T; <T>(list: Dictionary<T>, iterator?: Iterator_<T, any>, context?: any): T; }
> : ^^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^
>_ : Underscore.Static
> : ^^^^^^^^^^^^^^^^^
>max : { <T>(list: T[], iterator?: Iterator_<T, any>, context?: any): T; <T>(list: Dictionary<T>, iterator?: Iterator_<T, any>, context?: any): T; }
> : ^^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^ ^^ ^^ ^^ ^^^ ^^ ^^^ ^^^ ^^^
>stooges : { name: string; age: number; }[]
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>(stooge) => stooge.age : (stooge: { name: string; age: number; }) => number
> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>stooge : { name: string; age: number; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>stooge.age : number
> : ^^^^^^
>stooge : { name: string; age: number; }
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>age : number
> : ^^^^^^
| |
084236
|
a.ts(1,14): error TS2868: Cannot find name 'Bun'. Do you need to install type definitions for Bun? Try `npm i --save-dev @types/bun` and then add 'bun' to the types field in your tsconfig.
==== tsconfig.json (0 errors) ====
{ "compilerOptions": {"types": []} }
==== a.ts (1 errors) ====
const file = Bun.file("/a.ts");
~~~
!!! error TS2868: Cannot find name 'Bun'. Do you need to install type definitions for Bun? Try `npm i --save-dev @types/bun` and then add 'bun' to the types field in your tsconfig.
| |
086417
|
parser509693.ts(1,6): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
parser509693.ts(1,22): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
==== parser509693.ts (2 errors) ====
if (!module.exports) module.exports = "";
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
| |
097481
|
// ==ORIGINAL==
type APIResponse<T> = { success: true, data: T } | { success: false };
function wrapResponse<T>(response: T): APIResponse<T> {
return { success: true, data: response };
}
function /*[#|*/get/*|]*/() {
return Promise.resolve(undefined!).then<APIResponse<{ email: string }>>(d => {
console.log(d);
return wrapResponse(d);
});
}
// ==ASYNC FUNCTION::Convert to async function==
type APIResponse<T> = { success: true, data: T } | { success: false };
function wrapResponse<T>(response: T): APIResponse<T> {
return { success: true, data: response };
}
async function get() {
const d = await Promise.resolve(undefined!);
console.log(d);
const result: APIResponse<{ email: string; }> = wrapResponse(d);
return result;
}
| |
097499
|
// ==ORIGINAL==
function /*[#|*/f/*|]*/(): Promise<void>{
const result = getResult();
return fetch('https://typescriptlang.org').then(({ result }) => { console.log(result) });
}
// ==ASYNC FUNCTION::Convert to async function==
async function f(): Promise<void>{
const result = getResult();
const { result: result_1 } = await fetch('https://typescriptlang.org');
console.log(result_1);
}
| |
097517
|
// ==ORIGINAL==
type APIResponse<T> = { success: true, data: T } | { success: false };
function wrapResponse<T>(response: T): APIResponse<T> {
return { success: true, data: response };
}
function /*[#|*/get/*|]*/() {
return Promise.resolve(undefined!).then<APIResponse<{ email: string }>>(d => wrapResponse(d));
}
// ==ASYNC FUNCTION::Convert to async function==
type APIResponse<T> = { success: true, data: T } | { success: false };
function wrapResponse<T>(response: T): APIResponse<T> {
return { success: true, data: response };
}
async function get() {
const d = await Promise.resolve(undefined!);
const result: APIResponse<{ email: string; }> = wrapResponse(d);
return result;
}
| |
097527
|
// ==ORIGINAL==
type APIResponse<T> = { success: true, data: T } | { success: false };
function /*[#|*/get/*|]*/() {
return Promise
.resolve<APIResponse<{ email: string }>>({ success: true, data: { email: "" } })
.catch<APIResponse<{ email: string }>>(() => ({ success: false }));
}
// ==ASYNC FUNCTION::Convert to async function==
type APIResponse<T> = { success: true, data: T } | { success: false };
async function get() {
try {
return await Promise
.resolve<APIResponse<{ email: string; }>>({ success: true, data: { email: "" } });
} catch {
const result: APIResponse<{ email: string; }> = ({ success: false });
return result;
}
}
| |
097583
|
// ==ORIGINAL==
function /*[#|*/f/*|]*/(): Promise<void>{
const result = getResult();
return fetch('https://typescriptlang.org').then(([result]) => { console.log(result) });
}
// ==ASYNC FUNCTION::Convert to async function==
async function f(): Promise<void>{
const result = getResult();
const [result_1] = await fetch('https://typescriptlang.org');
console.log(result_1);
}
| |
097613
|
// ==ORIGINAL==
type APIResponse<T> = { success: true, data: T } | { success: false };
function wrapResponse<T>(response: T): APIResponse<T> {
return { success: true, data: response };
}
function /*[#|*/get/*|]*/() {
return Promise.resolve(undefined!).then<APIResponse<{ email: string }>>(wrapResponse);
}
// ==ASYNC FUNCTION::Convert to async function==
type APIResponse<T> = { success: true, data: T } | { success: false };
function wrapResponse<T>(response: T): APIResponse<T> {
return { success: true, data: response };
}
async function get() {
const response = await Promise.resolve(undefined!);
const result: APIResponse<{ email: string; }> = wrapResponse(response);
return result;
}
| |
098413
|
currentDirectory:: /home/src/workspaces/project useCaseSensitiveFileNames:: false
Input::
//// [/home/src/tslibs/TS/Lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }
interface ReadonlyArray<T> {}
declare const console: { log(msg: any): void; };
/home/src/tslibs/TS/Lib/tsc.js --help --all
Output::
tsc: The TypeScript Compiler - Version FakeTSVersion
[1mALL COMPILER OPTIONS[22m
### Command-line Options
[94m--all[39m
Show all compiler options.
[94m--build, -b[39m
Build one or more projects and their dependencies, if out of date
[94m--help, -h[39m
Print this message.
[94m--help, -?[39m
[94m--init[39m
Initializes a TypeScript project and creates a tsconfig.json file.
[94m--listFilesOnly[39m
Print names of files that are part of the compilation and then stop processing.
[94m--locale[39m
Set the language of the messaging from TypeScript. This does not affect emit.
[94m--project, -p[39m
Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
[94m--showConfig[39m
Print the final configuration instead of building.
[94m--version, -v[39m
Print the compiler's version.
[94m--watch, -w[39m
Watch input files.
### Modules
[94m--allowArbitraryExtensions[39m
Enable importing files with any extension, provided a declaration file is present.
type: boolean
default: false
[94m--allowImportingTsExtensions[39m
Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set.
type: boolean
default: false
[94m--allowUmdGlobalAccess[39m
Allow accessing UMD globals from modules.
type: boolean
default: false
[94m--baseUrl[39m
Specify the base directory to resolve non-relative module names.
[94m--customConditions[39m
Conditions to set in addition to the resolver-specific defaults when resolving imports.
[94m--module, -m[39m
Specify what module code is generated.
one of: none, commonjs, amd, umd, system, es6/es2015, es2020, es2022, esnext, node16, nodenext, preserve
default: undefined
[94m--moduleResolution[39m
Specify how TypeScript looks up a file from a given module specifier.
one of: classic, node10, node16, nodenext, bundler
default: module === `AMD` or `UMD` or `System` or `ES6`, then `Classic`, Otherwise `Node`
[94m--moduleSuffixes[39m
List of file name suffixes to search when resolving a module.
[94m--noResolve[39m
Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project.
type: boolean
default: false
[94m--noUncheckedSideEffectImports[39m
Check side effect imports.
type: boolean
default: false
[94m--paths[39m
Specify a set of entries that re-map imports to additional lookup locations.
default: undefined
[94m--resolveJsonModule[39m
Enable importing .json files.
type: boolean
default: false
[94m--resolvePackageJsonExports[39m
Use the package.json 'exports' field when resolving package imports.
type: boolean
default: `true` when 'moduleResolution' is 'node16', 'nodenext', or 'bundler'; otherwise `false`.
[94m--resolvePackageJsonImports[39m
Use the package.json 'imports' field when resolving imports.
type: boolean
default: `true` when 'moduleResolution' is 'node16', 'nodenext', or 'bundler'; otherwise `false`.
[94m--rewriteRelativeImportExtensions[39m
Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files.
type: boolean
default: false
[94m--rootDir[39m
Specify the root folder within your source files.
type: string
default: Computed from the list of input files
[94m--rootDirs[39m
Allow multiple folders to be treated as one when resolving modules.
one or more: string
default: Computed from the list of input files
[94m--typeRoots[39m
Specify multiple folders that act like './node_modules/@types'.
[94m--types[39m
Specify type package names to be included without being referenced in a source file.
### JavaScript Support
[94m--allowJs[39m
Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files.
type: boolean
default: false
[94m--checkJs[39m
Enable error reporting in type-checked JavaScript files.
type: boolean
default: false
[94m--maxNodeModuleJsDepth[39m
Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'.
type: number
default: 0
### Interop Constraints
[94m--allowSyntheticDefaultImports[39m
Allow 'import x from y' when a module doesn't have a default export.
type: boolean
default: module === "system" or esModuleInterop
[94m--esModuleInterop[39m
Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility.
type: boolean
default: false
[94m--forceConsistentCasingInFileNames[39m
Ensure that casing is correct in imports.
type: boolean
default: true
[94m--isolatedDeclarations[39m
Require sufficient annotation on exports so other tools can trivially generate declaration files.
type: boolean
default: false
[94m--isolatedModules[39m
Ensure that each file can be safely transpiled without relying on other imports.
type: boolean
default: false
[94m--preserveSymlinks[39m
Disable resolving symlinks to their realpath. This correlates to the same flag in node.
type: boolean
default: false
[94m--verbatimModuleSyntax[39m
Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting.
type: boolean
default: false
### Type Checking
[94m--allowUnreachableCode[39m
Disable error reporting for unreachable code.
type: boolean
default: undefined
[94m--allowUnusedLabels[39m
Disable error reporting for unused labels.
type: boolean
default: undefined
[94m--alwaysStrict[39m
Ensure 'use strict' is always emitted.
type: boolean
default: `false`, unless `strict` is set
[94m--exactOptionalPropertyTypes[39m
Interpret optional property types as written, rather than adding 'undefined'.
type: boolean
default: false
[94m--noFallthroughCasesInSwitch[39m
Enable error reporting for fallthrough cases in switch statements.
type: boolean
default: false
[94m--noImplicitAny[39m
Enable error reporting for expressions and declarations with an implied 'any' type.
type: boolean
default: `false`, unless `strict` is set
[94m--noImplicitOverride[39m
Ensure overriding members in derived classes are marked with an override modifier.
type: boolean
default: false
[94m--noImplicitReturns[39m
Enable error reporting for codepaths that do not explicitly return in a function.
type: boolean
default: false
[94m--noImplicitThis[39m
Enable error reporting when 'this' is given the type 'any'.
type: boolean
default: `false`, unless `strict` is set
[94m--noPropertyAccessFromIndexSignature[39m
Enforces using indexed accessors for keys declared using an indexed type.
type: boolean
default: false
[94m--noUncheckedIndexedAccess[39m
Add 'undefined' to a type when accessed using an index.
type: boolean
default: false
[94m--noUnusedLocals[39m
Enable error reporting when local variables aren't read.
type: boolean
default: false
[94m--noUnusedParameters[
| |
109488
|
WatchInfo: /user/username/projects/myproject/package.json 2000 undefined File location affecting resolution
FileWatcher:: Close:: WatchInfo: /user/username/projects/package.json 2000 undefined File location affecting resolution
FileWatcher:: Close:: WatchInfo: /user/username/projects/myproject/node_modules/@types/node/ts3.6/package.json 2000 undefined File location affecting resolution
[96mworker.ts[0m:[93m1[0m:[93m1[0m - [91merror[0m[90m TS2580: [0mCannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
[7m1[0m process.on("uncaughtException");
[7m [0m [91m~~~~~~~[0m
[[90mHH:MM:SS AM[0m] Found 1 error. Watching for file changes.
//// [/user/username/projects/myproject/worker.js] file written with same contents
PolledWatches::
/user/username/projects/node_modules/@types:
{"pollingInterval":500}
PolledWatches *deleted*::
/user/username/projects/myproject/node_modules/@types/node/package.json:
{"pollingInterval":2000}
/user/username/projects/myproject/node_modules/@types/node/ts3.6/package.json:
{"pollingInterval":2000}
/user/username/projects/myproject/node_modules/@types/package.json:
{"pollingInterval":2000}
/user/username/projects/myproject/node_modules/package.json:
{"pollingInterval":2000}
/user/username/projects/myproject/package.json:
{"pollingInterval":2000}
/user/username/projects/package.json:
{"pollingInterval":2000}
FsWatches::
/home/src/tslibs/TS/Lib/lib.d.ts:
{}
/user/username/projects/myproject/tsconfig.json:
{}
/user/username/projects/myproject/worker.ts:
{}
FsWatches *deleted*::
/user/username/projects/myproject/node_modules/@types/node/base.d.ts:
{}
/user/username/projects/myproject/node_modules/@types/node/globals.d.ts:
{}
/user/username/projects/myproject/node_modules/@types/node/index.d.ts:
{}
/user/username/projects/myproject/node_modules/@types/node/ts3.6/base.d.ts:
{}
FsWatchesRecursive::
/user/username/projects/myproject:
{}
/user/username/projects/myproject/node_modules:
{}
/user/username/projects/myproject/node_modules/@types:
{}
Program root files: [
"/user/username/projects/myproject/worker.ts"
]
Program options: {
"watch": true,
"extendedDiagnostics": true,
"configFilePath": "/user/username/projects/myproject/tsconfig.json"
}
Program structureReused: Not
Program files::
/home/src/tslibs/TS/Lib/lib.d.ts
/user/username/projects/myproject/worker.ts
Semantic diagnostics in builder refreshed for::
/home/src/tslibs/TS/Lib/lib.d.ts
/user/username/projects/myproject/worker.ts
Shape signatures in builder refreshed for::
/user/username/projects/myproject/worker.ts (computed .d.ts)
exitCode:: ExitStatus.undefined
Change:: npm ci step two: create atTypes but something else in the @types folder
Input::
//// [/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts]
export const foo = 10;
Output::
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
Scheduling update
Scheduling invalidateFailedLookup
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
Scheduling invalidateFailedLookup, Cancelled earlier one
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
Scheduling update
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
Scheduling update
Scheduling invalidateFailedLookup, Cancelled earlier one
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
Scheduling invalidateFailedLookup, Cancelled earlier one
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
Scheduling update
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha/index.d.ts :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
Scheduling update
Scheduling invalidateFailedLookup, Cancelled earlier one
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha/index.d.ts :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha/index.d.ts :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
Scheduling invalidateFailedLookup, Cancelled earlier one
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha/index.d.ts :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha/index.d.ts :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
Scheduling update
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/mocha/index.d.ts :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
Timeout callback:: count: 2
42: timerToInvalidateFailedLookupResolutions *new*
43: timerToUpdateProgram *new*
Before running Timeout callback:: count: 2
42: timerToInvalidateFailedLookupResolutions
43: timerToUpdateProgram
Host is moving to new time
After running Timeout callback:: count: 0
Output::
Reloading new file names and options
Synchronizing program
[[90mHH:MM:SS AM[0m] File change detected. Starting incremental compilation...
CreatingProgramWith::
roots: ["/user/username/projects/myproject/worker.ts"]
options: {"watch":true,"extendedDiagnostics":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"}
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types/mocha/index.d.ts 250 undefined Source file
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types/mocha/package.json 2000 undefined File location affecting resolution
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types/package.json 2000 undefined File location affecting resolution
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/package.json 2000 undefined File location affecting resolution
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/package.json 2000 undefined File location affecting resolution
FileWatcher:: Added:: WatchInfo: /user/username/projects/package.json 2000 undefined File location affecting resolution
[96mworker.ts[0m:[93m1[0m:[93m1[0
| |
109489
|
m - [91merror[0m[90m TS2580: [0mCannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
[7m1[0m process.on("uncaughtException");
[7m [0m [91m~~~~~~~[0m
[[90mHH:MM:SS AM[0m] Found 1 error. Watching for file changes.
PolledWatches::
/user/username/projects/myproject/node_modules/@types/mocha/package.json: *new*
{"pollingInterval":2000}
/user/username/projects/myproject/node_modules/@types/package.json: *new*
{"pollingInterval":2000}
/user/username/projects/myproject/node_modules/package.json: *new*
{"pollingInterval":2000}
/user/username/projects/myproject/package.json: *new*
{"pollingInterval":2000}
/user/username/projects/node_modules/@types:
{"pollingInterval":500}
/user/username/projects/package.json: *new*
{"pollingInterval":2000}
FsWatches::
/home/src/tslibs/TS/Lib/lib.d.ts:
{}
/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts: *new*
{}
/user/username/projects/myproject/tsconfig.json:
{}
/user/username/projects/myproject/worker.ts:
{}
FsWatchesRecursive::
/user/username/projects/myproject:
{}
/user/username/projects/myproject/node_modules:
{}
/user/username/projects/myproject/node_modules/@types:
{}
Program root files: [
"/user/username/projects/myproject/worker.ts"
]
Program options: {
"watch": true,
"extendedDiagnostics": true,
"configFilePath": "/user/username/projects/myproject/tsconfig.json"
}
Program structureReused: SafeModules
Program files::
/home/src/tslibs/TS/Lib/lib.d.ts
/user/username/projects/myproject/worker.ts
/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts
Semantic diagnostics in builder refreshed for::
/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts
Shape signatures in builder refreshed for::
/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts (used version)
exitCode:: ExitStatus.undefined
Change:: npm ci step three: create atTypes node folder
Input::
Output::
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
Scheduling update
Scheduling invalidateFailedLookup
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
Scheduling invalidateFailedLookup, Cancelled earlier one
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
Scheduling update
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
Timeout callback:: count: 2
46: timerToInvalidateFailedLookupResolutions *new*
47: timerToUpdateProgram *new*
Before running Timeout callback:: count: 2
46: timerToInvalidateFailedLookupResolutions
47: timerToUpdateProgram
Host is moving to new time
After running Timeout callback:: count: 0
Output::
Reloading new file names and options
Synchronizing program
[[90mHH:MM:SS AM[0m] File change detected. Starting incremental compilation...
CreatingProgramWith::
roots: ["/user/username/projects/myproject/worker.ts"]
options: {"watch":true,"extendedDiagnostics":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"}
DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/node_modules 1 undefined Failed Lookup Locations
Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/node_modules 1 undefined Failed Lookup Locations
[91merror[0m[90m TS2688: [0mCannot find type definition file for 'node'.
The file is in the program because:
Entry point for implicit type library 'node'
[[90mHH:MM:SS AM[0m] Found 1 error. Watching for file changes.
PolledWatches::
/user/username/projects/myproject/node_modules/@types/mocha/package.json:
{"pollingInterval":2000}
/user/username/projects/myproject/node_modules/@types/package.json:
{"pollingInterval":2000}
/user/username/projects/myproject/node_modules/package.json:
{"pollingInterval":2000}
/user/username/projects/myproject/package.json:
{"pollingInterval":2000}
/user/username/projects/node_modules: *new*
{"pollingInterval":500}
/user/username/projects/node_modules/@types:
{"pollingInterval":500}
/user/username/projects/package.json:
{"pollingInterval":2000}
FsWatches::
/home/src/tslibs/TS/Lib/lib.d.ts:
{}
/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts:
{}
/user/username/projects/myproject/tsconfig.json:
{}
/user/username/projects/myproject/worker.ts:
{}
FsWatchesRecursive::
/user/username/projects/myproject:
{}
/user/username/projects/myproject/node_modules:
{}
/user/username/projects/myproject/node_modules/@types:
{}
Program root files: [
"/user/username/projects/myproject/worker.ts"
]
Program options: {
"watch": true,
"extendedDiagnostics": true,
"configFilePath": "/user/username/projects/myproject/tsconfig.json"
}
Program structureReused: SafeModules
Program files::
/home/src/tslibs/TS/Lib/lib.d.ts
/user/username/projects/myproject/worker.ts
/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts
Semantic diagnostics in builder refreshed for::
No shapes updated in the builder::
exitCode:: ExitStatus.undefined
Change:: npm ci step four: create atTypes write all the files but dont invoke watcher for index.d.ts
Input::
//// [/user/username/projects/myproject/node_modules/@types/node/base.d.ts]
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript:
/// <reference path="ts3.6/base.d.ts" />
//// [/user/username/projects/myproject/node_modules/@types/node/index.d.ts]
/// <reference path="base.d.ts" />
//// [/user/username/projects/myproject/node_modules/@types/node/ts3.6/base.d.ts]
/// <reference path="../globals.d.ts" />
//// [/user/username/projects/myproject/node_modules/@types/node/globals.d.ts]
declare var process: NodeJS.Process;
declare namespace NodeJS {
interface Process {
on(msg: string): void;
}
}
Output::
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node/base.d.ts :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
Scheduling update
Scheduling invalidateFailedLookup
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node/base.d.ts :: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node/base.d.ts :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
Scheduling invalidateFailedLookup, Cancelled earlier one
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node/base.d.ts :: WatchInfo: /user/username/projects/myproject/node_modules 1 undefined Failed Lookup Locations
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node/base.d.ts :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
Scheduling update
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node/base.d.ts :: WatchInfo: /user/username/projects/myproject 1 undefined Wild card directory
DirectoryWatcher:: Triggered with /user/username/projects/myproject/node_modules/@types/node/ts3.6 :: WatchInfo: /user
| |
109726
|
currentDirectory:: /user/username/workspace/solution/projects/projectc useCaseSensitiveFileNames:: false
Input::
//// [/user/username/workspace/solution/projects/project/app.ts]
let x = 1
//// [/user/username/workspace/solution/projects/project/tsconfig.json]
{
"compilerOptions": {
"types": [
"node"
],
"typeRoots": []
}
}
//// [/user/username/workspace/solution/projects/project/node_modules/@types/node/index.d.ts]
declare var process: any
//// [/home/src/tslibs/TS/Lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }
interface ReadonlyArray<T> {}
declare const console: { log(msg: any): void; };
/home/src/tslibs/TS/Lib/tsc.js -w -p /user/username/workspace/solution/projects/project/tsconfig.json
Output::
>> Screen clear
[[90mHH:MM:SS AM[0m] Starting compilation in watch mode...
[91merror[0m[90m TS2688: [0mCannot find type definition file for 'node'.
The file is in the program because:
Entry point of type library 'node' specified in compilerOptions
[96m../project/tsconfig.json[0m:[93m4[0m:[93m7[0m
[7m4[0m "node"
[7m [0m [96m ~~~~~~[0m
File is entry point of type library specified here.
[[90mHH:MM:SS AM[0m] Found 1 error. Watching for file changes.
//// [/user/username/workspace/solution/projects/project/app.js]
var x = 1;
FsWatches::
/home/src/tslibs/TS/Lib/lib.d.ts: *new*
{}
/user/username/workspace/solution/projects/project/app.ts: *new*
{}
/user/username/workspace/solution/projects/project/tsconfig.json: *new*
{}
FsWatchesRecursive::
/user/username/workspace/solution/projects/project: *new*
{}
Program root files: [
"/user/username/workspace/solution/projects/project/app.ts"
]
Program options: {
"types": [
"node"
],
"typeRoots": [],
"watch": true,
"project": "/user/username/workspace/solution/projects/project/tsconfig.json",
"configFilePath": "/user/username/workspace/solution/projects/project/tsconfig.json"
}
Program structureReused: Not
Program files::
/home/src/tslibs/TS/Lib/lib.d.ts
/user/username/workspace/solution/projects/project/app.ts
No cached semantic diagnostics in the builder::
Shape signatures in builder refreshed for::
/home/src/tslibs/ts/lib/lib.d.ts (used version)
/user/username/workspace/solution/projects/project/app.ts (used version)
exitCode:: ExitStatus.undefined
| |
112074
|
### TypeScript
#### Typing
Avoid `any` where possible. If you find yourself using `any`, consider whether a generic may be
appropriate in your case.
For methods and properties that are part of a component's public API, all types must be explicitly
specified because our documentation tooling cannot currently infer types in places where TypeScript
can.
#### Fluent APIs
When creating a fluent or builder-pattern style API, use the `this` return type for methods:
```
class ConfigBuilder {
withName(name: string): this {
this.config.name = name;
return this;
}
}
```
#### Access modifiers
* Omit the `public` keyword as it is the default behavior.
* Use `private` when appropriate and possible, prefixing the name with an underscore.
* Use `protected` when appropriate and possible with no prefix.
* Prefix *library-internal* properties and methods with an underscore without using the `private`
keyword. This is necessary for anything that must be public (to be used by Angular), but should not
be part of the user-facing API. This typically applies to symbols used in template expressions,
`@ViewChildren` / `@ContentChildren` properties, host bindings, and `@Input` / `@Output` properties
(when using an alias).
Additionally, the `@docs-private` JsDoc annotation can be used to hide any symbol from the public
API docs.
#### Getters and Setters
* Only use getters and setters for `@Input` properties or when otherwise required for API
compatibility.
* Avoid long or complex getters and setters. If the logic of an accessor would take more than
three lines, introduce a new method to contain the logic.
* A getter should immediately precede its corresponding setter.
* Decorators such as `@Input` should be applied to the getter and not the setter.
* Always use a `readonly` property instead of a getter (with no setter) when possible.
```ts
/** YES */
readonly active: boolean;
/** NO */
get active(): boolean {
// Using a getter solely to make the property read-only.
return this._active;
}
```
#### JsDoc comments
All public APIs must have user-facing comments. These are extracted and shown in the documentation
on [material.angular.io](https://material.angular.io).
Private and internal APIs should have JsDoc when they are not obvious. Ultimately it is the purview
of the code reviewer as to what is "obvious", but the rule of thumb is that *most* classes,
properties, and methods should have a JsDoc description.
Properties should have a concise description of what the property means:
```ts
/** The label position relative to the checkbox. Defaults to 'after' */
@Input() labelPosition: 'before' | 'after' = 'after';
```
Methods blocks should describe what the function does and provide a description for each parameter
and the return value:
```ts
/**
* Opens a modal dialog containing the given component.
* @param component Type of the component to load into the dialog.
* @param config Dialog configuration options.
* @returns Reference to the newly-opened dialog.
*/
open<T>(component: ComponentType<T>, config?: MatDialogConfig): MatDialogRef<T> { ... }
```
Boolean properties and return values should use "Whether..." as opposed to "True if...":
```ts
/** Whether the button is disabled. */
disabled: boolean = false;
```
#### Try-Catch
Avoid `try-catch` blocks, instead preferring to prevent an error from being thrown in the first
place. When impossible to avoid, the `try-catch` block must include a comment that explains the
specific error being caught and why it cannot be prevented.
#### Naming
##### General
* Prefer writing out words instead of using abbreviations.
* Prefer *exact* names to short names (within reason). E.g., `labelPosition` is better than
`align` because the former much more exactly communicates what the property means.
* Except for `@Input` properties, use `is` and `has` prefixes for boolean properties / methods.
##### Observables
* Don't suffix observables with `$`.
##### Classes
Classes should be named based on what they're responsible for. Names should capture what the code
*does*, not how it is used:
```
/** NO: */
class RadioService { }
/** YES: */
class UniqueSelectionDispatcher { }
```
Avoid suffixing a class with "Service", as it communicates nothing about what the class does. Try to
think of the class name as a person's job title.
Classes that correspond to a directive with an `mat-` prefix should also be prefixed with `Mat`.
CDK classes should only have a `Cdk` prefix when the class is a directive with a `cdk` selector
prefix.
##### Methods
The name of a method should capture the action that is performed *by* that method rather than
describing when the method will be called. For example,
```ts
/** AVOID: does not describe what the function does. */
handleClick() {
// ...
}
/** PREFER: describes the action performed by the function. */
activateRipple() {
// ...
}
```
##### Selectors
* Component selectors should be lowercase and delimited by hyphens. Components should use element
selectors except when the component API uses a native HTML element.
* Directive selectors should be camel cased. Exceptions may be made for directives that act like a
component but would have an empty template, or when the directive is intended to match some
existing attribute.
#### Inheritance
Avoid using inheritance to apply reusable behaviors to multiple components. This limits how many
behaviors can be composed. Instead, [TypeScript mixins][ts-mixins] can be used to compose multiple
common behaviors into a single component.
#### Coercion
Component and directive inputs for boolean and number values must use an input transform function
to coerce values to the expected type.
For example:
```ts
import {Input, booleanAttribute} from '@angular/core';
@Input({transform: booleanAttribute}) disabled: boolean = false;
```
The above code allows users to set `disabled` similar to how it can be set on native inputs:
```html
<component disabled></component>
```
#### Expose native inputs
Native inputs used in components should be exposed to developers through `ng-content`. This allows
developers to interact directly with the input and allows us to avoid providing custom
implementations for all the input's native behaviors.
For example:
**Do:**
Implementation
```html
<ng-content></ng-content>
```
Usage
```html
<your-component>
<input>
</your-component>
```
**Don't:**
Implementation
```html
<input>
```
Usage
```html
<component></component>
```
### Angular
#### Host bindings
Prefer using the `host` object in the directive configuration instead of `@HostBinding` and
`@HostListener`. We do this because TypeScript preserves the type information of methods with
decorators, and when one of the arguments for the method is a native `Event` type, this preserved
type information can lead to runtime errors in non-browser environments (e.g., server-side
pre-rendering).
| |
112228
|
emTitle>;
toggle(): void;
_toggleOnInteraction(): void;
togglePosition: MatListOptionTogglePosition;
// (undocumented)
_unscopedContent: ElementRef<HTMLSpanElement>;
get value(): any;
set value(newValue: any);
// (undocumented)
static ɵcmp: i0.ɵɵComponentDeclaration<MatListOption, "mat-list-option", ["matListOption"], { "togglePosition": { "alias": "togglePosition"; "required": false; }; "checkboxPosition": { "alias": "checkboxPosition"; "required": false; }; "color": { "alias": "color"; "required": false; }; "value": { "alias": "value"; "required": false; }; "selected": { "alias": "selected"; "required": false; }; }, { "selectedChange": "selectedChange"; }, ["_lines", "_titles"], ["[matListItemAvatar],[matListItemIcon]", "[matListItemTitle]", "[matListItemLine]", "*", "mat-divider"], true, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<MatListOption, never>;
}
// @public
type MatListOptionTogglePosition = 'before' | 'after';
export { MatListOptionTogglePosition as MatListOptionCheckboxPosition }
export { MatListOptionTogglePosition }
// @public
export class MatListSubheaderCssMatStyler {
// (undocumented)
static ɵdir: i0.ɵɵDirectiveDeclaration<MatListSubheaderCssMatStyler, "[mat-subheader], [matSubheader]", never, {}, {}, never, never, true, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<MatListSubheaderCssMatStyler, never>;
}
// @public (undocumented)
export class MatNavList extends MatListBase {
// (undocumented)
_isNonInteractive: boolean;
// (undocumented)
static ɵcmp: i0.ɵɵComponentDeclaration<MatNavList, "mat-nav-list", ["matNavList"], {}, {}, never, ["*"], true, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<MatNavList, never>;
}
// @public (undocumented)
export class MatSelectionList extends MatListBase implements SelectionList, ControlValueAccessor, AfterViewInit, OnChanges, OnDestroy {
constructor(...args: unknown[]);
color: ThemePalette;
compareWith: (o1: any, o2: any) => boolean;
deselectAll(): MatListOption[];
get disabled(): boolean;
set disabled(value: BooleanInput);
// (undocumented)
_element: ElementRef<HTMLElement>;
_emitChangeEvent(options: MatListOption[]): void;
focus(options?: FocusOptions): void;
_handleKeydown(event: KeyboardEvent): void;
get hideSingleSelectionIndicator(): boolean;
set hideSingleSelectionIndicator(value: BooleanInput);
// (undocumented)
_items: QueryList<MatListOption>;
get multiple(): boolean;
set multiple(value: BooleanInput);
// (undocumented)
ngAfterViewInit(): void;
// (undocumented)
ngOnChanges(changes: SimpleChanges): void;
// (undocumented)
ngOnDestroy(): void;
_onTouched: () => void;
get options(): QueryList<MatListOption>;
registerOnChange(fn: (value: any) => void): void;
registerOnTouched(fn: () => void): void;
_reportValueChange(): void;
selectAll(): MatListOption[];
selectedOptions: SelectionModel<MatListOption>;
readonly selectionChange: EventEmitter<MatSelectionListChange>;
setDisabledState(isDisabled: boolean): void;
_value: string[] | null;
writeValue(values: string[]): void;
// (undocumented)
static ɵcmp: i0.ɵɵComponentDeclaration<MatSelectionList, "mat-selection-list", ["matSelectionList"], { "color": { "alias": "color"; "required": false; }; "compareWith": { "alias": "compareWith"; "required": false; }; "multiple": { "alias": "multiple"; "required": false; }; "hideSingleSelectionIndicator": { "alias": "hideSingleSelectionIndicator"; "required": false; }; "disabled": { "alias": "disabled"; "required": false; }; }, { "selectionChange": "selectionChange"; }, ["_items"], ["*"], true, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<MatSelectionList, never>;
}
// @public
export class MatSelectionListChange {
constructor(
source: MatSelectionList,
options: MatListOption[]);
options: MatListOption[];
source: MatSelectionList;
}
// @public
export const SELECTION_LIST: InjectionToken<SelectionList>;
// @public
export interface SelectionList extends MatListBase {
// (undocumented)
color: ThemePalette;
// (undocumented)
compareWith: (o1: any, o2: any) => boolean;
// (undocumented)
_emitChangeEvent(options: MatListOption[]): void;
// (undocumented)
hideSingleSelectionIndicator: boolean;
// (undocumented)
multiple: boolean;
// (undocumented)
_onTouched(): void;
// (undocumented)
_reportValueChange(): void;
// (undocumented)
selectedOptions: SelectionModel<MatListOption>;
// (undocumented)
_value: string[] | null;
}
// (No @packageDocumentation comment for this package)
```
| |
112393
|
"@ampproject/[email protected]", "@ampproject/remapping@^2.2.0":
version "2.3.0"
resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.3.0.tgz#ed441b6fa600072520ce18b43d2c8cc8caecc7f4"
integrity sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==
dependencies:
"@jridgewell/gen-mapping" "^0.3.5"
"@jridgewell/trace-mapping" "^0.3.24"
"@angular-devkit/[email protected]":
version "0.1900.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/architect/-/architect-0.1900.0-next.3.tgz#1e35eb39a11a93127001f53455e3377cbe8b8a83"
integrity sha512-uEVpjcojOPWfLfpjCqmbO/nphBbOIo+qBwruOiUv9WACSXown+GMYPvQSIkeuLdpQTKSGETjegEKs09VWgwomA==
dependencies:
"@angular-devkit/core" "19.0.0-next.3"
rxjs "7.8.1"
"@angular-devkit/build-angular@file:../../node_modules/@angular-devkit/build-angular":
version "19.0.0-next.3"
dependencies:
"@ampproject/remapping" "2.3.0"
"@angular-devkit/architect" "0.1900.0-next.3"
"@angular-devkit/build-webpack" "0.1900.0-next.3"
"@angular-devkit/core" "19.0.0-next.3"
"@angular/build" "19.0.0-next.3"
"@babel/core" "7.25.2"
"@babel/generator" "7.25.6"
"@babel/helper-annotate-as-pure" "7.24.7"
"@babel/helper-split-export-declaration" "7.24.7"
"@babel/plugin-transform-async-generator-functions" "7.25.4"
"@babel/plugin-transform-async-to-generator" "7.24.7"
"@babel/plugin-transform-runtime" "7.25.4"
"@babel/preset-env" "7.25.4"
"@babel/runtime" "7.25.6"
"@discoveryjs/json-ext" "0.6.1"
"@ngtools/webpack" "19.0.0-next.3"
"@vitejs/plugin-basic-ssl" "1.1.0"
ansi-colors "4.1.3"
autoprefixer "10.4.20"
babel-loader "9.1.3"
browserslist "^4.21.5"
copy-webpack-plugin "12.0.2"
critters "0.0.24"
css-loader "7.1.2"
esbuild-wasm "0.23.1"
fast-glob "3.3.2"
http-proxy-middleware "3.0.2"
https-proxy-agent "7.0.5"
istanbul-lib-instrument "6.0.3"
jsonc-parser "3.3.1"
karma-source-map-support "1.4.0"
less "4.2.0"
less-loader "12.2.0"
license-webpack-plugin "4.0.2"
loader-utils "3.3.1"
magic-string "0.30.11"
mini-css-extract-plugin "2.9.1"
mrmime "2.0.0"
open "10.1.0"
ora "5.4.1"
parse5-html-rewriting-stream "7.0.0"
picomatch "4.0.2"
piscina "4.6.1"
postcss "8.4.45"
postcss-loader "8.1.1"
resolve-url-loader "5.0.0"
rxjs "7.8.1"
sass "1.78.0"
sass-loader "16.0.1"
semver "7.6.3"
source-map-loader "5.0.0"
source-map-support "0.5.21"
terser "5.31.6"
tree-kill "1.2.2"
tslib "2.7.0"
vite "5.4.3"
watchpack "2.4.2"
webpack "5.94.0"
webpack-dev-middleware "7.4.2"
webpack-dev-server "5.1.0"
webpack-merge "6.0.1"
webpack-subresource-integrity "5.1.0"
optionalDependencies:
esbuild "0.23.1"
"@angular-devkit/[email protected]":
version "0.1900.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/build-webpack/-/build-webpack-0.1900.0-next.3.tgz#18102c548cd5cbc6ef21139ef2382ddb1940f196"
integrity sha512-5R6Hi90OlngS0D3PmzczAAk/afm3FWpzz3tj9iYRGjUd3XhBfBVxsaNOljZc75JOeq267Bkh5Fwec2W3HfK+GA==
dependencies:
"@angular-devkit/architect" "0.1900.0-next.3"
rxjs "7.8.1"
"@angular-devkit/[email protected]":
version "19.0.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/core/-/core-19.0.0-next.3.tgz#fcfd9b1e53213dd5361ac4e047ee8cf265e9453c"
integrity sha512-T8nrvv+lAz88/k/e9nHrhMq2W0JxuQEb4NztxYC8zbhdbO+rW9fHNne/bu96ck1vqHqSztTpsn50KXrbSNZVJQ==
dependencies:
ajv "8.17.1"
ajv-formats "3.0.1"
jsonc-parser "3.3.1"
picomatch "4.0.2"
rxjs "7.8.1"
source-map "0.7.4"
"@angular-devkit/[email protected]":
version "19.0.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/schematics/-/schematics-19.0.0-next.3.tgz#4c68d781a332397b0d686bdad9430d0a66cec16b"
integrity sha512-wTkbkiI8RoudBL4nLfbs9rezwOomhwA7ZoVNqSP6FUzSJpBtgHTLB2NzcwhOuBKqAmoGwZqg9n8R7P7P3lotzA==
dependencies:
"@angular-devkit/core" "19.0.0-next.3"
jsonc-parser "3.3.1"
magic-string "0.30.11"
ora "5.4.1"
rxjs "7.8.1"
"@angular/animations@file:../../node_modules/@angular/animations":
version "19.0.0-next.3"
dependencies:
tslib "^2.3.0"
| |
112495
|
"@ampproject/[email protected]", "@ampproject/remapping@^2.2.0":
version "2.3.0"
resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.3.0.tgz#ed441b6fa600072520ce18b43d2c8cc8caecc7f4"
integrity sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==
dependencies:
"@jridgewell/gen-mapping" "^0.3.5"
"@jridgewell/trace-mapping" "^0.3.24"
"@angular-devkit/[email protected]":
version "0.1900.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/architect/-/architect-0.1900.0-next.3.tgz#1e35eb39a11a93127001f53455e3377cbe8b8a83"
integrity sha512-uEVpjcojOPWfLfpjCqmbO/nphBbOIo+qBwruOiUv9WACSXown+GMYPvQSIkeuLdpQTKSGETjegEKs09VWgwomA==
dependencies:
"@angular-devkit/core" "19.0.0-next.3"
rxjs "7.8.1"
"@angular-devkit/build-angular@file:../../node_modules/@angular-devkit/build-angular":
version "19.0.0-next.3"
dependencies:
"@ampproject/remapping" "2.3.0"
"@angular-devkit/architect" "0.1900.0-next.3"
"@angular-devkit/build-webpack" "0.1900.0-next.3"
"@angular-devkit/core" "19.0.0-next.3"
"@angular/build" "19.0.0-next.3"
"@babel/core" "7.25.2"
"@babel/generator" "7.25.6"
"@babel/helper-annotate-as-pure" "7.24.7"
"@babel/helper-split-export-declaration" "7.24.7"
"@babel/plugin-transform-async-generator-functions" "7.25.4"
"@babel/plugin-transform-async-to-generator" "7.24.7"
"@babel/plugin-transform-runtime" "7.25.4"
"@babel/preset-env" "7.25.4"
"@babel/runtime" "7.25.6"
"@discoveryjs/json-ext" "0.6.1"
"@ngtools/webpack" "19.0.0-next.3"
"@vitejs/plugin-basic-ssl" "1.1.0"
ansi-colors "4.1.3"
autoprefixer "10.4.20"
babel-loader "9.1.3"
browserslist "^4.21.5"
copy-webpack-plugin "12.0.2"
critters "0.0.24"
css-loader "7.1.2"
esbuild-wasm "0.23.1"
fast-glob "3.3.2"
http-proxy-middleware "3.0.2"
https-proxy-agent "7.0.5"
istanbul-lib-instrument "6.0.3"
jsonc-parser "3.3.1"
karma-source-map-support "1.4.0"
less "4.2.0"
less-loader "12.2.0"
license-webpack-plugin "4.0.2"
loader-utils "3.3.1"
magic-string "0.30.11"
mini-css-extract-plugin "2.9.1"
mrmime "2.0.0"
open "10.1.0"
ora "5.4.1"
parse5-html-rewriting-stream "7.0.0"
picomatch "4.0.2"
piscina "4.6.1"
postcss "8.4.45"
postcss-loader "8.1.1"
resolve-url-loader "5.0.0"
rxjs "7.8.1"
sass "1.78.0"
sass-loader "16.0.1"
semver "7.6.3"
source-map-loader "5.0.0"
source-map-support "0.5.21"
terser "5.31.6"
tree-kill "1.2.2"
tslib "2.7.0"
vite "5.4.3"
watchpack "2.4.2"
webpack "5.94.0"
webpack-dev-middleware "7.4.2"
webpack-dev-server "5.1.0"
webpack-merge "6.0.1"
webpack-subresource-integrity "5.1.0"
optionalDependencies:
esbuild "0.23.1"
"@angular-devkit/[email protected]":
version "0.1900.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/build-webpack/-/build-webpack-0.1900.0-next.3.tgz#18102c548cd5cbc6ef21139ef2382ddb1940f196"
integrity sha512-5R6Hi90OlngS0D3PmzczAAk/afm3FWpzz3tj9iYRGjUd3XhBfBVxsaNOljZc75JOeq267Bkh5Fwec2W3HfK+GA==
dependencies:
"@angular-devkit/architect" "0.1900.0-next.3"
rxjs "7.8.1"
"@angular-devkit/[email protected]":
version "19.0.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/core/-/core-19.0.0-next.3.tgz#fcfd9b1e53213dd5361ac4e047ee8cf265e9453c"
integrity sha512-T8nrvv+lAz88/k/e9nHrhMq2W0JxuQEb4NztxYC8zbhdbO+rW9fHNne/bu96ck1vqHqSztTpsn50KXrbSNZVJQ==
dependencies:
ajv "8.17.1"
ajv-formats "3.0.1"
jsonc-parser "3.3.1"
picomatch "4.0.2"
rxjs "7.8.1"
source-map "0.7.4"
"@angular-devkit/[email protected]":
version "19.0.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/schematics/-/schematics-19.0.0-next.3.tgz#4c68d781a332397b0d686bdad9430d0a66cec16b"
integrity sha512-wTkbkiI8RoudBL4nLfbs9rezwOomhwA7ZoVNqSP6FUzSJpBtgHTLB2NzcwhOuBKqAmoGwZqg9n8R7P7P3lotzA==
dependencies:
"@angular-devkit/core" "19.0.0-next.3"
jsonc-parser "3.3.1"
magic-string "0.30.11"
ora "5.4.1"
rxjs "7.8.1"
"@angular/animations@file:../../node_modules/@angular/animations":
version "19.0.0-next.3"
dependencies:
tslib "^2.3.0"
| |
112615
|
"@ampproject/[email protected]", "@ampproject/remapping@^2.2.0":
version "2.3.0"
resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.3.0.tgz#ed441b6fa600072520ce18b43d2c8cc8caecc7f4"
integrity sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==
dependencies:
"@jridgewell/gen-mapping" "^0.3.5"
"@jridgewell/trace-mapping" "^0.3.24"
"@angular-devkit/[email protected]":
version "0.1900.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/architect/-/architect-0.1900.0-next.3.tgz#1e35eb39a11a93127001f53455e3377cbe8b8a83"
integrity sha512-uEVpjcojOPWfLfpjCqmbO/nphBbOIo+qBwruOiUv9WACSXown+GMYPvQSIkeuLdpQTKSGETjegEKs09VWgwomA==
dependencies:
"@angular-devkit/core" "19.0.0-next.3"
rxjs "7.8.1"
"@angular-devkit/build-angular@file:../../node_modules/@angular-devkit/build-angular":
version "19.0.0-next.3"
dependencies:
"@ampproject/remapping" "2.3.0"
"@angular-devkit/architect" "0.1900.0-next.3"
"@angular-devkit/build-webpack" "0.1900.0-next.3"
"@angular-devkit/core" "19.0.0-next.3"
"@angular/build" "19.0.0-next.3"
"@babel/core" "7.25.2"
"@babel/generator" "7.25.6"
"@babel/helper-annotate-as-pure" "7.24.7"
"@babel/helper-split-export-declaration" "7.24.7"
"@babel/plugin-transform-async-generator-functions" "7.25.4"
"@babel/plugin-transform-async-to-generator" "7.24.7"
"@babel/plugin-transform-runtime" "7.25.4"
"@babel/preset-env" "7.25.4"
"@babel/runtime" "7.25.6"
"@discoveryjs/json-ext" "0.6.1"
"@ngtools/webpack" "19.0.0-next.3"
"@vitejs/plugin-basic-ssl" "1.1.0"
ansi-colors "4.1.3"
autoprefixer "10.4.20"
babel-loader "9.1.3"
browserslist "^4.21.5"
copy-webpack-plugin "12.0.2"
critters "0.0.24"
css-loader "7.1.2"
esbuild-wasm "0.23.1"
fast-glob "3.3.2"
http-proxy-middleware "3.0.2"
https-proxy-agent "7.0.5"
istanbul-lib-instrument "6.0.3"
jsonc-parser "3.3.1"
karma-source-map-support "1.4.0"
less "4.2.0"
less-loader "12.2.0"
license-webpack-plugin "4.0.2"
loader-utils "3.3.1"
magic-string "0.30.11"
mini-css-extract-plugin "2.9.1"
mrmime "2.0.0"
open "10.1.0"
ora "5.4.1"
parse5-html-rewriting-stream "7.0.0"
picomatch "4.0.2"
piscina "4.6.1"
postcss "8.4.45"
postcss-loader "8.1.1"
resolve-url-loader "5.0.0"
rxjs "7.8.1"
sass "1.78.0"
sass-loader "16.0.1"
semver "7.6.3"
source-map-loader "5.0.0"
source-map-support "0.5.21"
terser "5.31.6"
tree-kill "1.2.2"
tslib "2.7.0"
vite "5.4.3"
watchpack "2.4.2"
webpack "5.94.0"
webpack-dev-middleware "7.4.2"
webpack-dev-server "5.1.0"
webpack-merge "6.0.1"
webpack-subresource-integrity "5.1.0"
optionalDependencies:
esbuild "0.23.1"
"@angular-devkit/[email protected]":
version "0.1900.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/build-webpack/-/build-webpack-0.1900.0-next.3.tgz#18102c548cd5cbc6ef21139ef2382ddb1940f196"
integrity sha512-5R6Hi90OlngS0D3PmzczAAk/afm3FWpzz3tj9iYRGjUd3XhBfBVxsaNOljZc75JOeq267Bkh5Fwec2W3HfK+GA==
dependencies:
"@angular-devkit/architect" "0.1900.0-next.3"
rxjs "7.8.1"
"@angular-devkit/[email protected]":
version "19.0.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/core/-/core-19.0.0-next.3.tgz#fcfd9b1e53213dd5361ac4e047ee8cf265e9453c"
integrity sha512-T8nrvv+lAz88/k/e9nHrhMq2W0JxuQEb4NztxYC8zbhdbO+rW9fHNne/bu96ck1vqHqSztTpsn50KXrbSNZVJQ==
dependencies:
ajv "8.17.1"
ajv-formats "3.0.1"
jsonc-parser "3.3.1"
picomatch "4.0.2"
rxjs "7.8.1"
source-map "0.7.4"
"@angular-devkit/[email protected]":
version "19.0.0-next.3"
resolved "https://registry.yarnpkg.com/@angular-devkit/schematics/-/schematics-19.0.0-next.3.tgz#4c68d781a332397b0d686bdad9430d0a66cec16b"
integrity sha512-wTkbkiI8RoudBL4nLfbs9rezwOomhwA7ZoVNqSP6FUzSJpBtgHTLB2NzcwhOuBKqAmoGwZqg9n8R7P7P3lotzA==
dependencies:
"@angular-devkit/core" "19.0.0-next.3"
jsonc-parser "3.3.1"
magic-string "0.30.11"
ora "5.4.1"
rxjs "7.8.1"
"@angular/animations@file:../../node_modules/@angular/animations":
version "19.0.0-next.3"
dependencies:
tslib "^2.3.0"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.