Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Getgauge Taiko Core Utilities

From Leeroopedia
Revision as of 11:17, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Getgauge_Taiko_Core_Utilities.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Sources
Domains Browser_Automation, Core_Utilities
Last Updated 2026-02-12 03:00 GMT

Overview

The Core Utilities module provides foundational utility functions used throughout the Taiko codebase, including type checking, assertions, timing primitives, retry logic, XPath escaping, and event listener management.

Description

This module is one of the most widely imported modules in the Taiko project. It originated from Puppeteer and has been adapted with additional Taiko-specific utilities. The module exports two categories of functionality:

The first is the Helper class (exported as a singleton instance helper), which provides project root resolution, event listener registration, and event listener cleanup. The projectRoot() method locates the Taiko package root by checking for the existence of package.json relative to the module's directory. The addEventListener/removeEventListeners pair provides a structured pattern for managing event subscriptions -- listeners are tracked as {emitter, eventName, handler} triples and can be bulk-removed later.

The second category consists of standalone utility functions for type checking (isString, isFunction, isObject, isRegex, isDate, isPromise, isStrictObject, isSelector, isElement), assertions (assert, assertType), timing (wait, sleep, waitUntil), and string processing (xpath escaping, handleUrlRedirection, commandlineArgs). The waitUntil function is particularly important as it implements the retry-with-timeout pattern used throughout Taiko for waiting on asynchronous conditions.

Usage

These utility functions are used across virtually every module in Taiko. Type-checking functions validate user inputs at API boundaries. The waitUntil function powers all wait-based operations (waiting for elements, navigation, network idle). The xpath function safely escapes strings containing quotes for use in XPath expressions. isSelector and isElement distinguish between Taiko selector objects and resolved element objects in polymorphic function signatures.

Code Reference

Source Location

Signature

// Helper class (exported as singleton instance `helper`)
class Helper {
  projectRoot() -> string
  addEventListener(emitter, eventName, handler) -> {emitter, eventName, handler}
  removeEventListeners(listeners) -> void
}

// Standalone functions
function assert(value, message) -> void
function assertType(obj, condition, message) -> void
function isFunction(functionToCheck) -> boolean
function isString(obj) -> boolean
function isObject(obj) -> boolean
function isRegex(obj) -> boolean
function isDate(obj) -> boolean
function isPromise(obj) -> boolean
function isStrictObject(obj) -> boolean
function wait(time) -> Promise<void>
function commandlineArgs() -> Object
function sleep(milliseconds) -> void
async function waitUntil(condition, retryInterval, retryTimeout, message) -> void
function xpath(s) -> string
function handleUrlRedirection(url) -> string
function isSelector(obj) -> boolean
function isElement(obj) -> boolean

Import

const {
  helper,
  assert,
  isFunction,
  isString,
  isObject,
  isDate,
  isRegex,
  isPromise,
  isStrictObject,
  wait,
  commandlineArgs,
  xpath,
  waitUntil,
  handleUrlRedirection,
  assertType,
  descEvent,
  isSelector,
  isElement,
} = require("./helper");

I/O Contract

assert(value, message)

Parameter Type Description
value any Value to test for truthiness.
message string Error message thrown if value is falsy.
Throws Condition
Error(message) When value is falsy.

assertType(obj, condition, message)

Parameter Type Default Description
obj any -- Value to validate.
condition Function isString Predicate function that returns boolean.
message string "String parameter expected" Error message thrown on failure.

waitUntil(condition, retryInterval, retryTimeout, message)

Parameter Type Description
condition Function Async function returning boolean. Polling stops when it returns true.
retryInterval number Milliseconds between retry attempts (uses busy-wait via sleep).
retryTimeout number Maximum milliseconds to keep retrying. If falsy, returns immediately.
message string Optional custom timeout error message.
Throws Condition
Error When timeout is exceeded. Uses either the last caught error or a default timeout message.
Error Immediately re-throws if the condition throws an error matching "Browser process with pid ... exited with".

xpath(s)

Parameter Type Description
s string Raw string to escape for safe use in XPath expressions.
Return Type Description
expression string XPath concat() expression that safely handles strings containing both single and double quotes.

Type Checking Functions

Function Returns true when
isFunction(obj) typeof obj === "function"
isString(obj) typeof obj === "string" or Object.prototype.toString includes "String"
isObject(obj) obj is truthy and typeof obj === "object" or toString includes "Object"
isRegex(obj) Object.prototype.toString includes "RegExp"
isDate(obj) obj is truthy and toString includes "Date"
isPromise(obj) obj is truthy and toString includes "Promise"
isStrictObject(obj) obj is truthy, typeof obj === "object", and constructor is Object
isSelector(obj) obj has both elements and exists properties, or has a selector property
isElement(obj) obj has both objectId and description properties

Algorithm

waitUntil Retry Loop

The waitUntil function implements a polling retry pattern:

const start = new Date().getTime();
while (true) {
  try {
    if (await condition()) break;    // Success: condition met
  } catch (e) {
    if (e.message.match(/Browser process.*exited/)) throw e;  // Fatal
    actualError = e;                  // Store for timeout reporting
  }
  if (new Date().getTime() - start > retryTimeout) {
    throw actualError || new Error(`waiting failed: retryTimeout ${retryTimeout}ms exceeded`);
  }
  sleep(retryInterval);              // Busy-wait between retries
}

Note that sleep uses a busy-wait loop (spinning on new Date().getTime()) rather than setTimeout. This is intentional to provide more predictable timing in the Node.js event loop, though it blocks the thread during the sleep interval.

XPath String Escaping

The xpath function splits the input string on quote boundaries and wraps each segment in the opposite quote type, then joins them with XPath concat():

  • Segments containing no quotes are wrapped in single quotes: 'segment'
  • Single-quote characters are wrapped in double quotes: "'"
  • Double-quote characters are wrapped in single quotes: '"'

This ensures any string -- even those containing both types of quotes -- can be safely embedded in an XPath expression.

handleUrlRedirection

Normalizes URLs for comparison by:

  1. Stripping trailing slash
  2. Removing www. prefix from the hostname

Usage Examples

// Type checking at API boundaries
const { isString, assertType } = require("./helper");
assertType(selector, isString, "Selector must be a string");

// Wait for an element to appear with retry
const { waitUntil } = require("./helper");
await waitUntil(
  async () => (await findElements("document.querySelector('#loaded')")).length > 0,
  100,   // retry every 100ms
  5000,  // timeout after 5 seconds
  "Element #loaded did not appear"
);

// Escape a string for XPath
const { xpath } = require("./helper");
const escaped = xpath("it's a \"test\"");
// => concat('it', "'", 's a ', '"', 'test', '"', "")

// Project root resolution
const { helper } = require("./helper");
const root = helper.projectRoot();
// => "/path/to/taiko"

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment