polyfills-B6TNHZQ6.js
Overview
This file implements a comprehensive Zone.js polyfill, which patches and augments asynchronous APIs in the JavaScript runtime environment to enable execution context tracking across asynchronous operations. It provides the foundational Zone class and related utilities for managing zones, which are execution contexts that persist through async calls, enabling advanced features such as async task tracking, error handling, and context propagation.
The polyfill patches core asynchronous mechanisms including promises, timers, event listeners, XMLHttpRequest, fetch, mutation observers, and various browser APIs. It ensures that asynchronous callbacks run within the correct zone context, allowing applications or frameworks to maintain logical continuity and state despite the asynchronous nature of JavaScript.
Key Components
Global Symbols and Utilities
te(name: string): string
Generates a zone-specific global symbol string prefixed with "zone_symbol" or a configured prefix. Used for symbolizing patched properties and methods to avoid collisions.Performance Marking Functions (
n,a)
Wrapper functions around performance.mark and performance.measure to mark and measure the patch loading process for performance diagnostics.
Class: Zone
The central class representing a zone — an execution context that persists across asynchronous tasks.
Static Members:
symbol: The symbol prefix function.
assertZonePatched(): Validates that
Promisehas not been overwritten after Zone.js initialization.root: Returns the root zone (topmost ancestor).
current: Returns the current active zone.currentTask: Returns the current executing task.
__load_patch(name, fn, forceDuplicate = false): Loads a patch under the given name, ensuring no duplicates unless forced.
Instance Properties:
_parent: Parent zone.
_name: Name of the zone.
_properties: Zone-specific properties._zoneDelegate: Delegate object handling zone lifecycle hooks.
Constructor:
constructor(parent: Zone|null, zoneSpec: object|null)
Creates a new zone with optional parent and zone specification.
Instance Methods:
get(key: string): Retrieves a property from the current zone or ancestors.getZoneWith(key: string): Finds the nearest zone in the hierarchy with the specified property.fork(zoneSpec: object): Creates a child zone with the given specification.wrap(callback: Function, source?: string): Wraps a function to execute within this zone.run(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): Runs a function synchronously within this zone.runGuarded(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): Runs a function with error handling.runTask(task: ZoneTask, applyThis?: any, applyArgs?: any[]): Runs a scheduled task within this zone.scheduleTask(task: ZoneTask): Schedules a task in this zone.scheduleMicroTask(source, callback, data, customSchedule): Schedules a microtask.scheduleMacroTask(source, callback, data, customSchedule, customCancel): Schedules a macro task.scheduleEventTask(source, callback, data, customSchedule, customCancel): Schedules an event task.cancelTask(task: ZoneTask): Cancels a scheduled task._updateTaskCount(task: ZoneTask, count: number): Updates internal task counts.
Class: ZoneDelegate
Acts as an intermediary between a zone and its zone specification, managing lifecycle events like forking, intercepting, invoking, error handling, scheduling, and cancellation.
Constructor Parameters:
zone: The current zone.parentDelegate: Delegate of the parent zone.zoneSpec: ZoneSpec object defining lifecycle hooks.
Methods:
fork(targetZone, zoneSpec): Fork a child zone.intercept(targetZone, callback, source): Intercept a callback.invoke(targetZone, callback, applyThis, applyArgs, source): Invoke a callback function.handleError(targetZone, error): Handle errors thrown in the zone.scheduleTask(targetZone, task): Schedule a task.invokeTask(targetZone, task, applyThis, applyArgs): Invoke a task.cancelTask(targetZone, task): Cancel a task.hasTask(targetZone, isEmpty): Notify about task count changes._updateTaskCount(taskType, count): Maintain task counts.
Class: ZoneTask
Represents an asynchronous task scheduled in a zone.
Properties:
source: String identifying task source.callback: The callback function to run.data: Additional task data.scheduleFn: Function to schedule the task.cancelFn: Function to cancel the task._zone: Zone to which the task belongs.
runCount: Number of times the task has run._state: Current state of the task (
notScheduled,scheduling,scheduled, etc.)._zoneDelegates: List of delegates involved in the task lifecycle.
Methods:
invoke(): Invokes the task callback._transitionTo(newState, expectedState1, expectedState2): Transitions task state with validation.cancelScheduleRequest(): Cancels scheduling request.toString(),toJSON(): Serialization helpers.
Promise Patching (ZoneAwarePromise)
Implements a ZoneAwarePromise class that patches the native Promise to maintain zone context across promise chains. It tracks unhandled rejections and integrates with zone error handling.
Key Features:
Overwrites the global
PromisewithZoneAwarePromise.Tracks promise states and rejection handlers.
Integrates with zone error handling and microtask scheduling.
Supports static methods like
resolve,reject,race,all,allSettled, andanywith zone awareness.
Patching of Asynchronous APIs
The file patches numerous platform APIs to ensure zone context propagation:
Timers (
setTimeout, setInterval, setImmediate)Animation frames (requestAnimationFrame, vendor-prefixed variants)
Blocking APIs (alert,
prompt,confirm)EventTarget and event listeners (addEventListener, removeEventListener, event properties)
MutationObserver and WebKitMutationObserver
IntersectionObserver
FileReader
Custom Elements lifecycle callbacks
XMLHttpRequest and XMLHttpRequestEventTarget
Geolocation APIs (getCurrentPosition, watchPosition)
Promise rejection events (unhandledrejection, rejectionhandled)
Patching involves intercepting native methods, wrapping callbacks with the current zone, and managing task scheduling/cancellation within the zone framework.
Event Listener Management
The patch includes sophisticated event listener management:
Wraps event listener callbacks to run in the correct zone.
Supports properties like onload,
onclickwith zone awareness.Handles special events like beforeunload with zone hooks.
Maintains internal maps of patched listeners for efficient add/remove.
Supports passive event listeners and once options.
Ensures correct propagation of event phases and stopImmediatePropagation behavior.
Internal Task Scheduling and Microtask Queue
The polyfill maintains an internal microtask queue for zone tasks:
Uses a queue
_to hold pending microtasks.Ensures microtask drain is triggered appropriately.
Uses native microtask scheduling if available (
Promise.resolve().then).Manages task invocation counts and draining states to avoid reentrancy issues.
Interactions with Other Parts of the System
This file defines the global
Zoneobject, used by other parts of the system to create zones, fork child zones, and run code within zones.It patches global asynchronous APIs to intercept and maintain zone context, affecting all asynchronous operations in the environment.
Other modules or application code can use
Zone.currentto retrieve the current zone or create new zones for instrumentation, error handling, or async context tracking.It integrates with error reporting by intercepting unhandled promise rejections and uncaught exceptions within the zone context.
The patching mechanism allows other patches to be loaded via Zone.__load_patch, enabling modular instrumentation of various APIs.
Usage Examples
// Create a new zone with a name and some properties
const myZone = Zone.current.fork({
name: 'myZone',
properties: { foo: 'bar' }
});
// Run a function within the new zone
myZone.run(() => {
console.log('Current zone:', Zone.current.name); // "myZone"
console.log('Property foo:', Zone.current.get('foo')); // "bar"
setTimeout(() => {
console.log('Timeout callback zone:', Zone.current.name); // "myZone"
}, 100);
});
Important Implementation Details and Algorithms
Zone Tree: Zones form a tree with parent-child relationships. Each zone inherits properties and delegates lifecycle events to its parent delegate.
Task Lifecycle: Tasks transition through states (
notScheduled,scheduling,scheduled,running,canceling,unknown) with strict validation to prevent illegal state transitions.Delegate Chain: Zone delegates chain lifecycle hooks, allowing multiple zone specs to cooperate or override behaviors.
Task Counting: Zone delegates maintain counts of active micro, macro, and event tasks, notifying zones when counts change (useful for detecting idle state).
Promise Wrapping: The patched
ZoneAwarePromisemanages internal states and handlers to maintain zone context across asynchronous promise chains, including error propagation and unhandled rejection tracking.Event Listener Wrapping: Listeners are wrapped to execute within the zone, and original listeners are tracked to prevent double patching or leaks.
Microtask Scheduling: Uses a combination of native microtask scheduling and an internal queue to manage task invocation order and avoid reentrancy bugs.
Mermaid Diagram
classDiagram
class Zone {
+parent
+name
+properties
+fork()
+wrap()
+run()
+runGuarded()
+runTask()
+scheduleTask()
+cancelTask()
+get()
+getZoneWith()
}
class ZoneDelegate {
+zone
+parentDelegate
+zoneSpec
+fork()
+intercept()
+invoke()
+handleError()
+scheduleTask()
+invokeTask()
+cancelTask()
+hasTask()
}
class ZoneTask {
+type
+source
+callback
+data
+scheduleFn
+cancelFn
+zone
+runCount
+state
+invoke()
+cancelScheduleRequest()
+_transitionTo()
}
class ZoneAwarePromise {
+then()
+catch()
+finally()
+resolve()
+reject()
+race()
+all()
+allSettled()
+any()
}
Zone --> ZoneDelegate : uses
ZoneDelegate --> Zone : delegates to parentDelegate
ZoneTask --> Zone : belongs to
ZoneAwarePromise ..|> Promise : patches
Summary
The polyfills-B6TNHZQ6.js file is a complete implementation of the Zone.js polyfill providing a robust mechanism for asynchronous context tracking in JavaScript environments. It introduces the Zone class hierarchy, task scheduling and lifecycle management, and patches numerous asynchronous APIs to ensure zone context propagation. This file is foundational for frameworks or applications requiring fine-grained async tracking, error handling, and context-aware instrumentation.