Implementation:Puppeteer Puppeteer Common Util
| Property | Value |
|---|---|
| sources | packages/puppeteer-core/src/common/util.ts |
| domains | Utilities, Core Infrastructure, PDF, Networking, Observables |
| last_updated | 2026-02-12 00:00 GMT |
Overview
Description
Common Util is an internal utility module that provides a wide collection of helper functions, constants, and classes used throughout Puppeteer's codebase. The module covers several functional areas:
Debug and Error Logging:
- debugError -- A debug logger instance prefixed with
'puppeteer:error'for error-level logging.
Constants:
- DEFAULT_VIEWPORT -- A frozen object
{ width: 800, height: 600 }defining Puppeteer's default viewport. - UTILITY_WORLD_NAME -- The name for Puppeteer's utility execution context world, versioned with the package version.
- NETWORK_IDLE_TIME -- 500ms constant used for network idle detection.
- SOURCE_URL_REGEX -- A regex for matching sourceURL comments in scripts.
- unitToPixels -- A mapping of length units (
px,in,cm,mm) to their pixel equivalents.
PuppeteerURL Class:
- PuppeteerURL -- A class that encodes/decodes function call site information into
pptr:-prefixed URLs for evaluation script source mapping. Provides static methodsfromCallSite,parse, andisPuppeteerURL.
Type Guard Functions:
- isString, isNumber, isPlainObject, isRegExp, isDate -- Type guard functions for runtime type checking.
Source URL Helpers:
- withSourcePuppeteerURLIfNone -- Attaches a PuppeteerURL source annotation to an object using the call stack.
- getSourcePuppeteerURLIfAvailable -- Retrieves the PuppeteerURL annotation from an object if present.
- getSourceUrlComment -- Generates a
//# sourceURL=comment string.
Evaluation Helper:
- evaluationString -- Converts a function and arguments into an immediately-invoked function expression string suitable for browser evaluation.
Stream/File Helpers:
- getReadableAsTypedArray -- Reads a
ReadableStream<Uint8Array>to completion, optionally writing to a file, and returns the merged Uint8Array. - getReadableFromProtocolStream -- Creates a
ReadableStreamfrom a CDP IO stream handle.
Dialog Validation:
- validateDialogType -- Validates and returns a dialog type string (
'alert','confirm','prompt','beforeunload').
PDF Options:
- parsePDFOptions -- Parses and normalizes PDFOptions into ParsedPDFOptions with proper unit conversion, default values, and paper format resolution.
Observable Helpers:
- timeout -- Creates an RxJS Observable that emits a TimeoutError after the specified duration.
- fromEmitterEvent -- Converts an EventEmitter event into an RxJS Observable stream.
- fromAbortSignal -- Converts an
AbortSignalinto an Observable that throws on abort. - filterAsync -- An RxJS operator that filters values using an async predicate function.
Usage
This module is imported by nearly every other module in Puppeteer's codebase. It centralizes common utilities to avoid duplication and provides type-safe helpers for frequent operations like evaluation string construction, stream reading, and observable creation.
Code Reference
Source Location
packages/puppeteer-core/src/common/util.ts
Signature
export const debugError: (...args: unknown[]) => void;
export const DEFAULT_VIEWPORT: Readonly<{width: number; height: number}>;
export const UTILITY_WORLD_NAME: string;
export const NETWORK_IDLE_TIME: number;
export const SOURCE_URL_REGEX: RegExp;
export const unitToPixels: {px: number; in: number; cm: number; mm: number};
export class PuppeteerURL {
static INTERNAL_URL: string;
static fromCallSite(functionName: string, site: NodeJS.CallSite): PuppeteerURL;
static parse(url: string): PuppeteerURL;
static isPuppeteerURL(url: string): boolean;
get functionName(): string;
get siteString(): string;
toString(): string;
}
export const withSourcePuppeteerURLIfNone: <T>(functionName: string, object: T) => T;
export const getSourcePuppeteerURLIfAvailable: <T>(object: T) => PuppeteerURL | undefined;
export const isString: (obj: unknown) => obj is string;
export const isNumber: (obj: unknown) => obj is number;
export const isPlainObject: (obj: unknown) => obj is Record<any, unknown>;
export const isRegExp: (obj: unknown) => obj is RegExp;
export const isDate: (obj: unknown) => obj is Date;
export function evaluationString(fun: Function | string, ...args: unknown[]): string;
export function getSourceUrlComment(url: string): string;
export function validateDialogType(type: string): 'alert' | 'confirm' | 'prompt' | 'beforeunload';
export function parsePDFOptions(options?: PDFOptions, lengthUnit?: 'in' | 'cm'): ParsedPDFOptions;
export async function getReadableAsTypedArray(
readable: ReadableStream<Uint8Array>,
path?: string,
): Promise<Uint8Array | null>;
export async function getReadableFromProtocolStream(
client: CDPSession,
handle: string,
): Promise<ReadableStream<Uint8Array>>;
export function timeout(ms: number, cause?: Error): Observable<never>;
export function fromEmitterEvent<Events, Event>(
emitter: EventEmitter<Events>,
eventName: Event,
): Observable<Events[Event]>;
export function fromAbortSignal(signal?: AbortSignal, cause?: Error): Observable<never>;
export function filterAsync<T>(
predicate: (value: T) => boolean | PromiseLike<boolean>,
): OperatorFunction<T, T>;
Import
import {
debugError,
DEFAULT_VIEWPORT,
PuppeteerURL,
evaluationString,
isString,
isNumber,
getReadableAsTypedArray,
parsePDFOptions,
timeout,
fromEmitterEvent,
UTILITY_WORLD_NAME,
NETWORK_IDLE_TIME,
} from './util.js';
I/O Contract
| Function | Input | Output | Description |
|---|---|---|---|
evaluationString |
Function or string, variadic args | string |
Produces an IIFE string for browser evaluation |
getReadableAsTypedArray |
ReadableStream<Uint8Array>, optional path |
null> | Reads stream to completion, optionally writes to file |
getReadableFromProtocolStream |
CDPSession, stream handle |
Promise<ReadableStream<Uint8Array>> |
Creates ReadableStream from CDP IO stream |
parsePDFOptions |
PDFOptions, length unit |
ParsedPDFOptions |
Normalizes PDF options with defaults and unit conversion |
validateDialogType |
string |
'confirm' | 'prompt' | 'beforeunload' | Validates and returns dialog type |
timeout |
number (ms), optional cause |
Observable<never> |
Emits TimeoutError after duration; returns NEVER for 0 |
fromEmitterEvent |
EventEmitter, event name | Observable<T> |
Wraps EventEmitter event as Observable |
fromAbortSignal |
optional AbortSignal, optional cause | Observable<never> |
Throws on signal abort; returns NEVER if no signal |
filterAsync |
async predicate function | OperatorFunction<T, T> |
RxJS operator for async filtering |
Usage Examples
import {
evaluationString,
isString,
isNumber,
DEFAULT_VIEWPORT,
parsePDFOptions,
PuppeteerURL,
} from './util.js';
// Build an evaluation string from a function
const evalStr = evaluationString((a, b) => a + b, 1, 2);
// Result: "((a, b) => a + b)(1,2)"
// Type guards
if (isString(someValue)) {
console.log(someValue.toUpperCase());
}
if (isNumber(someValue)) {
console.log(someValue.toFixed(2));
}
// Use default viewport
console.log(DEFAULT_VIEWPORT); // { width: 800, height: 600 }
// Parse PDF options with defaults
const pdfOpts = parsePDFOptions({
format: 'A4',
margin: { top: '1cm', bottom: '1cm' },
printBackground: true,
});
// Check if a URL is a Puppeteer internal URL
if (PuppeteerURL.isPuppeteerURL('pptr:evaluate;some-site')) {
const parsed = PuppeteerURL.parse('pptr:evaluate;some-site');
console.log(parsed.functionName); // 'evaluate'
}