or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-zone-js

Execution context library that persists across asynchronous operations for JavaScript applications

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/zone.js@0.15.x

To install, run

npx @tessl/cli install tessl/npm-zone-js@0.15.0

0

# Zone.js

1

2

Zone.js is an execution context library that persists across asynchronous operations, providing a mechanism to intercept and track asynchronous work. It implements the Zone concept inspired by Dart, enabling applications to maintain execution context across async boundaries such as setTimeout, Promise, DOM events, and XMLHttpRequest.

3

4

## Package Information

5

6

- **Package Name**: zone.js

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install zone.js`

10

11

## Core Imports

12

13

```typescript

14

import 'zone.js'; // Loads main zone.js with patches

15

```

16

17

For specific bundles:

18

19

```typescript

20

import 'zone.js/testing'; // Testing utilities

21

import 'zone.js/node'; // Node.js environment

22

import 'zone.js/mix'; // Mixed browser/node environment

23

```

24

25

CommonJS:

26

27

```javascript

28

require('zone.js');

29

require('zone.js/testing');

30

```

31

32

## Basic Usage

33

34

```typescript

35

import 'zone.js';

36

37

// Get current zone

38

const currentZone = Zone.current;

39

console.log('Current zone:', currentZone.name);

40

41

// Create a new zone with custom properties

42

const myZone = Zone.current.fork({

43

name: 'myZone',

44

properties: { userId: 123 }

45

});

46

47

// Run code in the zone

48

myZone.run(() => {

49

console.log('Zone name:', Zone.current.name); // 'myZone'

50

console.log('User ID:', Zone.current.get('userId')); // 123

51

52

// Async operations maintain zone context

53

setTimeout(() => {

54

console.log('Still in zone:', Zone.current.name); // 'myZone'

55

}, 100);

56

});

57

```

58

59

## Architecture

60

61

Zone.js is built around several key components:

62

63

- **Zone**: Execution context that persists across async operations

64

- **ZoneSpec**: Configuration object for customizing zone behavior via lifecycle hooks

65

- **Task System**: Categorizes async work into MicroTask, MacroTask, and EventTask types

66

- **Patching System**: Monkey patches browser APIs (EventTarget, timers, Promise) and Node.js APIs (fs, EventEmitter, timers) to integrate with zones

67

- **Testing Framework**: FakeAsync and other utilities for testing asynchronous code

68

69

## Capabilities

70

71

### Core Zone API

72

73

Zone creation, execution context management, and basic zone operations for maintaining execution state across asynchronous boundaries.

74

75

```typescript { .api }

76

interface Zone {

77

readonly parent: Zone | null;

78

readonly name: string;

79

80

get(key: string): any;

81

getZoneWith(key: string): Zone | null;

82

fork(zoneSpec: ZoneSpec): Zone;

83

wrap<F extends Function>(callback: F, source: string): F;

84

run<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;

85

runGuarded<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;

86

}

87

88

interface ZoneType {

89

readonly current: Zone;

90

readonly currentTask: Task | null;

91

readonly root: Zone;

92

assertZonePatched(): void;

93

__load_patch(name: string, fn: PatchFn, ignoreDuplicate?: boolean): void;

94

__symbol__(name: string): string;

95

}

96

```

97

98

[Core Zone API](./core-zone-api.md)

99

100

### Zone Specifications

101

102

Zone configuration system for customizing zone behavior through lifecycle hooks, error handling, and task interception.

103

104

```typescript { .api }

105

