npm package: @nazar-pasha/automation-lib
Description: Automation Library
Author: Nazar Pashazade
Latest version: 1.0.6

# Introduction

automation-lib makes browser automation traceable, debuggable, and observable at scale.

It is built for automation frameworks where every step — clicking, typing, navigating, validating — must produce consistent logs, snapshots, and failure reports.

Key features:

- Step-by-step execution wrapper

- Automatic success & failure snapshots

- Azure Storage integration

- Azure Service Bus logging

- Optional custom error handling

- Clean, declarative step definitions

- Azure Application Insights telemetry integration (events, traces, exceptions)

<br>

# Getting Started

## 1. Installation

```bash
npm install @nazar-pasha/automation-lib
```

<br>

## 2. Initialize the Library (Required)

Call init() once before running any automation steps. This connects the library to Azure Storage + Service Bus.

```js
const { init } = require("@nazar-pasha/automation-lib");

init({
  BLOB_STORAGE_CONNECTION_STRING: "...",
  BLOB_STORAGE_CONNECTION_STRING: "...",
  SERVICE_BUS_QUEUE_NAME: "...",
  SERVICE_BUS_CONNECTION_STRING: "...",
  APP_INSIGHTS_CLOUD_ROLE_NAME: "...",
  APP_INSIGHTS_CONNECTION_STRING: "...",
});
```

### Configuration Parameters

| Key                            | Description                                          |
| ------------------------------ | ---------------------------------------------------- |
| BLOB_STORAGE_CONTAINER_NAME    | Azure Storage container where snapshots are uploaded |
| BLOB_STORAGE_CONNECTION_STRING | Azure Storage connection string                      |
| SERVICE_BUS_QUEUE_NAME         | Azure Service Bus queue name for failed-step logs    |
| SERVICE_BUS_CONNECTION_STRING  | Azure Service Bus connection string                  |
| APP_INSIGHTS_CLOUD_ROLE_NAME   | Application Insights role name               |
| APP_INSIGHTS_CONNECTION_STRING | Application Insights connection string               |

<br>

## Library Overview

The library exposes four main functions:

### ✔️ `init(config)`

Initializes Azure Storage + Service Bus settings for logging and snapshot handling.

### ✔️ `executeStep(options)`

Wraps a single automation action (click, type, navigate, evaluate, etc.) inside a structured logging layer with automatic snapshot and error handling.

### ✔️ `getAppInsightsInstance()`

The library includes an Application Insights helper that returns a ready-to-use telemetry client. It reads configuration from init()

### ✔️ `getConfig()`

Returns the configuration previously set via `init()`.

<br>

## 🔹 `executeStep(options)`

### **Purpose**

- Standardize how automation steps are executed
- Automatically capture **pass** and **failure** snapshots
- Push structured logs to Azure Service Bus
- Allow optional custom error handling
- Keep steps consistent across all automation scripts

### **API Definition**

```ts
interface ExecuteStepOptions {
  stepName: string;
  page: any;
  storyboardId: string;
  actionFn: Function;
  selector?: string;
  additionalInfo?: object;
  expectNavigation?: boolean;
  onError?: Function;
}
```

<br>

## 🔹 Basic Usage Example

```js
const { executeStep } = require("@nazar-pasha/automation-lib");

await executeStep({
  storyboardId: "12345",
  stepName: "Click Login Button",
  page,
  selector: "#login-btn",
  expectNavigation: true,
  actionFn: async () => {
    const btn = await page.waitForSelector("#login-btn");
    await btn.click();
  },
});
```

<br>

## 🔹 Custom Error Handling

```js
await executeStep({
  storyboardId: STORYBOARD_ID,
  stepName: "Login - Enter Username",
  page,
  actionFn: async () => {
    const el = await page.waitForSelector(selectors.homepage.email);
    await el.type(credentials.userName, { delay: 125 });
  },
  onError: (err, log) => {
    console.error("Custom Error Handler:", err.message);
    throw err; // rethrow to keep default behavior
  },
});
```

### **Output Example**

```
Custom Error Handler: waiting for selector `#email` failed: timeout 30000ms exceeded
```

<br>

## Azure Service Bus – Example Payload

When a step fails, the following JSON payload is sent:

```json
{
  "storyboardId": "123e9078975b098094567e89b",
  "stepName": "Click Anwendungen",
  "sourceURL": "https://example.com/login",
  "selector": "/html/body/div[2]/div[2]/div[3]/a",
  "failureReason": "waiting for XPath `/html/body/div[2]/a` failed: timeout 30000ms exceeded",
  "lastPassedSnapshotURL": "https://example.com/snapshots/LastPassedSnapshot.html",
  "failureSnapshotURL": "https://example.com/snapshots/FailureSnapshot.html",
  "failedCodeSnippet": "const el = await page.waitForXPath(selectors.portalView.anwendungen);\nawait el.click()",
  "additionalInfo": {}
}
```

<br>

## Build & Test

```bash
npm install
npm test
```

## 🔹 `getAppInsightsInstance()`

### **Purpose**

- safe API for logging events, traces, and exceptions.
- Returns an initialized Application Insights instance using: (APP_INSIGHTS_CONNECTION_STRING, APP_INSIGHTS_CLOUD_ROLE_NAME)

### **API Definition**

- `trackEvent(name, properties?, metrics?)` Tracks a custom event.
- `trackTrace(message, properties?, severity?)` Tracks a trace message (defaults to Information) and flushes automatically.
- `trackException(error, properties?, metrics?)` Tracks an exception with optional metadata.
- `flush()` Flushes pending telemetry immediately.

```js
const { getAppInsightsInstance } = require("@nazar-pasha/automation-lib");

const ai = getAppInsightsInstance();

ai.trackEvent("AutomationStarted", { storyboardId: "12345" });

await ai.trackTrace("Navigating to login page", {
  storyboardId: "12345",
  url: "https://example.com/login",
});

try {
  // ... your automation code
} catch (err) {
  ai.trackException(err, { storyboardId: "12345", stepName: "Login" });
  throw err;
} finally {
  ai.flush();
}
```

<br>