_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/zone.js/test/rxjs/rxjs.asap.spec.ts_0_2080 | /**
* @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 {asapScheduler, of} from 'rxjs';
import {map, observeOn} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Scheduler.asap', () => {
let log: any[];
let errorCallback: Function;
const constructorZone: Zone = Zone.root.fork({name: 'Constructor Zone'});
beforeEach(() => {
log = [];
});
it(
'scheduler asap should run in correct zone',
asyncTest((done: any) => {
let observable: any;
constructorZone.run(() => {
observable = of(1, 2, 3).pipe(observeOn(asapScheduler));
});
const zone = Zone.current.fork({name: 'subscribeZone'});
zone.run(() => {
observable
.pipe(
map((value: number) => {
return value;
}),
)
.subscribe(
(value: number) => {
expect(Zone.current.name).toEqual(zone.name);
if (value === 3) {
setTimeout(done);
}
},
(err: any) => {
fail('should not be here');
},
);
});
}, Zone.root),
);
it(
'scheduler asap error should run in correct zone',
asyncTest((done: any) => {
let observable: any;
constructorZone.run(() => {
observable = of(1, 2, 3).pipe(observeOn(asapScheduler));
});
Zone.root.run(() => {
observable
.pipe(
map((value: number) => {
if (value === 3) {
throw new Error('oops');
}
return value;
}),
)
.subscribe(
(value: number) => {},
(err: any) => {
expect(err.message).toEqual('oops');
expect(Zone.current.name).toEqual('<root>');
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 2080,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.asap.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.combine.spec.ts_0_4870 | /**
* @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 {combineLatest, Observable, of} from 'rxjs';
import {combineAll, map} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable.combine', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'combineAll func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = of(1, 2);
const highOrder = source.pipe(
map((src: any) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return of(src);
}),
);
return highOrder.pipe(combineAll());
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([[1, 2], 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'combineAll func callback should run in the correct zone with project function',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = of(1, 2, 3);
const highOrder = source.pipe(
map((src: any) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return of(src);
}),
);
return highOrder.pipe(
combineAll((x: any, y: any) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return {x: x, y: y};
}),
);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([{x: 1, y: 2}, 'completed']);
done();
},
);
});
}, Zone.root),
);
it('combineLatest func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = of(1, 2, 3);
const input = of(4, 5, 6);
return combineLatest(source, input);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([[3, 4], [3, 5], [3, 6], 'completed']);
});
it('combineLatest func callback should run in the correct zone with project function', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = of(1, 2, 3);
const input = of(4, 5, 6);
return combineLatest(source, input, (x: number, y: number) => {
return x + y;
});
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([7, 8, 9, 'completed']);
});
});
| {
"end_byte": 4870,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.combine.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.common.spec.ts_0_7435 | /**
* @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, Subject} from 'rxjs';
import {map} from 'rxjs/operators';
/**
* The point of these tests, is to ensure that all callbacks execute in the Zone which was active
* when the callback was passed into the Rx.
*
* The implications are:
* - Observable callback passed into `Observable` executes in the same Zone as when the
* `new Observable` was invoked.
* - The subscription callbacks passed into `subscribe` execute in the same Zone as when the
* `subscribe` method was invoked.
* - The operator callbacks passe into `map`, etc..., execute in the same Zone as when the
* `operator` (`lift`) method was invoked.
*/
describe('Zone interaction', () => {
it('should run methods in the zone of declaration', () => {
const log: any[] = [];
const constructorZone: Zone = Zone.current.fork({name: 'Constructor Zone'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let subscriber: any = null;
const observable: any = constructorZone.run(
() =>
new Observable((_subscriber: any) => {
subscriber = _subscriber;
log.push('setup');
expect(Zone.current.name).toEqual(constructorZone.name);
return () => {
expect(Zone.current.name).toEqual(constructorZone.name);
log.push('cleanup');
};
}),
);
subscriptionZone.run(() =>
observable.subscribe(
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next');
},
(): any => null,
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('complete');
},
),
);
subscriber.next('MyValue');
subscriber.complete();
expect(log).toEqual(['setup', 'next', 'complete', 'cleanup']);
log.length = 0;
subscriptionZone.run(() =>
observable.subscribe(
(): any => null,
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('error');
},
(): any => null,
),
);
subscriber.next('MyValue');
subscriber.error('MyError');
expect(log).toEqual(['setup', 'error', 'cleanup']);
});
it('should run methods in the zone of declaration when nexting synchronously', () => {
const log: any[] = [];
const rootZone: Zone = Zone.current;
const constructorZone: Zone = Zone.current.fork({name: 'Constructor Zone'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const observable: any = constructorZone.run(
() =>
new Observable((subscriber: any) => {
// Execute the `next`/`complete` in different zone, and assert that
// correct zone
// is restored.
rootZone.run(() => {
subscriber.next('MyValue');
subscriber.complete();
});
return () => {
expect(Zone.current.name).toEqual(constructorZone.name);
log.push('cleanup');
};
}),
);
subscriptionZone.run(() =>
observable.subscribe(
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next');
},
(): any => null,
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('complete');
},
),
);
expect(log).toEqual(['next', 'complete', 'cleanup']);
});
it('should run operators in the zone of declaration', () => {
const log: any[] = [];
const rootZone: Zone = Zone.current;
const constructorZone: Zone = Zone.current.fork({name: 'Constructor Zone'});
const operatorZone: Zone = Zone.current.fork({name: 'Operator Zone'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable: any = constructorZone.run(
() =>
new Observable((subscriber: any) => {
// Execute the `next`/`complete` in different zone, and assert that
// correct zone
// is restored.
rootZone.run(() => {
subscriber.next('MyValue');
subscriber.complete();
});
return () => {
expect(Zone.current.name).toEqual(constructorZone.name);
log.push('cleanup');
};
}),
);
observable = operatorZone.run(() =>
observable.pipe(
map((value: any) => {
expect(Zone.current.name).toEqual(operatorZone.name);
log.push('map: ' + value);
return value;
}),
),
);
subscriptionZone.run(() =>
observable.subscribe(
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next');
},
(e: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('error: ' + e);
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('complete');
},
),
);
expect(log).toEqual(['map: MyValue', 'next', 'complete', 'cleanup']);
});
it('should run subscribe in zone of declaration with Observable.create', () => {
const log: any[] = [];
const constructorZone: Zone = Zone.current.fork({name: 'Constructor Zone'});
let observable: any = constructorZone.run(() =>
Observable.create((subscriber: any) => {
expect(Zone.current.name).toEqual(constructorZone.name);
subscriber.next(1);
subscriber.complete();
return () => {
expect(Zone.current.name).toEqual(constructorZone.name);
log.push('cleanup');
};
}),
);
observable.subscribe(() => {
log.push('next');
});
expect(log).toEqual(['next', 'cleanup']);
});
it('should run in the zone when subscribe is called to the same Subject', () => {
const log: any[] = [];
const constructorZone: Zone = Zone.current.fork({name: 'Constructor Zone'});
const subscriptionZone1: Zone = Zone.current.fork({name: 'Subscription Zone 1'});
const subscriptionZone2: Zone = Zone.current.fork({name: 'Subscription Zone 2'});
let subject: any;
constructorZone.run(() => {
subject = new Subject();
});
let subscription1: any;
let subscription2: any;
subscriptionZone1.run(() => {
subscription1 = subject.subscribe(
() => {
expect(Zone.current.name).toEqual(subscriptionZone1.name);
log.push('next1');
},
() => {},
() => {
expect(Zone.current.name).toEqual(subscriptionZone1.name);
log.push('complete1');
},
);
});
subscriptionZone2.run(() => {
subscription2 = subject.subscribe(
() => {
expect(Zone.current.name).toEqual(subscriptionZone2.name);
log.push('next2');
},
() => {},
() => {
expect(Zone.current.name).toEqual(subscriptionZone2.name);
log.push('complete2');
},
);
});
subject.next(1);
subject.complete();
expect(log).toEqual(['next1', 'next2', 'complete1', 'complete2']);
});
});
| {
"end_byte": 7435,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.common.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.fromPromise.spec.ts_0_1460 | /**
* @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 {from} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.fromPromise', () => {
let log: any[];
let observable1: any;
beforeEach(() => {
log = [];
});
it(
'fromPromise func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const promiseZone1: Zone = Zone.current.fork({name: 'Promise Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let res: any;
let promise: any = promiseZone1.run(() => {
return new Promise((resolve, reject) => {
res = resolve;
});
});
observable1 = constructorZone1.run(() => {
return from(promise);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
expect(log).toEqual([1]);
done();
},
() => {
fail('should not call error');
},
() => {},
);
});
res(1);
expect(log).toEqual([]);
}, Zone.root),
);
});
| {
"end_byte": 1460,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.fromPromise.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.buffer.spec.ts_0_6414 | /**
* @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 {empty, interval, Observable, of} from 'rxjs';
import {buffer, bufferCount, bufferTime, bufferToggle, bufferWhen} from 'rxjs/operators';
import {asyncTest} from '../test-util';
xdescribe('Observable.buffer', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'buffer func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = interval(350);
const iv = interval(100);
return iv.pipe(buffer(source));
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
if (result[0] >= 3) {
subscriber.unsubscribe();
}
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([[0, 1, 2], [3, 4, 5], 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
it(
'bufferCount func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const iv = interval(100);
return iv.pipe(bufferCount(3));
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
if (result[0] >= 3) {
subscriber.unsubscribe();
}
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([[0, 1, 2], [3, 4, 5], 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
it(
'bufferTime func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const iv = interval(100);
return iv.pipe(bufferTime(350));
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
if (result[0] >= 3) {
subscriber.unsubscribe();
}
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([[0, 1, 2], [3, 4, 5], 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
it(
'bufferToggle func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = interval(10);
const opening = interval(25);
const closingSelector = (v: any) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return v % 2 === 0 ? of(v) : empty();
};
return source.pipe(bufferToggle(opening, closingSelector));
});
let i = 0;
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
subscriber.unsubscribe();
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([[], 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
it(
'bufferWhen func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = interval(100);
return source.pipe(
bufferWhen(() => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return interval(220);
}),
);
});
let i = 0;
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
if (i++ >= 3) {
subscriber.unsubscribe();
}
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([[0, 1], [2, 3], [4, 5], [6, 7], 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
});
| {
"end_byte": 6414,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.buffer.spec.ts"
} |
angular/packages/zone.js/test/node/process.spec.ts_0_5325 | /**
* @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 {zoneSymbol} from '../../lib/common/utils';
describe('process related test', () => {
let zoneA: Zone, result: any[];
beforeEach(() => {
zoneA = Zone.current.fork({name: 'zoneA'});
result = [];
});
it('process.nextTick callback should in zone', (done) => {
zoneA.run(function () {
process.nextTick(() => {
expect(Zone.current.name).toEqual('zoneA');
done();
});
});
});
it('process.nextTick should be executed before macroTask and promise', (done) => {
zoneA.run(function () {
setTimeout(() => {
result.push('timeout');
}, 0);
process.nextTick(() => {
result.push('tick');
});
setTimeout(() => {
expect(result).toEqual(['tick', 'timeout']);
done();
});
});
});
it('process.nextTick should be treated as microTask', (done) => {
let zoneTick = Zone.current.fork({
name: 'zoneTick',
onScheduleTask: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task => {
result.push({callback: 'scheduleTask', targetZone: targetZone.name, task: task.source});
return parentZoneDelegate.scheduleTask(targetZone, task);
},
onInvokeTask: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
applyThis?: any,
applyArgs?: any,
): any => {
result.push({callback: 'invokeTask', targetZone: targetZone.name, task: task.source});
return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
},
});
zoneTick.run(() => {
process.nextTick(() => {
result.push('tick');
});
});
setTimeout(() => {
expect(result.length).toBe(3);
expect(result[0]).toEqual({
callback: 'scheduleTask',
targetZone: 'zoneTick',
task: 'process.nextTick',
});
expect(result[1]).toEqual({
callback: 'invokeTask',
targetZone: 'zoneTick',
task: 'process.nextTick',
});
done();
});
});
it('should support process.on(unhandledRejection)', async function () {
return await jasmine.spyOnGlobalErrorsAsync(async () => {
const hookSpy = jasmine.createSpy('hook');
let p: any = null;
(Zone as any)[zoneSymbol('ignoreConsoleErrorUncaughtError')] = true;
Zone.current.fork({name: 'promise'}).run(function () {
const listener = function (reason: any, promise: any) {
hookSpy(promise, reason.message);
process.removeListener('unhandledRejection', listener);
};
process.on('unhandledRejection', listener);
p = new Promise((resolve, reject) => {
throw new Error('promise error');
});
});
return new Promise((res) => {
setTimeout(function () {
expect(hookSpy).toHaveBeenCalledWith(p, 'promise error');
res();
});
});
});
});
it('should support process.on(rejectionHandled)', async function () {
return await jasmine.spyOnGlobalErrorsAsync(async () => {
let p: any = null;
(Zone as any)[zoneSymbol('ignoreConsoleErrorUncaughtError')] = true;
let r: any = null;
let p1: any = new Promise((res) => {
r = res;
});
Zone.current.fork({name: 'promise'}).run(function () {
const listener = function (promise: any) {
expect(promise).toEqual(p);
process.removeListener('rejectionHandled', listener);
r();
};
process.on('rejectionHandled', listener);
p = new Promise((resolve, reject) => {
throw new Error('promise error');
});
});
setTimeout(function () {
p.catch((reason: any) => {});
});
return p1;
});
});
it('should support multiple process.on(unhandledRejection)', async function () {
await jasmine.spyOnGlobalErrorsAsync(async () => {
const hookSpy = jasmine.createSpy('hook');
(Zone as any)[zoneSymbol('ignoreConsoleErrorUncaughtError')] = true;
let p: any = null;
Zone.current.fork({name: 'promise'}).run(function () {
const listener1 = function (reason: any, promise: any) {
hookSpy(promise, reason.message);
process.removeListener('unhandledRejection', listener1);
};
const listener2 = function (reason: any, promise: any) {
hookSpy(promise, reason.message);
process.removeListener('unhandledRejection', listener2);
};
process.on('unhandledRejection', listener1);
process.on('unhandledRejection', listener2);
p = new Promise((resolve, reject) => {
throw new Error('promise error');
});
});
return new Promise((res) =>
setTimeout(function () {
expect(hookSpy.calls.count()).toBe(2);
expect(hookSpy.calls.allArgs()).toEqual([
[p, 'promise error'],
[p, 'promise error'],
]);
res();
}),
);
});
});
});
| {
"end_byte": 5325,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/node/process.spec.ts"
} |
angular/packages/zone.js/test/node/events.spec.ts_0_7245 | /**
* @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 {EventEmitter} from 'events';
describe('nodejs EventEmitter', () => {
let zone: Zone,
zoneA: Zone,
zoneB: Zone,
emitter: EventEmitter,
expectZoneACount: number,
zoneResults: string[];
beforeEach(() => {
zone = Zone.current;
zoneA = zone.fork({name: 'A'});
zoneB = zone.fork({name: 'B'});
emitter = new EventEmitter();
expectZoneACount = 0;
zoneResults = [];
});
function expectZoneA(value: string) {
expectZoneACount++;
expect(Zone.current.name).toBe('A');
expect(value).toBe('test value');
}
function listenerA() {
zoneResults.push('A');
}
function listenerB() {
zoneResults.push('B');
}
function shouldNotRun() {
fail('this listener should not run');
}
it('should register listeners in the current zone', () => {
zoneA.run(() => {
emitter.on('test', expectZoneA);
emitter.addListener('test', expectZoneA);
});
zoneB.run(() => emitter.emit('test', 'test value'));
expect(expectZoneACount).toBe(2);
});
it('allows chaining methods', () => {
zoneA.run(() => {
expect(emitter.on('test', expectZoneA)).toBe(emitter);
expect(emitter.addListener('test', expectZoneA)).toBe(emitter);
});
});
it('should remove listeners properly', () => {
zoneA.run(() => {
emitter.on('test', shouldNotRun);
emitter.on('test2', shouldNotRun);
emitter.removeListener('test', shouldNotRun);
});
zoneB.run(() => {
emitter.removeListener('test2', shouldNotRun);
emitter.emit('test', 'test value');
emitter.emit('test2', 'test value');
});
});
it('should remove listeners by calling off properly', () => {
zoneA.run(() => {
emitter.on('test', shouldNotRun);
emitter.on('test2', shouldNotRun);
emitter.off('test', shouldNotRun);
});
zoneB.run(() => {
emitter.off('test2', shouldNotRun);
emitter.emit('test', 'test value');
emitter.emit('test2', 'test value');
});
});
it('remove listener should return event emitter', () => {
zoneA.run(() => {
emitter.on('test', shouldNotRun);
expect(emitter.removeListener('test', shouldNotRun)).toEqual(emitter);
emitter.emit('test', 'test value');
});
});
it('should return all listeners for an event', () => {
zoneA.run(() => {
emitter.on('test', expectZoneA);
});
zoneB.run(() => {
emitter.on('test', shouldNotRun);
});
expect(emitter.listeners('test')).toEqual([expectZoneA, shouldNotRun]);
});
it('should return empty array when an event has no listeners', () => {
zoneA.run(() => {
expect(emitter.listeners('test')).toEqual([]);
});
});
it('should prepend listener by order', () => {
zoneA.run(() => {
emitter.on('test', listenerA);
emitter.on('test', listenerB);
expect(emitter.listeners('test')).toEqual([listenerA, listenerB]);
emitter.emit('test');
expect(zoneResults).toEqual(['A', 'B']);
zoneResults = [];
emitter.removeAllListeners('test');
emitter.on('test', listenerA);
emitter.prependListener('test', listenerB);
expect(emitter.listeners('test')).toEqual([listenerB, listenerA]);
emitter.emit('test');
expect(zoneResults).toEqual(['B', 'A']);
});
});
it('should remove All listeners properly', () => {
zoneA.run(() => {
emitter.on('test', expectZoneA);
emitter.on('test', expectZoneA);
emitter.removeAllListeners('test');
expect(emitter.listeners('test').length).toEqual(0);
});
});
it('remove All listeners should return event emitter', () => {
zoneA.run(() => {
emitter.on('test', expectZoneA);
emitter.on('test', expectZoneA);
expect(emitter.removeAllListeners('test')).toEqual(emitter);
expect(emitter.listeners('test').length).toEqual(0);
});
});
it('should remove All listeners properly even without a type parameter', () => {
zoneA.run(() => {
emitter.on('test', shouldNotRun);
emitter.on('test1', shouldNotRun);
emitter.removeAllListeners();
expect(emitter.listeners('test').length).toEqual(0);
expect(emitter.listeners('test1').length).toEqual(0);
});
});
it('should remove once listener after emit', () => {
zoneA.run(() => {
emitter.once('test', expectZoneA);
emitter.emit('test', 'test value');
expect(emitter.listeners('test').length).toEqual(0);
});
});
it('should remove once listener properly before listener triggered', () => {
zoneA.run(() => {
emitter.once('test', shouldNotRun);
emitter.removeListener('test', shouldNotRun);
emitter.emit('test');
});
});
it('should trigger removeListener when remove listener', () => {
zoneA.run(() => {
emitter.on('removeListener', function (type: string, handler: any) {
zoneResults.push('remove' + type);
});
emitter.on('newListener', function (type: string, handler: any) {
zoneResults.push('new' + type);
});
emitter.on('test', shouldNotRun);
emitter.removeListener('test', shouldNotRun);
expect(zoneResults).toEqual(['newtest', 'removetest']);
});
});
it('should trigger removeListener when remove all listeners with eventname ', () => {
zoneA.run(() => {
emitter.on('removeListener', function (type: string, handler: any) {
zoneResults.push('remove' + type);
});
emitter.on('test', shouldNotRun);
emitter.on('test1', expectZoneA);
emitter.removeAllListeners('test');
expect(zoneResults).toEqual(['removetest']);
expect(emitter.listeners('removeListener').length).toBe(1);
});
});
it('should trigger removeListener when remove all listeners without eventname', () => {
zoneA.run(() => {
emitter.on('removeListener', function (type: string, handler: any) {
zoneResults.push('remove' + type);
});
emitter.on('test', shouldNotRun);
emitter.on('test1', shouldNotRun);
emitter.removeAllListeners();
expect(zoneResults).toEqual(['removetest', 'removetest1']);
expect(emitter.listeners('test').length).toBe(0);
expect(emitter.listeners('test1').length).toBe(0);
expect(emitter.listeners('removeListener').length).toBe(0);
});
});
it('should not enter endless loop when register uncaughtException to process', () => {
require('domain');
zoneA.run(() => {
process.on('uncaughtException', function () {});
});
});
it('should be able to addEventListener with symbol eventName', () => {
zoneA.run(() => {
const testSymbol = Symbol('test');
const test1Symbol = Symbol('test1');
emitter.on(testSymbol, expectZoneA);
emitter.on(test1Symbol, shouldNotRun);
emitter.removeListener(test1Symbol, shouldNotRun);
expect(emitter.listeners(testSymbol).length).toBe(1);
expect(emitter.listeners(test1Symbol).length).toBe(0);
emitter.emit(testSymbol, 'test value');
});
});
});
| {
"end_byte": 7245,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/node/events.spec.ts"
} |
angular/packages/zone.js/test/node/fs.spec.ts_0_7612 | /**
* @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 {
closeSync,
exists,
fstatSync,
openSync,
read,
realpath,
unlink,
unlinkSync,
unwatchFile,
watch,
watchFile,
write,
writeFile,
} from 'fs';
import url from 'url';
import util from 'util';
const currentFile = url.fileURLToPath(import.meta.url);
describe('nodejs file system', () => {
describe('async method patch test', () => {
it('has patched exists()', (done) => {
const zoneA = Zone.current.fork({name: 'A'});
zoneA.run(() => {
exists('testfile', (_) => {
expect(Zone.current.name).toBe(zoneA.name);
done();
});
});
});
it('has patched exists as macroTask', (done) => {
const zoneASpec = {
name: 'A',
onScheduleTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task => {
return delegate.scheduleTask(targetZone, task);
},
};
const zoneA = Zone.current.fork(zoneASpec);
spyOn(zoneASpec, 'onScheduleTask').and.callThrough();
zoneA.run(() => {
exists('testfile', (_) => {
expect(zoneASpec.onScheduleTask).toHaveBeenCalled();
done();
});
});
});
it('has patched realpath as macroTask', (done) => {
const testZoneSpec = {
name: 'test',
onScheduleTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task => {
return delegate.scheduleTask(targetZone, task);
},
};
const testZone = Zone.current.fork(testZoneSpec);
spyOn(testZoneSpec, 'onScheduleTask').and.callThrough();
testZone.run(() => {
realpath('testfile', () => {
expect(Zone.current).toBe(testZone);
expect(testZoneSpec.onScheduleTask).toHaveBeenCalled();
done();
});
});
});
// https://github.com/angular/angular/issues/45546
// Note that this is intentionally marked with `xit` because `realpath.native`
// is patched by Bazel's `node_patches.js` and doesn't allow further patching
// of `realpath.native` in unit tests. Essentially, there's no original delegate
// for `realpath` because it's also patched. The code below functions correctly
// in the actual production environment.
xit('has patched realpath.native as macroTask', (done) => {
const testZoneSpec = {
name: 'test',
onScheduleTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task => {
return delegate.scheduleTask(targetZone, task);
},
};
const testZone = Zone.current.fork(testZoneSpec);
spyOn(testZoneSpec, 'onScheduleTask').and.callThrough();
testZone.run(() => {
realpath.native('testfile', () => {
expect(Zone.current).toBe(testZone);
expect(testZoneSpec.onScheduleTask).toHaveBeenCalled();
done();
});
});
});
});
describe('watcher related methods test', () => {
const zoneASpec = {
name: 'A',
onScheduleTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task => {
return delegate.scheduleTask(targetZone, task);
},
};
it('fs.watch has been patched as eventTask', (done) => {
spyOn(zoneASpec, 'onScheduleTask').and.callThrough();
const zoneA = Zone.current.fork(zoneASpec);
zoneA.run(() => {
writeFile('testfile', 'test content', () => {
const watcher = watch('testfile', (eventType, filename) => {
expect(filename).toEqual('testfile');
expect(eventType).toEqual('change');
expect(zoneASpec.onScheduleTask).toHaveBeenCalled();
expect(Zone.current.name).toBe('A');
watcher.close();
unlink('testfile', () => {
done();
});
});
writeFile('testfile', 'test new content', () => {});
});
});
});
it('fs.watchFile has been patched as eventTask', (done) => {
spyOn(zoneASpec, 'onScheduleTask').and.callThrough();
const zoneA = Zone.current.fork(zoneASpec);
zoneA.run(() => {
writeFile('testfile', 'test content', () => {
watchFile('testfile', {persistent: false, interval: 1000}, (curr, prev) => {
expect(curr.size).toBe(16);
expect(prev.size).toBe(12);
expect(zoneASpec.onScheduleTask).toHaveBeenCalled();
expect(Zone.current.name).toBe('A');
unwatchFile('testfile');
unlink('testfile', () => {
done();
});
});
writeFile('testfile', 'test new content', () => {});
});
});
});
});
});
describe('util.promisify', () => {
it('fs.exists should work with util.promisify', (done: DoneFn) => {
const promisifyExists = util.promisify(exists);
promisifyExists(currentFile).then(
(r) => {
expect(r).toBe(true);
done();
},
(err) => {
fail(`should not be here with error: ${err}`);
},
);
});
it('fs.realpath should work with util.promisify', (done: DoneFn) => {
const promisifyRealpath = util.promisify(realpath);
promisifyRealpath(currentFile).then(
(r) => {
expect(r).toBeDefined();
done();
},
(err) => {
fail(`should not be here with error: ${err}`);
},
);
});
it('fs.realpath.native should work with util.promisify', (done: DoneFn) => {
const promisifyRealpathNative = util.promisify(realpath.native);
promisifyRealpathNative(currentFile).then(
(r) => {
expect(r).toBeDefined();
done();
},
(err) => {
fail(`should not be here with error: ${err}`);
},
);
});
it('fs.read should work with util.promisify', (done: DoneFn) => {
const promisifyRead = util.promisify(read);
const fd = openSync(currentFile, 'r');
const stats = fstatSync(fd);
const bufferSize = stats.size;
const chunkSize = 512;
const buffer = new Buffer(bufferSize);
let bytesRead = 0;
// fd, buffer, offset, length, position, callback
promisifyRead(fd, buffer, bytesRead, chunkSize, bytesRead).then(
(value) => {
expect(value.bytesRead).toBe(chunkSize);
closeSync(fd);
done();
},
(err) => {
closeSync(fd);
fail(`should not be here with error: ${err}.`);
},
);
});
it('fs.write should work with util.promisify', (done: DoneFn) => {
const promisifyWrite = util.promisify(write);
const dest = currentFile + 'write';
const fd = openSync(dest, 'a');
const stats = fstatSync(fd);
const chunkSize = 512;
const buffer = new Buffer(chunkSize);
for (let i = 0; i < chunkSize; i++) {
buffer[i] = 0;
}
// fd, buffer, offset, length, position, callback
promisifyWrite(fd, buffer, 0, chunkSize, 0).then(
(value) => {
expect(value.bytesWritten).toBe(chunkSize);
closeSync(fd);
unlinkSync(dest);
done();
},
(err) => {
closeSync(fd);
unlinkSync(dest);
fail(`should not be here with error: ${err}.`);
},
);
});
});
| {
"end_byte": 7612,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/node/fs.spec.ts"
} |
angular/packages/zone.js/test/node/http.spec.ts_0_1243 | /**
* @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 http from 'http';
describe('http test', () => {
it('http.request should be patched as eventTask', (done) => {
const server = http.createServer((req: any, res: any) => {
res.end();
});
server.listen(9999, () => {
const zoneASpec = {
name: 'A',
onScheduleTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task => {
return delegate.scheduleTask(targetZone, task);
},
};
const zoneA = Zone.current.fork(zoneASpec);
spyOn(zoneASpec, 'onScheduleTask').and.callThrough();
zoneA.run(() => {
const req = http.request(
{hostname: 'localhost', port: '9999', method: 'GET'},
(res: any) => {
expect(Zone.current.name).toEqual('A');
expect(zoneASpec.onScheduleTask).toHaveBeenCalled();
server.close(() => {
done();
});
},
);
req.end();
});
});
});
});
| {
"end_byte": 1243,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/node/http.spec.ts"
} |
angular/packages/zone.js/test/node/timer.spec.ts_0_2787 | /**
* @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 {setTimeout as sleep} from 'node:timers/promises';
import {promisify} from 'node:util';
import {taskSymbol} from '../../lib/common/timers';
describe('node timer', () => {
it('util.promisify should work with setTimeout', (done: DoneFn) => {
const setTimeoutPromise = promisify(setTimeout);
setTimeoutPromise(50, 'value').then(
(value) => {
expect(value).toEqual('value');
done();
},
(error) => {
fail(`should not be here with error: ${error}.`);
},
);
});
it('util.promisify should work with setImmediate', (done: DoneFn) => {
const setImmediatePromise = promisify(setImmediate);
setImmediatePromise('value').then(
(value) => {
expect(value).toEqual('value');
done();
},
(error) => {
fail(`should not be here with error: ${error}.`);
},
);
});
it(`'Timeout.refresh' should restart the 'setTimeout' when it is not scheduled`, async () => {
const spy = jasmine.createSpy();
const timeout = setTimeout(spy, 100) as unknown as NodeJS.Timeout;
let iterations = 5;
for (let i = 1; i <= iterations; i++) {
timeout.refresh();
await sleep(150);
}
expect((timeout as any)[taskSymbol].runCount).toBe(iterations);
clearTimeout(timeout);
expect((timeout as any)[taskSymbol]).toBeNull();
expect(spy).toHaveBeenCalledTimes(iterations);
});
it(`'Timeout.refresh' restarts the 'setTimeout' when it is running`, async () => {
let timeout: NodeJS.Timeout;
const spy = jasmine.createSpy().and.callFake(() => timeout.refresh());
timeout = setTimeout(spy, 100) as unknown as NodeJS.Timeout;
await sleep(250);
expect((timeout as any)[taskSymbol].runCount).toBe(2);
clearTimeout(timeout);
expect((timeout as any)[taskSymbol]).toBeNull();
expect(spy).toHaveBeenCalledTimes(2);
});
it(`'Timeout.refresh' should restart the 'setInterval'`, async () => {
const spy = jasmine.createSpy();
const interval = setInterval(spy, 200) as unknown as NodeJS.Timeout;
// Restart the interval multiple times before the elapsed time.
for (let i = 1; i <= 4; i++) {
interval.refresh();
await sleep(100);
}
// Time did not elapse
expect((interval as any)[taskSymbol].runCount).toBe(0);
expect(spy).toHaveBeenCalledTimes(0);
await sleep(350);
expect((interval as any)[taskSymbol].runCount).toBe(2);
clearInterval(interval);
expect((interval as any)[taskSymbol]).toBeNull();
expect(spy).toHaveBeenCalledTimes(2);
});
});
| {
"end_byte": 2787,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/node/timer.spec.ts"
} |
angular/packages/zone.js/test/node/console.spec.ts_0_1073 | /**
* @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
*/
describe('node console', () => {
const log: string[] = [];
const zone = Zone.current.fork({
name: 'console',
onScheduleTask: function (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
) {
log.push(task.source);
return delegate.scheduleTask(targetZone, task);
},
});
beforeEach(() => {
log.length = 0;
});
it('console methods should run in root zone', () => {
zone.run(() => {
console.log('test');
console.warn('test');
console.error('test');
console.info('test');
console.trace('test');
try {
console.assert(false, 'test');
} catch (error) {}
console.dir('.');
console.time('start');
console.timeEnd('start');
console.debug && console.debug('test');
});
expect(log).toEqual([]);
});
});
| {
"end_byte": 1073,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/node/console.spec.ts"
} |
angular/packages/zone.js/test/node/Error.spec.ts_0_1679 | /**
* @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
*/
describe('ZoneAwareError', () => {
// If the environment does not supports stack rewrites, then these tests will fail
// and there is no point in running them.
if (!(Error as any)['stackRewrite']) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
it('should have all properties from NativeError', () => {
let obj: any = new Object();
Error.captureStackTrace(obj);
expect(obj.stack).not.toBeUndefined();
});
it('should support prepareStackTrace', () => {
const originalPrepareStackTrace = (<any>Error).prepareStackTrace;
(<any>Error).prepareStackTrace = function (error: Error, stack: string) {
return stack;
};
let obj: any = new Object();
Error.captureStackTrace(obj);
expect(obj.stack[0].getFileName()).not.toBeUndefined();
(<any>Error).prepareStackTrace = originalPrepareStackTrace;
});
it('should not add additional stacktrace from Zone when use prepareStackTrace', () => {
const originalPrepareStackTrace = (<any>Error).prepareStackTrace;
(<any>Error).prepareStackTrace = function (error: Error, stack: string) {
return stack;
};
let obj: any = new Object();
Error.captureStackTrace(obj);
expect(obj.stack.length).not.toBe(0);
obj.stack.forEach(function (st: any) {
expect(st.getFunctionName()).not.toEqual('zoneCaptureStackTrace');
});
(<any>Error).prepareStackTrace = originalPrepareStackTrace;
});
});
| {
"end_byte": 1679,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/node/Error.spec.ts"
} |
angular/packages/zone.js/test/node/crypto.spec.ts_0_2995 | /**
* @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
*/
describe('crypto test', () => {
let crypto: any = null;
try {
crypto = require('crypto');
} catch (err) {}
it('crypto randomBytes method should be patched as tasks', (done) => {
if (!crypto) {
done();
return;
}
const zoneASpec = {
name: 'A',
onScheduleTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task => {
return delegate.scheduleTask(targetZone, task);
},
};
const zoneA = Zone.current.fork(zoneASpec);
spyOn(zoneASpec, 'onScheduleTask').and.callThrough();
zoneA.run(() => {
crypto.randomBytes(256, (err: Error, buf: any) => {
expect(err).toBeFalsy();
expect(zoneASpec.onScheduleTask).toHaveBeenCalled();
expect(buf.length).toBe(256);
expect(Zone.current.name).toEqual('A');
done();
});
});
});
it('crypto pbkdf2 method should be patched as tasks', (done) => {
if (!crypto) {
done();
return;
}
const zoneASpec = {
name: 'A',
onScheduleTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task => {
return delegate.scheduleTask(targetZone, task);
},
};
const zoneA = Zone.current.fork(zoneASpec);
spyOn(zoneASpec, 'onScheduleTask').and.callThrough();
zoneA.run(() => {
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err: Error, key: any) => {
expect(err).toBeFalsy();
expect(zoneASpec.onScheduleTask).toHaveBeenCalled();
expect(key.toString('hex')).toEqual(
'3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e47471cc47ed941c7ad618e827304f083f8707f12b7cfdd5f489b782f10cc269e3c08d59ae04919ee902c99dba309cde75569fbe8e6d5c341d6f2576f6618c589e77911a261ee964e242797e64aeca9a134de5ced37fe2521d35d87303edb55a844c8cf11e3b42b18dbd7add0739ea9b172dc3810f911396fa3956f499415db35b79488d74926cdc0c15c3910bf2e4918f5a8efd7de3d4c314bace50c7a95150339eccd32dda2e15d961ea2c91eddd8b03110135a72b3562f189c2d15568854f9a1844cfa62fb77214f2810a2277fd21be95a794cde78e0fe5267a2c1b0894c7729fc4be378156aeb1cff8a215bb4df12312ba676fe2f270dfc3e2b54d8f9c74dfb531530042a09b226fafbcef45368a1ec75f9224a80f2280f75258ff74a2b9a864d857ede49af6a23af837a1f502a6c32e3537402280bef200d847d8fee42649e6d9a00df952ab2fbefc84ba8927f73137fdfbea81f86088edd4cf329edf3f6982429797143cbd43128777c2da269fadd55d18c7921308c7ad7a5bb85ef8d614e2e8461ea3b7fc2edcf72b85da6828a4198c46000953afb1f3a19ecac0df0d660848a0f89ed3d0e0a82115347c9918bdf16fad479c1de16a6b9798437622acff245e6cf80c9ee9d56cada8523ebb6ff348c73c836e5828761f8dda1dd5ab1633caa39b34',
);
expect(Zone.current.name).toEqual('A');
done();
});
});
});
});
| {
"end_byte": 2995,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/node/crypto.spec.ts"
} |
angular/packages/zone.js/test/performance/performance_setup.js_0_8133 | /**
* @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
*/
(function (_global) {
var allTasks = _global['__zone_symbol__performance_tasks'];
if (!allTasks) {
allTasks = _global['__zone_symbol__performance_tasks'] = [];
}
var mark = (_global['__zone_symbol__mark'] = function (name) {
performance && performance['mark'] && performance['mark'](name);
});
var measure = (_global['__zone_symbol__measure'] = function (name, label) {
performance && performance['measure'] && performance['measure'](name, label);
});
var getEntries = (_global['__zone_symbol__getEntries'] = function () {
performance && performance['getEntries'] && performance['getEntries']();
});
var getEntriesByName = (_global['__zone_symbol__getEntriesByName'] = function (name) {
return performance && performance['getEntriesByName'] && performance['getEntriesByName'](name);
});
var clearMarks = (_global['__zone_symbol__clearMarks'] = function (name) {
return performance && performance['clearMarks'] && performance['clearMarks'](name);
});
var clearMeasures = (_global['__zone_symbol__clearMeasures'] = function (name) {
return performance && performance['clearMeasures'] && performance['clearMeasures'](name);
});
var averageMeasures = (_global['__zone_symbol__averageMeasures'] = function (name, times) {
var sum = _global['__zone_symbol__getEntriesByName'](name)
.filter(function (m) {
return m.entryType === 'measure';
})
.map(function (m) {
return m.duration;
})
.reduce(function (sum, d) {
return sum + d;
});
return sum / times;
});
var serialPromise = (_global['__zone_symbol__serialPromise'] = function (promiseFactories) {
let lastPromise;
for (var i = 0; i < promiseFactories.length; i++) {
var promiseFactory = promiseFactories[i];
if (!lastPromise) {
lastPromise = promiseFactory.factory(promiseFactory.context).then(function (value) {
return {value, idx: 0};
});
} else {
lastPromise = lastPromise.then(function (ctx) {
var idx = ctx.idx + 1;
var promiseFactory = promiseFactories[idx];
return promiseFactory.factory(promiseFactory.context).then(function (value) {
return {value, idx};
});
});
}
}
return lastPromise;
});
var callbackContext = (_global['__zone_symbol__callbackContext'] = {});
var zone = (_global['__zone_symbol__callbackZone'] = Zone.current.fork({
name: 'callback',
onScheduleTask: function (delegate, curr, target, task) {
delegate.scheduleTask(target, task);
if (
task.type === callbackContext.type &&
task.source.indexOf(callbackContext.source) !== -1
) {
if (task.type === 'macroTask' || task.type === 'eventTask') {
var invoke = task.invoke;
task.invoke = function () {
mark(callbackContext.measureName);
var result = invoke.apply(this, arguments);
measure(callbackContext.measureName, callbackContext.measureName);
return result;
};
} else if (task.type === 'microTask') {
var callback = task.callback;
task.callback = function () {
mark(callbackContext.measureName);
var result = callback.apply(this, arguments);
measure(callbackContext.measureName, callbackContext.measureName);
return result;
};
}
}
return task;
},
}));
var runAsync = (_global['__zone_symbol__runAsync'] = function (testFn, times, _delay) {
var delay = _delay | 100;
const fnPromise = function () {
return new Promise(function (res, rej) {
// run test with a setTimeout
// several times to decrease measurement error
setTimeout(function () {
testFn().then(function () {
res();
});
}, delay);
});
};
var promiseFactories = [];
for (var i = 0; i < times; i++) {
promiseFactories.push({factory: fnPromise, context: {}});
}
return serialPromise(promiseFactories);
});
var getNativeMethodName = function (nativeWithSymbol) {
return nativeWithSymbol.replace('__zone_symbol__', 'native_');
};
function testAddRemove(api, count) {
var timerId = [];
var name = api.method;
mark(name);
for (var i = 0; i < count; i++) {
timerId.push(api.run());
}
measure(name, name);
if (api.supportClear) {
var clearName = api.clearMethod;
mark(clearName);
for (var i = 0; i < count; i++) {
api.runClear(timerId[i]);
}
measure(clearName, clearName);
}
timerId = [];
var nativeName = getNativeMethodName(api.nativeMethod);
mark(nativeName);
for (var i = 0; i < count; i++) {
timerId.push(api.nativeRun());
}
measure(nativeName, nativeName);
if (api.supportClear) {
var nativeClearName = getNativeMethodName(api.nativeClearMethod);
mark(nativeClearName);
for (var i = 0; i < count; i++) {
api.nativeRunClear(timerId[i]);
}
measure(nativeClearName, nativeClearName);
}
return Promise.resolve(1);
}
function testCallback(api, count) {
var promises = [Promise.resolve(1)];
for (var i = 0; i < count; i++) {
var r = api.run();
if (api.isAsync) {
promises.push(r);
}
}
for (var i = 0; i < count; i++) {
var r = api.nativeRun();
if (api.isAsync) {
promises.push(r);
}
}
return Promise.all(promises);
}
function measureCallback(api, ops) {
var times = ops.times;
var displayText = ops.displayText;
var rawData = ops.rawData;
var summary = ops.summary;
var name = api.method;
var nativeName = getNativeMethodName(api.nativeMethod);
var measure = averageMeasures(name, times);
var nativeMeasure = averageMeasures(nativeName, times);
displayText += `- ${name} costs ${measure} ms\n`;
displayText += `- ${nativeName} costs ${nativeMeasure} ms\n`;
var absolute = Math.floor(1000 * (measure - nativeMeasure)) / 1000;
displayText += `# ${name} is ${absolute}ms slower than ${nativeName}\n`;
rawData[name + '_measure'] = measure;
rawData[nativeName + '_measure'] = nativeMeasure;
summary[name] = absolute + 'ms';
}
function measureAddRemove(api, ops) {
var times = ops.times;
var displayText = ops.displayText;
var rawData = ops.rawData;
var summary = ops.summary;
var name = api.method;
var nativeName = getNativeMethodName(api.nativeMethod);
var measure = averageMeasures(name, times);
var nativeMeasure = averageMeasures(nativeName, times);
displayText += `- ${name} costs ${measure} ms\n`;
displayText += `- ${nativeName} costs ${nativeMeasure} ms\n`;
var percent = Math.floor((100 * (measure - nativeMeasure)) / nativeMeasure);
displayText += `# ${name} is ${percent}% slower than ${nativeName}\n`;
rawData[name + '_measure'] = measure;
rawData[nativeName + '_measure'] = nativeMeasure;
summary[name] = percent + '%';
if (api.supportClear) {
var clearName = api.clearMethod;
var nativeClearName = getNativeMethodName(api.nativeClearMethod);
var clearMeasure = averageMeasures(clearName, times);
var nativeClearMeasure = averageMeasures(nativeClearName, times);
var clearPercent = Math.floor(
(100 * (clearMeasure - nativeClearMeasure)) / nativeClearMeasure,
);
displayText += `- ${clearName} costs ${clearMeasure} ms\n`;
displayText += `- ${nativeClearName} costs ${nativeClearMeasure} ms\n`;
displayText += `# ${clearName} is ${clearPercent}% slower than ${nativeClearName}\n`;
rawData[clearName + '_measure'] = clearMeasure;
rawData[nativeClearName + '_measure'] = nativeClearMeasure;
summary[clearName] = clearPercent + '%';
}
} | {
"end_byte": 8133,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/performance_setup.js"
} |
angular/packages/zone.js/test/performance/performance_setup.js_8137_10285 | var testRunner = (_global['__zone_symbol__testRunner'] = function (testTarget) {
var title = testTarget.title;
var apis = testTarget.apis;
var methods = apis.reduce(function (acc, api) {
return acc.concat(
[api.method, api.nativeMethod].concat(
api.supportClear ? [api.clearMethod, api.nativeClearMethod] : [],
).concat[(api.method + '_callback', api.nativeMethod + '_callback')],
);
}, []);
var times = testTarget.times;
allTasks.push({
title: title,
cleanFn: function () {
methods.forEach(function (m) {
clearMarks(m);
clearMeasures(m);
});
},
before: function () {
testTarget.before && testTarget.before();
},
after: function () {
testTarget.after && testTarget.after();
},
testFn: function () {
var count = typeof testTarget.count === 'number' ? testTarget.count : 10000;
var times = typeof testTarget.times === 'number' ? testTarget.times : 5;
var testFunction = function () {
var promises = [];
apis.forEach(function (api) {
if (api.isCallback) {
var r = testCallback(api, count / 100);
promises.push(api.isAsync ? r : Promise.resolve(1));
} else {
var r = testAddRemove(api, count);
promises.push[api.isAsync ? r : Promise.resolve(1)];
}
});
return Promise.all(promises);
};
return runAsync(testFunction, times).then(function () {
var displayText = `running ${count} times\n`;
var rawData = {};
var summary = {};
apis.forEach(function (api) {
if (api.isCallback) {
measureCallback(api, {times, displayText, rawData, summary});
} else {
measureAddRemove(api, {times, displayText, rawData, summary});
}
});
return Promise.resolve({displayText: displayText, rawData: rawData, summary: summary});
});
},
});
});
})(typeof window === 'undefined' ? global : window); | {
"end_byte": 10285,
"start_byte": 8137,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/performance_setup.js"
} |
angular/packages/zone.js/test/performance/eventTarget.js_0_3078 | /**
* @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
*/
(function (_global) {
var testRunner = _global['__zone_symbol__testRunner'];
var mark = _global['__zone_symbol__mark'];
var measure = _global['__zone_symbol__measure'];
var zone = _global['__zone_symbol__callbackZone'];
var button;
var testTarget = {
title: 'addEventListener',
times: 10,
before: function () {
button = document.createElement('button');
document.body.appendChild(button);
_global['__zone_symbol__callbackContext'].measureName = 'addEventListener_callback';
_global['__zone_symbol__callbackContext'].type = 'eventTask';
_global['__zone_symbol__callbackContext'].source = 'addEventListener';
},
after: function () {
document.body.removeChild(button);
button = null;
},
apis: [
{
supportClear: true,
method: 'addEventListener',
nativeMethod: '__zone_symbol__addEventListener',
clearMethod: 'removeEventListener',
nativeClearMethod: '__zone_symbol__removeEventListener',
run: function () {
var listener = function () {};
button.addEventListener('click', listener);
return listener;
},
runClear: function (timerId) {
return button.removeEventListener('click', timerId);
},
nativeRun: function () {
var listener = function () {};
button['__zone_symbol__addEventListener']('click', listener);
return listener;
},
nativeRunClear: function (timerId) {
return button['__zone_symbol__removeEventListener']('click', timerId);
},
},
{
isCallback: true,
supportClear: false,
method: 'addEventListener_callback',
nativeMethod: 'native_addEventListener_callback',
run: function () {
var listener = function () {};
zone.run(function () {
button.addEventListener('click', listener);
});
var event = document.createEvent('Event');
event.initEvent('click', true, true);
button.dispatchEvent(event);
button.removeEventListener('click', listener);
},
nativeRun: function () {
var func = function () {};
var listener = function () {
mark('native_addEventListener_callback');
func.apply(this, arguments);
measure('native_addEventListener_callback', 'native_addEventListener_callback');
};
button['__zone_symbol__addEventListener']('click', listener);
var event = document.createEvent('Event');
event.initEvent('click', true, true);
button.dispatchEvent(event);
button['__zone_symbol__removeEventListener']('click', listener);
},
},
],
};
return testRunner(testTarget);
})(typeof window === 'undefined' ? global : window);
| {
"end_byte": 3078,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/eventTarget.js"
} |
angular/packages/zone.js/test/performance/timeout.js_0_2257 | /**
* @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
*/
(function (_global) {
var mark = _global['__zone_symbol__mark'];
var measure = _global['__zone_symbol__measure'];
var testRunner = _global['__zone_symbol__testRunner'];
var setTimeout = _global['setTimeout'];
var clearTimeout = _global['clearTimeout'];
var nativeSetTimeout = _global['__zone_symbol__setTimeout'];
var nativeClearTimeout = _global['__zone_symbol__clearTimeout'];
var zone = _global['__zone_symbol__callbackZone'];
var testTarget = {
title: 'timer',
times: 10,
before: function () {
_global['__zone_symbol__callbackContext'].measureName = 'setTimeout_callback';
_global['__zone_symbol__callbackContext'].type = 'macroTask';
_global['__zone_symbol__callbackContext'].source = 'setTimeout';
},
apis: [
{
supportClear: true,
method: 'setTimeout',
nativeMethod: '__zone_symbol__setTimeout',
clearMethod: 'clearTimeout',
nativeClearMethod: '__zone_symbol__clearTimeout',
run: function () {
return setTimeout(function () {});
},
runClear: function (timerId) {
return clearTimeout(timerId);
},
nativeRun: function () {
return nativeSetTimeout(function () {});
},
nativeRunClear: function (timerId) {
return nativeClearTimeout(timerId);
},
},
{
isCallback: true,
supportClear: false,
method: 'setTimeout_callback',
nativeMethod: 'native_setTimeout_callback',
run: function () {
zone.run(function () {
setTimeout(function () {});
});
},
nativeRun: function () {
var func = function () {};
nativeSetTimeout(function () {
mark('native_setTimeout_callback');
func.apply(this, arguments);
measure('native_setTimeout_callback', 'native_setTimeout_callback');
});
},
},
],
};
return testRunner(testTarget);
})(typeof window === 'undefined' ? global : window);
| {
"end_byte": 2257,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/timeout.js"
} |
angular/packages/zone.js/test/performance/promise.js_0_2101 | /**
* @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
*/
(function (_global) {
var mark = _global['__zone_symbol__mark'];
var measure = _global['__zone_symbol__measure'];
var testRunner = _global['__zone_symbol__testRunner'];
var zone = _global['__zone_symbol__callbackZone'];
var nativePromise = _global['__zone_symbol__Promise'];
var resolved = Promise.resolve(1);
var nativeResolved = nativePromise.resolve(1);
var testTarget = {
title: 'Promise',
times: 10,
before: function () {
_global['__zone_symbol__callbackContext'].measureName = 'Promise_callback';
_global['__zone_symbol__callbackContext'].type = 'microTask';
_global['__zone_symbol__callbackContext'].source = 'Promise.then';
},
apis: [
{
supportClear: false,
isAsync: true,
method: 'Promise',
nativeMethod: 'native_Promise',
run: function () {
return resolved.then(function () {});
},
nativeRun: function () {
return nativeResolved['__zone_symbol__then'](function () {});
},
},
{
isCallback: true,
isAsync: true,
supportClear: false,
method: 'Promise_callback',
nativeMethod: 'native_Promise_callback',
run: function () {
return zone.run(function () {
return Promise.resolve(1).then(function (v) {
return v;
});
});
},
nativeRun: function () {
var func = function () {};
return _global['__zone_symbol__Promise'].resolve(1)['__zone_symbol__then'](function () {
mark('native_Promise_callback');
var result = func.apply(this, arguments);
measure('native_Promise_callback', 'native_Promise_callback');
return result;
});
},
},
],
};
return testRunner(testTarget);
})(typeof window === 'undefined' ? global : window);
| {
"end_byte": 2101,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/promise.js"
} |
angular/packages/zone.js/test/performance/performance_ui.js_0_4689 | /**
* @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
*/
(function (_global) {
var options;
function setAttributes(elem, attrs) {
if (!attrs) {
return;
}
Object.keys(attrs).forEach(function (key) {
elem.setAttribute(key, attrs[key]);
});
}
function createLi(attrs) {
var li = document.createElement('li');
setAttributes(li, attrs);
return li;
}
function createLabel(attrs) {
var label = document.createElement('label');
setAttributes(label, attrs);
return label;
}
function createButton(attrs, innerHtml) {
var button = document.createElement('button');
button.innerHTML = innerHtml;
setAttributes(button, attrs);
return button;
}
function createTextNode(text) {
return document.createTextNode(text);
}
function createCheckbox(attrs, checked) {
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = !!checked;
setAttributes(checkbox, attrs);
return checkbox;
}
function createUl(attrs) {
var ul = document.createElement('ul');
setAttributes(ul, attrs);
return ul;
}
var serailPromise = _global['__zone_symbol__serialPromise'];
_global['__zone_symbol__testTargetsUIBuild'] = function (_options) {
options = _options;
var allButton = createButton({}, 'test selected');
allButton.addEventListener('click', function () {
var promiseFactories = [];
for (var i = 0; i < options.tests.length; i++) {
var checkbox = document.getElementById('testcheck' + i);
if (checkbox.checked) {
var test = options.tests[i];
promiseFactories.push({
factory: function (context) {
return doTest(context.test, context.idx);
},
context: {test: test, idx: i},
});
}
}
serailPromise(promiseFactories);
});
options.targetContainer.appendChild(allButton);
var ul = createUl();
options.targetContainer.appendChild(ul);
for (var i = 0; i < options.tests.length; i++) {
buildTestItemUI(ul, options.tests[i], i);
}
};
function buildTestItemUI(ul, testItem, idx) {
var li = createLi({'id': 'test' + idx});
var button = createButton({'id': 'buttontest' + idx}, 'begin test');
buildButtonClickHandler(button);
var title = createTextNode(options.tests[idx].title);
var checkbox = createCheckbox({'id': 'testcheck' + idx}, true);
var label = createLabel({'id': 'label' + idx});
li.appendChild(checkbox);
li.appendChild(title);
li.appendChild(button);
li.appendChild(label);
ul.appendChild(li);
}
function processTestResult(test, result, id) {
var split = result.displayText.split('\n');
options.jsonResult[test.title] = result.rawData;
options.jsonContainer.innerHTML =
'<div style="display:none">' + JSON.stringify(options.jsonResult) + '</div>';
var summary = result.summary;
var row = options.resultsContainer.insertRow();
var cell = row.insertCell();
cell.innerHTML = test.title;
cell.rowSpan = Object.keys(summary).length;
var idx = 0;
Object.keys(summary).forEach(function (key) {
var tableRow = row;
if (idx !== 0) {
tableRow = options.resultsContainer.insertRow();
}
var keyCell = tableRow.insertCell();
keyCell.innerHTML = key;
var valueCell = tableRow.insertCell();
valueCell.innerHTML = summary[key];
idx++;
});
var testLi = document.getElementById('test' + id);
for (var j = 0; j < split.length; j++) {
var br = document.createElement('br');
var s = document.createTextNode(split[j]);
testLi.appendChild(br);
testLi.appendChild(s);
}
}
function doTest(test, id) {
test.cleanFn();
test.before();
var button = document.getElementById('buttontest' + id);
button.setAttribute('enabled', 'false');
var label = document.getElementById('label' + id);
label.innerHTML = 'Testing';
return test.testFn().then(function (result) {
processTestResult(test, result, id);
test.after();
label.innerHTML = 'Finished';
button.setAttribute('enabled', 'true');
});
}
function buildButtonClickHandler(button) {
button.onclick = function (event) {
var target = event.target;
var id = target.getAttribute('id').substring(10);
var test = options.tests[id];
doTest(test, id);
};
}
})(typeof window === 'undefined' ? global : window);
| {
"end_byte": 4689,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/performance_ui.js"
} |
angular/packages/zone.js/test/performance/performance.html_0_1526 | <!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
}
table,
th,
td {
border: 1px solid black;
}
ul {
font-size: 24px
}
li {
font-size: 16px
}
</style>
<script src='../../dist/zone.js'></script>
<script src='./performance_setup.js'></script>
<script src='./performance_ui.js'></script>
<script src='./timeout.js'></script>
<script src='./requestAnimationFrame.js'></script>
<script src='./eventTarget.js'></script>
<script src='./xhr.js'></script>
<script src='./promise.js'></script>
<script>
window.onload = function () {
var jsonResult = {};
var div = document.getElementById('tests');
var json = document.getElementById('json');
var table = document.getElementById('summary');
var tests = window['__zone_symbol__performance_tasks'];
window['__zone_symbol__testTargetsUIBuild']({
tests: tests,
targetContainer: div,
resultsContainer: table,
jsonContainer: json,
jsonResult: jsonResult
});
}
</script>
</head>
<body>
<div id="thetext">Performance Bencnhmark of Zone.js vs Native Delegate!</div>
<div id="tests"></div>
<div>
<table id="summary" class="table">
<tr class="tableheader">
<th>
Module
</th>
<th>
API
</th>
<th>
Performance overhead
</th>
</tr>
</table>
</div>
<div id="json"></div>
</body>
</html>
| {
"end_byte": 1526,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/performance.html"
} |
angular/packages/zone.js/test/performance/requestAnimationFrame.js_0_2403 | /**
* @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
*/
(function (_global) {
var mark = _global['__zone_symbol__mark'];
var measure = _global['__zone_symbol__measure'];
var zone = _global['__zone_symbol__callbackZone'];
var testRunner = _global['__zone_symbol__testRunner'];
var raf = _global['requestAnimationFrame'];
var cancel = _global['cancelAnimationFrame'];
var nativeRaf = _global['__zone_symbol__requestAnimationFrame'];
var nativeCancel = _global['__zone_symbol__cancelAnimationFrame'];
var testTarget = {
title: 'requestAnimationFrame',
times: 10,
before: function () {
_global['__zone_symbol__callbackContext'].measureName = 'requestAnimationFrame_callback';
_global['__zone_symbol__callbackContext'].type = 'macroTask';
_global['__zone_symbol__callbackContext'].source = 'requestAnimationFrame';
},
apis: [
{
supportClear: true,
method: 'requestAnimationFrame',
nativeMethod: '__zone_symbol__requestAnimationFrame',
clearMethod: 'cancelAnimationFrame',
nativeClearMethod: '__zone_symbol__cancelAnimationFrame',
run: function () {
return raf(function () {});
},
runClear: function (timerId) {
return cancel(timerId);
},
nativeRun: function () {
return nativeRaf(function () {});
},
nativeRunClear: function (timerId) {
return nativeCancel(timerId);
},
},
{
isCallback: true,
supportClear: false,
method: 'requestAnimationFrame_callback',
nativeMethod: 'native_requestAnimationFrame_callback',
run: function () {
zone.run(function () {
raf(function () {});
});
},
nativeRun: function () {
var func = function () {};
nativeRaf(function () {
mark('native_requestAnimationFrame_callback');
func.apply(this, arguments);
measure(
'native_requestAnimationFrame_callback',
'native_requestAnimationFrame_callback',
);
});
},
},
],
};
return testRunner(testTarget);
})(typeof window === 'undefined' ? global : window);
| {
"end_byte": 2403,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/requestAnimationFrame.js"
} |
angular/packages/zone.js/test/performance/xhr.js_0_1618 | /**
* @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
*/
(function (_global) {
var mark = _global['__zone_symbol__mark'];
var measure = _global['__zone_symbol__measure'];
var testRunner = _global['__zone_symbol__testRunner'];
var zone = _global['__zone_symbol__callbackZone'];
var testTarget = {
title: 'xhr',
times: 3,
count: 1000,
before: function () {
_global['__zone_symbol__callbackContext'].measureName = 'xhr_callback';
_global['__zone_symbol__callbackContext'].type = 'macroTask';
_global['__zone_symbol__callbackContext'].source = 'send';
},
apis: [
{
supportClear: true,
method: 'XHR.send',
nativeMethod: 'native.XHR.send',
clearMethod: 'XHR.abort',
nativeClearMethod: 'native.XHR.abort',
run: function () {
var xhr = new XMLHttpRequest();
xhr.open('get', 'http://localhost:8080', true);
xhr.send();
return xhr;
},
runClear: function (xhr) {
xhr.abort();
},
nativeRun: function () {
var xhr = new XMLHttpRequest();
xhr['__zone_symbol__open']('get', 'http://localhost:8080', true);
xhr['__zone_symbol__send']();
return xhr;
},
nativeRunClear: function (xhr) {
xhr['__zone_symbol__abort']();
},
},
],
};
return testRunner(testTarget);
})(typeof window === 'undefined' ? global : window);
| {
"end_byte": 1618,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/performance/xhr.js"
} |
angular/packages/zone.js/test/assets/worker.js_0_226 | /**
* @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
*/
postMessage('worker');
| {
"end_byte": 226,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/assets/worker.js"
} |
angular/packages/zone.js/test/assets/import.html_0_11 | <p>hey</p>
| {
"end_byte": 11,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/assets/import.html"
} |
angular/packages/zone.js/test/assets/empty-worker.js_0_203 | /**
* @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
*/
| {
"end_byte": 203,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/assets/empty-worker.js"
} |
angular/packages/zone.js/test/zone-spec/task-tracking.spec.ts_0_3819 | /**
* @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 {TaskTrackingZoneSpec} from '../../lib/zone-spec/task-tracking';
import {supportPatchXHROnProperty} from '../test-util';
declare const global: any;
describe('TaskTrackingZone', function () {
let _TaskTrackingZoneSpec: typeof TaskTrackingZoneSpec = (Zone as any)['TaskTrackingZoneSpec'];
let taskTrackingZoneSpec: TaskTrackingZoneSpec | null = null;
let taskTrackingZone: Zone;
beforeEach(() => {
taskTrackingZoneSpec = new _TaskTrackingZoneSpec();
taskTrackingZone = Zone.current.fork(taskTrackingZoneSpec);
});
it('should track tasks', (done: Function) => {
taskTrackingZone.run(() => {
taskTrackingZone.scheduleMicroTask('test1', () => {});
expect(taskTrackingZoneSpec!.microTasks.length).toBe(1);
expect(taskTrackingZoneSpec!.microTasks[0].source).toBe('test1');
setTimeout(() => {});
expect(taskTrackingZoneSpec!.macroTasks.length).toBe(1);
expect(taskTrackingZoneSpec!.macroTasks[0].source).toBe('setTimeout');
taskTrackingZone.cancelTask(taskTrackingZoneSpec!.macroTasks[0]);
expect(taskTrackingZoneSpec!.macroTasks.length).toBe(0);
setTimeout(() => {
// assert on execution it is null
expect(taskTrackingZoneSpec!.macroTasks.length).toBe(0);
expect(taskTrackingZoneSpec!.microTasks.length).toBe(0);
// If a browser does not have XMLHttpRequest, then end test here.
if (typeof global['XMLHttpRequest'] == 'undefined') return done();
const xhr = new XMLHttpRequest();
xhr.open('get', '/', true);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
// clear current event tasks using setTimeout
setTimeout(() => {
expect(taskTrackingZoneSpec!.macroTasks.length).toBe(0);
expect(taskTrackingZoneSpec!.microTasks.length).toBe(0);
if (supportPatchXHROnProperty()) {
expect(taskTrackingZoneSpec!.eventTasks.length).not.toBe(0);
}
taskTrackingZoneSpec!.clearEvents();
expect(taskTrackingZoneSpec!.eventTasks.length).toBe(0);
done();
});
}
};
xhr.send();
expect(taskTrackingZoneSpec!.macroTasks.length).toBe(1);
expect(taskTrackingZoneSpec!.macroTasks[0].source).toBe('XMLHttpRequest.send');
if (supportPatchXHROnProperty()) {
expect(taskTrackingZoneSpec!.eventTasks[0].source).toMatch(
/\.addEventListener:readystatechange/,
);
}
});
});
});
it('should capture task creation stacktrace', (done) => {
taskTrackingZone.run(() => {
setTimeout(() => {
done();
});
expect((taskTrackingZoneSpec!.macroTasks[0] as any)['creationLocation']).toBeTruthy();
});
});
it('should track periodic task until it is canceled', (done) => {
taskTrackingZone.run(() => {
const intervalCallback = jasmine.createSpy('intervalCallback');
const interval = setInterval(intervalCallback, 1);
expect(intervalCallback).not.toHaveBeenCalled();
expect(taskTrackingZoneSpec!.macroTasks.length).toBe(1);
expect(taskTrackingZoneSpec!.macroTasks[0].source).toBe('setInterval');
setTimeout(() => {
expect(intervalCallback).toHaveBeenCalled();
expect(taskTrackingZoneSpec!.macroTasks.length).toBe(1);
expect(taskTrackingZoneSpec!.macroTasks[0].source).toBe('setInterval');
clearInterval(interval);
expect(taskTrackingZoneSpec!.macroTasks.length).toBe(0);
done();
}, 2);
});
});
});
| {
"end_byte": 3819,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/task-tracking.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/long-stack-trace-zone.spec.ts_0_6684 | /**
* @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 {isBrowser, isIE, zoneSymbol} from '../../lib/common/utils';
import {ifEnvSupports, isSafari, isSupportSetErrorStack} from '../test-util';
const defineProperty = (Object as any)[zoneSymbol('defineProperty')] || Object.defineProperty;
describe(
'longStackTraceZone',
ifEnvSupports(isSupportSetErrorStack, function () {
let log: Error[];
let lstz: Zone;
let longStackTraceZoneSpec = (Zone as any)['longStackTraceZoneSpec'];
let defaultTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
beforeEach(function () {
lstz = Zone.current.fork(longStackTraceZoneSpec).fork({
name: 'long-stack-trace-zone-test',
onHandleError: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
): boolean => {
parentZoneDelegate.handleError(targetZone, error);
log.push(error);
return false;
},
});
log = [];
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
});
afterEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = defaultTimeout;
});
function expectElapsed(stack: string, expectedCount: number) {
try {
let actualCount = stack.split('_Elapsed_').length;
if (actualCount !== expectedCount) {
expect(actualCount).toEqual(expectedCount);
console.log(stack);
}
} catch (e) {
expect(e).toBe(null);
}
}
it('should produce long stack traces', function (done) {
lstz.run(function () {
setTimeout(function () {
setTimeout(function () {
setTimeout(function () {
expectElapsed(log[0].stack!, 3);
done();
}, 0);
throw new Error('Hello');
}, 0);
}, 0);
});
});
it(
'should produce long stack traces for optimized eventTask',
ifEnvSupports(
() => isBrowser,
function () {
lstz.run(function () {
const button = document.createElement('button');
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
document.body.appendChild(button);
button.addEventListener('click', function () {
expectElapsed(log[0].stack!, 1);
});
button.dispatchEvent(clickEvent);
document.body.removeChild(button);
});
},
),
);
it(
'should not overwrite long stack traces data for different optimized eventTasks',
ifEnvSupports(
() => isBrowser,
function () {
lstz.run(function () {
const button = document.createElement('button');
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
document.body.appendChild(button);
const div = document.createElement('div');
const enterEvent = document.createEvent('Event');
enterEvent.initEvent('mouseenter', true, true);
document.body.appendChild(div);
button.addEventListener('click', function () {
throw new Error('clickError');
});
div.addEventListener('mouseenter', function () {
throw new Error('enterError');
});
button.dispatchEvent(clickEvent);
div.dispatchEvent(enterEvent);
expect(log.length).toBe(2);
if (!isSafari() && !isIE()) {
expect(log[0].stack === log[1].stack).toBe(false);
}
document.body.removeChild(button);
document.body.removeChild(div);
});
},
),
);
it('should produce a long stack trace even if stack setter throws', (done) => {
let wasStackAssigned = false;
let error = new Error('Expected error');
defineProperty(error, 'stack', {
configurable: false,
get: () => 'someStackTrace',
set: (v: any) => {
throw new Error('no writes');
},
});
lstz.run(() => {
setTimeout(() => {
throw error;
});
});
setTimeout(() => {
const e = log[0];
expect((e as any).longStack).toBeTruthy();
done();
});
});
it('should produce long stack traces when has uncaught error in promise', function (done) {
lstz.runGuarded(function () {
setTimeout(function () {
setTimeout(function () {
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
reject(new Error('Hello Promise'));
}, 0);
});
promise.then(function () {
fail('should not get here');
});
setTimeout(function () {
expectElapsed(log[0].stack!, 5);
done();
}, 0);
}, 0);
}, 0);
});
});
it('should produce long stack traces when handling error in promise', function (done) {
lstz.runGuarded(function () {
setTimeout(function () {
setTimeout(function () {
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
try {
throw new Error('Hello Promise');
} catch (err) {
reject(err);
}
}, 0);
});
promise.catch(function (error) {
// should be able to get long stack trace
const longStackFrames: string = longStackTraceZoneSpec.getLongStackTrace(error);
expectElapsed(longStackFrames, 4);
done();
});
}, 0);
}, 0);
});
});
it('should not produce long stack traces if Error.stackTraceLimit = 0', function (done) {
const originalStackTraceLimit = Error.stackTraceLimit;
lstz.run(function () {
setTimeout(function () {
setTimeout(function () {
setTimeout(function () {
if (log[0].stack) {
expectElapsed(log[0].stack!, 1);
}
Error.stackTraceLimit = originalStackTraceLimit;
done();
}, 0);
Error.stackTraceLimit = 0;
throw new Error('Hello');
}, 0);
}, 0);
});
});
}),
);
| {
"end_byte": 6684,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/long-stack-trace-zone.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/async-test.spec.ts_0_8086 | /**
* @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 {ProxyZoneSpec} from '../../lib/zone-spec/proxy';
import {ifEnvSupports} from '../test-util';
describe('AsyncTestZoneSpec', function () {
let log: string[];
const AsyncTestZoneSpec = (Zone as any)['AsyncTestZoneSpec'];
function failCallback() {
log.push('fail');
}
function emptyRun() {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
}
beforeEach(() => {
log = [];
});
it('should call finish after zone is run in sync call', (done) => {
let finished = false;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
expect(finished).toBe(true);
done();
},
failCallback,
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
finished = true;
});
});
it('should call finish after a setTimeout is done', (done) => {
let finished = false;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
expect(finished).toBe(true);
done();
},
() => {
done.fail('async zone called failCallback unexpectedly');
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
setTimeout(() => {
finished = true;
}, 10);
});
});
it('should call finish after microtasks are done', (done) => {
let finished = false;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
expect(finished).toBe(true);
done();
},
() => {
done.fail('async zone called failCallback unexpectedly');
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
Promise.resolve().then(() => {
finished = true;
});
});
});
it('should call finish after both micro and macrotasks are done', (done) => {
let finished = false;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
expect(finished).toBe(true);
done();
},
() => {
done.fail('async zone called failCallback unexpectedly');
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
new Promise<void>((resolve) => {
setTimeout(() => {
resolve();
}, 10);
}).then(() => {
finished = true;
});
});
});
it('should call finish after both macro and microtasks are done', (done) => {
let finished = false;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
expect(finished).toBe(true);
done();
},
() => {
done.fail('async zone called failCallback unexpectedly');
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
Promise.resolve().then(() => {
setTimeout(() => {
finished = true;
}, 10);
});
});
});
it('should not call done multiple times in sync test', (done) => {
const testFn = () => {
Zone.current.run(() => {});
Zone.current.run(() => {});
};
let doneCalledCount = 0;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
doneCalledCount++;
},
() => {},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(testFn);
setTimeout(() => {
expect(doneCalledCount).toBe(1);
done();
});
});
it('should not call done multiple times in async test with nested zone', (done) => {
const testFn = () => {
Promise.resolve(1).then(() => {});
};
let doneCalledCount = 0;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
doneCalledCount++;
},
() => {},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
const c1 = atz.fork({
name: 'child1',
onHasTask: (delegate, current, target, hasTaskState) => {
return delegate.hasTask(target, hasTaskState);
},
});
const c2 = c1.fork({
name: 'child2',
onHasTask: (delegate, current, target, hasTaskState) => {
return delegate.hasTask(target, hasTaskState);
},
});
c2.run(testFn);
setTimeout(() => {
expect(doneCalledCount).toBe(1);
done();
}, 50);
});
it(
'should not call done multiple times when proxy zone captures previously ' +
'captured microtasks',
(done) => {
const ProxyZoneSpec = (Zone as any)['ProxyZoneSpec'];
const proxyZoneSpec = new ProxyZoneSpec(null) as ProxyZoneSpec;
const proxyZone = Zone.current.fork(proxyZoneSpec);
// This simulates a simple `beforeEach` patched, running in the proxy zone,
// but not necessarily waiting for the promise to be resolved. This can
// be the case e.g. in the AngularJS upgrade tests where the bootstrap is
// performed in the before each, but the waiting is done in the actual `it` specs.
proxyZone.run(() => {
Promise.resolve().then(() => {});
});
let doneCalledCount = 0;
const testFn = () => {
// When a test executes with `waitForAsync`, the proxy zone delegates to the async
// test zone, potentially also capturing tasks leaking from `beforeEach`.
proxyZoneSpec.setDelegate(testZoneSpec);
};
const testZoneSpec = new AsyncTestZoneSpec(
() => {
// reset the proxy zone delegate after test completion.
proxyZoneSpec.setDelegate(null);
doneCalledCount++;
},
() => done.fail('Error occurred in the async test zone.'),
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(testFn);
setTimeout(() => {
expect(doneCalledCount).toBe(1);
done();
}, 50);
},
);
describe(
'event tasks',
ifEnvSupports(
'document',
() => {
let button: HTMLButtonElement;
beforeEach(function () {
button = document.createElement('button');
document.body.appendChild(button);
});
afterEach(function () {
document.body.removeChild(button);
});
it('should call finish because an event task is considered as sync', (done) => {
let finished = false;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
expect(finished).toBe(true);
done();
},
() => {
done.fail('async zone called failCallback unexpectedly');
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
const listener = () => {
finished = true;
};
button.addEventListener('click', listener);
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
button.dispatchEvent(clickEvent);
});
});
it('should call finish after an event task is done asynchronously', (done) => {
let finished = false;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
expect(finished).toBe(true);
done();
},
() => {
done.fail('async zone called failCallback unexpectedly');
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
button.addEventListener('click', () => {
setTimeout(() => {
finished = true;
}, 10);
});
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
button.dispatchEvent(clickEvent);
});
});
},
emptyRun,
),
); | {
"end_byte": 8086,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/async-test.spec.ts_8090_12110 | describe(
'XHRs',
ifEnvSupports(
'XMLHttpRequest',
() => {
beforeEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 200000;
});
beforeEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
});
it('should wait for XHRs to complete', function (done) {
let req: XMLHttpRequest;
let finished = false;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
expect(finished).toBe(true);
done();
},
(err: Error) => {
done.fail('async zone called failCallback unexpectedly');
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState === XMLHttpRequest.DONE) {
finished = true;
}
};
req.open('get', '/', true);
req.send();
});
});
it('should fail if an xhr fails', function (done) {
let req: XMLHttpRequest;
const testZoneSpec = new AsyncTestZoneSpec(
() => {
done.fail('expected failCallback to be called');
},
(err: Error) => {
expect(err.message).toEqual('bad url failure');
done();
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
req = new XMLHttpRequest();
req.onload = () => {
if (req.status != 200) {
throw new Error('bad url failure');
}
};
req.open('get', '/bad-url', true);
req.send();
});
});
},
emptyRun,
),
);
it('should not fail if setInterval is used and canceled', (done) => {
const testZoneSpec = new AsyncTestZoneSpec(
() => {
done();
},
(err: Error) => {
done.fail('async zone called failCallback unexpectedly');
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
let id = setInterval(() => {
clearInterval(id);
}, 100);
});
});
it('should fail if an error is thrown asynchronously', (done) => {
const testZoneSpec = new AsyncTestZoneSpec(
() => {
done.fail('expected failCallback to be called');
},
(err: Error) => {
expect(err.message).toEqual('my error');
done();
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
setTimeout(() => {
throw new Error('my error');
}, 10);
});
});
it('should fail if a promise rejection is unhandled', (done) => {
const testZoneSpec = new AsyncTestZoneSpec(
() => {
done.fail('expected failCallback to be called');
},
(err: Error) => {
expect(err.message).toEqual('Uncaught (in promise): my reason');
// Without the `runInTestZone` function, the callback continues to execute
// in the async test zone. We don't want to trigger new tasks upon
// the failure callback already being invoked (`jasmine.done` schedules tasks)
Zone.root.run(() => done());
},
'name',
);
const atz = Zone.current.fork(testZoneSpec);
atz.run(function () {
Promise.reject('my reason');
});
});
const asyncTest: any = (Zone as any)[Zone.__symbol__('asyncTest')];
function wrapAsyncTest(fn: Function, doneFn?: Function) {
return function (this: unknown, done: Function) {
const asyncWrapper = asyncTest(fn);
return asyncWrapper.apply(this, [
function (this: unknown) {
if (doneFn) {
doneFn();
}
return done.apply(this, arguments);
},
]);
};
} | {
"end_byte": 12110,
"start_byte": 8090,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/async-test.spec.ts_12114_17998 | describe('async', () => {
describe('non zone aware async task in promise should be detected', () => {
let finished = false;
const _global: any =
(typeof window !== 'undefined' && window) ||
(typeof self !== 'undefined' && self) ||
global;
beforeEach(() => {
_global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] = true;
});
afterEach(() => {
_global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] = false;
});
it(
'should be able to detect non zone aware async task in promise',
wrapAsyncTest(
() => {
new Promise((res, rej) => {
const g: any = typeof window === 'undefined' ? global : window;
g[Zone.__symbol__('setTimeout')](res, 100);
}).then(() => {
finished = true;
});
},
() => {
expect(finished).toBe(true);
},
),
);
});
describe('test without beforeEach', () => {
const logs: string[] = [];
it(
'should automatically done after async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('timeout');
}, 100);
},
() => {
expect(logs).toEqual(['timeout']);
logs.splice(0);
},
),
);
it(
'should automatically done after all nested async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('timeout');
setTimeout(() => {
logs.push('nested timeout');
}, 100);
}, 100);
},
() => {
expect(logs).toEqual(['timeout', 'nested timeout']);
logs.splice(0);
},
),
);
it(
'should automatically done after multiple async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('1st timeout');
}, 100);
setTimeout(() => {
logs.push('2nd timeout');
}, 100);
},
() => {
expect(logs).toEqual(['1st timeout', '2nd timeout']);
logs.splice(0);
},
),
);
});
describe('test with sync beforeEach', () => {
const logs: string[] = [];
beforeEach(() => {
logs.splice(0);
logs.push('beforeEach');
});
it(
'should automatically done after async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('timeout');
}, 100);
},
() => {
expect(logs).toEqual(['beforeEach', 'timeout']);
},
),
);
});
describe('test with async beforeEach', () => {
const logs: string[] = [];
beforeEach(
wrapAsyncTest(() => {
setTimeout(() => {
logs.splice(0);
logs.push('beforeEach');
}, 100);
}),
);
it(
'should automatically done after async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('timeout');
}, 100);
},
() => {
expect(logs).toEqual(['beforeEach', 'timeout']);
},
),
);
it(
'should automatically done after all nested async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('timeout');
setTimeout(() => {
logs.push('nested timeout');
}, 100);
}, 100);
},
() => {
expect(logs).toEqual(['beforeEach', 'timeout', 'nested timeout']);
},
),
);
it(
'should automatically done after multiple async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('1st timeout');
}, 100);
setTimeout(() => {
logs.push('2nd timeout');
}, 100);
},
() => {
expect(logs).toEqual(['beforeEach', '1st timeout', '2nd timeout']);
},
),
);
});
describe('test with async beforeEach and sync afterEach', () => {
const logs: string[] = [];
beforeEach(
wrapAsyncTest(() => {
setTimeout(() => {
expect(logs).toEqual([]);
logs.push('beforeEach');
}, 100);
}),
);
afterEach(() => {
logs.splice(0);
});
it(
'should automatically done after async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('timeout');
}, 100);
},
() => {
expect(logs).toEqual(['beforeEach', 'timeout']);
},
),
);
});
describe('test with async beforeEach and async afterEach', () => {
const logs: string[] = [];
beforeEach(
wrapAsyncTest(() => {
setTimeout(() => {
expect(logs).toEqual([]);
logs.push('beforeEach');
}, 100);
}),
);
afterEach(
wrapAsyncTest(() => {
setTimeout(() => {
logs.splice(0);
}, 100);
}),
);
it(
'should automatically done after async tasks finished',
wrapAsyncTest(
() => {
setTimeout(() => {
logs.push('timeout');
}, 100);
},
() => {
expect(logs).toEqual(['beforeEach', 'timeout']);
},
),
);
});
});
}); | {
"end_byte": 17998,
"start_byte": 12114,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/fake-async-test.spec.ts_0_3272 | /**
* @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 '../../lib/rxjs/rxjs-fake-async';
import {Observable} from 'rxjs';
import {delay} from 'rxjs/operators';
import {isNode, patchMacroTask} from '../../lib/common/utils';
import {ifEnvSupports} from '../test-util';
function supportNode() {
return isNode;
}
function emptyRun() {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
}
(supportNode as any).message = 'support node';
describe('FakeAsyncTestZoneSpec', () => {
let FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec'];
let testZoneSpec: any;
let fakeAsyncTestZone: Zone;
beforeEach(() => {
testZoneSpec = new FakeAsyncTestZoneSpec('name');
fakeAsyncTestZone = Zone.current.fork(testZoneSpec);
});
it('sets the FakeAsyncTestZoneSpec property', () => {
fakeAsyncTestZone.run(() => {
expect(Zone.current.get('FakeAsyncTestZoneSpec')).toEqual(testZoneSpec);
});
});
describe('synchronous code', () => {
it('should run', () => {
let ran = false;
fakeAsyncTestZone.run(() => {
ran = true;
});
expect(ran).toEqual(true);
});
it('should throw the error in the code', () => {
expect(() => {
fakeAsyncTestZone.run(() => {
throw new Error('sync');
});
}).toThrowError('sync');
});
it('should throw error on Rejected promise', () => {
expect(() => {
fakeAsyncTestZone.run(() => {
Promise.reject('myError');
testZoneSpec.flushMicrotasks();
});
}).toThrowError('Uncaught (in promise): myError');
});
});
describe('asynchronous code', () => {
it('should run', () => {
fakeAsyncTestZone.run(() => {
let thenRan = false;
Promise.resolve(null).then((_) => {
thenRan = true;
});
expect(thenRan).toEqual(false);
testZoneSpec.flushMicrotasks();
expect(thenRan).toEqual(true);
});
});
it('should rethrow the exception on flushMicroTasks for error thrown in Promise callback', () => {
fakeAsyncTestZone.run(() => {
Promise.resolve(null).then((_) => {
throw new Error('async');
});
expect(() => {
testZoneSpec.flushMicrotasks();
}).toThrowError(/Uncaught \(in promise\): Error: async/);
});
});
it('should run chained thens', () => {
fakeAsyncTestZone.run(() => {
let log: number[] = [];
Promise.resolve(null)
.then((_) => log.push(1))
.then((_) => log.push(2));
expect(log).toEqual([]);
testZoneSpec.flushMicrotasks();
expect(log).toEqual([1, 2]);
});
});
it('should run Promise created in Promise', () => {
fakeAsyncTestZone.run(() => {
let log: number[] = [];
Promise.resolve(null).then((_) => {
log.push(1);
Promise.resolve(null).then((_) => log.push(2));
});
expect(log).toEqual([]);
testZoneSpec.flushMicrotasks();
expect(log).toEqual([1, 2]);
});
});
}); | {
"end_byte": 3272,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/fake-async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/fake-async-test.spec.ts_3276_11761 | describe('timers', () => {
it('should run queued zero duration timer on zero tick', () => {
fakeAsyncTestZone.run(() => {
let ran = false;
setTimeout(() => {
ran = true;
}, 0);
expect(ran).toEqual(false);
testZoneSpec.tick();
expect(ran).toEqual(true);
});
});
it(
'should run queued immediate timer on zero tick',
ifEnvSupports('setImmediate', () => {
fakeAsyncTestZone.run(() => {
let ran = false;
setImmediate(() => {
ran = true;
});
expect(ran).toEqual(false);
testZoneSpec.tick();
expect(ran).toEqual(true);
});
}),
);
it('should default to processNewMacroTasksSynchronously if providing other flags', () => {
function nestedTimer(callback: () => any): void {
setTimeout(() => setTimeout(() => callback()));
}
fakeAsyncTestZone.run(() => {
const callback = jasmine.createSpy('callback');
nestedTimer(callback);
expect(callback).not.toHaveBeenCalled();
testZoneSpec.tick(0, null, {});
expect(callback).toHaveBeenCalled();
});
});
it('should not queue new macro task on tick with processNewMacroTasksSynchronously=false', () => {
function nestedTimer(callback: () => any): void {
setTimeout(() => setTimeout(() => callback()));
}
fakeAsyncTestZone.run(() => {
const callback = jasmine.createSpy('callback');
nestedTimer(callback);
expect(callback).not.toHaveBeenCalled();
testZoneSpec.tick(0, null, {processNewMacroTasksSynchronously: false});
expect(callback).not.toHaveBeenCalled();
testZoneSpec.flush();
expect(callback).toHaveBeenCalled();
});
});
it('should run queued timer after sufficient clock ticks', () => {
fakeAsyncTestZone.run(() => {
let ran = false;
setTimeout(() => {
ran = true;
}, 10);
testZoneSpec.tick(6);
expect(ran).toEqual(false);
testZoneSpec.tick(4);
expect(ran).toEqual(true);
});
});
it('should run doTick callback even if no work ran', () => {
fakeAsyncTestZone.run(() => {
let totalElapsed = 0;
function doTick(elapsed: number) {
totalElapsed += elapsed;
}
setTimeout(() => {}, 10);
testZoneSpec.tick(6, doTick);
expect(totalElapsed).toEqual(6);
testZoneSpec.tick(6, doTick);
expect(totalElapsed).toEqual(12);
testZoneSpec.tick(6, doTick);
expect(totalElapsed).toEqual(18);
});
});
it('should run queued timer created by timer callback', () => {
fakeAsyncTestZone.run(() => {
let counter = 0;
const startCounterLoop = () => {
counter++;
setTimeout(startCounterLoop, 10);
};
startCounterLoop();
expect(counter).toEqual(1);
testZoneSpec.tick(10);
expect(counter).toEqual(2);
testZoneSpec.tick(10);
expect(counter).toEqual(3);
testZoneSpec.tick(30);
expect(counter).toEqual(6);
});
});
it('should run queued timer only once', () => {
fakeAsyncTestZone.run(() => {
let cycles = 0;
setTimeout(() => {
cycles++;
}, 10);
testZoneSpec.tick(10);
expect(cycles).toEqual(1);
testZoneSpec.tick(10);
expect(cycles).toEqual(1);
testZoneSpec.tick(10);
expect(cycles).toEqual(1);
});
expect(testZoneSpec.pendingTimers.length).toBe(0);
});
it('should not run cancelled timer', () => {
fakeAsyncTestZone.run(() => {
let ran = false;
let id: any = setTimeout(() => {
ran = true;
}, 10);
clearTimeout(id);
testZoneSpec.tick(10);
expect(ran).toEqual(false);
});
});
it('should pass arguments to times', () => {
fakeAsyncTestZone.run(() => {
let value = 'genuine value';
let id = setTimeout(
(arg1, arg2) => {
value = arg1 + arg2;
},
0,
'expected',
' value',
);
testZoneSpec.tick();
expect(value).toEqual('expected value');
});
});
it('should clear internal timerId cache', () => {
let taskSpy: jasmine.Spy = jasmine.createSpy('taskGetState');
fakeAsyncTestZone
.fork({
name: 'scheduleZone',
onScheduleTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
(task as any)._state = task.state;
Object.defineProperty(task, 'state', {
configurable: true,
enumerable: true,
get: () => {
taskSpy();
return (task as any)._state;
},
set: (newState: string) => {
(task as any)._state = newState;
},
});
return delegate.scheduleTask(target, task);
},
})
.run(() => {
const id = setTimeout(() => {}, 0);
testZoneSpec.tick();
clearTimeout(id);
// This is a hack way to test the timerId cache is cleaned or not
// since the tasksByHandleId cache is an internal variable held by
// zone.js timer patch, if the cache is not cleared, the code in `timer.ts`
// will call `task.state` one more time to check whether to clear the
// task or not, so here we use this count to check the issue is fixed or not
// For details, please refer to https://github.com/angular/angular/issues/40387
expect(taskSpy.calls.count()).toBe(4);
});
});
it(
'should pass arguments to setImmediate',
ifEnvSupports('setImmediate', () => {
fakeAsyncTestZone.run(() => {
let value = 'genuine value';
let id = setImmediate(
(arg1, arg2) => {
value = arg1 + arg2;
},
'expected',
' value',
);
testZoneSpec.tick();
expect(value).toEqual('expected value');
});
}),
);
it('should run periodic timers', () => {
fakeAsyncTestZone.run(() => {
let cycles = 0;
let id = setInterval(() => {
cycles++;
}, 10);
expect(id).toBeGreaterThan(0);
testZoneSpec.tick(10);
expect(cycles).toEqual(1);
testZoneSpec.tick(10);
expect(cycles).toEqual(2);
testZoneSpec.tick(10);
expect(cycles).toEqual(3);
testZoneSpec.tick(30);
expect(cycles).toEqual(6);
});
});
it('should pass arguments to periodic timers', () => {
fakeAsyncTestZone.run(() => {
let value = 'genuine value';
let id = setInterval(
(arg1, arg2) => {
value = arg1 + arg2;
},
10,
'expected',
' value',
);
testZoneSpec.tick(10);
expect(value).toEqual('expected value');
});
});
it('should not run cancelled periodic timer', () => {
fakeAsyncTestZone.run(() => {
let ran = false;
let id = setInterval(() => {
ran = true;
}, 10);
testZoneSpec.tick(10);
expect(ran).toEqual(true);
ran = false;
clearInterval(id);
testZoneSpec.tick(10);
expect(ran).toEqual(false);
});
});
it('should be able to cancel periodic timers from a callback', () => {
fakeAsyncTestZone.run(() => {
let cycles = 0;
let id: number;
id = setInterval(() => {
cycles++;
clearInterval(id);
}, 10) as any as number;
testZoneSpec.tick(10);
expect(cycles).toEqual(1);
testZoneSpec.tick(10);
expect(cycles).toEqual(1);
});
});
it('should process microtasks before timers', () => {
fakeAsyncTestZone.run(() => {
let log: string[] = [];
Promise.resolve(null).then((_) => log.push('microtask'));
setTimeout(() => log.push('timer'), 9);
setInterval(() => log.push('periodic timer'), 10);
expect(log).toEqual([]);
testZoneSpec.tick(10);
expect(log).toEqual(['microtask', 'timer', 'periodic timer']);
});
}); | {
"end_byte": 11761,
"start_byte": 3276,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/fake-async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/fake-async-test.spec.ts_11767_20373 | it('should process micro-tasks created in timers before next timers', () => {
fakeAsyncTestZone.run(() => {
let log: string[] = [];
Promise.resolve(null).then((_) => log.push('microtask'));
setTimeout(() => {
log.push('timer');
Promise.resolve(null).then((_) => log.push('t microtask'));
}, 9);
let id = setInterval(() => {
log.push('periodic timer');
Promise.resolve(null).then((_) => log.push('pt microtask'));
}, 10);
testZoneSpec.tick(10);
expect(log).toEqual([
'microtask',
'timer',
't microtask',
'periodic timer',
'pt microtask',
]);
testZoneSpec.tick(10);
expect(log).toEqual([
'microtask',
'timer',
't microtask',
'periodic timer',
'pt microtask',
'periodic timer',
'pt microtask',
]);
});
});
it('should throw the exception from tick for error thrown in timer callback', () => {
fakeAsyncTestZone.run(() => {
setTimeout(() => {
throw new Error('timer');
}, 10);
expect(() => {
testZoneSpec.tick(10);
}).toThrowError('timer');
});
// There should be no pending timers after the error in timer callback.
expect(testZoneSpec.pendingTimers.length).toBe(0);
});
it('should throw the exception from tick for error thrown in periodic timer callback', () => {
fakeAsyncTestZone.run(() => {
let count = 0;
setInterval(() => {
count++;
throw new Error(count.toString());
}, 10);
expect(() => {
testZoneSpec.tick(10);
}).toThrowError('1');
// Periodic timer is cancelled on first error.
expect(count).toBe(1);
testZoneSpec.tick(10);
expect(count).toBe(1);
});
// Periodic timer is removed from pending queue on error.
expect(testZoneSpec.pendingPeriodicTimers.length).toBe(0);
});
});
it('should be able to resume processing timer callbacks after handling an error', () => {
fakeAsyncTestZone.run(() => {
let ran = false;
setTimeout(() => {
throw new Error('timer');
}, 10);
setTimeout(() => {
ran = true;
}, 10);
expect(() => {
testZoneSpec.tick(10);
}).toThrowError('timer');
expect(ran).toBe(false);
// Restart timer queue processing.
testZoneSpec.tick(0);
expect(ran).toBe(true);
});
// There should be no pending timers after the error in timer callback.
expect(testZoneSpec.pendingTimers.length).toBe(0);
});
describe('flushing all tasks', () => {
it('should flush all pending timers', () => {
fakeAsyncTestZone.run(() => {
let x = false;
let y = false;
let z = false;
setTimeout(() => {
x = true;
}, 10);
setTimeout(() => {
y = true;
}, 100);
setTimeout(() => {
z = true;
}, 70);
let elapsed = testZoneSpec.flush();
expect(elapsed).toEqual(100);
expect(x).toBe(true);
expect(y).toBe(true);
expect(z).toBe(true);
});
});
it('should flush nested timers', () => {
fakeAsyncTestZone.run(() => {
let x = true;
let y = true;
setTimeout(() => {
x = true;
setTimeout(() => {
y = true;
}, 100);
}, 200);
let elapsed = testZoneSpec.flush();
expect(elapsed).toEqual(300);
expect(x).toBe(true);
expect(y).toBe(true);
});
});
it('should advance intervals', () => {
fakeAsyncTestZone.run(() => {
let x = false;
let y = false;
let z = 0;
setTimeout(() => {
x = true;
}, 50);
setTimeout(() => {
y = true;
}, 141);
setInterval(() => {
z++;
}, 10);
let elapsed = testZoneSpec.flush();
expect(elapsed).toEqual(141);
expect(x).toBe(true);
expect(y).toBe(true);
expect(z).toEqual(14);
});
});
it('should not wait for intervals', () => {
fakeAsyncTestZone.run(() => {
let z = 0;
setInterval(() => {
z++;
}, 10);
let elapsed = testZoneSpec.flush();
expect(elapsed).toEqual(0);
expect(z).toEqual(0);
});
});
it('should process micro-tasks created in timers before next timers', () => {
fakeAsyncTestZone.run(() => {
let log: string[] = [];
Promise.resolve(null).then((_) => log.push('microtask'));
setTimeout(() => {
log.push('timer');
Promise.resolve(null).then((_) => log.push('t microtask'));
}, 20);
let id = setInterval(() => {
log.push('periodic timer');
Promise.resolve(null).then((_) => log.push('pt microtask'));
}, 10);
testZoneSpec.flush();
expect(log).toEqual([
'microtask',
'periodic timer',
'pt microtask',
'timer',
't microtask',
]);
});
});
it('should throw the exception from tick for error thrown in timer callback', () => {
fakeAsyncTestZone.run(() => {
setTimeout(() => {
throw new Error('timer');
}, 10);
expect(() => {
testZoneSpec.flush();
}).toThrowError('timer');
});
// There should be no pending timers after the error in timer callback.
expect(testZoneSpec.pendingTimers.length).toBe(0);
});
it('should do something reasonable with polling timeouts', () => {
expect(() => {
fakeAsyncTestZone.run(() => {
let z = 0;
let poll = () => {
setTimeout(() => {
z++;
poll();
}, 10);
};
poll();
testZoneSpec.flush();
});
}).toThrowError(
'flush failed after reaching the limit of 20 tasks. Does your code use a polling timeout?',
);
});
it('accepts a custom limit', () => {
expect(() => {
fakeAsyncTestZone.run(() => {
let z = 0;
let poll = () => {
setTimeout(() => {
z++;
poll();
}, 10);
};
poll();
testZoneSpec.flush(10);
});
}).toThrowError(
'flush failed after reaching the limit of 10 tasks. Does your code use a polling timeout?',
);
});
it('can flush periodic timers if flushPeriodic is true', () => {
fakeAsyncTestZone.run(() => {
let x = 0;
setInterval(() => {
x++;
}, 10);
let elapsed = testZoneSpec.flush(20, true);
expect(elapsed).toEqual(10);
expect(x).toEqual(1);
});
});
it('can flush multiple periodic timers if flushPeriodic is true', () => {
fakeAsyncTestZone.run(() => {
let x = 0;
let y = 0;
setInterval(() => {
x++;
}, 10);
setInterval(() => {
y++;
}, 100);
let elapsed = testZoneSpec.flush(20, true);
expect(elapsed).toEqual(100);
expect(x).toEqual(10);
expect(y).toEqual(1);
});
});
it('can flush till the last periodic task is processed', () => {
fakeAsyncTestZone.run(() => {
let x = 0;
let y = 0;
setInterval(() => {
x++;
}, 10);
// This shouldn't cause the flush to throw an exception even though
// it would require 100 iterations of the shorter timer.
setInterval(() => {
y++;
}, 1000);
let elapsed = testZoneSpec.flush(20, true);
// Should stop right after the longer timer has been processed.
expect(elapsed).toEqual(1000);
expect(x).toEqual(100);
expect(y).toEqual(1);
});
});
});
describe('outside of FakeAsync Zone', () => {
it('calling flushMicrotasks should throw exception', () => {
expect(() => {
testZoneSpec.flushMicrotasks();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
it('calling tick should throw exception', () => {
expect(() => {
testZoneSpec.tick();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
}); | {
"end_byte": 20373,
"start_byte": 11767,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/fake-async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/fake-async-test.spec.ts_20377_29012 | const animationFrameFns = [
['requestAnimationFrame', 'cancelAnimationFrame'],
['webkitRequestAnimationFrame', 'webkitCancelAnimationFrame'],
['mozRequestAnimationFrame', 'mozCancelAnimationFrame'],
];
const availableAnimationFrameFns = animationFrameFns
.map(([fnName, cancelFnName]) => [
fnName,
(global as any)[fnName],
(global as any)[cancelFnName],
])
.filter(([_, fn]) => fn !== undefined) as [
string,
typeof requestAnimationFrame,
typeof cancelAnimationFrame,
][];
if (availableAnimationFrameFns.length > 0) {
describe('requestAnimationFrame', () => {
availableAnimationFrameFns.forEach(
([name, requestAnimationFrameFn, cancelAnimationFrameFn]) => {
describe(name, () => {
it('should schedule a requestAnimationFrame with timeout of 16ms', () => {
fakeAsyncTestZone.run(() => {
let ran = false;
requestAnimationFrameFn(() => {
ran = true;
});
testZoneSpec.tick(6);
expect(ran).toEqual(false);
testZoneSpec.tick(10);
expect(ran).toEqual(true);
});
});
it('does not count as a pending timer', () => {
fakeAsyncTestZone.run(() => {
requestAnimationFrameFn(() => {});
});
expect(testZoneSpec.pendingTimers.length).toBe(0);
expect(testZoneSpec.pendingPeriodicTimers.length).toBe(0);
});
it('should cancel a scheduled requestAnimationFrame', () => {
fakeAsyncTestZone.run(() => {
let ran = false;
const id = requestAnimationFrameFn(() => {
ran = true;
});
testZoneSpec.tick(6);
expect(ran).toEqual(false);
cancelAnimationFrameFn(id);
testZoneSpec.tick(10);
expect(ran).toEqual(false);
});
});
it('is not flushed when flushPeriodic is false', () => {
let ran = false;
fakeAsyncTestZone.run(() => {
requestAnimationFrameFn(() => {
ran = true;
});
testZoneSpec.flush(20);
expect(ran).toEqual(false);
});
});
it('is flushed when flushPeriodic is true', () => {
let ran = false;
fakeAsyncTestZone.run(() => {
requestAnimationFrameFn(() => {
ran = true;
});
const elapsed = testZoneSpec.flush(20, true);
expect(elapsed).toEqual(16);
expect(ran).toEqual(true);
});
});
it('should pass timestamp as parameter', () => {
let timestamp = 0;
let timestamp1 = 0;
fakeAsyncTestZone.run(() => {
requestAnimationFrameFn((ts) => {
timestamp = ts;
requestAnimationFrameFn((ts1) => {
timestamp1 = ts1;
});
});
const elapsed = testZoneSpec.flush(20, true);
const elapsed1 = testZoneSpec.flush(20, true);
expect(elapsed).toEqual(16);
expect(elapsed1).toEqual(16);
expect(timestamp).toEqual(16);
expect(timestamp1).toEqual(32);
});
});
});
},
);
});
}
describe(
'XHRs',
ifEnvSupports(
'XMLHttpRequest',
() => {
it('should throw an exception if an XHR is initiated in the zone', () => {
expect(() => {
fakeAsyncTestZone.run(() => {
let finished = false;
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState === XMLHttpRequest.DONE) {
finished = true;
}
};
req.open('GET', '/test', true);
req.send();
});
}).toThrowError('Cannot make XHRs from within a fake async test. Request URL: /test');
});
},
emptyRun,
),
);
describe(
'node process',
ifEnvSupports(
supportNode,
() => {
it('should be able to schedule microTask with additional arguments', () => {
const process = global['process'];
const nextTick = process && process['nextTick'];
if (!nextTick) {
return;
}
fakeAsyncTestZone.run(() => {
let tickRun = false;
let cbArgRun = false;
nextTick(
(strArg: string, cbArg: Function) => {
tickRun = true;
expect(strArg).toEqual('stringArg');
cbArg();
},
'stringArg',
() => {
cbArgRun = true;
},
);
expect(tickRun).toEqual(false);
testZoneSpec.flushMicrotasks();
expect(tickRun).toEqual(true);
expect(cbArgRun).toEqual(true);
});
});
},
emptyRun,
),
);
describe('should allow user define which macroTask fakeAsyncTest', () => {
let FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec'];
let testZoneSpec: any;
let fakeAsyncTestZone: Zone;
it('should support custom non perodic macroTask', () => {
testZoneSpec = new FakeAsyncTestZoneSpec('name', false, [
{source: 'TestClass.myTimeout', callbackArgs: ['test']},
]);
class TestClass {
myTimeout(callback: Function) {}
}
fakeAsyncTestZone = Zone.current.fork(testZoneSpec);
fakeAsyncTestZone.run(() => {
let ran = false;
patchMacroTask(TestClass.prototype, 'myTimeout', (self: any, args: any[]) => ({
name: 'TestClass.myTimeout',
target: self,
cbIdx: 0,
args: args,
}));
const testClass = new TestClass();
testClass.myTimeout(function (callbackArgs: any) {
ran = true;
expect(callbackArgs).toEqual('test');
});
expect(ran).toEqual(false);
testZoneSpec.tick();
expect(ran).toEqual(true);
});
});
it('should support custom non perodic macroTask by global flag', () => {
testZoneSpec = new FakeAsyncTestZoneSpec('name');
class TestClass {
myTimeout(callback: Function) {}
}
fakeAsyncTestZone = Zone.current.fork(testZoneSpec);
fakeAsyncTestZone.run(() => {
let ran = false;
patchMacroTask(TestClass.prototype, 'myTimeout', (self: any, args: any[]) => ({
name: 'TestClass.myTimeout',
target: self,
cbIdx: 0,
args: args,
}));
const testClass = new TestClass();
testClass.myTimeout(() => {
ran = true;
});
expect(ran).toEqual(false);
testZoneSpec.tick();
expect(ran).toEqual(true);
});
});
it('should support custom perodic macroTask', () => {
testZoneSpec = new FakeAsyncTestZoneSpec('name', false, [
{source: 'TestClass.myInterval', isPeriodic: true},
]);
fakeAsyncTestZone = Zone.current.fork(testZoneSpec);
fakeAsyncTestZone.run(() => {
let cycle = 0;
class TestClass {
myInterval(callback: Function, interval: number): any {
return null;
}
}
patchMacroTask(TestClass.prototype, 'myInterval', (self: any, args: any[]) => ({
name: 'TestClass.myInterval',
target: self,
cbIdx: 0,
args: args,
}));
const testClass = new TestClass();
const id = testClass.myInterval(() => {
cycle++;
}, 10);
expect(cycle).toEqual(0);
testZoneSpec.tick(10);
expect(cycle).toEqual(1);
testZoneSpec.tick(10);
expect(cycle).toEqual(2);
clearInterval(id);
});
});
});
describe('return promise', () => {
let log: string[];
beforeEach(() => {
log = [];
});
it('should wait for promise to resolve', () => {
return new Promise<void>((res, _) => {
setTimeout(() => {
log.push('resolved');
res();
}, 100);
});
});
afterEach(() => {
expect(log).toEqual(['resolved']);
});
}); | {
"end_byte": 29012,
"start_byte": 20377,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/fake-async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/fake-async-test.spec.ts_29016_32435 | describe('fakeAsyncTest should patch Date', () => {
let FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec'];
let testZoneSpec: any;
let fakeAsyncTestZone: Zone;
beforeEach(() => {
testZoneSpec = new FakeAsyncTestZoneSpec('name', false);
fakeAsyncTestZone = Zone.current.fork(testZoneSpec);
});
it('should get date diff correctly', () => {
fakeAsyncTestZone.run(() => {
const start = Date.now();
testZoneSpec.tick(100);
const end = Date.now();
expect(end - start).toBe(100);
});
});
it('should check date type correctly', () => {
fakeAsyncTestZone.run(() => {
const d: any = new Date();
expect(d instanceof Date).toBe(true);
});
});
it('should new Date with parameter correctly', () => {
fakeAsyncTestZone.run(() => {
const d: Date = new Date(0);
expect(d.getFullYear()).toBeLessThan(1971);
const d1: Date = new Date('December 17, 1995 03:24:00');
expect(d1.getFullYear()).toEqual(1995);
const d2: Date = new Date(1995, 11, 17, 3, 24, 0);
expect(d2.getFullYear()).toEqual(1995);
d2.setFullYear(1985);
expect(isNaN(d2.getTime())).toBeFalsy();
expect(d2.getFullYear()).toBe(1985);
expect(d2.getMonth()).toBe(11);
expect(d2.getDate()).toBe(17);
});
});
it('should get Date.UTC() correctly', () => {
fakeAsyncTestZone.run(() => {
const utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0));
expect(utcDate.getFullYear()).toBe(1996);
});
});
it('should call Date.parse() correctly', () => {
fakeAsyncTestZone.run(() => {
const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
expect(unixTimeZero).toBe(0);
});
});
});
describe(
'fakeAsyncTest should patch rxjs scheduler',
ifEnvSupports(
() => isNode,
() => {
let FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec'];
let testZoneSpec: any;
let fakeAsyncTestZone: Zone;
beforeEach(() => {
testZoneSpec = new FakeAsyncTestZoneSpec('name', false);
fakeAsyncTestZone = Zone.current.fork(testZoneSpec);
});
it('should get date diff correctly', (done) => {
fakeAsyncTestZone.run(() => {
let result: any = null;
const observable = new Observable((subscribe: any) => {
subscribe.next('hello');
subscribe.complete();
});
observable.pipe(delay(1000)).subscribe((v: any) => {
result = v;
});
expect(result).toBe(null);
testZoneSpec.tick(1000);
expect(result).toBe('hello');
done();
});
});
},
emptyRun,
),
);
});
class Log<T> {
logItems: T[];
constructor() {
this.logItems = [];
}
add(value: T): void {
this.logItems.push(value);
}
clear(): void {
this.logItems = [];
}
result(): string {
return this.logItems.join('; ');
}
}
const resolvedPromise = Promise.resolve(null);
const ProxyZoneSpec: {assertPresent: () => void} = (Zone as any)['ProxyZoneSpec'];
const fakeAsyncTestModule = (Zone as any)[Zone.__symbol__('fakeAsyncTest')];
const {fakeAsync, tick, discardPeriodicTasks, flush, flushMicrotasks} = fakeAsyncTestModule; | {
"end_byte": 32435,
"start_byte": 29016,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/fake-async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/fake-async-test.spec.ts_32437_40005 | describe('fake async', () => {
it('should run synchronous code', () => {
let ran = false;
fakeAsync(() => {
ran = true;
})();
expect(ran).toEqual(true);
});
it('should pass arguments to the wrapped function', () => {
fakeAsync((foo: string, bar: string) => {
expect(foo).toEqual('foo');
expect(bar).toEqual('bar');
})('foo', 'bar');
});
it('should throw on nested calls', () => {
expect(() => {
fakeAsync(() => {
fakeAsync((): null => null)();
})();
}).toThrowError('fakeAsync() calls can not be nested');
});
it('should flush microtasks before returning', () => {
let thenRan = false;
fakeAsync(() => {
resolvedPromise.then((_) => {
thenRan = true;
});
})();
expect(thenRan).toEqual(true);
});
it('should propagate the return value', () => {
expect(fakeAsync(() => 'foo')()).toEqual('foo');
});
describe('Promise', () => {
it('should run asynchronous code', fakeAsync(() => {
let thenRan = false;
resolvedPromise.then((_) => {
thenRan = true;
});
expect(thenRan).toEqual(false);
flushMicrotasks();
expect(thenRan).toEqual(true);
}));
it('should run chained thens', fakeAsync(() => {
const log = new Log<number>();
resolvedPromise.then((_) => log.add(1)).then((_) => log.add(2));
expect(log.result()).toEqual('');
flushMicrotasks();
expect(log.result()).toEqual('1; 2');
}));
it('should run Promise created in Promise', fakeAsync(() => {
const log = new Log<number>();
resolvedPromise.then((_) => {
log.add(1);
resolvedPromise.then((_) => log.add(2));
});
expect(log.result()).toEqual('');
flushMicrotasks();
expect(log.result()).toEqual('1; 2');
}));
it('should complain if the test throws an exception during async calls', () => {
expect(() => {
fakeAsync(() => {
resolvedPromise.then((_) => {
throw new Error('async');
});
flushMicrotasks();
})();
}).toThrowError(/Uncaught \(in promise\): Error: async/);
});
it('should complain if a test throws an exception', () => {
expect(() => {
fakeAsync(() => {
throw new Error('sync');
})();
}).toThrowError('sync');
});
});
describe('timers', () => {
it('should run queued zero duration timer on zero tick', fakeAsync(() => {
let ran = false;
setTimeout(() => {
ran = true;
}, 0);
expect(ran).toEqual(false);
tick();
expect(ran).toEqual(true);
}));
it('should run queued timer after sufficient clock ticks', fakeAsync(() => {
let ran = false;
setTimeout(() => {
ran = true;
}, 10);
tick(6);
expect(ran).toEqual(false);
tick(6);
expect(ran).toEqual(true);
}));
it('should run queued timer only once', fakeAsync(() => {
let cycles = 0;
setTimeout(() => {
cycles++;
}, 10);
tick(10);
expect(cycles).toEqual(1);
tick(10);
expect(cycles).toEqual(1);
tick(10);
expect(cycles).toEqual(1);
}));
it('should not run cancelled timer', fakeAsync(() => {
let ran = false;
const id = setTimeout(() => {
ran = true;
}, 10);
clearTimeout(id);
tick(10);
expect(ran).toEqual(false);
}));
it('should throw an error on dangling timers', () => {
expect(() => {
fakeAsync(
() => {
setTimeout(() => {}, 10);
},
{flush: false},
)();
}).toThrowError('1 timer(s) still in the queue.');
});
it('should throw an error on dangling periodic timers', () => {
expect(() => {
fakeAsync(
() => {
setInterval(() => {}, 10);
},
{flush: false},
)();
}).toThrowError('1 periodic timer(s) still in the queue.');
});
it('should run periodic timers', fakeAsync(() => {
let cycles = 0;
const id = setInterval(() => {
cycles++;
}, 10);
tick(10);
expect(cycles).toEqual(1);
tick(10);
expect(cycles).toEqual(2);
tick(10);
expect(cycles).toEqual(3);
clearInterval(id);
}));
it('should not run cancelled periodic timer', fakeAsync(() => {
let ran = false;
const id = setInterval(() => {
ran = true;
}, 10);
clearInterval(id);
tick(10);
expect(ran).toEqual(false);
}));
it('should be able to cancel periodic timers from a callback', fakeAsync(() => {
let cycles = 0;
let id: NodeJS.Timer;
id = setInterval(() => {
cycles++;
clearInterval(id);
}, 10);
tick(10);
expect(cycles).toEqual(1);
tick(10);
expect(cycles).toEqual(1);
}));
it('should clear periodic timers', fakeAsync(() => {
let cycles = 0;
const id = setInterval(() => {
cycles++;
}, 10);
tick(10);
expect(cycles).toEqual(1);
discardPeriodicTasks();
// Tick once to clear out the timer which already started.
tick(10);
expect(cycles).toEqual(2);
tick(10);
// Nothing should change
expect(cycles).toEqual(2);
}));
it('should process microtasks before timers', fakeAsync(() => {
const log = new Log<string>();
resolvedPromise.then((_) => log.add('microtask'));
setTimeout(() => log.add('timer'), 9);
const id = setInterval(() => log.add('periodic timer'), 10);
expect(log.result()).toEqual('');
tick(10);
expect(log.result()).toEqual('microtask; timer; periodic timer');
clearInterval(id);
}));
it('should process micro-tasks created in timers before next timers', fakeAsync(() => {
const log = new Log<string>();
resolvedPromise.then((_) => log.add('microtask'));
setTimeout(() => {
log.add('timer');
resolvedPromise.then((_) => log.add('t microtask'));
}, 9);
const id = setInterval(() => {
log.add('periodic timer');
resolvedPromise.then((_) => log.add('pt microtask'));
}, 10);
tick(10);
expect(log.result()).toEqual('microtask; timer; t microtask; periodic timer; pt microtask');
tick(10);
expect(log.result()).toEqual(
'microtask; timer; t microtask; periodic timer; pt microtask; periodic timer; pt microtask',
);
clearInterval(id);
}));
it('should flush tasks', fakeAsync(() => {
let ran = false;
setTimeout(() => {
ran = true;
}, 10);
flush();
expect(ran).toEqual(true);
}));
it('should flush multiple tasks', fakeAsync(() => {
let ran = false;
let ran2 = false;
setTimeout(() => {
ran = true;
}, 10);
setTimeout(() => {
ran2 = true;
}, 30);
let elapsed = flush();
expect(ran).toEqual(true);
expect(ran2).toEqual(true);
expect(elapsed).toEqual(30);
}));
it('should move periodic tasks', fakeAsync(() => {
let ran = false;
let count = 0;
setInterval(() => {
count++;
}, 10);
setTimeout(() => {
ran = true;
}, 35);
let elapsed = flush();
expect(count).toEqual(3);
expect(ran).toEqual(true);
expect(elapsed).toEqual(35);
discardPeriodicTasks();
}));
}); | {
"end_byte": 40005,
"start_byte": 32437,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/fake-async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/fake-async-test.spec.ts_40009_43224 | describe('outside of the fakeAsync zone', () => {
it('calling flushMicrotasks should throw', () => {
expect(() => {
flushMicrotasks();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
it('calling tick should throw', () => {
expect(() => {
tick();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
it('calling flush should throw', () => {
expect(() => {
flush();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
it('calling discardPeriodicTasks should throw', () => {
expect(() => {
discardPeriodicTasks();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
});
describe('only one `fakeAsync` zone per test', () => {
let zoneInBeforeEach: Zone;
let zoneInTest1: Zone;
beforeEach(fakeAsync(() => {
zoneInBeforeEach = Zone.current;
}));
it('should use the same zone as in beforeEach', fakeAsync(() => {
zoneInTest1 = Zone.current;
expect(zoneInTest1).toBe(zoneInBeforeEach);
}));
});
describe('fakeAsync should work with Date', () => {
it('should get date diff correctly', fakeAsync(() => {
const start = Date.now();
tick(100);
const end = Date.now();
expect(end - start).toBe(100);
}));
it('should check date type correctly', fakeAsync(() => {
const d: any = new Date();
expect(d instanceof Date).toBe(true);
}));
it('should new Date with parameter correctly', fakeAsync(() => {
const d: Date = new Date(0);
expect(d.getFullYear()).toBeLessThan(1971);
const d1: Date = new Date('December 17, 1995 03:24:00');
expect(d1.getFullYear()).toEqual(1995);
const d2: Date = new Date(1995, 11, 17, 3, 24, 0);
expect(isNaN(d2.getTime())).toBeFalsy();
expect(d2.getFullYear()).toEqual(1995);
d2.setFullYear(1985);
expect(d2.getFullYear()).toBe(1985);
expect(d2.getMonth()).toBe(11);
expect(d2.getDate()).toBe(17);
}));
it('should get Date.UTC() correctly', fakeAsync(() => {
const utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0));
expect(utcDate.getFullYear()).toBe(1996);
}));
it('should call Date.parse() correctly', fakeAsync(() => {
const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
expect(unixTimeZero).toBe(0);
}));
});
});
describe('ProxyZone', () => {
beforeEach(() => {
ProxyZoneSpec.assertPresent();
});
afterEach(() => {
ProxyZoneSpec.assertPresent();
});
it('should allow fakeAsync zone to retroactively set a zoneSpec outside of fakeAsync', () => {
ProxyZoneSpec.assertPresent();
let state: string = 'not run';
const testZone = Zone.current.fork({name: 'test-zone'});
fakeAsync(() => {
testZone.run(() => {
Promise.resolve('works').then((v) => (state = v));
expect(state).toEqual('not run');
flushMicrotasks();
expect(state).toEqual('works');
});
})();
expect(state).toEqual('works');
});
}); | {
"end_byte": 43224,
"start_byte": 40009,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/fake-async-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/proxy.spec.ts_0_7253 | /**
* @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
*/
describe('ProxySpec', () => {
let ProxyZoneSpec: any;
let delegate: ZoneSpec;
let proxyZoneSpec: any;
let proxyZone: Zone;
beforeEach(() => {
ProxyZoneSpec = (Zone as any)['ProxyZoneSpec'];
expect(typeof ProxyZoneSpec).toBe('function');
delegate = {name: 'delegate'};
proxyZoneSpec = new ProxyZoneSpec(delegate);
proxyZone = Zone.current.fork(proxyZoneSpec);
});
describe('properties', () => {
it('should expose ProxyZone in the properties', () => {
expect(proxyZone.get('ProxyZoneSpec')).toBe(proxyZoneSpec);
});
it('should assert that it is in or out of ProxyZone', () => {
let rootZone = Zone.current;
while (rootZone.parent) {
rootZone = rootZone.parent;
}
rootZone.run(() => {
expect(() => ProxyZoneSpec.assertPresent()).toThrow();
expect(ProxyZoneSpec.isLoaded()).toBe(false);
expect(ProxyZoneSpec.get()).toBe(undefined);
proxyZone.run(() => {
expect(ProxyZoneSpec.isLoaded()).toBe(true);
expect(() => ProxyZoneSpec.assertPresent()).not.toThrow();
expect(ProxyZoneSpec.get()).toBe(proxyZoneSpec);
});
});
});
it('should reset properties', () => {
expect(proxyZone.get('myTestKey')).toBe(undefined);
proxyZoneSpec.setDelegate({name: 'd1', properties: {'myTestKey': 'myTestValue'}});
expect(proxyZone.get('myTestKey')).toBe('myTestValue');
proxyZoneSpec.resetDelegate();
expect(proxyZone.get('myTestKey')).toBe(undefined);
});
});
describe('delegate', () => {
it('should set/reset delegate', () => {
const defaultDelegate: ZoneSpec = {name: 'defaultDelegate'};
const otherDelegate: ZoneSpec = {name: 'otherDelegate'};
const proxyZoneSpec = new ProxyZoneSpec(defaultDelegate);
const proxyZone = Zone.current.fork(proxyZoneSpec);
expect(proxyZoneSpec.getDelegate()).toEqual(defaultDelegate);
proxyZoneSpec.setDelegate(otherDelegate);
expect(proxyZoneSpec.getDelegate()).toEqual(otherDelegate);
proxyZoneSpec.resetDelegate();
expect(proxyZoneSpec.getDelegate()).toEqual(defaultDelegate);
});
});
describe('forwarding', () => {
beforeEach(() => {
proxyZoneSpec = new ProxyZoneSpec();
proxyZone = Zone.current.fork(proxyZoneSpec);
});
it('should fork', () => {
const forkedZone = proxyZone.fork({name: 'fork'});
expect(forkedZone).not.toBe(proxyZone);
expect(forkedZone.name).toBe('fork');
let called = false;
proxyZoneSpec.setDelegate({
name: '.',
onFork: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
zoneSpec: ZoneSpec,
) => {
expect(currentZone).toBe(proxyZone);
expect(targetZone).toBe(proxyZone), expect(zoneSpec.name).toBe('fork2');
called = true;
},
});
proxyZone.fork({name: 'fork2'});
expect(called).toBe(true);
});
it('should intercept', () => {
const fn = (a: any) => a;
expect(proxyZone.wrap(fn, 'test')('works')).toEqual('works');
proxyZoneSpec.setDelegate({
name: '.',
onIntercept: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
source: string,
): Function => {
return () => '(works)';
},
});
expect(proxyZone.wrap(fn, 'test')('works')).toEqual('(works)');
});
it('should invoke', () => {
const fn = () => 'works';
expect(proxyZone.run(fn)).toEqual('works');
proxyZoneSpec.setDelegate({
name: '.',
onInvoke: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
applyThis: any,
applyArgs: any[],
source: string,
) => {
return `(${parentZoneDelegate.invoke(
targetZone,
delegate,
applyThis,
applyArgs,
source,
)})`;
},
});
expect(proxyZone.run(fn)).toEqual('(works)');
});
it('should handleError', () => {
const error = new Error('TestError');
const fn = () => {
throw error;
};
expect(() => proxyZone.run(fn)).toThrow(error);
proxyZoneSpec.setDelegate({
name: '.',
onHandleError: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
): boolean => {
expect(error).toEqual(error);
return false;
},
});
expect(() => proxyZone.runGuarded(fn)).not.toThrow();
});
it('should Task', () => {
const fn = (): any => null;
const task = proxyZone.scheduleMacroTask(
'test',
fn,
{},
() => null,
() => null,
);
expect(task.source).toEqual('test');
proxyZone.cancelTask(task);
});
});
describe('delegateSpec change', () => {
let log: string[] = [];
beforeEach(() => {
log = [];
});
it('should trigger hasTask when invoke', (done: Function) => {
const zoneSpec1 = {
name: 'zone1',
onHasTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, hasTask: HasTaskState) => {
log.push(`zoneSpec1 hasTask: ${hasTask.microTask},${hasTask.macroTask}`);
return delegate.hasTask(target, hasTask);
},
};
const zoneSpec2 = {
name: 'zone2',
onHasTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, hasTask: HasTaskState) => {
log.push(`zoneSpec2 hasTask: ${hasTask.microTask},${hasTask.macroTask}`);
return delegate.hasTask(target, hasTask);
},
};
proxyZoneSpec.setDelegate(zoneSpec1);
proxyZone.run(() => {
setTimeout(() => {
log.push('timeout in zoneSpec1');
}, 50);
});
proxyZoneSpec.setDelegate(zoneSpec2);
proxyZone.run(() => {
Promise.resolve(1).then(() => {
log.push('then in zoneSpec2');
});
});
proxyZoneSpec.setDelegate(null);
proxyZone.run(() => {
setTimeout(() => {
log.push('timeout in null spec');
}, 50);
});
proxyZoneSpec.setDelegate(zoneSpec2);
proxyZone.run(() => {
Promise.resolve(1).then(() => {
log.push('then in zoneSpec2');
});
});
setTimeout(() => {
expect(log).toEqual([
'zoneSpec1 hasTask: false,true',
'zoneSpec2 hasTask: false,true',
'zoneSpec2 hasTask: true,true',
'zoneSpec2 hasTask: true,true',
'then in zoneSpec2',
'then in zoneSpec2',
'zoneSpec2 hasTask: false,true',
'timeout in zoneSpec1',
'timeout in null spec',
'zoneSpec2 hasTask: false,false',
]);
done();
}, 300);
});
});
});
| {
"end_byte": 7253,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/proxy.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/sync-test.spec.ts_0_1869 | /**
* @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 {ifEnvSupports} from '../test-util';
describe('SyncTestZoneSpec', () => {
const SyncTestZoneSpec = (Zone as any)['SyncTestZoneSpec'];
let testZoneSpec;
let syncTestZone: Zone;
beforeEach(() => {
testZoneSpec = new SyncTestZoneSpec('name');
syncTestZone = Zone.current.fork(testZoneSpec);
});
it('should fail on Promise.then', () => {
syncTestZone.run(() => {
expect(() => {
Promise.resolve().then(function () {});
}).toThrow(
new Error('Cannot call Promise.then from within a sync test (syncTestZone for name).'),
);
});
});
it('should fail on setTimeout', () => {
syncTestZone.run(() => {
expect(() => {
setTimeout(() => {}, 100);
}).toThrow(
new Error('Cannot call setTimeout from within a sync test (syncTestZone for name).'),
);
});
});
describe(
'event tasks',
ifEnvSupports(
'document',
() => {
it('should work with event tasks', () => {
syncTestZone.run(() => {
const button = document.createElement('button');
document.body.appendChild(button);
let x = 1;
try {
button.addEventListener('click', () => {
x++;
});
button.click();
expect(x).toEqual(2);
button.click();
expect(x).toEqual(3);
} finally {
document.body.removeChild(button);
}
});
});
},
emptyRun,
),
);
});
function emptyRun() {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
}
| {
"end_byte": 1869,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/sync-test.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/clock-tests/enable-clock-patch.ts_0_290 | /**
* @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
*/
(global as any)['__zone_symbol_test__fakeAsyncAutoFakeAsyncWhenClockPatched'] = true;
| {
"end_byte": 290,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/clock-tests/enable-clock-patch.ts"
} |
angular/packages/zone.js/test/zone-spec/clock-tests/fake-async-unpatched-clock.spec.ts_0_3838 | /**
* @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
*/
// Note: We uninstall the clock before starting the tests. This is necessary because
// ZoneJS is loaded after Jasmine has captured the global timing functions. Jasmine
// now doesn't allow `clock().install` because Zone modified e.g. `setTimeout`.
// Uninstalling results in Jasmine resetting to the original NodeJS globals.
// This is fine for this test as it doesn't rely on e.g. patched `setTimeout`.
// https://github.com/jasmine/jasmine/blob/169a2a8ad23a7e5cb12be0a2df02ea4337b9811a/src/core/Clock.js#L17.
jasmine.clock().uninstall();
describe('fake async unpatched clock tests', () => {
const fakeAsync = (Zone as any)[Zone.__symbol__('fakeAsyncTest')].fakeAsync;
let spy: any;
beforeEach(() => {
spy = jasmine.createSpy('timer');
jasmine.clock().install();
});
afterEach(() => {
jasmine.clock().uninstall();
});
it('should check date type correctly', fakeAsync(() => {
const d: any = new Date();
expect(d instanceof Date).toBe(true);
}));
it('should check date type correctly without fakeAsync', () => {
const d: any = new Date();
expect(d instanceof Date).toBe(true);
});
it('should tick correctly', fakeAsync(() => {
jasmine.clock().mockDate();
const start = Date.now();
jasmine.clock().tick(100);
const end = Date.now();
expect(end - start).toBe(100);
}));
it('should tick correctly without fakeAsync', () => {
jasmine.clock().mockDate();
const start = Date.now();
jasmine.clock().tick(100);
const end = Date.now();
expect(end - start).toBe(100);
});
it('should mock date correctly', fakeAsync(() => {
const baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
const start = Date.now();
expect(start).toBe(baseTime.getTime());
jasmine.clock().tick(100);
const end = Date.now();
expect(end - start).toBe(100);
expect(end).toBe(baseTime.getTime() + 100);
expect(new Date().getFullYear()).toEqual(2013);
}));
it('should mock date correctly without fakeAsync', () => {
const baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
const start = Date.now();
expect(start).toBe(baseTime.getTime());
jasmine.clock().tick(100);
const end = Date.now();
expect(end - start).toBe(100);
expect(end).toBe(baseTime.getTime() + 100);
expect(new Date().getFullYear()).toEqual(2013);
});
it('should handle new Date correctly', fakeAsync(() => {
const baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
const start = new Date();
expect(start.getTime()).toBe(baseTime.getTime());
jasmine.clock().tick(100);
const end = new Date();
expect(end.getTime() - start.getTime()).toBe(100);
expect(end.getTime()).toBe(baseTime.getTime() + 100);
}));
it('should handle new Date correctly without fakeAsync', () => {
const baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
const start = new Date();
expect(start.getTime()).toBe(baseTime.getTime());
jasmine.clock().tick(100);
const end = new Date();
expect(end.getTime() - start.getTime()).toBe(100);
expect(end.getTime()).toBe(baseTime.getTime() + 100);
});
it('should handle setTimeout correctly', fakeAsync(() => {
setTimeout(spy, 100);
expect(spy).not.toHaveBeenCalled();
jasmine.clock().tick(100);
expect(spy).toHaveBeenCalled();
}));
it('should handle setTimeout correctly without fakeAsync', () => {
setTimeout(spy, 100);
expect(spy).not.toHaveBeenCalled();
jasmine.clock().tick(100);
expect(spy).toHaveBeenCalled();
});
});
| {
"end_byte": 3838,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/clock-tests/fake-async-unpatched-clock.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/clock-tests/patched.init.ts_0_273 | /**
* @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 './enable-clock-patch';
import '../../node_entry_point.init';
| {
"end_byte": 273,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/clock-tests/patched.init.ts"
} |
angular/packages/zone.js/test/zone-spec/clock-tests/fake-async-patched-clock.spec.ts_0_1846 | /**
* @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
*/
describe('fake async unpatched clock tests', () => {
let spy: any;
beforeEach(() => {
spy = jasmine.createSpy('timer');
jasmine.clock().install();
});
afterEach(() => {
jasmine.clock().uninstall();
});
it('should check date type correctly', () => {
const d: any = new Date();
expect(d instanceof Date).toBe(true);
});
it('should get date diff correctly', () => {
const start = Date.now();
jasmine.clock().tick(100);
const end = Date.now();
expect(end - start).toBe(100);
});
it('should tick correctly', () => {
const start = Date.now();
jasmine.clock().tick(100);
const end = Date.now();
expect(end - start).toBe(100);
});
it('should mock date correctly', () => {
const baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
const start = Date.now();
expect(start).toBe(baseTime.getTime());
jasmine.clock().tick(100);
const end = Date.now();
expect(end - start).toBe(100);
expect(end).toBe(baseTime.getTime() + 100);
});
it('should handle new Date correctly', () => {
const baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
const start = new Date();
expect(start.getTime()).toBe(baseTime.getTime());
jasmine.clock().tick(100);
const end = new Date();
expect(end.getTime() - start.getTime()).toBe(100);
expect(end.getTime()).toBe(baseTime.getTime() + 100);
});
it('should handle setTimeout correctly', () => {
setTimeout(spy, 100);
expect(spy).not.toHaveBeenCalled();
jasmine.clock().tick(100);
expect(spy).toHaveBeenCalled();
});
});
| {
"end_byte": 1846,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/clock-tests/fake-async-patched-clock.spec.ts"
} |
angular/packages/zone.js/test/zone-spec/clock-tests/unpatched.init.ts_0_242 | /**
* @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 '../../node_entry_point.init';
| {
"end_byte": 242,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/clock-tests/unpatched.init.ts"
} |
angular/packages/zone.js/test/zone-spec/clock-tests/BUILD.bazel_0_1101 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "patched_init",
testonly = True,
srcs = [
"enable-clock-patch.ts",
"patched.init.ts",
],
deps = [
"//packages/zone.js/test:node_entry_point",
],
)
ts_library(
name = "test_patched_lib",
testonly = True,
srcs = [
"fake-async-patched-clock.spec.ts",
],
deps = [
"//packages/zone.js/lib:zone_d_ts",
],
)
ts_library(
name = "unpatched_init",
testonly = True,
srcs = [
"unpatched.init.ts",
],
deps = [
"//packages/zone.js/test:node_entry_point",
],
)
ts_library(
name = "test_unpatched_lib",
testonly = True,
srcs = [
"fake-async-unpatched-clock.spec.ts",
],
deps = [
"//packages/zone.js/lib:zone_d_ts",
],
)
jasmine_node_test(
name = "test_patched",
bootstrap = [":patched_init"],
deps = [":test_patched_lib"],
)
jasmine_node_test(
name = "test_unpatched",
bootstrap = [":unpatched_init"],
deps = [":test_unpatched_lib"],
)
| {
"end_byte": 1101,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/zone-spec/clock-tests/BUILD.bazel"
} |
angular/packages/zone.js/test/jest/jest.node.config.js_0_113 | module.exports = {
setupFilesAfterEnv: ['./jest-zone.js'],
testEnvironment: './zone-node-environment.js',
};
| {
"end_byte": 113,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/jest/jest.node.config.js"
} |
angular/packages/zone.js/test/jest/jest.config.js_0_114 | module.exports = {
setupFilesAfterEnv: ['./jest-zone.js'],
testEnvironment: './zone-jsdom-environment.js',
};
| {
"end_byte": 114,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/jest/jest.config.js"
} |
angular/packages/zone.js/test/jest/jest-zone.js_0_349 | const {legacyFakeTimers, modernFakeTimers} = global;
require('../../../../dist/bin/packages/zone.js/npm_package/bundles/zone.umd.js');
require('../../../../dist/bin/packages/zone.js/npm_package/bundles/zone-testing.umd.js');
if (Zone && Zone.patchJestObject) {
Zone.patchJestObject(legacyFakeTimers);
Zone.patchJestObject(modernFakeTimers);
}
| {
"end_byte": 349,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/jest/jest-zone.js"
} |
angular/packages/zone.js/test/jest/jest.spec.js_0_6646 | function assertInsideProxyZone() {
expect(Zone.current.name).toEqual('ProxyZone');
}
function assertInsideSyncDescribeZone() {
expect(Zone.current.name).toEqual('syncTestZone for jest.describe');
}
describe('describe', () => {
assertInsideSyncDescribeZone();
beforeEach(() => {
assertInsideProxyZone();
});
beforeAll(() => {
assertInsideProxyZone();
});
afterEach(() => {
assertInsideProxyZone();
});
afterAll(() => {
assertInsideProxyZone();
});
it('dummy test since jest does not allow before/after each without test', () => {
expect(true).toBe(true);
});
});
describe.each([[1, 2]])('describe.each', (arg1, arg2) => {
assertInsideSyncDescribeZone();
expect(arg1).toBe(1);
expect(arg2).toBe(2);
});
describe('test', () => {
it('it', () => {
assertInsideProxyZone();
});
it.each([[1, 2]])('it.each', (arg1, arg2) => {
assertInsideProxyZone();
expect(arg1).toBe(1);
expect(arg2).toBe(2);
});
test('test', () => {
assertInsideProxyZone();
});
test.each([[]])('test.each', () => {
assertInsideProxyZone();
});
});
it('it', () => {
assertInsideProxyZone();
});
it('it with done', (done) => {
assertInsideProxyZone();
done();
});
it.each([[1, 2]])('it.each', (arg1, arg2, done) => {
assertInsideProxyZone();
expect(arg1).toBe(1);
expect(arg2).toBe(2);
done();
});
it.each([2])('it.each with 1D array', (arg1) => {
assertInsideProxyZone();
expect(arg1).toBe(2);
});
it.each([2])('it.each with 1D array and done', (arg1, done) => {
assertInsideProxyZone();
expect(arg1).toBe(2);
done();
});
it.each`
foo | bar
${1} | ${2}
`('it.each should work with table as a tagged template literal', ({foo, bar}) => {
expect(foo).toBe(1);
expect(bar).toBe(2);
});
it.each`
foo | bar
${1} | ${2}
`('it.each should work with table as a tagged template literal with done', ({foo, bar}, done) => {
expect(foo).toBe(1);
expect(bar).toBe(2);
done();
});
it.each`
foo | bar
${1} | ${2}
`('(async) it.each should work with table as a tagged template literal', async ({foo, bar}) => {
expect(foo).toBe(1);
expect(bar).toBe(2);
});
it.failing('it is not equal', () => {
expect(5).toBe(6); // this test will pass
});
test('test', () => {
assertInsideProxyZone();
});
test.each([[]])('test.each', () => {
assertInsideProxyZone();
});
test.todo('todo');
test.failing('it is not equal', () => {
expect(5).toBe(6); // this test will pass
});
function enableJestPatch() {
global[Zone.__symbol__('fakeAsyncDisablePatchingFakeTimer')] = true;
}
function disableJestPatch() {
global[Zone.__symbol__('fakeAsyncDisablePatchingFakeTimer')] = false;
}
const {resetFakeAsyncZone, flushMicrotasks, discardPeriodicTasks, tick, flush, fakeAsync} =
Zone[Zone.__symbol__('fakeAsyncTest')];
describe('jest modern fakeTimers with zone.js fakeAsync', () => {
beforeEach(() => {
jest.useFakeTimers('modern');
});
afterEach(() => {
jest.useRealTimers();
});
test('should run into fakeAsync() automatically', () => {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
expect(fakeAsyncZoneSpec).toBeTruthy();
expect(typeof fakeAsyncZoneSpec.tick).toEqual('function');
});
test('setSystemTime should set FakeDate.currentFakeTime', () => {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
let d = fakeAsyncZoneSpec.getRealSystemTime();
jest.setSystemTime(d);
expect(Date.now()).toEqual(d);
for (let i = 0; i < 100000; i++) {}
expect(fakeAsyncZoneSpec.getRealSystemTime()).not.toEqual(d);
d = fakeAsyncZoneSpec.getRealSystemTime();
let timeoutTriggered = false;
setTimeout(() => {
timeoutTriggered = true;
}, 100);
jest.setSystemTime(d);
tick(100);
expect(timeoutTriggered).toBe(true);
expect(Date.now()).toEqual(d + 100);
});
test('runAllTicks should run all microTasks', () => {
const logs = [];
Promise.resolve(1).then((v) => logs.push(v));
expect(logs).toEqual([]);
jest.runAllTicks();
expect(logs).toEqual([1]);
});
test('runAllTimers should run all macroTasks', () => {
const logs = [];
Promise.resolve(1).then((v) => logs.push(v));
setTimeout(() => {
logs.push('timeout');
});
const id = setInterval(() => {
logs.push('interval');
}, 100);
expect(logs).toEqual([]);
jest.runAllTimers();
expect(logs).toEqual([1, 'timeout', 'interval']);
clearInterval(id);
});
test('advanceTimersByTime should act as tick', () => {
const logs = [];
setTimeout(() => {
logs.push('timeout');
}, 100);
expect(logs).toEqual([]);
jest.advanceTimersByTime(100);
expect(logs).toEqual(['timeout']);
});
test('runOnlyPendingTimers should run all macroTasks and ignore new spawn macroTasks', () => {
const logs = [];
Promise.resolve(1).then((v) => logs.push(v));
let nestedTimeoutId;
setTimeout(() => {
logs.push('timeout');
nestedTimeoutId = setTimeout(() => {
logs.push('new timeout');
});
});
expect(logs).toEqual([]);
jest.runOnlyPendingTimers();
expect(logs).toEqual([1, 'timeout']);
clearTimeout(nestedTimeoutId);
});
test('advanceTimersToNextTimer should trigger correctly', () => {
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout11');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setTimeout(() => {
logs.push('timeout3');
}, 300);
expect(logs).toEqual([]);
jest.advanceTimersToNextTimer();
expect(logs).toEqual(['timeout1', 'timeout11']);
jest.advanceTimersToNextTimer(2);
expect(logs).toEqual(['timeout1', 'timeout11', 'timeout2', 'timeout3']);
});
test('clearAllTimers should clear all macroTasks', () => {
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setInterval(() => {
logs.push('interval');
}, 100);
expect(logs).toEqual([]);
jest.clearAllTimers();
jest.advanceTimersByTime(300);
expect(logs).toEqual([]);
});
test('getTimerCount should get the count of macroTasks correctly', () => {
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setInterval(() => {
logs.push('interval');
}, 100);
expect(logs).toEqual([]);
expect(jest.getTimerCount()).toEqual(3);
jest.clearAllTimers();
});
}); | {
"end_byte": 6646,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/jest/jest.spec.js"
} |
angular/packages/zone.js/test/jest/jest.spec.js_6648_13507 | describe('jest legacy fakeTimers with zone.js fakeAsync', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test('should run into fakeAsync() automatically', () => {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
expect(fakeAsyncZoneSpec).toBeTruthy();
expect(typeof fakeAsyncZoneSpec.tick).toEqual('function');
});
test('runAllTicks should run all microTasks', () => {
const logs = [];
Promise.resolve(1).then((v) => logs.push(v));
expect(logs).toEqual([]);
jest.runAllTicks();
expect(logs).toEqual([1]);
});
test('runAllTimers should run all macroTasks', () => {
const logs = [];
Promise.resolve(1).then((v) => logs.push(v));
setTimeout(() => {
logs.push('timeout');
});
const id = setInterval(() => {
logs.push('interval');
}, 100);
expect(logs).toEqual([]);
jest.runAllTimers();
expect(logs).toEqual([1, 'timeout', 'interval']);
clearInterval(id);
});
test('advanceTimersByTime should act as tick', () => {
const logs = [];
setTimeout(() => {
logs.push('timeout');
}, 100);
expect(logs).toEqual([]);
jest.advanceTimersByTime(100);
expect(logs).toEqual(['timeout']);
});
test('runOnlyPendingTimers should run all macroTasks and ignore new spawn macroTasks', () => {
const logs = [];
Promise.resolve(1).then((v) => logs.push(v));
let nestedTimeoutId;
setTimeout(() => {
logs.push('timeout');
nestedTimeoutId = setTimeout(() => {
logs.push('new timeout');
});
});
expect(logs).toEqual([]);
jest.runOnlyPendingTimers();
expect(logs).toEqual([1, 'timeout']);
clearTimeout(nestedTimeoutId);
});
test('advanceTimersToNextTimer should trigger correctly', () => {
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout11');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setTimeout(() => {
logs.push('timeout3');
}, 300);
expect(logs).toEqual([]);
jest.advanceTimersToNextTimer();
expect(logs).toEqual(['timeout1', 'timeout11']);
jest.advanceTimersToNextTimer(2);
expect(logs).toEqual(['timeout1', 'timeout11', 'timeout2', 'timeout3']);
});
test('clearAllTimers should clear all macroTasks', () => {
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setInterval(() => {
logs.push('interval');
}, 100);
expect(logs).toEqual([]);
jest.clearAllTimers();
jest.advanceTimersByTime(300);
expect(logs).toEqual([]);
});
test('getTimerCount should get the count of macroTasks correctly', () => {
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setInterval(() => {
logs.push('interval');
}, 100);
expect(logs).toEqual([]);
expect(jest.getTimerCount()).toEqual(3);
jest.clearAllTimers();
});
});
describe('jest fakeTimers inside test should call native delegate', () => {
test('setSystemTime should set FakeDate.currentRealTime', () => {
let fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
expect(fakeAsyncZoneSpec).toBeFalsy();
jest.useFakeTimers('modern');
fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
expect(fakeAsyncZoneSpec).toBeFalsy();
const d = Date.now();
jest.setSystemTime(d);
for (let i = 0; i < 100000; i++) {}
expect(jest.getRealSystemTime()).not.toEqual(d);
jest.useRealTimers();
});
test('runAllTicks should run all microTasks', () => {
jest.useFakeTimers();
const logs = [];
process.nextTick(() => {
logs.push(1);
});
expect(logs).toEqual([]);
jest.runAllTicks();
expect(logs).toEqual([1]);
jest.useRealTimers();
});
test('runAllTimers should run all macroTasks', () => {
jest.useFakeTimers();
const logs = [];
process.nextTick(() => {
logs.push(1);
});
setTimeout(() => {
logs.push('timeout');
});
const id = setInterval(() => {
logs.push('interval');
clearInterval(id);
}, 100);
expect(logs).toEqual([]);
jest.runAllTimers();
expect(logs).toEqual([1, 'timeout', 'interval']);
jest.useRealTimers();
});
test('advanceTimersByTime should act as tick', () => {
jest.useFakeTimers();
const logs = [];
setTimeout(() => {
logs.push('timeout');
}, 100);
expect(logs).toEqual([]);
jest.advanceTimersByTime(100);
expect(logs).toEqual(['timeout']);
jest.useRealTimers();
});
test('runOnlyPendingTimers should run all macroTasks and ignore new spawn macroTasks', () => {
jest.useFakeTimers();
const logs = [];
let nestedTimeoutId;
setTimeout(() => {
logs.push('timeout');
nestedTimeoutId = setTimeout(() => {
logs.push('new timeout');
});
});
expect(logs).toEqual([]);
jest.runOnlyPendingTimers();
expect(logs).toEqual(['timeout']);
clearTimeout(nestedTimeoutId);
jest.useRealTimers();
});
test('advanceTimersToNextTimer should trigger correctly', () => {
jest.useFakeTimers();
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout11');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setTimeout(() => {
logs.push('timeout3');
}, 300);
expect(logs).toEqual([]);
jest.advanceTimersToNextTimer();
expect(logs).toEqual(['timeout1', 'timeout11']);
jest.advanceTimersToNextTimer(2);
expect(logs).toEqual(['timeout1', 'timeout11', 'timeout2', 'timeout3']);
jest.useRealTimers();
});
test('clearAllTimers should clear all macroTasks', () => {
jest.useFakeTimers();
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setInterval(() => {
logs.push('interval');
}, 100);
expect(logs).toEqual([]);
jest.clearAllTimers();
jest.advanceTimersByTime(300);
expect(logs).toEqual([]);
jest.useRealTimers();
});
test('getTimerCount should get the count of macroTasks correctly', () => {
jest.useFakeTimers();
const logs = [];
setTimeout(() => {
logs.push('timeout1');
}, 100);
setTimeout(() => {
logs.push('timeout2');
}, 200);
setInterval(() => {
logs.push('interval');
}, 100);
expect(logs).toEqual([]);
expect(jest.getTimerCount()).toEqual(3);
jest.clearAllTimers();
jest.useRealTimers();
});
}); | {
"end_byte": 13507,
"start_byte": 6648,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/jest/jest.spec.js"
} |
angular/packages/zone.js/test/jest/jest-zone-patch-fake-timer.js_0_233 | const exportFakeTimersToSandboxGlobal = function (jestEnv) {
jestEnv.global.legacyFakeTimers = jestEnv.fakeTimers;
jestEnv.global.modernFakeTimers = jestEnv.fakeTimersModern;
};
module.exports = exportFakeTimersToSandboxGlobal;
| {
"end_byte": 233,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/jest/jest-zone-patch-fake-timer.js"
} |
angular/packages/zone.js/test/jest/zone-jsdom-environment.js_0_519 | const JSDOMEnvironment = require('jest-environment-jsdom').default;
const exportFakeTimersToSandboxGlobal = require('./jest-zone-patch-fake-timer');
class ZoneJsDOMEnvironment extends JSDOMEnvironment {
constructor(config, context) {
super(config, context);
exportFakeTimersToSandboxGlobal(this);
}
async setup() {
await super.setup();
}
async teardown() {
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
module.exports = ZoneJsDOMEnvironment;
| {
"end_byte": 519,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/jest/zone-jsdom-environment.js"
} |
angular/packages/zone.js/test/jest/zone-node-environment.js_0_514 | const NodeEnvironment = require('jest-environment-node').default;
const exportFakeTimersToSandboxGlobal = require('./jest-zone-patch-fake-timer');
class ZoneNodeEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
exportFakeTimersToSandboxGlobal(this);
}
async setup() {
await super.setup();
}
async teardown() {
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
module.exports = ZoneNodeEnvironment;
| {
"end_byte": 514,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/jest/zone-node-environment.js"
} |
angular/packages/zone.js/example/basic.html_0_1245 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zone.js Basic Demo</title>
<link rel="stylesheet" href="css/style.css">
<script src="../dist/zone.js"></script>
<script src="../dist/long-stack-trace-zone.js"></script>
</head>
<body>
<h1>Basic Example</h1>
<button id="b1">Bind Error</button>
<button id="b2">Cause Error</button>
<script>
/*
* This is a simple example of async stack traces with zones
*/
function main () {
b1.addEventListener('click', bindSecondButton);
}
/*
* What if your stack trace could tell you what
* order the user pushed the buttons from the stack trace?
*
* What if you could log this back to the server?
*
* Think of how much more productive your debugging could be!
*/
function bindSecondButton () {
b2.addEventListener('click', throwError);
}
function throwError () {
throw new Error('aw shucks');
}
/*
* Bootstrap the app
*/
//main();
Zone.current.fork(
{
onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
console.log(error.stack);
}
}
).fork(Zone.longStackTraceZoneSpec).run(main);
</script>
</body>
</html> | {
"end_byte": 1245,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/basic.html"
} |
angular/packages/zone.js/example/counting.html_0_2657 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Counting Pending Tasks</title>
<link rel="stylesheet" href="css/style.css">
<script src="../dist/zone.js"></script>
<script src="js/counting-zone.js"></script>
</head>
<body>
<h1>Counting Pending Tasks</h1>
<p>We want to know about just the events from a single mouse click
while a bunch of other stuff is happening on the page</p>
<p>This is useful in E2E testing. Because you know when there are
no async tasks, you avoid adding timeouts that wait for tasks that
run for an indeterminable amount of time.</p>
<button id="b1">Start</button>
<p id="output"></p>
<script>
/*
* Zone that counts pending async tasks
*/
const outputElem = document.getElementById('output');
const countingZoneSpec = Zone['countingZoneSpec'];
const myCountingZone = Zone.current.fork(countingZoneSpec).fork({
onScheduleTask(parent, current, target, task) {
parent.scheduleTask(target, task);
console.log('Scheduled ' + task.source + ' => ' + task.data.handleId);
outputElem.innerText = countingZoneSpec.counter();
},
onInvokeTask(parent, current, target, task) {
console.log('Invoking ' + task.source + ' => ' + task.data.handleId);
parent.invokeTask(target, task);
outputElem.innerText = countingZoneSpec.counter();
},
onHasTask(parent, current, target, hasTask) {
if (hasTask.macroTask) {
console.log("There are outstanding MacroTasks.");
} else {
console.log("All MacroTasks have been completed.");
}
}
});
/*
* We want to profile just the actions that are a result of this button, so with
* a single line of code, we can run `main` in the countingZone
*/
b1.addEventListener('click', function () {
myCountingZone.run(main);
});
/*
* Spawns a bunch of setTimeouts which in turn spawn more setTimeouts!
* This is a boring way to simulate HTTP requests and other async actions.
*/
function main () {
for (var i = 0; i < 10; i++) {
recur(i, 800);
}
}
function recur (x, t) {
if (x > 0) {
setTimeout(function () {
for (var i = x; i < 8; i++) {
recur(x - 1, Math.random()*t);
}
}, t);
}
}
/*
* There may be other async actions going on in the background.
* Because this is not in the zone, our profiling ignores it.
* Nice.
*/
function noop () {
setTimeout(noop, 10*Math.random());
}
noop();
</script>
</body>
</html>
| {
"end_byte": 2657,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/counting.html"
} |
angular/packages/zone.js/example/index.html_0_511 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zone.js Examples</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Examples</h1>
<ol>
<li><a href="basic.html">Tracing user actions with long stack traces</a></li>
<li><a href="counting.html">Counting Tasks</a></li>
<li><a href="profiling.html">Profiling Across Tasks</a></li>
<li><a href="throttle.html">Throttle</a></li>
<li><a href="web-socket.html">WebSocket</a></li>
</ol>
</body>
</html>
| {
"end_byte": 511,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/index.html"
} |
angular/packages/zone.js/example/web-socket.html_0_1067 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSockets with Zones</title>
<link rel="stylesheet" href="css/style.css">
<script src="../dist/zone.js"></script>
</head>
<body>
<p>
Ensure that you started <code>node test/ws-server.js</code> before loading
this page. Then check console output.
</p>
<script>
var ws = new WebSocket('ws://localhost:8001');
ws.onopen = function() {
Zone.current.fork({properties: {secretPayload: 'bah!'}, name: 'secrete-zone'}).run(function() {
ws.onmessage = function(eventListener) {
if (Zone.current.get('secretPayload') === 'bah!') {
console.log("The current zone (id: %s) has secretPayload. Zones are working!",
Zone.current.name);
} else {
console.error('Secret payload not found where expected! Zones are not working! :-(', Zone.current.name);
}
};
console.log('Setting secret payload in the current zone (id: %s)', Zone.current.name);
});
ws.send('hello!');
};
</script>
</body>
</html>
| {
"end_byte": 1067,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/web-socket.html"
} |
angular/packages/zone.js/example/profiling.html_0_3108 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zones Profiling</title>
<link rel="stylesheet" href="css/style.css">
<script>
__Zone_disable_Error = true;
__Zone_disable_on_property = true;
__Zone_disable_geolocation = true;
__Zone_disable_toString = true;
__Zone_disable_blocking = true;
__Zone_disable_PromiseRejectionEvent = true;
</script>
<script src="../dist/zone.js"></script>
<script src="../dist/long-stack-trace-zone.js"></script>
</head>
<body>
<h1>Profiling with Zones</h1>
<button id="b1">Start Profiling</button>
<script>
/*
* Let's say we want to know the CPU cost from some action
* that includes async tasks. We can do this with zones!
*/
/*
* For this demo, we're going to sort an array using an async
* algorithm when a button is pressed.
*/
function sortAndPrintArray (unsortedArray) {
profilingZoneSpec.reset();
asyncBogosort(unsortedArray, function (sortedArray) {
console.log(sortedArray);
console.log('sorting took ' + profilingZoneSpec.time() + ' of CPU time');
});
}
/*
* This is a really efficient algorithm.
*
* First, check if the array is sorted.
* - If it is, call the wrapCallback
* - If it isn't, randomize the array and recur
*
* This implementation is async because JavaScript
*/
function asyncBogosort (arr, cb) {
setTimeout(function () {
if (isSorted(arr)) {
cb(arr);
} else {
var newArr = arr.slice(0);
newArr.sort(function () {
return Math.random() - 0.5;
});
asyncBogosort(newArr, cb);
}
}, 0);
}
function isSorted (things) {
for (var i = 1; i < things.length; i += 1) {
if (things[i] < things[i - 1]) {
return false;
}
}
return true;
}
/*
* Bind button
*/
function main () {
var unsortedArray = [3,4,1,2,7];
b1.addEventListener('click', function () {
sortAndPrintArray(unsortedArray);
});
}
/*
* This zone starts a timer at the start of each taskEnv,
* and stops it at the end. It accumulates the total run
* time internally, exposing it via `zone.time()`
*
* Note that this is the time the CPU is spending doing
* bogosort, as opposed to the time from the start
* of the algorithm until it's completion.
*/
var profilingZoneSpec = (function () {
var time = 0,
// use the high-res timer if available
timer = performance ?
performance.now.bind(performance) :
Date.now.bind(Date);
return {
onInvokeTask: function (delegate, current, target, task, applyThis, applyArgs) {
this.start = timer();
delegate.invokeTask(target, task, applyThis, applyArgs);
time += timer() - this.start;
},
time: function () {
return Math.floor(time*100) / 100 + 'ms';
},
reset: function () {
time = 0;
}
};
}());
/*
* Bootstrap the app
*/
Zone.current.fork(profilingZoneSpec).run(main);
</script>
</body>
</html>
| {
"end_byte": 3108,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/profiling.html"
} |
angular/packages/zone.js/example/throttle.html_0_1915 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zones throttle</title>
<link rel="stylesheet" href="css/style.css">
<script src="../dist/zone.js"></script>
<script src="../dist/long-stack-trace-zone.js"></script>
</head>
<body>
<h1>Throttle Example</h1>
<button id="b2">Error</button>
<script>
/*
* In this example, we have a button that makes some request
* to our server. We want to only make the request once per
* 1s, so we use a `throttle` helper. If the request fails,
* it's difficult to see where the failure originated from.
*
* Thankfully, we can use zones to preserve the stack even
* across async tasks to get a better picture of the control
* flow of the app.
*/
var throttleMakeRequest;
/*
* Start the app
* Bind listeners
*/
function bootstrap () {
b2.addEventListener('click', throttleMakeRequest);
}
/*
* Makes a request to the server
* Will only make the request once every 1000ms
*/
throttleMakeRequest = throttle(function () {
makeRequestToServer(handleServerResponse);
}, 1000);
/*
* Pretend this makes a request to a server
*/
function makeRequestToServer (cb) {
setTimeout(cb, 100);
}
function handleServerResponse (err, data) {
throw new Error('Oops');
}
/*
* Returns a fn that can only be called once
* per `time` milliseconds
*/
function throttle (fn, time) {
var id = null;
if (typeof time !== 'number') {
time = 0;
}
return function () {
if (!id) {
id = setTimeout(function () {
id = null;
fn();
}, time);
}
};
}
/*
* Start the application
*
* If we start the application with `zone.run`, we
* get long stack traces in the console!
*/
//bootstrap();
Zone.current.fork(Zone.longStackTraceZoneSpec).run(bootstrap);
</script>
</body>
</html>
| {
"end_byte": 1915,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/throttle.html"
} |
angular/packages/zone.js/example/css/style.css_0_111 | body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}
| {
"end_byte": 111,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/css/style.css"
} |
angular/packages/zone.js/example/js/counting-zone.js_0_801 | /*
* See example/counting.html
*/
Zone['countingZoneSpec'] = {
name: 'counterZone',
// setTimeout
onScheduleTask: function (delegate, current, target, task) {
this.data.count += 1;
delegate.scheduleTask(target, task);
},
// fires when...
// - clearTimeout
// - setTimeout finishes
onInvokeTask: function (delegate, current, target, task, applyThis, applyArgs) {
delegate.invokeTask(target, task, applyThis, applyArgs);
this.data.count -= 1;
},
onHasTask: function (delegate, current, target, hasTask) {
if (this.data.count === 0 && !this.data.flushed) {
this.data.flushed = true;
target.run(this.onFlush);
}
},
counter: function () {
return this.data.count;
},
data: {count: 0, flushed: false},
onFlush: function () {},
};
| {
"end_byte": 801,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/js/counting-zone.js"
} |
angular/packages/zone.js/example/benchmarks/event_emitter.js_0_1445 | /**
* @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
*/
const events = require('events');
const EventEmitter = events.EventEmitter;
require('../../dist/zone-node');
const emitters = [];
const callbacks = [];
const size = 100000;
for (let i = 0; i < size; i++) {
const emitter = new EventEmitter();
const callback = (function (i) {
return function () {
console.log(i);
};
})(i);
emitters[i] = emitter;
callbacks[i] = callback;
}
function addRemoveCallback(reuse, useZone) {
const start = new Date();
let callback = callbacks[0];
for (let i = 0; i < size; i++) {
const emitter = emitters[i];
if (!reuse) callback = callbacks[i];
if (useZone) emitter.on('msg', callback);
else emitter.__zone_symbol__addListener('msg', callback);
}
for (let i = 0; i < size; i++) {
const emitter = emitters[i];
if (!reuse) callback = callbacks[i];
if (useZone) emitter.removeListener('msg', callback);
else emitter.__zone_symbol__removeListener('msg', callback);
}
const end = new Date();
console.log(useZone ? 'use zone' : 'native', reuse ? 'reuse' : 'new');
console.log('Execution time: %dms', end - start);
}
addRemoveCallback(false, false);
addRemoveCallback(false, true);
addRemoveCallback(true, false);
addRemoveCallback(true, true);
| {
"end_byte": 1445,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/benchmarks/event_emitter.js"
} |
angular/packages/zone.js/example/benchmarks/addEventListener.html_0_2050 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zone.js addEventListenerBenchmark</title>
<link rel="stylesheet" href="../css/style.css">
<script src="../../dist/zone.js"></script>
</head>
<body>
<h1>addEventListener Benchmark</h1>
<h2>No Zone</h2>
<button id="b1">Add/Remove same callback</button>
<button id="b2">Add/Remove different callback</button>
<h2>With Zone</h2>
<button id="b3">Add/Remove same callback</button>
<button id="b4">Add/Remove different callback</button>
<div id="rootDiv"></div>
<script>
b1.addEventListener('click', function () { addRemoveCallback(true, false); });
b2.addEventListener('click', function () { addRemoveCallback(false, false); });
b3.addEventListener('click', function () { addRemoveCallback(true, true); });
b4.addEventListener('click', function () { addRemoveCallback(false, true); });
var divs = [];
var callbacks = [];
var size = 100000;
for(var i = 0; i < size; i++) {
var div = document.createElement("div");
var callback = (function(i) { return function() { console.log(i); }; })(i);
rootDiv.appendChild(div);
divs[i] = div;
callbacks[i] = callback;
}
function addRemoveCallback(reuse, useZone) {
var start = performance.now();
var callback = callbacks[0];
for(var i = 0; i < size; i++) {
var div = divs[i];
if (!reuse) callback = callbacks[i];
if (useZone)
div.addEventListener('click', callback);
else
div.__zone_symbol__addEventListener('click', callback);
}
for(var i = 0; i < size; i++) {
var div = divs[i];
if (!reuse) callback = callbacks[i];
if (useZone)
div.removeEventListener('click', callback);
else
div.__zone_symbol__removeEventListener('click', callback);
}
var end = performance.now();
console.log(useZone ? 'use zone': 'native', reuse ? 'reuse' : 'new', end - start, 'ms');
}
</script>
</body>
</html>
| {
"end_byte": 2050,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/example/benchmarks/addEventListener.html"
} |
angular/packages/zone.js/fesm2015/BUILD.bazel_0_223 | load("//packages/zone.js:tools.bzl", "generate_dist")
load("//packages/zone.js:bundles.bzl", "BUNDLES_ENTRY_POINTS")
generate_dist(
bundles = BUNDLES_ENTRY_POINTS.items(),
output_format = "es2015",
umd = "",
)
| {
"end_byte": 223,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/fesm2015/BUILD.bazel"
} |
angular/packages/zone.js/scripts/grab-blink-idl.sh_0_650 | #!/bin/bash
set -e
trap "echo Exit; exit;" SIGINT SIGTERM
CORE_URL="https://src.chromium.org/blink/trunk/Source/core/"
MODULE_URL="https://src.chromium.org/blink/trunk/Source/modules/"
mkdir -p blink-idl/core
mkdir -p blink-idl/modules
echo "Fetching core idl files..."
rm tmp/ -rf
svn co $CORE_URL tmp -q
for IDL in $(find tmp/ -iname '*.idl' -type f -printf '%P\n')
do
echo "- $IDL"
mv "tmp/$IDL" blink-idl/core
done
echo "Fetching modules idl files..."
rm tmp/ -rf
svn co $MODULE_URL tmp -q
for IDL in $(find tmp/ -iname '*.idl' -type f -printf '%P\n')
do
echo "- $IDL"
mv "tmp/$IDL" blink-idl/modules
done
rm tmp/ -rf
| {
"end_byte": 650,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/scripts/grab-blink-idl.sh"
} |
angular/packages/zone.js/scripts/closure/closure_flagfile_0_211 | --compilation_level ADVANCED_OPTIMIZATIONS
--js_output_file "build/closure/zone-closure-bundle.js"
--rewrite_polyfills false
--js "build/zone.umd.js"
--js "build/test/zone.closure.mjs"
--formatting PRETTY_PRINT
| {
"end_byte": 211,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/scripts/closure/closure_flagfile"
} |
angular/packages/zone.js/scripts/sauce/sauce_connect_setup.sh_0_1674 | #!/bin/bash
set -e -o pipefail
# Setup and start Sauce Connect for your TravisCI build
# This script requires your .travis.yml to include the following two private env variables:
# SAUCE_USERNAME
# SAUCE_ACCESS_KEY
# Follow the steps at https://saucelabs.com/opensource/travis to set that up.
#
# Curl and run this script as part of your .travis.yml before_script section:
# before_script:
# - curl https://gist.github.com/santiycr/5139565/raw/sauce_connect_setup.sh | bash
CONNECT_URL="https://saucelabs.com/downloads/sc-4.3.14-linux.tar.gz"
CONNECT_DIR="/tmp/sauce-connect-$RANDOM"
CONNECT_DOWNLOAD="sc-latest-linux.tar.gz"
CONNECT_LOG="$LOGS_DIR/sauce-connect"
CONNECT_STDOUT="$LOGS_DIR/sauce-connect.stdout"
CONNECT_STDERR="$LOGS_DIR/sauce-connect.stderr"
# Get Connect and start it
mkdir -p $CONNECT_DIR
cd $CONNECT_DIR
curl $CONNECT_URL -o $CONNECT_DOWNLOAD 2> /dev/null 1> /dev/null
mkdir sauce-connect
tar --extract --file=$CONNECT_DOWNLOAD --strip-components=1 --directory=sauce-connect > /dev/null
rm $CONNECT_DOWNLOAD
SAUCE_ACCESS_KEY=`echo $SAUCE_ACCESS_KEY | rev`
ARGS=""
# Set tunnel-id only on Travis, to make local testing easier.
if [ ! -z "$TRAVIS_JOB_NUMBER" ]; then
ARGS="$ARGS --tunnel-identifier $TRAVIS_JOB_NUMBER"
fi
if [ ! -z "$BROWSER_PROVIDER_READY_FILE" ]; then
ARGS="$ARGS --readyfile $BROWSER_PROVIDER_READY_FILE"
fi
echo "Starting Sauce Connect in the background, logging into:"
echo " $CONNECT_LOG"
echo " $CONNECT_STDOUT"
echo " $CONNECT_STDERR"
sauce-connect/bin/sc -u $SAUCE_USERNAME -k $SAUCE_ACCESS_KEY $ARGS \
--reconnect 100 --no-ssl-bump-domains all --logfile $CONNECT_LOG 2> $CONNECT_STDERR 1> $CONNECT_STDOUT &
| {
"end_byte": 1674,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/scripts/sauce/sauce_connect_setup.sh"
} |
angular/packages/zone.js/scripts/sauce/sauce_connect_block.sh_0_249 | #!/bin/bash
# Wait for Connect to be ready before exiting
printf "Connecting to Sauce."
while [ ! -f $BROWSER_PROVIDER_READY_FILE ]; do
printf "."
#dart2js takes longer than the travis 10 min timeout to complete
sleep .5
done
echo "Connected" | {
"end_byte": 249,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/scripts/sauce/sauce_connect_block.sh"
} |
angular/packages/zone.js/lib/zone.api.extensions.ts_0_1774 | /**
* @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
*/
declare global {
/**
* Additional `EventTarget` methods added by `Zone.js`.
*
* 1. removeAllListeners, remove all event listeners of the given event name.
* 2. eventListeners, get all event listeners of the given event name.
*/
interface EventTarget {
/**
*
* Remove all event listeners by name for this event target.
*
* This method is optional because it may not be available if you use `noop zone` when
* bootstrapping Angular application or disable the `EventTarget` monkey patch by `zone.js`.
*
* If the `eventName` is provided, will remove event listeners of that name.
* If the `eventName` is not provided, will remove all event listeners associated with
* `EventTarget`.
*
* @param eventName the name of the event, such as `click`. This parameter is optional.
*/
removeAllListeners?(eventName?: string): void;
/**
*
* Retrieve all event listeners by name.
*
* This method is optional because it may not be available if you use `noop zone` when
* bootstrapping Angular application or disable the `EventTarget` monkey patch by `zone.js`.
*
* If the `eventName` is provided, will return an array of event handlers or event listener
* objects of the given event.
* If the `eventName` is not provided, will return all listeners.
*
* @param eventName the name of the event, such as click. This parameter is optional.
*/
eventListeners?(eventName?: string): EventListenerOrEventListenerObject[];
}
}
export {};
| {
"end_byte": 1774,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone.api.extensions.ts"
} |
angular/packages/zone.js/lib/zone.configurations.api.ts_0_8185 | /**
* @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
*/
declare global {
/**
* Interface of `zone.js` configurations.
*
* You can define the following configurations on the `window/global` object before
* importing `zone.js` to change `zone.js` default behaviors.
*/
interface ZoneGlobalConfigurations {
/**
* Disable the monkey patch of the `Node.js` `EventEmitter` API.
*
* By default, `zone.js` monkey patches the `Node.js` `EventEmitter` APIs to make asynchronous
* callbacks of those APIs in the same zone when scheduled.
*
* Consider the following example:
*
* ```
* const EventEmitter = require('events');
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
*
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* myEmitter.on('event', () => {
* console.log('an event occurs in the zone', Zone.current.name);
* // the callback runs in the zone when it is scheduled,
* // so the output is 'an event occurs in the zone myZone'.
* });
* });
* myEmitter.emit('event');
* ```
*
* If you set `__Zone_disable_EventEmitter = true` before importing `zone.js`,
* `zone.js` does not monkey patch the `EventEmitter` APIs and the above code
* outputs 'an event occurred <root>'.
*/
__Zone_disable_EventEmitter?: boolean;
/**
* Disable the monkey patch of the `Node.js` `fs` API.
*
* By default, `zone.js` monkey patches `Node.js` `fs` APIs to make asynchronous callbacks of
* those APIs in the same zone when scheduled.
*
* Consider the following example:
*
* ```
* const fs = require('fs');
*
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* fs.stat('/tmp/world', (err, stats) => {
* console.log('fs.stats() callback is invoked in the zone', Zone.current.name);
* // since the callback of the `fs.stat()` runs in the same zone
* // when it is called, so the output is 'fs.stats() callback is invoked in the zone
* myZone'.
* });
* });
* ```
*
* If you set `__Zone_disable_fs = true` before importing `zone.js`,
* `zone.js` does not monkey patch the `fs` API and the above code
* outputs 'get stats occurred <root>'.
*/
__Zone_disable_fs?: boolean;
/**
* Disable the monkey patch of the `Node.js` `timer` API.
*
* By default, `zone.js` monkey patches the `Node.js` `timer` APIs to make asynchronous
* callbacks of those APIs in the same zone when scheduled.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* setTimeout(() => {
* console.log('setTimeout() callback is invoked in the zone', Zone.current.name);
* // since the callback of `setTimeout()` runs in the same zone
* // when it is scheduled, so the output is 'setTimeout() callback is invoked in the zone
* // myZone'.
* });
* });
* ```
*
* If you set `__Zone_disable_timers = true` before importing `zone.js`,
* `zone.js` does not monkey patch the `timer` APIs and the above code
* outputs 'timeout <root>'.
*/
__Zone_disable_node_timers?: boolean;
/**
* Disable the monkey patch of the `Node.js` `process.nextTick()` API.
*
* By default, `zone.js` monkey patches the `Node.js` `process.nextTick()` API to make the
* callback in the same zone when calling `process.nextTick()`.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* process.nextTick(() => {
* console.log('process.nextTick() callback is invoked in the zone', Zone.current.name);
* // since the callback of `process.nextTick()` runs in the same zone
* // when it is scheduled, so the output is 'process.nextTick() callback is invoked in the
* // zone myZone'.
* });
* });
* ```
*
* If you set `__Zone_disable_nextTick = true` before importing `zone.js`,
* `zone.js` does not monkey patch the `process.nextTick()` API and the above code
* outputs 'nextTick <root>'.
*/
__Zone_disable_nextTick?: boolean;
/**
* Disable the monkey patch of the `Node.js` `crypto` API.
*
* By default, `zone.js` monkey patches the `Node.js` `crypto` APIs to make asynchronous
* callbacks of those APIs in the same zone when called.
*
* Consider the following example:
*
* ```
* const crypto = require('crypto');
*
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* crypto.randomBytes(() => {
* console.log('crypto.randomBytes() callback is invoked in the zone', Zone.current.name);
* // since the callback of `crypto.randomBytes()` runs in the same zone
* // when it is called, so the output is 'crypto.randomBytes() callback is invoked in the
* // zone myZone'.
* });
* });
* ```
*
* If you set `__Zone_disable_crypto = true` before importing `zone.js`,
* `zone.js` does not monkey patch the `crypto` API and the above code
* outputs 'crypto <root>'.
*/
__Zone_disable_crypto?: boolean;
/**
* Disable the monkey patch of the `Object.defineProperty()` API.
*
* Note: This configuration is available only in the legacy bundle (dist/zone.js). This module
* is not available in the evergreen bundle (zone-evergreen.js).
*
* In the legacy browser, the default behavior of `zone.js` is to monkey patch
* `Object.defineProperty()` and `Object.create()` to try to ensure PropertyDescriptor
* parameter's configurable property to be true. This patch is only needed in some old mobile
* browsers.
*
* If you set `__Zone_disable_defineProperty = true` before importing `zone.js`,
* `zone.js` does not monkey patch the `Object.defineProperty()` API and does not
* modify desc.configurable to true.
*
*/
__Zone_disable_defineProperty?: boolean;
/**
* Disable the monkey patch of the browser `registerElement()` API.
*
* NOTE: This configuration is only available in the legacy bundle (dist/zone.js), this
* module is not available in the evergreen bundle (zone-evergreen.js).
*
* In the legacy browser, the default behavior of `zone.js` is to monkey patch the
* `registerElement()` API to make asynchronous callbacks of the API in the same zone when
* `registerElement()` is called.
*
* Consider the following example:
*
* ```
* const proto = Object.create(HTMLElement.prototype);
* proto.createdCallback = function() {
* console.log('createdCallback is invoked in the zone', Zone.current.name);
* };
* proto.attachedCallback = function() {
* console.log('attachedCallback is invoked in the zone', Zone.current.name);
* };
* proto.detachedCallback = function() {
* console.log('detachedCallback is invoked in the zone', Zone.current.name);
* };
* proto.attributeChangedCallback = function() {
* console.log('attributeChangedCallback is invoked in the zone', Zone.current.name);
* };
*
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* document.registerElement('x-elem', {prototype: proto});
* });
* ```
*
* When these callbacks are invoked, those callbacks will be in the zone when
* `registerElement()` is called.
*
* If you set `__Zone_disable_registerElement = true` before importing `zone.js`,
* `zone.js` does not monkey patch `registerElement()` API and the above code
* outputs '<root>'.
*/
__Zone_disable_registerElement?: boolean; | {
"end_byte": 8185,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone.configurations.api.ts"
} |
angular/packages/zone.js/lib/zone.configurations.api.ts_8191_15344 | /**
* Disable the monkey patch of the browser legacy `EventTarget` API.
*
* NOTE: This configuration is only available in the legacy bundle (dist/zone.js), this module
* is not available in the evergreen bundle (zone-evergreen.js).
*
* In some old browsers, the `EventTarget` is not available, so `zone.js` cannot directly monkey
* patch the `EventTarget`. Instead, `zone.js` patches all known HTML elements' prototypes (such
* as `HtmlDivElement`). The callback of the `addEventListener()` will be in the same zone when
* the `addEventListener()` is called.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* div.addEventListener('click', () => {
* console.log('div click event listener is invoked in the zone', Zone.current.name);
* // the output is 'div click event listener is invoked in the zone myZone'.
* });
* });
* ```
*
* If you set `__Zone_disable_EventTargetLegacy = true` before importing `zone.js`
* In some old browsers, where `EventTarget` is not available, if you set
* `__Zone_disable_EventTargetLegacy = true` before importing `zone.js`, `zone.js` does not
* monkey patch all HTML element APIs and the above code outputs 'clicked <root>'.
*/
__Zone_disable_EventTargetLegacy?: boolean;
/**
* Disable the monkey patch of the browser `timer` APIs.
*
* By default, `zone.js` monkey patches browser timer
* APIs (`setTimeout()`/`setInterval()`/`setImmediate()`) to make asynchronous callbacks of
* those APIs in the same zone when scheduled.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* setTimeout(() => {
* console.log('setTimeout() callback is invoked in the zone', Zone.current.name);
* // since the callback of `setTimeout()` runs in the same zone
* // when it is scheduled, so the output is 'setTimeout() callback is invoked in the zone
* // myZone'.
* });
* });
* ```
*
* If you set `__Zone_disable_timers = true` before importing `zone.js`,
* `zone.js` does not monkey patch `timer` API and the above code
* outputs 'timeout <root>'.
*
*/
__Zone_disable_timers?: boolean;
/**
* Disable the monkey patch of the browser `requestAnimationFrame()` API.
*
* By default, `zone.js` monkey patches the browser `requestAnimationFrame()` API
* to make the asynchronous callback of the `requestAnimationFrame()` in the same zone when
* scheduled.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* requestAnimationFrame(() => {
* console.log('requestAnimationFrame() callback is invoked in the zone',
* Zone.current.name);
* // since the callback of `requestAnimationFrame()` will be in the same zone
* // when it is scheduled, so the output will be 'requestAnimationFrame() callback is
* invoked
* // in the zone myZone'
* });
* });
* ```
*
* If you set `__Zone_disable_requestAnimationFrame = true` before importing `zone.js`,
* `zone.js` does not monkey patch the `requestAnimationFrame()` API and the above code
* outputs 'raf <root>'.
*/
__Zone_disable_requestAnimationFrame?: boolean;
/**
*
* Disable the monkey patching of the `queueMicrotask()` API.
*
* By default, `zone.js` monkey patches the `queueMicrotask()` API
* to ensure that `queueMicrotask()` callback is invoked in the same zone as zone used to invoke
* `queueMicrotask()`. And also the callback is running as `microTask` like
* `Promise.prototype.then()`.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* queueMicrotask(() => {
* console.log('queueMicrotask() callback is invoked in the zone', Zone.current.name);
* // Since `queueMicrotask()` was invoked in `myZone`, same zone is restored
* // when 'queueMicrotask() callback is invoked, resulting in `myZone` being console
* logged.
* });
* });
* ```
*
* If you set `__Zone_disable_queueMicrotask = true` before importing `zone.js`,
* `zone.js` does not monkey patch the `queueMicrotask()` API and the above code
* output will change to: 'queueMicrotask() callback is invoked in the zone <root>'.
*/
__Zone_disable_queueMicrotask?: boolean;
/**
*
* Disable the monkey patch of the browser blocking APIs(`alert()`/`prompt()`/`confirm()`).
*/
__Zone_disable_blocking?: boolean;
/**
* Disable the monkey patch of the browser `EventTarget` APIs.
*
* By default, `zone.js` monkey patches EventTarget APIs. The callbacks of the
* `addEventListener()` run in the same zone when the `addEventListener()` is called.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* div.addEventListener('click', () => {
* console.log('div event listener is invoked in the zone', Zone.current.name);
* // the output is 'div event listener is invoked in the zone myZone'.
* });
* });
* ```
*
* If you set `__Zone_disable_EventTarget = true` before importing `zone.js`,
* `zone.js` does not monkey patch EventTarget API and the above code
* outputs 'clicked <root>'.
*
*/
__Zone_disable_EventTarget?: boolean;
/**
* Disable the monkey patch of the browser `FileReader` APIs.
*/
__Zone_disable_FileReader?: boolean;
/**
* Disable the monkey patch of the browser `MutationObserver` APIs.
*/
__Zone_disable_MutationObserver?: boolean;
/**
* Disable the monkey patch of the browser `IntersectionObserver` APIs.
*/
__Zone_disable_IntersectionObserver?: boolean;
/**
* Disable the monkey patch of the browser onProperty APIs(such as onclick).
*
* By default, `zone.js` monkey patches onXXX properties (such as onclick). The callbacks of
* onXXX properties run in the same zone when the onXXX properties is set.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
* zone.run(() => {
* div.onclick = () => {
* console.log('div click event listener is invoked in the zone', Zone.current.name);
* // the output will be 'div click event listener is invoked in the zone myZone'
* }
* });
* ```
*
* If you set `__Zone_disable_on_property = true` before importing `zone.js`,
* `zone.js` does not monkey patch onXXX properties and the above code
* outputs 'clicked <root>'.
*
*/
__Zone_disable_on_property?: boolean; | {
"end_byte": 15344,
"start_byte": 8191,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone.configurations.api.ts"
} |
angular/packages/zone.js/lib/zone.configurations.api.ts_15350_23317 | /**
* Disable the monkey patch of the browser `customElements` APIs.
*
* By default, `zone.js` monkey patches `customElements` APIs to make callbacks run in the
* same zone when the `customElements.define()` is called.
*
* Consider the following example:
*
* ```
* class TestCustomElement extends HTMLElement {
* constructor() { super(); }
* connectedCallback() {}
* disconnectedCallback() {}
* attributeChangedCallback(attrName, oldVal, newVal) {}
* adoptedCallback() {}
* formAssociatedCallback(form) {}
* formDisabledCallback(isDisabled) {}
* formResetCallback() {}
* formStateRestoreCallback(state, reason) {}
* }
*
* const zone = Zone.fork({name: 'myZone'});
* zone.run(() => {
* customElements.define('x-elem', TestCustomElement);
* });
* ```
*
* All those callbacks defined in TestCustomElement runs in the zone when
* the `customElements.define()` is called.
*
* If you set `__Zone_disable_customElements = true` before importing `zone.js`,
* `zone.js` does not monkey patch `customElements` APIs and the above code
* runs inside <root> zone.
*/
__Zone_disable_customElements?: boolean;
/**
* Disable the monkey patch of the browser `XMLHttpRequest` APIs.
*
* By default, `zone.js` monkey patches `XMLHttpRequest` APIs to make XMLHttpRequest act
* as macroTask.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({
* name: 'myZone',
* onScheduleTask: (delegate, curr, target, task) => {
* console.log('task is scheduled', task.type, task.source, task.zone.name);
* return delegate.scheduleTask(target, task);
* }
* })
* const xhr = new XMLHttpRequest();
* zone.run(() => {
* xhr.onload = function() {};
* xhr.open('get', '/', true);
* xhr.send();
* });
* ```
*
* In this example, the instance of XMLHttpRequest runs in the zone and acts as a macroTask. The
* output is 'task is scheduled macroTask, XMLHttpRequest.send, zone'.
*
* If you set `__Zone_disable_XHR = true` before importing `zone.js`,
* `zone.js` does not monkey patch `XMLHttpRequest` APIs and the above onScheduleTask callback
* will not be called.
*
*/
__Zone_disable_XHR?: boolean;
/**
* Disable the monkey patch of the browser geolocation APIs.
*
* By default, `zone.js` monkey patches geolocation APIs to make callbacks run in the same zone
* when those APIs are called.
*
* Consider the following examples:
*
* ```
* const zone = Zone.current.fork({
* name: 'myZone'
* });
*
* zone.run(() => {
* navigator.geolocation.getCurrentPosition(pos => {
* console.log('navigator.getCurrentPosition() callback is invoked in the zone',
* Zone.current.name);
* // output is 'navigator.getCurrentPosition() callback is invoked in the zone myZone'.
* }
* });
* ```
*
* If set you `__Zone_disable_geolocation = true` before importing `zone.js`,
* `zone.js` does not monkey patch geolocation APIs and the above code
* outputs 'getCurrentPosition <root>'.
*
*/
__Zone_disable_geolocation?: boolean;
/**
* Disable the monkey patch of the browser `canvas` APIs.
*
* By default, `zone.js` monkey patches `canvas` APIs to make callbacks run in the same zone
* when those APIs are called.
*
* Consider the following example:
*
* ```
* const zone = Zone.current.fork({
* name: 'myZone'
* });
*
* zone.run(() => {
* canvas.toBlob(blog => {
* console.log('canvas.toBlob() callback is invoked in the zone', Zone.current.name);
* // output is 'canvas.toBlob() callback is invoked in the zone myZone'.
* }
* });
* ```
*
* If you set `__Zone_disable_canvas = true` before importing `zone.js`,
* `zone.js` does not monkey patch `canvas` APIs and the above code
* outputs 'canvas.toBlob <root>'.
*/
__Zone_disable_canvas?: boolean;
/**
* Disable the `Promise` monkey patch.
*
* By default, `zone.js` monkey patches `Promise` APIs to make the `then()/catch()` callbacks in
* the same zone when those callbacks are called.
*
* Consider the following examples:
*
* ```
* const zone = Zone.current.fork({name: 'myZone'});
*
* const p = Promise.resolve(1);
*
* zone.run(() => {
* p.then(() => {
* console.log('then() callback is invoked in the zone', Zone.current.name);
* // output is 'then() callback is invoked in the zone myZone'.
* });
* });
* ```
*
* If you set `__Zone_disable_ZoneAwarePromise = true` before importing `zone.js`,
* `zone.js` does not monkey patch `Promise` APIs and the above code
* outputs 'promise then callback <root>'.
*/
__Zone_disable_ZoneAwarePromise?: boolean;
/**
* Define event names that users don't want monkey patched by the `zone.js`.
*
* By default, `zone.js` monkey patches EventTarget.addEventListener(). The event listener
* callback runs in the same zone when the addEventListener() is called.
*
* Sometimes, you don't want all of the event names used in this patched version because it
* impacts performance. For example, you might want `scroll` or `mousemove` event listeners to
* run the native `addEventListener()` for better performance.
*
* Users can achieve this goal by defining `__zone_symbol__UNPATCHED_EVENTS = ['scroll',
* 'mousemove'];` before importing `zone.js`.
*/
__zone_symbol__UNPATCHED_EVENTS?: string[];
/**
* Define a list of `on` properties to be ignored when being monkey patched by the `zone.js`.
*
* By default, `zone.js` monkey patches `on` properties on inbuilt browser classes as
* `WebSocket`, `XMLHttpRequest`, `Worker`, `HTMLElement` and others (see `patchTargets` in
* `propertyDescriptorPatch`). `on` properties may be `WebSocket.prototype.onclose`,
* `XMLHttpRequest.prototype.onload`, etc.
*
* Sometimes, we're not able to customise third-party libraries, which setup `on` listeners.
* Given a library creates a `Websocket` and sets `socket.onmessage`, this will impact
* performance if the `onmessage` property is set within the Angular zone, because this will
* trigger change detection on any message coming through the socket. We can exclude specific
* targets and their `on` properties from being patched by zone.js.
*
* Users can achieve this by defining `__Zone_ignore_on_properties`, it expects an array of
* objects where `target` is the actual object `on` properties will be set on:
* ```
* __Zone_ignore_on_properties = [
* {
* target: WebSocket.prototype,
* ignoreProperties: ['message', 'close', 'open']
* }
* ];
* ```
*
* In order to check whether `on` properties have been successfully ignored or not, it's enough
* to open the console in the browser, run `WebSocket.prototype` and expand the object, we
* should see the following:
* ```
* {
* __zone_symbol__ononclosepatched: true,
* __zone_symbol__ononerrorpatched: true,
* __zone_symbol__ononmessagepatched: true,
* __zone_symbol__ononopenpatched: true
* }
* ```
* These `__zone_symbol__*` properties are set by zone.js when `on` properties have been patched
* previously. When `__Zone_ignore_on_properties` is setup, we should not see those properties
* on targets.
*/
__Zone_ignore_on_properties?: {target: any; ignoreProperties: string[]}[]; | {
"end_byte": 23317,
"start_byte": 15350,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone.configurations.api.ts"
} |
angular/packages/zone.js/lib/zone.configurations.api.ts_23323_25032 | /**
* Define the event names of the passive listeners.
*
* To add passive event listeners, you can use `elem.addEventListener('scroll', listener,
* {passive: true});` or implement your own `EventManagerPlugin`.
*
* You can also define a global variable as follows:
*
* ```
* __zone_symbol__PASSIVE_EVENTS = ['scroll'];
* ```
*
* The preceding code makes all scroll event listeners passive.
*/
__zone_symbol__PASSIVE_EVENTS?: string[];
/**
* Disable wrapping uncaught promise rejection.
*
* By default, `zone.js` throws the original error occurs in the uncaught promise rejection.
*
* If you set `__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION = false;` before
* importing `zone.js`, `zone.js` will wrap the uncaught promise rejection in a new `Error`
* object which contains additional information such as a value of the rejection and a stack
* trace.
*/
__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION?: boolean;
/**
* https://github.com/angular/angular/issues/47579
*
* Enables the default `beforeunload` handling behavior, allowing the result of the event
* handling invocation to be set on the event's `returnValue`. The browser may then prompt
* the user with a string returned from the event handler.
*/
__zone_symbol__enable_beforeunload?: boolean;
}
/**
* Interface of `zone-testing.js` test configurations.
*
* You can define the following configurations on the `window` or `global` object before
* importing `zone-testing.js` to change `zone-testing.js` default behaviors in the test runner.
*/ | {
"end_byte": 25032,
"start_byte": 23323,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone.configurations.api.ts"
} |
angular/packages/zone.js/lib/zone.configurations.api.ts_25035_32707 | interface ZoneTestConfigurations {
/**
* Disable the Jasmine integration.
*
* In the `zone-testing.js` bundle, by default, `zone-testing.js` monkey patches Jasmine APIs
* to make Jasmine APIs run in specified zone.
*
* 1. Make the `describe()`/`xdescribe()`/`fdescribe()` methods run in the syncTestZone.
* 2. Make the `it()`/`xit()`/`fit()`/`beforeEach()`/`afterEach()`/`beforeAll()`/`afterAll()`
* methods run in the ProxyZone.
*
* With this patch, `async()`/`fakeAsync()` can work with the Jasmine runner.
*
* If you set `__Zone_disable_jasmine = true` before importing `zone-testing.js`,
* `zone-testing.js` does not monkey patch the jasmine APIs and the `async()`/`fakeAsync()`
* cannot work with the Jasmine runner any longer.
*/
__Zone_disable_jasmine?: boolean;
/**
* Disable the Mocha integration.
*
* In the `zone-testing.js` bundle, by default, `zone-testing.js` monkey patches the Mocha APIs
* to make Mocha APIs run in the specified zone.
*
* 1. Make the `describe()`/`xdescribe()`/`fdescribe()` methods run in the syncTestZone.
* 2. Make the `it()`/`xit()`/`fit()`/`beforeEach()`/`afterEach()`/`beforeAll()`/`afterAll()`
* methods run in the ProxyZone.
*
* With this patch, `async()`/`fakeAsync()` can work with the Mocha runner.
*
* If you set `__Zone_disable_mocha = true` before importing `zone-testing.js`,
* `zone-testing.js` does not monkey patch the Mocha APIs and the `async()/`fakeAsync()` can not
* work with the Mocha runner any longer.
*/
__Zone_disable_mocha?: boolean;
/**
* Disable the Jest integration.
*
* In the `zone-testing.js` bundle, by default, `zone-testing.js` monkey patches Jest APIs
* to make Jest APIs run in the specified zone.
*
* 1. Make the `describe()`/`xdescribe()`/`fdescribe()` methods run in the syncTestZone.
* 2. Make the `it()`/`xit()`/`fit()`/`beforeEach()`/`afterEach()`/`before()`/`after()` methods
* run in the ProxyZone.
*
* With this patch, `async()`/`fakeAsync()` can work with the Jest runner.
*
* If you set `__Zone_disable_jest = true` before importing `zone-testing.js`,
* `zone-testing.js` does not monkey patch the jest APIs and `async()`/`fakeAsync()` cannot
* work with the Jest runner any longer.
*/
__Zone_disable_jest?: boolean;
/**
* Disable monkey patch the jasmine clock APIs.
*
* By default, `zone-testing.js` monkey patches the `jasmine.clock()` API,
* so the `jasmine.clock()` can work with the `fakeAsync()/tick()` API.
*
* Consider the following example:
*
* ```
* describe('jasmine.clock integration', () => {
* beforeEach(() => {
* jasmine.clock().install();
* });
* afterEach(() => {
* jasmine.clock().uninstall();
* });
* it('fakeAsync test', fakeAsync(() => {
* setTimeout(spy, 100);
* expect(spy).not.toHaveBeenCalled();
* jasmine.clock().tick(100);
* expect(spy).toHaveBeenCalled();
* }));
* });
* ```
*
* In the `fakeAsync()` method, `jasmine.clock().tick()` works just like `tick()`.
*
* If you set `__zone_symbol__fakeAsyncDisablePatchingClock = true` before importing
* `zone-testing.js`,`zone-testing.js` does not monkey patch the `jasmine.clock()` APIs and the
* `jasmine.clock()` cannot work with `fakeAsync()` any longer.
*/
__zone_symbol__fakeAsyncDisablePatchingClock?: boolean;
/**
* Enable auto running into `fakeAsync()` when installing the `jasmine.clock()`.
*
* By default, `zone-testing.js` does not automatically run into `fakeAsync()`
* if the `jasmine.clock().install()` is called.
*
* Consider the following example:
*
* ```
* describe('jasmine.clock integration', () => {
* beforeEach(() => {
* jasmine.clock().install();
* });
* afterEach(() => {
* jasmine.clock().uninstall();
* });
* it('fakeAsync test', fakeAsync(() => {
* setTimeout(spy, 100);
* expect(spy).not.toHaveBeenCalled();
* jasmine.clock().tick(100);
* expect(spy).toHaveBeenCalled();
* }));
* });
* ```
*
* You must run `fakeAsync()` to make test cases in the `FakeAsyncTestZone`.
*
* If you set `__zone_symbol__fakeAsyncAutoFakeAsyncWhenClockPatched = true` before importing
* `zone-testing.js`, `zone-testing.js` can run test case automatically in the
* `FakeAsyncTestZone` without calling the `fakeAsync()`.
*
* Consider the following example:
*
* ```
* describe('jasmine.clock integration', () => {
* beforeEach(() => {
* jasmine.clock().install();
* });
* afterEach(() => {
* jasmine.clock().uninstall();
* });
* it('fakeAsync test', () => { // here we don't need to call fakeAsync
* setTimeout(spy, 100);
* expect(spy).not.toHaveBeenCalled();
* jasmine.clock().tick(100);
* expect(spy).toHaveBeenCalled();
* });
* });
* ```
*
*/
__zone_symbol__fakeAsyncAutoFakeAsyncWhenClockPatched?: boolean;
/**
* Enable waiting for the unresolved promise in the `async()` test.
*
* In the `async()` test, `AsyncTestZone` waits for all the asynchronous tasks to finish. By
* default, if some promises remain unresolved, `AsyncTestZone` does not wait and reports that
* it received an unexpected result.
*
* Consider the following example:
*
* ```
* describe('wait never resolved promise', () => {
* it('async with never resolved promise test', async(() => {
* const p = new Promise(() => {});
* p.then(() => {
* // do some expectation.
* });
* }))
* });
* ```
*
* By default, this case passes, because the callback of `p.then()` is never called. Because `p`
* is an unresolved promise, there is no pending asynchronous task, which means the `async()`
* method does not wait.
*
* If you set `__zone_symbol__supportWaitUnResolvedChainedPromise = true`, the above case
* times out, because `async()` will wait for the unresolved promise.
*/
__zone_symbol__supportWaitUnResolvedChainedPromise?: boolean;
}
/**
* The interface of the `zone.js` runtime configurations.
*
* These configurations can be defined on the `Zone` object after
* importing zone.js to change behaviors. The differences between
* the `ZoneRuntimeConfigurations` and the `ZoneGlobalConfigurations` are,
*
* 1. `ZoneGlobalConfigurations` must be defined on the `global/window` object before importing
* `zone.js`. The value of the configuration cannot be changed at runtime.
*
* 2. `ZoneRuntimeConfigurations` must be defined on the `Zone` object after importing `zone.js`.
* You can change the value of this configuration at runtime.
*
*/
interface ZoneRuntimeConfigurations {
/**
* Ignore outputting errors to the console when uncaught Promise errors occur.
*
* By default, if an uncaught Promise error occurs, `zone.js` outputs the
* error to the console by calling `console.error()`.
*
* If you set `__zone_symbol__ignoreConsoleErrorUncaughtError = true`, `zone.js` does not output
* the uncaught error to `console.error()`.
*/
__zone_symbol__ignoreConsoleErrorUncaughtError?: boolean;
}
}
export {}; | {
"end_byte": 32707,
"start_byte": 25035,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone.configurations.api.ts"
} |
angular/packages/zone.js/lib/zone.ts_0_2554 | /**
* @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 {
__symbol__,
EventTask as _EventTask,
HasTaskState as _HasTaskState,
initZone,
MacroTask as _MacroTask,
MicroTask as _MicroTask,
PatchFn,
Task as _Task,
TaskData as _TaskData,
TaskState as _TaskState,
TaskType as _TaskType,
UncaughtPromiseError as _UncaughtPromiseError,
Zone as _Zone,
ZoneDelegate as _ZoneDelegate,
ZoneFrame,
ZonePrivate,
ZoneSpec as _ZoneSpec,
ZoneType as _ZoneType,
} from './zone-impl';
declare global {
const Zone: ZoneType;
type Zone = _Zone;
type ZoneType = _ZoneType;
type _PatchFn = PatchFn;
type _ZonePrivate = ZonePrivate;
type _ZoneFrame = ZoneFrame;
type UncaughtPromiseError = _UncaughtPromiseError;
type ZoneSpec = _ZoneSpec;
type ZoneDelegate = _ZoneDelegate;
type HasTaskState = _HasTaskState;
type TaskType = _TaskType;
type TaskState = _TaskState;
type TaskData = _TaskData;
type Task = _Task;
type MicroTask = _MicroTask;
type MacroTask = _MacroTask;
type EventTask = _EventTask;
/**
* Extend the Error with additional fields for rewritten stack frames
*/
interface Error {
/**
* Stack trace where extra frames have been removed and zone names added.
*/
zoneAwareStack?: string;
/**
* Original stack trace with no modifications
*/
originalStack?: string;
}
}
export function loadZone(): ZoneType {
// if global['Zone'] already exists (maybe zone.js was already loaded or
// some other lib also registered a global object named Zone), we may need
// to throw an error, but sometimes user may not want this error.
// For example,
// we have two web pages, page1 includes zone.js, page2 doesn't.
// and the 1st time user load page1 and page2, everything work fine,
// but when user load page2 again, error occurs because global['Zone'] already exists.
// so we add a flag to let user choose whether to throw this error or not.
// By default, if existing Zone is from zone.js, we will not throw the error.
const global = globalThis as any;
const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
if (global['Zone'] && (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function')) {
throw new Error('Zone already loaded.');
}
// Initialize global `Zone` constant.
global['Zone'] ??= initZone();
return global['Zone'];
}
| {
"end_byte": 2554,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone.ts"
} |
angular/packages/zone.js/lib/zone-global.d.ts_0_484 | /**
* @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
*/
// CommonJS / Node have global context exposed as "global" variable.
// This code should run in a Browser, so we don't want to include the whole node.d.ts
// typings for this compilation unit.
// We'll just fake the global "global" var for now.
declare var global: NodeJS.Global;
| {
"end_byte": 484,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-global.d.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_0_6626 | /**
* @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
*/
/**
* Suppress closure compiler errors about unknown 'global' variable
* @fileoverview
* @suppress {undefinedVars}
*/
/**
* Zone is a mechanism for intercepting and keeping track of asynchronous work.
*
* A Zone is a global object which is configured with rules about how to intercept and keep track
* of the asynchronous callbacks. Zone has these responsibilities:
*
* 1. Intercept asynchronous task scheduling
* 2. Wrap callbacks for error-handling and zone tracking across async operations.
* 3. Provide a way to attach data to zones
* 4. Provide a context specific last frame error handling
* 5. (Intercept blocking methods)
*
* A zone by itself does not do anything, instead it relies on some other code to route existing
* platform API through it. (The zone library ships with code which monkey patches all of the
* browsers's asynchronous API and redirects them through the zone for interception.)
*
* In its simplest form a zone allows one to intercept the scheduling and calling of asynchronous
* operations, and execute additional code before as well as after the asynchronous task. The
* rules of interception are configured using [ZoneConfig]. There can be many different zone
* instances in a system, but only one zone is active at any given time which can be retrieved
* using [Zone#current].
*
*
*
* ## Callback Wrapping
*
* An important aspect of the zones is that they should persist across asynchronous operations. To
* achieve this, when a future work is scheduled through async API, it is necessary to capture,
* and subsequently restore the current zone. For example if a code is running in zone `b` and it
* invokes `setTimeout` to scheduleTask work later, the `setTimeout` method needs to 1) capture
* the current zone and 2) wrap the `wrapCallback` in code which will restore the current zone `b`
* once the wrapCallback executes. In this way the rules which govern the current code are
* preserved in all future asynchronous tasks. There could be a different zone `c` which has
* different rules and is associated with different asynchronous tasks. As these tasks are
* processed, each asynchronous wrapCallback correctly restores the correct zone, as well as
* preserves the zone for future asynchronous callbacks.
*
* Example: Suppose a browser page consist of application code as well as third-party
* advertisement code. (These two code bases are independent, developed by different mutually
* unaware developers.) The application code may be interested in doing global error handling and
* so it configures the `app` zone to send all of the errors to the server for analysis, and then
* executes the application in the `app` zone. The advertising code is interested in the same
* error processing but it needs to send the errors to a different third-party. So it creates the
* `ads` zone with a different error handler. Now both advertising as well as application code
* create many asynchronous operations, but the [Zone] will ensure that all of the asynchronous
* operations created from the application code will execute in `app` zone with its error
* handler and all of the advertisement code will execute in the `ads` zone with its error
* handler. This will not only work for the async operations created directly, but also for all
* subsequent asynchronous operations.
*
* If you think of chain of asynchronous operations as a thread of execution (bit of a stretch)
* then [Zone#current] will act as a thread local variable.
*
*
*
* ## Asynchronous operation scheduling
*
* In addition to wrapping the callbacks to restore the zone, all operations which cause a
* scheduling of work for later are routed through the current zone which is allowed to intercept
* them by adding work before or after the wrapCallback as well as using different means of
* achieving the request. (Useful for unit testing, or tracking of requests). In some instances
* such as `setTimeout` the wrapping of the wrapCallback and scheduling is done in the same
* wrapCallback, but there are other examples such as `Promises` where the `then` wrapCallback is
* wrapped, but the execution of `then` is triggered by `Promise` scheduling `resolve` work.
*
* Fundamentally there are three kinds of tasks which can be scheduled:
*
* 1. [MicroTask] used for doing work right after the current task. This is non-cancelable which
* is guaranteed to run exactly once and immediately.
* 2. [MacroTask] used for doing work later. Such as `setTimeout`. This is typically cancelable
* which is guaranteed to execute at least once after some well understood delay.
* 3. [EventTask] used for listening on some future event. This may execute zero or more times,
* with an unknown delay.
*
* Each asynchronous API is modeled and routed through one of these APIs.
*
*
* ### [MicroTask]
*
* [MicroTask]s represent work which will be done in current VM turn as soon as possible, before
* VM yielding.
*
*
* ### [MacroTask]
*
* [MacroTask]s represent work which will be done after some delay. (Sometimes the delay is
* approximate such as on next available animation frame). Typically these methods include:
* `setTimeout`, `setImmediate`, `setInterval`, `requestAnimationFrame`, and all browser specific
* variants.
*
*
* ### [EventTask]
*
* [EventTask]s represent a request to create a listener on an event. Unlike the other task
* events they may never be executed, but typically execute more than once. There is no queue of
* events, rather their callbacks are unpredictable both in order and time.
*
*
* ## Global Error Handling
*
*
* ## Composability
*
* Zones can be composed together through [Zone.fork()]. A child zone may create its own set of
* rules. A child zone is expected to either:
*
* 1. Delegate the interception to a parent zone, and optionally add before and after wrapCallback
* hooks.
* 2. Process the request itself without delegation.
*
* Composability allows zones to keep their concerns clean. For example a top most zone may choose
* to handle error handling, while child zones may choose to do user action tracking.
*
*
* ## Root Zone
*
* At the start the browser will run in a special root zone, which is configured to behave exactly
* like the platform, making any existing code which is not zone-aware behave as expected. All
* zones are children of the root zone.
*
*/ | {
"end_byte": 6626,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_6627_12418 | export declare interface Zone {
/**
*
* @returns {Zone} The parent Zone.
*/
parent: Zone | null;
/**
* @returns {string} The Zone name (useful for debugging)
*/
name: string;
/**
* Returns a value associated with the `key`.
*
* If the current zone does not have a key, the request is delegated to the parent zone. Use
* [ZoneSpec.properties] to configure the set of properties associated with the current zone.
*
* @param key The key to retrieve.
* @returns {any} The value for the key, or `undefined` if not found.
*/
get(key: string): any;
/**
* Returns a Zone which defines a `key`.
*
* Recursively search the parent Zone until a Zone which has a property `key` is found.
*
* @param key The key to use for identification of the returned zone.
* @returns {Zone} The Zone which defines the `key`, `null` if not found.
*/
getZoneWith(key: string): Zone | null;
/**
* Used to create a child zone.
*
* @param zoneSpec A set of rules which the child zone should follow.
* @returns {Zone} A new child zone.
*/
fork(zoneSpec: ZoneSpec): Zone;
/**
* Wraps a callback function in a new function which will properly restore the current zone upon
* invocation.
*
* The wrapped function will properly forward `this` as well as `arguments` to the `callback`.
*
* Before the function is wrapped the zone can intercept the `callback` by declaring
* [ZoneSpec.onIntercept].
*
* @param callback the function which will be wrapped in the zone.
* @param source A unique debug location of the API being wrapped.
* @returns {function(): *} A function which will invoke the `callback` through
* [Zone.runGuarded].
*/
wrap<F extends Function>(callback: F, source: string): F;
/**
* Invokes a function in a given zone.
*
* The invocation of `callback` can be intercepted by declaring [ZoneSpec.onInvoke].
*
* @param callback The function to invoke.
* @param applyThis
* @param applyArgs
* @param source A unique debug location of the API being invoked.
* @returns {any} Value from the `callback` function.
*/
run<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
/**
* Invokes a function in a given zone and catches any exceptions.
*
* Any exceptions thrown will be forwarded to [Zone.HandleError].
*
* The invocation of `callback` can be intercepted by declaring [ZoneSpec.onInvoke]. The
* handling of exceptions can be intercepted by declaring [ZoneSpec.handleError].
*
* @param callback The function to invoke.
* @param applyThis
* @param applyArgs
* @param source A unique debug location of the API being invoked.
* @returns {any} Value from the `callback` function.
*/
runGuarded<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
/**
* Execute the Task by restoring the [Zone.currentTask] in the Task's zone.
*
* @param task to run
* @param applyThis
* @param applyArgs
* @returns {any} Value from the `task.callback` function.
*/
runTask<T>(task: Task, applyThis?: any, applyArgs?: any): T;
/**
* Schedule a MicroTask.
*
* @param source
* @param callback
* @param data
* @param customSchedule
*/
scheduleMicroTask(
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
): MicroTask;
/**
* Schedule a MacroTask.
*
* @param source
* @param callback
* @param data
* @param customSchedule
* @param customCancel
*/
scheduleMacroTask(
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): MacroTask;
/**
* Schedule an EventTask.
*
* @param source
* @param callback
* @param data
* @param customSchedule
* @param customCancel
*/
scheduleEventTask(
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): EventTask;
/**
* Schedule an existing Task.
*
* Useful for rescheduling a task which was already canceled.
*
* @param task
*/
scheduleTask<T extends Task>(task: T): T;
/**
* Allows the zone to intercept canceling of scheduled Task.
*
* The interception is configured using [ZoneSpec.onCancelTask]. The default canceler invokes
* the [Task.cancelFn].
*
* @param task
* @returns {any}
*/
cancelTask(task: Task): any;
}
export declare interface ZoneType {
/**
* @returns {Zone} Returns the current [Zone]. The only way to change
* the current zone is by invoking a run() method, which will update the current zone for the
* duration of the run method callback.
*/
current: Zone;
/**
* @returns {Task} The task associated with the current execution.
*/
currentTask: Task | null;
/**
* Verify that Zone has been correctly patched. Specifically that Promise is zone aware.
*/
assertZonePatched(): void;
/**
* Return the root zone.
*/
root: Zone;
/**
* load patch for specified native module, allow user to
* define their own patch, user can use this API after loading zone.js
*/
__load_patch(name: string, fn: PatchFn, ignoreDuplicate?: boolean): void;
/**
* Zone symbol API to generate a string with __zone_symbol__ prefix
*/
__symbol__(name: string): string;
}
/**
* Patch Function to allow user define their own monkey patch module.
*/
export type PatchFn = (global: Window, Zone: ZoneType, api: ZonePrivate) => void;
/**
* ZonePrivate interface to provide helper method to help user implement
* their own monkey patch module.
*/ | {
"end_byte": 12418,
"start_byte": 6627,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_12419_19625 | export declare interface ZonePrivate {
currentZoneFrame: () => ZoneFrame;
symbol: (name: string) => string;
scheduleMicroTask: (task?: MicroTask) => void;
onUnhandledError: (error: Error) => void;
microtaskDrainDone: () => void;
showUncaughtError: () => boolean;
patchEventTarget: (global: any, api: ZonePrivate, apis: any[], options?: any) => boolean[];
patchOnProperties: (obj: any, properties: string[] | null, prototype?: any) => void;
patchThen: (ctro: Function) => void;
patchMethod: (
target: any,
name: string,
patchFn: (
delegate: Function,
delegateName: string,
name: string,
) => (self: any, args: any[]) => any,
) => Function | null;
bindArguments: (args: any[], source: string) => any[];
patchMacroTask: (
obj: any,
funcName: string,
metaCreator: (self: any, args: any[]) => any,
) => void;
patchEventPrototype: (_global: any, api: ZonePrivate) => void;
isIEOrEdge: () => boolean;
ObjectDefineProperty: (
o: any,
p: PropertyKey,
attributes: PropertyDescriptor & ThisType<any>,
) => any;
ObjectGetOwnPropertyDescriptor: (o: any, p: PropertyKey) => PropertyDescriptor | undefined;
ObjectCreate(o: object | null, properties?: PropertyDescriptorMap & ThisType<any>): any;
ArraySlice(start?: number, end?: number): any[];
patchClass: (className: string) => void;
wrapWithCurrentZone: (callback: any, source: string) => any;
filterProperties: (target: any, onProperties: string[], ignoreProperties: any[]) => string[];
attachOriginToPatched: (target: any, origin: any) => void;
_redefineProperty: (target: any, callback: string, desc: any) => void;
nativeScheduleMicroTask: (func: Function) => void;
patchCallbacks: (
api: ZonePrivate,
target: any,
targetName: string,
method: string,
callbacks: string[],
) => void;
getGlobalObjects: () =>
| {
globalSources: any;
zoneSymbolEventNames: any;
eventNames: string[];
isBrowser: boolean;
isMix: boolean;
isNode: boolean;
TRUE_STR: string;
FALSE_STR: string;
ZONE_SYMBOL_PREFIX: string;
ADD_EVENT_LISTENER_STR: string;
REMOVE_EVENT_LISTENER_STR: string;
}
| undefined;
}
/**
* ZoneFrame represents zone stack frame information
*/
export declare interface ZoneFrame {
parent: ZoneFrame | null;
zone: Zone;
}
export declare interface UncaughtPromiseError extends Error {
zone: Zone;
task: Task;
promise: Promise<any>;
rejection: any;
throwOriginal?: boolean;
}
/**
* Provides a way to configure the interception of zone events.
*
* Only the `name` property is required (all other are optional).
*/
export declare interface ZoneSpec {
/**
* The name of the zone. Useful when debugging Zones.
*/
name: string;
/**
* A set of properties to be associated with Zone. Use [Zone.get] to retrieve them.
*/
properties?: {[key: string]: any};
/**
* Allows the interception of zone forking.
*
* When the zone is being forked, the request is forwarded to this method for interception.
*
* @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
* @param currentZone The current [Zone] where the current interceptor has been declared.
* @param targetZone The [Zone] which originally received the request.
* @param zoneSpec The argument passed into the `fork` method.
*/
onFork?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
zoneSpec: ZoneSpec,
) => Zone;
/**
* Allows interception of the wrapping of the callback.
*
* @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
* @param currentZone The current [Zone] where the current interceptor has been declared.
* @param targetZone The [Zone] which originally received the request.
* @param delegate The argument passed into the `wrap` method.
* @param source The argument passed into the `wrap` method.
*/
onIntercept?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
source: string,
) => Function;
/**
* Allows interception of the callback invocation.
*
* @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
* @param currentZone The current [Zone] where the current interceptor has been declared.
* @param targetZone The [Zone] which originally received the request.
* @param delegate The argument passed into the `run` method.
* @param applyThis The argument passed into the `run` method.
* @param applyArgs The argument passed into the `run` method.
* @param source The argument passed into the `run` method.
*/
onInvoke?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
) => any;
/**
* Allows interception of the error handling.
*
* @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
* @param currentZone The current [Zone] where the current interceptor has been declared.
* @param targetZone The [Zone] which originally received the request.
* @param error The argument passed into the `handleError` method.
*/
onHandleError?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
) => boolean;
/**
* Allows interception of task scheduling.
*
* @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
* @param currentZone The current [Zone] where the current interceptor has been declared.
* @param targetZone The [Zone] which originally received the request.
* @param task The argument passed into the `scheduleTask` method.
*/
onScheduleTask?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
) => Task;
onInvokeTask?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
applyThis: any,
applyArgs?: any[],
) => any;
/**
* Allows interception of task cancellation.
*
* @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
* @param currentZone The current [Zone] where the current interceptor has been declared.
* @param targetZone The [Zone] which originally received the request.
* @param task The argument passed into the `cancelTask` method.
*/
onCancelTask?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
) => any;
/**
* Notifies of changes to the task queue empty status.
*
* @param parentZoneDelegate Delegate which performs the parent [ZoneSpec] operation.
* @param currentZone The current [Zone] where the current interceptor has been declared.
* @param targetZone The [Zone] which originally received the request.
* @param hasTaskState
*/
onHasTask?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
hasTaskState: HasTaskState,
) => void;
} | {
"end_byte": 19625,
"start_byte": 12419,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_19627_26429 | /**
* A delegate when intercepting zone operations.
*
* A ZoneDelegate is needed because a child zone can't simply invoke a method on a parent zone.
* For example a child zone wrap can't just call parent zone wrap. Doing so would create a
* callback which is bound to the parent zone. What we are interested in is intercepting the
* callback before it is bound to any zone. Furthermore, we also need to pass the targetZone (zone
* which received the original request) to the delegate.
*
* The ZoneDelegate methods mirror those of Zone with an addition of extra targetZone argument in
* the method signature. (The original Zone which received the request.) Some methods are renamed
* to prevent confusion, because they have slightly different semantics and arguments.
*
* - `wrap` => `intercept`: The `wrap` method delegates to `intercept`. The `wrap` method returns
* a callback which will run in a given zone, where as intercept allows wrapping the callback
* so that additional code can be run before and after, but does not associate the callback
* with the zone.
* - `run` => `invoke`: The `run` method delegates to `invoke` to perform the actual execution of
* the callback. The `run` method switches to new zone; saves and restores the `Zone.current`;
* and optionally performs error handling. The invoke is not responsible for error handling,
* or zone management.
*
* Not every method is usually overwritten in the child zone, for this reason the ZoneDelegate
* stores the closest zone which overwrites this behavior along with the closest ZoneSpec.
*
* NOTE: We have tried to make this API analogous to Event bubbling with target and current
* properties.
*
* Note: The ZoneDelegate treats ZoneSpec as class. This allows the ZoneSpec to use its `this` to
* store internal state.
*/
export declare interface ZoneDelegate {
zone: Zone;
fork(targetZone: Zone, zoneSpec: ZoneSpec): Zone;
intercept(targetZone: Zone, callback: Function, source: string): Function;
invoke(
targetZone: Zone,
callback: Function,
applyThis?: any,
applyArgs?: any[],
source?: string,
): any;
handleError(targetZone: Zone, error: any): boolean;
scheduleTask(targetZone: Zone, task: Task): Task;
invokeTask(targetZone: Zone, task: Task, applyThis?: any, applyArgs?: any[]): any;
cancelTask(targetZone: Zone, task: Task): any;
hasTask(targetZone: Zone, isEmpty: HasTaskState): void;
}
export type HasTaskState = {
microTask: boolean;
macroTask: boolean;
eventTask: boolean;
change: TaskType;
};
/**
* Task type: `microTask`, `macroTask`, `eventTask`.
*/
export type TaskType = 'microTask' | 'macroTask' | 'eventTask';
/**
* Task type: `notScheduled`, `scheduling`, `scheduled`, `running`, `canceling`, 'unknown'.
*/
export type TaskState =
| 'notScheduled'
| 'scheduling'
| 'scheduled'
| 'running'
| 'canceling'
| 'unknown';
/**
*/
export declare interface TaskData {
/**
* A periodic [MacroTask] is such which get automatically rescheduled after it is executed.
*/
isPeriodic?: boolean;
/**
* A [MacroTask] that can be manually rescheduled.
*/
isRefreshable?: boolean;
/**
* Delay in milliseconds when the Task will run.
*/
delay?: number;
/**
* identifier returned by the native setTimeout.
*/
handleId?: number;
/** The target handler. */
handle?: any;
}
/**
* Represents work which is executed with a clean stack.
*
* Tasks are used in Zones to mark work which is performed on clean stack frame. There are three
* kinds of task. [MicroTask], [MacroTask], and [EventTask].
*
* A JS VM can be modeled as a [MicroTask] queue, [MacroTask] queue, and [EventTask] set.
*
* - [MicroTask] queue represents a set of tasks which are executing right after the current stack
* frame becomes clean and before a VM yield. All [MicroTask]s execute in order of insertion
* before VM yield and the next [MacroTask] is executed.
* - [MacroTask] queue represents a set of tasks which are executed one at a time after each VM
* yield. The queue is ordered by time, and insertions can happen in any location.
* - [EventTask] is a set of tasks which can at any time be inserted to the end of the [MacroTask]
* queue. This happens when the event fires.
*
*/
export declare interface Task {
/**
* Task type: `microTask`, `macroTask`, `eventTask`.
*/
type: TaskType;
/**
* Task state: `notScheduled`, `scheduling`, `scheduled`, `running`, `canceling`, `unknown`.
*/
state: TaskState;
/**
* Debug string representing the API which requested the scheduling of the task.
*/
source: string;
/**
* The Function to be used by the VM upon entering the [Task]. This function will delegate to
* [Zone.runTask] and delegate to `callback`.
*/
invoke: Function;
/**
* Function which needs to be executed by the Task after the [Zone.currentTask] has been set to
* the current task.
*/
callback: Function;
/**
* Task specific options associated with the current task. This is passed to the `scheduleFn`.
*/
data?: TaskData;
/**
* Represents the default work which needs to be done to schedule the Task by the VM.
*
* A zone may choose to intercept this function and perform its own scheduling.
*/
scheduleFn?: (task: Task) => void;
/**
* Represents the default work which needs to be done to un-schedule the Task from the VM. Not
* all Tasks are cancelable, and therefore this method is optional.
*
* A zone may chose to intercept this function and perform its own un-scheduling.
*/
cancelFn?: (task: Task) => void;
/**
* @type {Zone} The zone which will be used to invoke the `callback`. The Zone is captured
* at the time of Task creation.
*/
readonly zone: Zone;
/**
* Number of times the task has been executed, or -1 if canceled.
*/
runCount: number;
/**
* Cancel the scheduling request. This method can be called from `ZoneSpec.onScheduleTask` to
* cancel the current scheduling interception. Once canceled the task can be discarded or
* rescheduled using `Zone.scheduleTask` on a different zone.
*/
cancelScheduleRequest(): void;
}
export declare interface MicroTask extends Task {
type: 'microTask';
}
export declare interface MacroTask extends Task {
type: 'macroTask';
}
export declare interface EventTask extends Task {
type: 'eventTask';
}
export type AmbientZone = Zone;
const global = globalThis as any;
// __Zone_symbol_prefix global can be used to override the default zone
// symbol prefix with a custom one if needed.
export function __symbol__(name: string) {
const symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
return symbolPrefix + name;
} | {
"end_byte": 26429,
"start_byte": 19627,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_26431_33825 | export function initZone(): ZoneType {
const performance: {mark(name: string): void; measure(name: string, label: string): void} =
global['performance'];
function mark(name: string) {
performance && performance['mark'] && performance['mark'](name);
}
function performanceMeasure(name: string, label: string) {
performance && performance['measure'] && performance['measure'](name, label);
}
mark('Zone');
class ZoneImpl implements AmbientZone {
// tslint:disable-next-line:require-internal-with-underscore
static __symbol__: (name: string) => string = __symbol__;
static assertZonePatched() {
if (global['Promise'] !== patches['ZoneAwarePromise']) {
throw new Error(
'Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
'has been overwritten.\n' +
'Most likely cause is that a Promise polyfill has been loaded ' +
'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
'If you must load one, do so before loading zone.js.)',
);
}
}
static get root(): AmbientZone {
let zone = ZoneImpl.current;
while (zone.parent) {
zone = zone.parent;
}
return zone;
}
static get current(): AmbientZone {
return _currentZoneFrame.zone;
}
static get currentTask(): Task | null {
return _currentTask;
}
// tslint:disable-next-line:require-internal-with-underscore
static __load_patch(name: string, fn: PatchFn, ignoreDuplicate = false): void {
if (patches.hasOwnProperty(name)) {
// `checkDuplicate` option is defined from global variable
// so it works for all modules.
// `ignoreDuplicate` can work for the specified module
const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
if (!ignoreDuplicate && checkDuplicate) {
throw Error('Already loaded patch: ' + name);
}
} else if (!global['__Zone_disable_' + name]) {
const perfName = 'Zone:' + name;
mark(perfName);
patches[name] = fn(global, ZoneImpl, _api);
performanceMeasure(perfName, perfName);
}
}
public get parent(): AmbientZone | null {
return this._parent;
}
public get name(): string {
return this._name;
}
private _parent: ZoneImpl | null;
private _name: string;
private _properties: {[key: string]: any};
private _zoneDelegate: _ZoneDelegate;
constructor(parent: ZoneImpl | null, zoneSpec: ZoneSpec | null) {
this._parent = parent as ZoneImpl;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
this._properties = (zoneSpec && zoneSpec.properties) || {};
this._zoneDelegate = new _ZoneDelegate(
this,
this._parent && this._parent._zoneDelegate,
zoneSpec,
);
}
public get(key: string): any {
const zone: ZoneImpl = this.getZoneWith(key) as ZoneImpl;
if (zone) return zone._properties[key];
}
public getZoneWith(key: string): AmbientZone | null {
let current: ZoneImpl | null = this;
while (current) {
if (current._properties.hasOwnProperty(key)) {
return current;
}
current = current._parent;
}
return null;
}
public fork(zoneSpec: ZoneSpec): AmbientZone {
if (!zoneSpec) throw new Error('ZoneSpec required!');
return this._zoneDelegate.fork(this, zoneSpec);
}
public wrap<T extends Function>(callback: T, source: string): T {
if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
const _callback = this._zoneDelegate.intercept(this, callback, source);
const zone: ZoneImpl = this;
return function (this: unknown) {
return zone.runGuarded(_callback, this, <any>arguments, source);
} as any as T;
}
public run(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
public run<T>(
callback: (...args: any[]) => T,
applyThis?: any,
applyArgs?: any[],
source?: string,
): T {
_currentZoneFrame = {parent: _currentZoneFrame, zone: this};
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
} finally {
_currentZoneFrame = _currentZoneFrame.parent!;
}
}
public runGuarded(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
public runGuarded<T>(
callback: (...args: any[]) => T,
applyThis: any = null,
applyArgs?: any[],
source?: string,
) {
_currentZoneFrame = {parent: _currentZoneFrame, zone: this};
try {
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
} catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
} finally {
_currentZoneFrame = _currentZoneFrame.parent!;
}
}
runTask(task: Task, applyThis?: any, applyArgs?: any): any {
if (task.zone != this) {
throw new Error(
'A task can only be run in the zone of creation! (Creation: ' +
(task.zone || NO_ZONE).name +
'; Execution: ' +
this.name +
')',
);
}
const zoneTask = task as ZoneTask<any>;
// https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
// run such kind of task but just return
const {type, data: {isPeriodic = false, isRefreshable = false} = {}} = task;
if (task.state === notScheduled && (type === eventTask || type === macroTask)) {
return;
}
const reEntryGuard = task.state != running;
reEntryGuard && zoneTask._transitionTo(running, scheduled);
const previousTask = _currentTask;
_currentTask = zoneTask;
_currentZoneFrame = {parent: _currentZoneFrame, zone: this};
try {
if (type == macroTask && task.data && !isPeriodic && !isRefreshable) {
task.cancelFn = undefined;
}
try {
return this._zoneDelegate.invokeTask(this, zoneTask, applyThis, applyArgs);
} catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
} finally {
// if the task's state is notScheduled or unknown, then it has already been cancelled
// we should not reset the state to scheduled
const state = task.state;
if (state !== notScheduled && state !== unknown) {
if (type == eventTask || isPeriodic || (isRefreshable && state === scheduling)) {
reEntryGuard && zoneTask._transitionTo(scheduled, running, scheduling);
} else {
const zoneDelegates = zoneTask._zoneDelegates;
this._updateTaskCount(zoneTask, -1);
reEntryGuard && zoneTask._transitionTo(notScheduled, running, notScheduled);
if (isRefreshable) {
zoneTask._zoneDelegates = zoneDelegates;
}
}
}
_currentZoneFrame = _currentZoneFrame.parent!;
_currentTask = previousTask;
}
} | {
"end_byte": 33825,
"start_byte": 26431,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_33831_38519 | scheduleTask<T extends Task>(task: T): T {
if (task.zone && task.zone !== this) {
// check if the task was rescheduled, the newZone
// should not be the children of the original zone
let newZone: any = this;
while (newZone) {
if (newZone === task.zone) {
throw Error(
`can not reschedule task to ${this.name} which is descendants of the original zone ${task.zone.name}`,
);
}
newZone = newZone.parent;
}
}
(task as any as ZoneTask<any>)._transitionTo(scheduling, notScheduled);
const zoneDelegates: _ZoneDelegate[] = [];
(task as any as ZoneTask<any>)._zoneDelegates = zoneDelegates;
(task as any as ZoneTask<any>)._zone = this;
try {
task = this._zoneDelegate.scheduleTask(this, task) as T;
} catch (err) {
// should set task's state to unknown when scheduleTask throw error
// because the err may from reschedule, so the fromState maybe notScheduled
(task as any as ZoneTask<any>)._transitionTo(unknown, scheduling, notScheduled);
// TODO: @JiaLiPassion, should we check the result from handleError?
this._zoneDelegate.handleError(this, err);
throw err;
}
if ((task as any as ZoneTask<any>)._zoneDelegates === zoneDelegates) {
// we have to check because internally the delegate can reschedule the task.
this._updateTaskCount(task as any as ZoneTask<any>, 1);
}
if ((task as any as ZoneTask<any>).state == scheduling) {
(task as any as ZoneTask<any>)._transitionTo(scheduled, scheduling);
}
return task;
}
scheduleMicroTask(
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
): MicroTask {
return this.scheduleTask(
new ZoneTask(microTask, source, callback, data, customSchedule, undefined),
);
}
scheduleMacroTask(
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): MacroTask {
return this.scheduleTask(
new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel),
);
}
scheduleEventTask(
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): EventTask {
return this.scheduleTask(
new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel),
);
}
cancelTask(task: Task): any {
if (task.zone != this)
throw new Error(
'A task can only be cancelled in the zone of creation! (Creation: ' +
(task.zone || NO_ZONE).name +
'; Execution: ' +
this.name +
')',
);
if (task.state !== scheduled && task.state !== running) {
return;
}
(task as ZoneTask<any>)._transitionTo(canceling, scheduled, running);
try {
this._zoneDelegate.cancelTask(this, task);
} catch (err) {
// if error occurs when cancelTask, transit the state to unknown
(task as ZoneTask<any>)._transitionTo(unknown, canceling);
this._zoneDelegate.handleError(this, err);
throw err;
}
this._updateTaskCount(task as ZoneTask<any>, -1);
(task as ZoneTask<any>)._transitionTo(notScheduled, canceling);
task.runCount = -1;
return task;
}
private _updateTaskCount(task: ZoneTask<any>, count: number) {
const zoneDelegates = task._zoneDelegates!;
if (count == -1) {
task._zoneDelegates = null;
}
for (let i = 0; i < zoneDelegates.length; i++) {
zoneDelegates[i]._updateTaskCount(task.type, count);
}
}
}
const DELEGATE_ZS: ZoneSpec = {
name: '',
onHasTask: (
delegate: ZoneDelegate,
_: AmbientZone,
target: AmbientZone,
hasTaskState: HasTaskState,
): void => delegate.hasTask(target, hasTaskState),
onScheduleTask: (
delegate: ZoneDelegate,
_: AmbientZone,
target: AmbientZone,
task: Task,
): Task => delegate.scheduleTask(target, task),
onInvokeTask: (
delegate: ZoneDelegate,
_: AmbientZone,
target: AmbientZone,
task: Task,
applyThis: any,
applyArgs: any,
): any => delegate.invokeTask(target, task, applyThis, applyArgs),
onCancelTask: (delegate: ZoneDelegate, _: AmbientZone, target: AmbientZone, task: Task): any =>
delegate.cancelTask(target, task),
}; | {
"end_byte": 38519,
"start_byte": 33831,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_38523_45360 | class _ZoneDelegate implements ZoneDelegate {
public get zone(): Zone {
return this._zone;
}
private _zone: ZoneImpl;
private _taskCounts: {microTask: number; macroTask: number; eventTask: number} = {
'microTask': 0,
'macroTask': 0,
'eventTask': 0,
};
private _parentDelegate: _ZoneDelegate | null;
private _forkDlgt: _ZoneDelegate | null;
private _forkZS: ZoneSpec | null;
private _forkCurrZone: Zone | null;
private _interceptDlgt: _ZoneDelegate | null;
private _interceptZS: ZoneSpec | null;
private _interceptCurrZone: Zone | null;
private _invokeDlgt: _ZoneDelegate | null;
private _invokeZS: ZoneSpec | null;
private _invokeCurrZone: ZoneImpl | null;
private _handleErrorDlgt: _ZoneDelegate | null;
private _handleErrorZS: ZoneSpec | null;
private _handleErrorCurrZone: ZoneImpl | null;
private _scheduleTaskDlgt: _ZoneDelegate | null;
private _scheduleTaskZS: ZoneSpec | null;
private _scheduleTaskCurrZone: ZoneImpl | null;
private _invokeTaskDlgt: _ZoneDelegate | null;
private _invokeTaskZS: ZoneSpec | null;
private _invokeTaskCurrZone: ZoneImpl | null;
private _cancelTaskDlgt: _ZoneDelegate | null;
private _cancelTaskZS: ZoneSpec | null;
private _cancelTaskCurrZone: ZoneImpl | null;
private _hasTaskDlgt: _ZoneDelegate | null;
private _hasTaskDlgtOwner: _ZoneDelegate | null;
private _hasTaskZS: ZoneSpec | null;
private _hasTaskCurrZone: ZoneImpl | null;
constructor(zone: Zone, parentDelegate: _ZoneDelegate | null, zoneSpec: ZoneSpec | null) {
this._zone = zone as ZoneImpl;
this._parentDelegate = parentDelegate;
this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate!._forkZS);
this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate!._forkDlgt);
this._forkCurrZone =
zoneSpec && (zoneSpec.onFork ? this._zone : parentDelegate!._forkCurrZone);
this._interceptZS =
zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate!._interceptZS);
this._interceptDlgt =
zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate!._interceptDlgt);
this._interceptCurrZone =
zoneSpec && (zoneSpec.onIntercept ? this._zone : parentDelegate!._interceptCurrZone);
this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate!._invokeZS);
this._invokeDlgt =
zoneSpec && (zoneSpec.onInvoke ? parentDelegate! : parentDelegate!._invokeDlgt);
this._invokeCurrZone =
zoneSpec && (zoneSpec.onInvoke ? this._zone : parentDelegate!._invokeCurrZone);
this._handleErrorZS =
zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate!._handleErrorZS);
this._handleErrorDlgt =
zoneSpec && (zoneSpec.onHandleError ? parentDelegate! : parentDelegate!._handleErrorDlgt);
this._handleErrorCurrZone =
zoneSpec && (zoneSpec.onHandleError ? this._zone : parentDelegate!._handleErrorCurrZone);
this._scheduleTaskZS =
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate!._scheduleTaskZS);
this._scheduleTaskDlgt =
zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate! : parentDelegate!._scheduleTaskDlgt);
this._scheduleTaskCurrZone =
zoneSpec && (zoneSpec.onScheduleTask ? this._zone : parentDelegate!._scheduleTaskCurrZone);
this._invokeTaskZS =
zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate!._invokeTaskZS);
this._invokeTaskDlgt =
zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate! : parentDelegate!._invokeTaskDlgt);
this._invokeTaskCurrZone =
zoneSpec && (zoneSpec.onInvokeTask ? this._zone : parentDelegate!._invokeTaskCurrZone);
this._cancelTaskZS =
zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate!._cancelTaskZS);
this._cancelTaskDlgt =
zoneSpec && (zoneSpec.onCancelTask ? parentDelegate! : parentDelegate!._cancelTaskDlgt);
this._cancelTaskCurrZone =
zoneSpec && (zoneSpec.onCancelTask ? this._zone : parentDelegate!._cancelTaskCurrZone);
this._hasTaskZS = null;
this._hasTaskDlgt = null;
this._hasTaskDlgtOwner = null;
this._hasTaskCurrZone = null;
const zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
const parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
if (zoneSpecHasTask || parentHasTask) {
// If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
// a case all task related interceptors must go through this ZD. We can't short circuit it.
this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
this._hasTaskDlgt = parentDelegate;
this._hasTaskDlgtOwner = this;
this._hasTaskCurrZone = this._zone;
if (!zoneSpec!.onScheduleTask) {
this._scheduleTaskZS = DELEGATE_ZS;
this._scheduleTaskDlgt = parentDelegate!;
this._scheduleTaskCurrZone = this._zone;
}
if (!zoneSpec!.onInvokeTask) {
this._invokeTaskZS = DELEGATE_ZS;
this._invokeTaskDlgt = parentDelegate!;
this._invokeTaskCurrZone = this._zone;
}
if (!zoneSpec!.onCancelTask) {
this._cancelTaskZS = DELEGATE_ZS;
this._cancelTaskDlgt = parentDelegate!;
this._cancelTaskCurrZone = this._zone;
}
}
}
fork(targetZone: ZoneImpl, zoneSpec: ZoneSpec): AmbientZone {
return this._forkZS
? this._forkZS.onFork!(this._forkDlgt!, this.zone, targetZone, zoneSpec)
: new ZoneImpl(targetZone, zoneSpec);
}
intercept(targetZone: ZoneImpl, callback: Function, source: string): Function {
return this._interceptZS
? this._interceptZS.onIntercept!(
this._interceptDlgt!,
this._interceptCurrZone!,
targetZone,
callback,
source,
)
: callback;
}
invoke(
targetZone: ZoneImpl,
callback: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
): any {
return this._invokeZS
? this._invokeZS.onInvoke!(
this._invokeDlgt!,
this._invokeCurrZone!,
targetZone,
callback,
applyThis,
applyArgs,
source,
)
: callback.apply(applyThis, applyArgs);
}
handleError(targetZone: ZoneImpl, error: any): boolean {
return this._handleErrorZS
? this._handleErrorZS.onHandleError!(
this._handleErrorDlgt!,
this._handleErrorCurrZone!,
targetZone,
error,
)
: true;
} | {
"end_byte": 45360,
"start_byte": 38523,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_45366_53845 | scheduleTask(targetZone: ZoneImpl, task: Task): Task {
let returnTask: ZoneTask<any> = task as ZoneTask<any>;
if (this._scheduleTaskZS) {
if (this._hasTaskZS) {
returnTask._zoneDelegates!.push(this._hasTaskDlgtOwner!);
}
returnTask = this._scheduleTaskZS.onScheduleTask!(
this._scheduleTaskDlgt!,
this._scheduleTaskCurrZone!,
targetZone,
task,
) as ZoneTask<any>;
if (!returnTask) returnTask = task as ZoneTask<any>;
} else {
if (task.scheduleFn) {
task.scheduleFn(task);
} else if (task.type == microTask) {
scheduleMicroTask(<MicroTask>task);
} else {
throw new Error('Task is missing scheduleFn.');
}
}
return returnTask;
}
invokeTask(targetZone: ZoneImpl, task: Task, applyThis: any, applyArgs?: any[]): any {
return this._invokeTaskZS
? this._invokeTaskZS.onInvokeTask!(
this._invokeTaskDlgt!,
this._invokeTaskCurrZone!,
targetZone,
task,
applyThis,
applyArgs,
)
: task.callback.apply(applyThis, applyArgs);
}
cancelTask(targetZone: ZoneImpl, task: Task): any {
let value: any;
if (this._cancelTaskZS) {
value = this._cancelTaskZS.onCancelTask!(
this._cancelTaskDlgt!,
this._cancelTaskCurrZone!,
targetZone,
task,
);
} else {
if (!task.cancelFn) {
throw Error('Task is not cancelable');
}
value = task.cancelFn(task);
}
return value;
}
hasTask(targetZone: ZoneImpl, isEmpty: HasTaskState) {
// hasTask should not throw error so other ZoneDelegate
// can still trigger hasTask callback
try {
this._hasTaskZS &&
this._hasTaskZS.onHasTask!(
this._hasTaskDlgt!,
this._hasTaskCurrZone!,
targetZone,
isEmpty,
);
} catch (err) {
this.handleError(targetZone, err);
}
}
// tslint:disable-next-line:require-internal-with-underscore
_updateTaskCount(type: TaskType, count: number) {
const counts = this._taskCounts;
const prev = counts[type];
const next = (counts[type] = prev + count);
if (next < 0) {
throw new Error('More tasks executed then were scheduled.');
}
if (prev == 0 || next == 0) {
const isEmpty: HasTaskState = {
microTask: counts['microTask'] > 0,
macroTask: counts['macroTask'] > 0,
eventTask: counts['eventTask'] > 0,
change: type,
};
this.hasTask(this._zone, isEmpty);
}
}
}
class ZoneTask<T extends TaskType> implements Task {
public type: T;
public source: string;
public invoke: Function;
public callback: Function;
public data: TaskData | undefined;
public scheduleFn: ((task: Task) => void) | undefined;
public cancelFn: ((task: Task) => void) | undefined;
// tslint:disable-next-line:require-internal-with-underscore
_zone: ZoneImpl | null = null;
public runCount: number = 0;
// tslint:disable-next-line:require-internal-with-underscore
_zoneDelegates: _ZoneDelegate[] | null = null;
// tslint:disable-next-line:require-internal-with-underscore
_state: TaskState = 'notScheduled';
constructor(
type: T,
source: string,
callback: Function,
options: TaskData | undefined,
scheduleFn: ((task: Task) => void) | undefined,
cancelFn: ((task: Task) => void) | undefined,
) {
this.type = type;
this.source = source;
this.data = options;
this.scheduleFn = scheduleFn;
this.cancelFn = cancelFn;
if (!callback) {
throw new Error('callback is not defined');
}
this.callback = callback;
const self = this;
// TODO: @JiaLiPassion options should have interface
if (type === eventTask && options && (options as any).useG) {
this.invoke = ZoneTask.invokeTask;
} else {
this.invoke = function () {
return ZoneTask.invokeTask.call(global, self, this, <any>arguments);
};
}
}
static invokeTask(task: any, target: any, args: any): any {
if (!task) {
task = this;
}
_numberOfNestedTaskFrames++;
try {
task.runCount++;
return task.zone.runTask(task, target, args);
} finally {
if (_numberOfNestedTaskFrames == 1) {
drainMicroTaskQueue();
}
_numberOfNestedTaskFrames--;
}
}
get zone(): ZoneImpl {
return this._zone!;
}
get state(): TaskState {
return this._state;
}
public cancelScheduleRequest() {
this._transitionTo(notScheduled, scheduling);
}
// tslint:disable-next-line:require-internal-with-underscore
_transitionTo(toState: TaskState, fromState1: TaskState, fromState2?: TaskState) {
if (this._state === fromState1 || this._state === fromState2) {
this._state = toState;
if (toState == notScheduled) {
this._zoneDelegates = null;
}
} else {
throw new Error(
`${this.type} '${
this.source
}': can not transition to '${toState}', expecting state '${fromState1}'${
fromState2 ? " or '" + fromState2 + "'" : ''
}, was '${this._state}'.`,
);
}
}
public toString() {
if (this.data && typeof this.data.handleId !== 'undefined') {
return this.data.handleId.toString();
} else {
return Object.prototype.toString.call(this);
}
}
// add toJSON method to prevent cyclic error when
// call JSON.stringify(zoneTask)
public toJSON() {
return {
type: this.type,
state: this.state,
source: this.source,
zone: this.zone.name,
runCount: this.runCount,
};
}
}
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// MICROTASK QUEUE
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
const symbolSetTimeout = __symbol__('setTimeout');
const symbolPromise = __symbol__('Promise');
const symbolThen = __symbol__('then');
let _microTaskQueue: Task[] = [];
let _isDrainingMicrotaskQueue: boolean = false;
let nativeMicroTaskQueuePromise: any;
function nativeScheduleMicroTask(func: Function) {
if (!nativeMicroTaskQueuePromise) {
if (global[symbolPromise]) {
nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
}
}
if (nativeMicroTaskQueuePromise) {
let nativeThen = nativeMicroTaskQueuePromise[symbolThen];
if (!nativeThen) {
// native Promise is not patchable, we need to use `then` directly
// issue 1078
nativeThen = nativeMicroTaskQueuePromise['then'];
}
nativeThen.call(nativeMicroTaskQueuePromise, func);
} else {
global[symbolSetTimeout](func, 0);
}
}
function scheduleMicroTask(task?: MicroTask) {
// if we are not running in any task, and there has not been anything scheduled
// we must bootstrap the initial task creation by manually scheduling the drain
if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
// We are not running in Task, so we need to kickstart the microtask queue.
nativeScheduleMicroTask(drainMicroTaskQueue);
}
task && _microTaskQueue.push(task);
}
function drainMicroTaskQueue() {
if (!_isDrainingMicrotaskQueue) {
_isDrainingMicrotaskQueue = true;
while (_microTaskQueue.length) {
const queue = _microTaskQueue;
_microTaskQueue = [];
for (let i = 0; i < queue.length; i++) {
const task = queue[i];
try {
task.zone.runTask(task, null, null);
} catch (error) {
_api.onUnhandledError(error as Error);
}
}
}
_api.microtaskDrainDone();
_isDrainingMicrotaskQueue = false;
}
}
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// BOOTSTRAP
//////////////////////////////////////////////////////
////////////////////////////////////////////////////// | {
"end_byte": 53845,
"start_byte": 45366,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/zone-impl.ts_53849_55552 | const NO_ZONE = {name: 'NO ZONE'};
const notScheduled: 'notScheduled' = 'notScheduled',
scheduling: 'scheduling' = 'scheduling',
scheduled: 'scheduled' = 'scheduled',
running: 'running' = 'running',
canceling: 'canceling' = 'canceling',
unknown: 'unknown' = 'unknown';
const microTask: 'microTask' = 'microTask',
macroTask: 'macroTask' = 'macroTask',
eventTask: 'eventTask' = 'eventTask';
const patches: {[key: string]: any} = {};
const _api: ZonePrivate = {
symbol: __symbol__,
currentZoneFrame: () => _currentZoneFrame,
onUnhandledError: noop,
microtaskDrainDone: noop,
scheduleMicroTask: scheduleMicroTask,
showUncaughtError: () => !(ZoneImpl as any)[__symbol__('ignoreConsoleErrorUncaughtError')],
patchEventTarget: () => [],
patchOnProperties: noop,
patchMethod: () => noop,
bindArguments: () => [],
patchThen: () => noop,
patchMacroTask: () => noop,
patchEventPrototype: () => noop,
isIEOrEdge: () => false,
getGlobalObjects: () => undefined,
ObjectDefineProperty: () => noop,
ObjectGetOwnPropertyDescriptor: () => undefined,
ObjectCreate: () => undefined,
ArraySlice: () => [],
patchClass: () => noop,
wrapWithCurrentZone: () => noop,
filterProperties: () => [],
attachOriginToPatched: () => noop,
_redefineProperty: () => noop,
patchCallbacks: () => noop,
nativeScheduleMicroTask: nativeScheduleMicroTask,
};
let _currentZoneFrame: ZoneFrame = {parent: null, zone: new ZoneImpl(null, null)};
let _currentTask: Task | null = null;
let _numberOfNestedTaskFrames = 0;
function noop() {}
performanceMeasure('Zone', 'Zone');
return ZoneImpl;
} | {
"end_byte": 55552,
"start_byte": 53849,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-impl.ts"
} |
angular/packages/zone.js/lib/BUILD.bazel_0_795 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
exports_files(glob([
"**/*",
]))
ts_library(
name = "zone_d_ts",
srcs = [
":zone.api.extensions.ts",
":zone.configurations.api.ts",
":zone.ts",
":zone-impl.ts",
],
deps = [
"@npm//@types/node",
],
)
ts_library(
name = "lib",
package_name = "zone.js/lib",
srcs = glob(
["**/*.ts"],
exclude = [
"zone.ts",
"zone-impl.ts",
"zone.api.extensions.ts",
"zone.configurations.api.ts",
],
),
module_name = "zone.js/lib",
deps = [
":zone_d_ts",
"@npm//@types/jasmine",
"@npm//@types/node",
"@npm//rxjs",
],
)
| {
"end_byte": 795,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/BUILD.bazel"
} |
angular/packages/zone.js/lib/mocha/rollup-mocha.ts_0_259 | /**
* @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 {patchMocha} from './mocha';
patchMocha(Zone);
| {
"end_byte": 259,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/mocha/rollup-mocha.ts"
} |
angular/packages/zone.js/lib/mocha/mocha.ts_0_5963 | /**
* @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 {ZoneType} from '../zone-impl';
('use strict');
export function patchMocha(Zone: ZoneType): void {
Zone.__load_patch('mocha', (global: any, Zone: ZoneType) => {
const Mocha = global.Mocha;
if (typeof Mocha === 'undefined') {
// return if Mocha is not available, because now zone-testing
// will load mocha patch with jasmine/jest patch
return;
}
if (typeof Zone === 'undefined') {
throw new Error('Missing Zone.js');
}
const ProxyZoneSpec = (Zone as any)['ProxyZoneSpec'];
const SyncTestZoneSpec = (Zone as any)['SyncTestZoneSpec'];
if (!ProxyZoneSpec) {
throw new Error('Missing ProxyZoneSpec');
}
if (Mocha['__zone_patch__']) {
throw new Error('"Mocha" has already been patched with "Zone".');
}
Mocha['__zone_patch__'] = true;
const rootZone = Zone.current;
const syncZone = rootZone.fork(new SyncTestZoneSpec('Mocha.describe'));
let testZone: Zone | null = null;
const suiteZone = rootZone.fork(new ProxyZoneSpec());
const mochaOriginal = {
after: global.after,
afterEach: global.afterEach,
before: global.before,
beforeEach: global.beforeEach,
describe: global.describe,
it: global.it,
};
function modifyArguments(args: IArguments, syncTest: Function, asyncTest?: Function): any[] {
for (let i = 0; i < args.length; i++) {
let arg = args[i];
if (typeof arg === 'function') {
// The `done` callback is only passed through if the function expects at
// least one argument.
// Note we have to make a function with correct number of arguments,
// otherwise mocha will
// think that all functions are sync or async.
args[i] = arg.length === 0 ? syncTest(arg) : asyncTest!(arg);
// Mocha uses toString to view the test body in the result list, make sure we return the
// correct function body
args[i].toString = function () {
return arg.toString();
};
}
}
return args as any;
}
function wrapDescribeInZone(args: IArguments): any[] {
const syncTest: any = function (fn: Function) {
return function (this: unknown) {
return syncZone.run(fn, this, arguments as any as any[]);
};
};
return modifyArguments(args, syncTest);
}
function wrapTestInZone(args: IArguments): any[] {
const asyncTest = function (fn: Function) {
return function (this: unknown, done: Function) {
return testZone!.run(fn, this, [done]);
};
};
const syncTest: any = function (fn: Function) {
return function (this: unknown) {
return testZone!.run(fn, this);
};
};
return modifyArguments(args, syncTest, asyncTest);
}
function wrapSuiteInZone(args: IArguments): any[] {
const asyncTest = function (fn: Function) {
return function (this: unknown, done: Function) {
return suiteZone.run(fn, this, [done]);
};
};
const syncTest: any = function (fn: Function) {
return function (this: unknown) {
return suiteZone.run(fn, this);
};
};
return modifyArguments(args, syncTest, asyncTest);
}
global.describe = global.suite = function () {
return mochaOriginal.describe.apply(this, wrapDescribeInZone(arguments));
};
global.xdescribe =
global.suite.skip =
global.describe.skip =
function () {
return mochaOriginal.describe.skip.apply(this, wrapDescribeInZone(arguments));
};
global.describe.only = global.suite.only = function () {
return mochaOriginal.describe.only.apply(this, wrapDescribeInZone(arguments));
};
global.it =
global.specify =
global.test =
function () {
return mochaOriginal.it.apply(this, wrapTestInZone(arguments));
};
global.xit =
global.xspecify =
global.it.skip =
function () {
return mochaOriginal.it.skip.apply(this, wrapTestInZone(arguments));
};
global.it.only = global.test.only = function () {
return mochaOriginal.it.only.apply(this, wrapTestInZone(arguments));
};
global.after = global.suiteTeardown = function () {
return mochaOriginal.after.apply(this, wrapSuiteInZone(arguments));
};
global.afterEach = global.teardown = function () {
return mochaOriginal.afterEach.apply(this, wrapTestInZone(arguments));
};
global.before = global.suiteSetup = function () {
return mochaOriginal.before.apply(this, wrapSuiteInZone(arguments));
};
global.beforeEach = global.setup = function () {
return mochaOriginal.beforeEach.apply(this, wrapTestInZone(arguments));
};
((originalRunTest, originalRun) => {
Mocha.Runner.prototype.runTest = function (fn: Function) {
Zone.current.scheduleMicroTask('mocha.forceTask', () => {
originalRunTest.call(this, fn);
});
};
Mocha.Runner.prototype.run = function (fn: Function) {
this.on('test', (e: any) => {
testZone = rootZone.fork(new ProxyZoneSpec());
});
this.on('fail', (test: any, err: any) => {
const proxyZoneSpec = testZone && testZone.get('ProxyZoneSpec');
if (proxyZoneSpec && err) {
try {
// try catch here in case err.message is not writable
err.message += proxyZoneSpec.getAndClearPendingTasksInfo();
} catch (error) {}
}
});
return originalRun.call(this, fn);
};
})(Mocha.Runner.prototype.runTest, Mocha.Runner.prototype.run);
});
}
| {
"end_byte": 5963,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/mocha/mocha.ts"
} |
angular/packages/zone.js/lib/mix/rollup-mix.ts_0_463 | /**
* @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 {patchBrowser} from '../browser/browser';
import {patchCommon} from '../browser/rollup-common';
import {patchNode} from '../node/node';
import {loadZone} from '../zone';
const Zone = loadZone();
patchCommon(Zone);
patchBrowser(Zone);
patchNode(Zone);
| {
"end_byte": 463,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/mix/rollup-mix.ts"
} |
angular/packages/zone.js/lib/testing/rollup-promise-testing.ts_0_287 | /**
* @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 {patchPromiseTesting} from './promise-testing';
patchPromiseTesting(Zone);
| {
"end_byte": 287,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/testing/rollup-promise-testing.ts"
} |
angular/packages/zone.js/lib/testing/promise-testing.ts_0_2621 | /**
* @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 {ZoneType} from '../zone-impl';
export function patchPromiseTesting(Zone: ZoneType): void {
/**
* Promise for async/fakeAsync zoneSpec test
* can support async operation which not supported by zone.js
* such as
* it ('test jsonp in AsyncZone', async() => {
* new Promise(res => {
* jsonp(url, (data) => {
* // success callback
* res(data);
* });
* }).then((jsonpResult) => {
* // get jsonp result.
*
* // user will expect AsyncZoneSpec wait for
* // then, but because jsonp is not zone aware
* // AsyncZone will finish before then is called.
* });
* });
*/
Zone.__load_patch('promisefortest', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
const symbolState: string = api.symbol('state');
const UNRESOLVED: null = null;
const symbolParentUnresolved = api.symbol('parentUnresolved');
// patch Promise.prototype.then to keep an internal
// number for tracking unresolved chained promise
// we will decrease this number when the parent promise
// being resolved/rejected and chained promise was
// scheduled as a microTask.
// so we can know such kind of chained promise still
// not resolved in AsyncTestZone
(Promise as any)[api.symbol('patchPromiseForTest')] = function patchPromiseForTest() {
let oriThen = (Promise as any)[Zone.__symbol__('ZonePromiseThen')];
if (oriThen) {
return;
}
oriThen = (Promise as any)[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
Promise.prototype.then = function () {
const chained = oriThen.apply(this, arguments);
if ((this as any)[symbolState] === UNRESOLVED) {
// parent promise is unresolved.
const asyncTestZoneSpec = Zone.current.get('AsyncTestZoneSpec');
if (asyncTestZoneSpec) {
asyncTestZoneSpec.unresolvedChainedPromiseCount++;
chained[symbolParentUnresolved] = true;
}
}
return chained;
};
};
(Promise as any)[api.symbol('unPatchPromiseForTest')] = function unpatchPromiseForTest() {
// restore origin then
const oriThen = (Promise as any)[Zone.__symbol__('ZonePromiseThen')];
if (oriThen) {
Promise.prototype.then = oriThen;
(Promise as any)[Zone.__symbol__('ZonePromiseThen')] = undefined;
}
};
});
}
| {
"end_byte": 2621,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/testing/promise-testing.ts"
} |
angular/packages/zone.js/lib/testing/zone-testing.ts_0_1007 | /**
* @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 {patchJasmine} from '../jasmine/jasmine';
import {patchJest} from '../jest/jest';
import {patchMocha} from '../mocha/mocha';
import {ZoneType} from '../zone-impl';
import {patchAsyncTest} from '../zone-spec/async-test';
import {patchFakeAsyncTest} from '../zone-spec/fake-async-test';
import {patchLongStackTrace} from '../zone-spec/long-stack-trace';
import {patchProxyZoneSpec} from '../zone-spec/proxy';
import {patchSyncTest} from '../zone-spec/sync-test';
import {patchPromiseTesting} from './promise-testing';
export function rollupTesting(Zone: ZoneType): void {
patchLongStackTrace(Zone);
patchProxyZoneSpec(Zone);
patchSyncTest(Zone);
patchJasmine(Zone);
patchJest(Zone);
patchMocha(Zone);
patchAsyncTest(Zone);
patchFakeAsyncTest(Zone);
patchPromiseTesting(Zone);
}
| {
"end_byte": 1007,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/testing/zone-testing.ts"
} |
angular/packages/zone.js/lib/testing/async-testing.ts_0_283 | /**
* @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 {patchAsyncTest} from '../zone-spec/async-test';
patchAsyncTest(Zone);
| {
"end_byte": 283,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/testing/async-testing.ts"
} |
angular/packages/zone.js/lib/testing/fake-async.ts_0_295 | /**
* @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 {patchFakeAsyncTest} from '../zone-spec/fake-async-test';
patchFakeAsyncTest(Zone);
| {
"end_byte": 295,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/testing/fake-async.ts"
} |
angular/packages/zone.js/lib/testing/rollup-zone-testing.ts_0_272 | /**
* @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 {rollupTesting} from './zone-testing';
rollupTesting(Zone);
| {
"end_byte": 272,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/testing/rollup-zone-testing.ts"
} |
angular/packages/zone.js/lib/browser/rollup-webapis-notification.ts_0_290 | /**
* @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 {patchNotifications} from './webapis-notification';
patchNotifications(Zone);
| {
"end_byte": 290,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-webapis-notification.ts"
} |
angular/packages/zone.js/lib/browser/websocket.ts_0_2452 | /**
* @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
*/
// we have to patch the instance since the proto is non-configurable
export function apply(api: _ZonePrivate, _global: any) {
const {ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR} = api.getGlobalObjects()!;
const WS = (<any>_global).WebSocket;
// On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
// On older Chrome, no need since EventTarget was already patched
if (!(<any>_global).EventTarget) {
api.patchEventTarget(_global, api, [WS.prototype]);
}
(<any>_global).WebSocket = function (x: any, y: any) {
const socket = arguments.length > 1 ? new WS(x, y) : new WS(x);
let proxySocket: any;
let proxySocketProto: any;
// Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
const onmessageDesc = api.ObjectGetOwnPropertyDescriptor(socket, 'onmessage');
if (onmessageDesc && onmessageDesc.configurable === false) {
proxySocket = api.ObjectCreate(socket);
// socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror'
// but proxySocket not, so we will keep socket as prototype and pass it to
// patchOnProperties method
proxySocketProto = socket;
[ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(
function (propName) {
proxySocket[propName] = function () {
const args = api.ArraySlice.call(arguments);
if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
const eventName = args.length > 0 ? args[0] : undefined;
if (eventName) {
const propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
socket[propertySymbol] = proxySocket[propertySymbol];
}
}
return socket[propName].apply(socket, args);
};
},
);
} else {
// we can patch the real socket
proxySocket = socket;
}
api.patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto);
return proxySocket;
};
const globalWebSocket = _global['WebSocket'];
for (const prop in WS) {
globalWebSocket[prop] = WS[prop];
}
}
| {
"end_byte": 2452,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/websocket.ts"
} |
angular/packages/zone.js/lib/browser/canvas.ts_0_789 | /**
* @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 {ZoneType} from '../zone-impl';
export function patchCanvas(Zone: ZoneType): void {
Zone.__load_patch('canvas', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
const HTMLCanvasElement = global['HTMLCanvasElement'];
if (
typeof HTMLCanvasElement !== 'undefined' &&
HTMLCanvasElement.prototype &&
HTMLCanvasElement.prototype.toBlob
) {
api.patchMacroTask(HTMLCanvasElement.prototype, 'toBlob', (self: any, args: any[]) => {
return {name: 'HTMLCanvasElement.toBlob', target: self, cbIdx: 0, args: args};
});
}
});
}
| {
"end_byte": 789,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/canvas.ts"
} |
angular/packages/zone.js/lib/browser/webapis-user-media.ts_0_886 | /**
* @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 {ZoneType} from '../zone-impl';
export function patchUserMedia(Zone: ZoneType): void {
Zone.__load_patch('getUserMedia', (global: any, Zone: any, api: _ZonePrivate) => {
function wrapFunctionArgs(func: Function, source?: string): Function {
return function (this: unknown) {
const args = Array.prototype.slice.call(arguments);
const wrappedArgs = api.bindArguments(args, source ? source : (func as any).name);
return func.apply(this, wrappedArgs);
};
}
let navigator = global['navigator'];
if (navigator && navigator.getUserMedia) {
navigator.getUserMedia = wrapFunctionArgs(navigator.getUserMedia);
}
});
}
| {
"end_byte": 886,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/webapis-user-media.ts"
} |
angular/packages/zone.js/lib/browser/event-target-legacy.ts_0_5262 | /**
* @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
*/
export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
const {eventNames, globalSources, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX} =
api.getGlobalObjects()!;
const WTF_ISSUE_555 =
'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
const NO_EVENT_TARGET =
'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'.split(
',',
);
const EVENT_TARGET = 'EventTarget';
let apis: any[] = [];
const isWtf = _global['wtf'];
const WTF_ISSUE_555_ARRAY = WTF_ISSUE_555.split(',');
if (isWtf) {
// Workaround for: https://github.com/google/tracing-framework/issues/555
apis = WTF_ISSUE_555_ARRAY.map((v) => 'HTML' + v + 'Element').concat(NO_EVENT_TARGET);
} else if (_global[EVENT_TARGET]) {
apis.push(EVENT_TARGET);
} else {
// Note: EventTarget is not available in all browsers,
// if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
apis = NO_EVENT_TARGET;
}
const isDisableIECheck = _global['__Zone_disable_IE_check'] || false;
const isEnableCrossContextCheck = _global['__Zone_enable_cross_context_check'] || false;
const ieOrEdge = api.isIEOrEdge();
const ADD_EVENT_LISTENER_SOURCE = '.addEventListener:';
const FUNCTION_WRAPPER = '[object FunctionWrapper]';
const BROWSER_TOOLS = 'function __BROWSERTOOLS_CONSOLE_SAFEFUNC() { [native code] }';
const pointerEventsMap: {[key: string]: string} = {
'MSPointerCancel': 'pointercancel',
'MSPointerDown': 'pointerdown',
'MSPointerEnter': 'pointerenter',
'MSPointerHover': 'pointerhover',
'MSPointerLeave': 'pointerleave',
'MSPointerMove': 'pointermove',
'MSPointerOut': 'pointerout',
'MSPointerOver': 'pointerover',
'MSPointerUp': 'pointerup',
};
// predefine all __zone_symbol__ + eventName + true/false string
for (let i = 0; i < eventNames.length; i++) {
const eventName = eventNames[i];
const falseEventName = eventName + FALSE_STR;
const trueEventName = eventName + TRUE_STR;
const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames[eventName] = {};
zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
}
// predefine all task.source string
for (let i = 0; i < WTF_ISSUE_555_ARRAY.length; i++) {
const target: any = WTF_ISSUE_555_ARRAY[i];
const targets: any = (globalSources[target] = {});
for (let j = 0; j < eventNames.length; j++) {
const eventName = eventNames[j];
targets[eventName] = target + ADD_EVENT_LISTENER_SOURCE + eventName;
}
}
const checkIEAndCrossContext = function (
nativeDelegate: any,
delegate: any,
target: any,
args: any,
) {
if (!isDisableIECheck && ieOrEdge) {
if (isEnableCrossContextCheck) {
try {
const testString = delegate.toString();
if (testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS) {
nativeDelegate.apply(target, args);
return false;
}
} catch (error) {
nativeDelegate.apply(target, args);
return false;
}
} else {
const testString = delegate.toString();
if (testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS) {
nativeDelegate.apply(target, args);
return false;
}
}
} else if (isEnableCrossContextCheck) {
try {
delegate.toString();
} catch (error) {
nativeDelegate.apply(target, args);
return false;
}
}
return true;
};
const apiTypes: any[] = [];
for (let i = 0; i < apis.length; i++) {
const type = _global[apis[i]];
apiTypes.push(type && type.prototype);
}
// vh is validateHandler to check event handler
// is valid or not(for security check)
api.patchEventTarget(_global, api, apiTypes, {
vh: checkIEAndCrossContext,
transferEventName: (eventName: string) => {
const pointerEventName = pointerEventsMap[eventName];
return pointerEventName || eventName;
},
});
(Zone as any)[api.symbol('patchEventTarget')] = !!_global[EVENT_TARGET];
return true;
}
export function patchEvent(global: any, api: _ZonePrivate) {
api.patchEventPrototype(global, api);
}
| {
"end_byte": 5262,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/event-target-legacy.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.