interface ZoneSpec {

106

name: string;

107

properties?: {[key: string]: any};

108

109

onFork?: (parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, zoneSpec: ZoneSpec) => Zone;

110

onIntercept?: (parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function, source: string) => Function;

111

onInvoke?: (parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function, applyThis: any, applyArgs?: any[], source?: string) => any;

112

onHandleError?: (parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any) => boolean;

113

onScheduleTask?: (parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => Task;

114

onInvokeTask?: (parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task, applyThis: any, applyArgs?: any[]) => any;

115

onCancelTask?: (parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => any;

116

onHasTask?: (parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, hasTaskState: HasTaskState) => void;

117

}

118

```

119

120

[Zone Specifications](./zone-specifications.md)

121

122

### Task System

123

124

Asynchronous task scheduling and management system that categorizes async work into microtasks, macrotasks, and event tasks.

125

126

```typescript { .api }

127

interface Task {

128

readonly type: TaskType;

129

state: TaskState;

130

readonly source: string;

131

readonly zone: Zone;

132

callback: Function;

133

data?: TaskData;

134

runCount: number;

135

cancelScheduleRequest(): void;

136

}

137

138

type TaskType = 'microTask' | 'macroTask' | 'eventTask';

139

type TaskState = 'notScheduled' | 'scheduling' | 'scheduled' | 'running' | 'canceling' | 'unknown';

140

141

interface MicroTask extends Task { type: 'microTask'; }

142

interface MacroTask extends Task { type: 'macroTask'; }

143

interface EventTask extends Task { type: 'eventTask'; }

144

```

145

146

[Task System](./task-system.md)

147

148

### Testing Utilities

149

150

Comprehensive testing framework with fakeAsync, async testing zones, and task tracking for testing asynchronous code in a controlled environment.

151

152

```typescript { .api }

153

function fakeAsync(fn: Function, options?: {flush?: boolean}): (...args: any[]) => any;

154

function tick(millis?: number, ignoreNestedTimeout?: boolean): void;

155

function flush(maxTurns?: number): number;

156

function flushMicrotasks(): void;

157

function discardPeriodicTasks(): void;

158

159

class FakeAsyncTestZoneSpec implements ZoneSpec {

160

name: 'fakeAsync';

161

tick(millis?: number, doTick?: (elapsed: number) => void): void;

162

flush(maxTurns?: number): number;

163

flushMicrotasks(): void;

164

}

165

```

166

167

[Testing Utilities](./testing-utilities.md)

168

169

### Patching System

170

171

Monkey patching infrastructure for browser and Node.js APIs, enabling zone context preservation across various asynchronous operations.

172

173

```typescript { .api }

174

type PatchFn = (global: Window, Zone: ZoneType, api: ZonePrivate) => void;

175

176

interface ZonePrivate {

177

patchEventTarget(global: any, api: ZonePrivate, apis: any[], options?: any): boolean[];

178

patchMethod(target: any, name: string, patchFn: Function): Function | null;

179

patchMacroTask(obj: any, funcName: string, metaCreator: Function): void;

180

patchOnProperties(obj: any, properties: string[] | null, prototype?: any): void;

181

bindArguments(args: any[], source: string): any[];

182

}

183

```

184

185

[Patching System](./patching-system.md)

186

187

### Configuration API

188

189

Global configuration system for selectively disabling patches and customizing zone behavior across different environments and use cases.

190

191

```typescript { .api }

192

interface ZoneGlobalConfigurations {

193

__Zone_disable_timers?: boolean;

194

__Zone_disable_Promise?: boolean;

195

__Zone_disable_EventTarget?: boolean;

196

__Zone_disable_requestAnimationFrame?: boolean;

197

__zone_symbol__UNPATCHED_EVENTS?: string[];

198

__zone_symbol__PASSIVE_EVENTS?: string[];

199

__Zone_ignore_on_properties?: Array<{target: any; ignoreProperties: string[]}>;

200

}

201

```

202

203

[Configuration API](./configuration-api.md)

204

205

## Types

206

207

```typescript { .api }

208

interface ZoneDelegate {

209

readonly zone: Zone;

210

fork(targetZone: Zone, zoneSpec: ZoneSpec): Zone;

211

intercept(targetZone: Zone, callback: Function, source: string): Function;

212

invoke(targetZone: Zone, callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;

213

handleError(targetZone: Zone, error: any): boolean;

214

scheduleTask(targetZone: Zone, task: Task): Task;

215

invokeTask(targetZone: Zone, task: Task, applyThis?: any, applyArgs?: any[]): any;

216

cancelTask(targetZone: Zone, task: Task): any;

217

hasTask(targetZone: Zone, isEmpty: HasTaskState): void;

218

}

219

220

interface TaskData {

221

isPeriodic?: boolean;

222

isRefreshable?: boolean;

223

delay?: number;

224

handleId?: number;

225

handle?: any;

226

}

227

228

type HasTaskState = {

229

microTask: boolean;

230

macroTask: boolean;

231

eventTask: boolean;

232

change: TaskType;

233

};

234

235

interface UncaughtPromiseError extends Error {

236

zone: Zone;

237

task: Task;

238

promise: Promise<any>;

239

rejection: any;

240

throwOriginal?: boolean;

241

}

242

```