> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hyperprobe.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK Setup Guide

> Install, initialize, and optimize the HyperProbe Node.js SDK inside in-process Node applications.

The HyperProbe Node.js SDK runs as an extremely lightweight in-process agent. It hooks directly into the V8 Virtual Machine inspector layer to execute non-blocking debugging, variable captures, metrics, and log injection in **microseconds**.

***

## Technical Prerequisites

* **Runtime:** Node.js 18 and later.
* **Metadata:** Access to the active git commit SHA (mandatory for matching local source coordinates to production builds).
* **Source Maps:** Mandatory for transpiled or bundled projects (TypeScript, Esbuild, Webpack).

***

## Installation

Add the SDK as a dependency using your package manager:

<CodeGroup>
  ```bash npm theme={null}
  npm install @hyperprobe/node-sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @hyperprobe/node-sdk
  ```

  ```bash yarn theme={null}
  yarn add @hyperprobe/node-sdk
  ```
</CodeGroup>

***

## 🗺️ Configuring Source Maps for Transpilers

If your project is transpiled or bundled, **source maps are strictly mandatory** for the SDK agent to translate compiled bytecode coordinates back to your local source files.

<Tabs>
  <Tab title="TypeScript (tsconfig.json)">
    Ensure `"sourceMap": true` is enabled in your compiler options:

    ```json tsconfig.json theme={null}
    {
      "compilerOptions": {
        "sourceMap": true,  // Must be true
        "outDir": "./dist",
        "rootDir": "./src"
      }
    }
    ```
  </Tab>

  <Tab title="Esbuild">
    Pass the `--sourcemap` flag inside your CLI build command, or set `sourcemap: true` in your build script API:

    ```javascript build.js theme={null}
    import esbuild from 'esbuild';

    esbuild.build({
      entryPoints: ['src/index.ts'],
      bundle: true,
      sourcemap: true, // Must be true (generates *.js.map)
      outdir: 'dist',
    });
    ```
  </Tab>

  <Tab title="Webpack">
    Set the `devtool` option inside your `webpack.config.js` to compile standard external source maps:

    ```javascript webpack.config.js theme={null}
    module.exports = {
      entry: './src/index.ts',
      devtool: 'source-map', // Must be 'source-map'
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
      },
    };
    ```
  </Tab>
</Tabs>

***

## Initialization Walkthrough

Follow these steps to initialize the HyperProbe agent inside your application:

<Steps>
  <Step title="Create your initialization file">
    Create a dedicated file named `hyperprobe.ts` (or `hyperprobe.js`) inside your project source root. Select your module syntax below:

    <Tabs>
      <Tab title="TypeScript / ES Modules (hyperprobe.ts)">
        ```typescript src/hyperprobe.ts theme={null}
        import { HyperProbe } from '@hyperprobe/node-sdk';

        HyperProbe.start({
          serviceId: '<service-uuid-from-dashboard>',
          environment: process.env.NODE_ENV, // Your environment name (e.g. dev, staging, production). Use whatever variable contains the env value.
          brokerUrl: 'https://logger.app.hyperprobe.co',
          commitSha: process.env.GIT_COMMIT, // CI-injected commit SHA (reads process.env.GIT_COMMIT by default)
          distLocation: 'dist',              // Output directory name (e.g. 'dist' or 'build')
          sourceMapDir: './dist'             // Directory containing your *.js.map source map files
        });
        ```
      </Tab>

      <Tab title="CommonJS (hyperprobe.js)">
        ```javascript src/hyperprobe.js theme={null}
        const { HyperProbe } = require('@hyperprobe/node-sdk');

        HyperProbe.start({
          serviceId: '<service-uuid-from-dashboard>',
          environment: process.env.NODE_ENV, // Your environment name (e.g. dev, staging, production). Use whatever variable contains the env value.
          brokerUrl: 'https://logger.app.hyperprobe.co',
          commitSha: process.env.GIT_COMMIT, // CI-injected commit SHA (reads process.env.GIT_COMMIT by default)
          distLocation: 'dist',              // Output directory name (e.g. 'dist' or 'build')
          sourceMapDir: './dist'             // Directory containing your *.js.map source map files
        });
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Import it in your entrypoint">
    In your main application entrypoint (e.g., `index.ts`, `server.ts`, or `app.js`), import your newly created `./hyperprobe` module **as early as possible** before starting your web server:

    <CodeGroup>
      ```typescript src/index.ts (ES Modules / TypeScript) theme={null}
      import './hyperprobe.js'; // Import as early as possible
      import express from 'express';

      const app = express();
      ...
      ```

      ```javascript src/index.js (CommonJS) theme={null}
      require('./hyperprobe.js'); // Import as early as possible
      const express = require('express');

      const app = express();
      ...
      ```
    </CodeGroup>

    <Warning>
      **Environment Variables Loading Order:** You should import `./hyperprobe` as early as possible. However, if you are configuring parameters inside `hyperprobe.ts` that rely on environment variables (such as those loaded via `dotenv`), ensure that you import/initialize `./hyperprobe` **after your environment configuration loader has run completely**, if needed.
    </Warning>
  </Step>

  <Step title="Configure your Dockerfile">
    To enable Docker-based deployments, define a `GIT_COMMIT` build argument inside your `Dockerfile` with a default value of `unknown`.

    This ensures that existing local builds or developers' environments do not fail if they do not yet pass a build argument—safely fallback-disabling the HyperProbe agent until a valid SHA is injected:

    ```dockerfile Dockerfile theme={null}
    # Define build argument with 'unknown' fallback to protect non-CI builds
    ARG GIT_COMMIT=unknown
    ENV GIT_COMMIT=${GIT_COMMIT}
    ```
  </Step>

  <Step title="Run local Docker builds">
    For building and testing Docker containers locally on your laptop, inject your active git head using standard command line arguments:

    ```bash theme={null}
    docker build --build-arg GIT_COMMIT=$(git rev-parse HEAD) -t api:latest .
    ```
  </Step>

  <Step title="Inject correct SHA in CI/CD (The PR Merge Trap)">
    To protect alignment, HyperProbe refuses to start if `commitSha` resolves to `"unknown"`. Map your CI/CD platform's built-in commit SHA environment variable to `GIT_COMMIT` at deployment.

    Always use your CI/CD engine's native environment variables to pass the real commit SHA:

    | Platform / Engine         | Configuration Option             | Build Argument Syntax                                                              |
    | :------------------------ | :------------------------------- | :--------------------------------------------------------------------------------- |
    | **GitHub Actions**        | PR-Safe HEAD Check (Recommended) | `--build-arg GIT_COMMIT=${{ github.event.pull_request.head.sha \|\| github.sha }}` |
    | **GitHub Actions (Push)** | Standard Branch Push             | `--build-arg GIT_COMMIT=${{ github.sha }}`                                         |
    | **GitLab CI/CD**          | GitLab Variable                  | `--build-arg GIT_COMMIT=$CI_COMMIT_SHA`                                            |
    | **CircleCI**              | CircleCI Variable                | `--build-arg GIT_COMMIT=$CIRCLE_SHA1`                                              |
    | **PM2 / Systemd**         | Native Linux CLI                 | `GIT_COMMIT=$(git rev-parse HEAD) pm2 start dist/app.js`                           |

    <Warning>
      **⚠️ Beware of the PR Merge Commit Trap:**
      By default, GitHub Actions checking out on a `pull_request` trigger checkout a **virtual merge commit** (testing how your branch merges into `main`) instead of the actual branch commit you pushed.

      If you run `git rev-parse HEAD` or use `${{ github.sha }}` inside a PR workflow, **coordinate mapping will fail** because your local VS Code environment is pointing to your actual branch head.

      To bypass this, always configure GitHub Actions on PRs to use:
      `${{ github.event.pull_request.head.sha || github.sha }}`
    </Warning>
  </Step>
</Steps>

***

## ⚙️ Configuration & Environment Variables Reference

You can configure the agent by passing properties inside your `HyperProbe.start()` options object, or by overriding them using **environment variables**.

The code block below illustrates a complete initialization containing all available options, along with their default values and corresponding **`HYPERPROBE_*` environment variables** which can override them:

```typescript src/hyperprobe.ts theme={null}
import { HyperProbe } from '@hyperprobe/node-sdk';

HyperProbe.start({
  // --- CORE OPTIONS ---
  serviceId: '<service-uuid-from-dashboard>',   // Env: HYPERPROBE_SERVICE_ID
  environment: process.env.NODE_ENV,             // Env: HYPERPROBE_ENVIRONMENT
  brokerUrl: 'https://logger.app.hyperprobe.co',
  commitSha: process.env.GIT_COMMIT,             // Env: GIT_COMMIT (Mandatory)

  // --- BUFFERING & PERFORMANCE ---
  maxQueueSize: 100,      // Env: HYPERPROBE_MAX_QUEUE_SIZE      - Cap on telemetry stored in memory
  flushIntervalMs: 1000,  // Env: HYPERPROBE_FLUSH_INTERVAL_MS   - Milliseconds before draining the queue
  syncIntervalMs: 60000,  // Env: HYPERPROBE_SYNC_INTERVAL_MS    - Sync cycle to fetch new active probes

  // --- SAFETY GUARDRAILS ---
  hitsPerSec: 10,         // Env: HYPERPROBE_HITS_PER_SEC         - Global limit on triggers per second
  bandwidthKbPerSec: 1024,// Env: HYPERPROBE_BANDWIDTH_KB_PER_SEC - Throughput cap in Kilobytes/sec
  maxLagMs: 80,           // Env: HYPERPROBE_MAX_LAG_MS          - Cooldown triggers if loop lag exceeds this (ms)
  pauseBudgetMs: 30,      // Env: HYPERPROBE_PAUSE_BUDGET_MS     - Max cumulative CPU overhead allowed per second (ms)
  cooldownSec: 10,        // Env: HYPERPROBE_COOLDOWN_SEC        - Duration (in seconds) the agent remains dormant after entering cooldown

  // --- DATA SOURCE MAPS ---
  distLocation: 'dist',   // Env: HYPERPROBE_DIST_LOCATION       - Compiled code folder name
  sourceMapDir: './dist', // Env: HYPERPROBE_SOURCE_MAP_DIR       - Directory containing *.js.map files
  appRoot: '',            // Env: HYPERPROBE_APP_ROOT            - Subdirectory path in monorepos

  // --- DATA & REDACTION CONTROLS ---
  redactKeys: [           // Env: HYPERPROBE_REDACT_KEYS (comma-separated list, e.g. HYPERPROBE_REDACT_KEYS=password,secret,token,ssn,cvv)
    'password', 'secret', 'token', 'authorization', 'cookie', 'key', 'signature'
  ],                      // Blacklisted keys are completely stripped and replaced with [REDACTED] in-process
  redactValues: [],       // Env: HYPERPROBE_REDACT_VALUES (comma-separated list) of literal strings to redact
  maxObjectDepth: 3,      // Env: HYPERPROBE_MAX_OBJECT_DEPTH     - Max nested properties serialized
  maxArrayLength: 3,      // Env: HYPERPROBE_MAX_ARRAY_LENGTH     - Max elements serialized per array
  maxObjectProperties: 50,// Env: HYPERPROBE_MAX_OBJECT_PROPERTIES - Max key-value parameters recorded per object
  maxStringLength: 1024,  // Env: HYPERPROBE_MAX_STRING_LENGTH    - Max character count before string truncation
  stackFrameDepth: 3,     // Env: HYPERPROBE_STACK_FRAME_DEPTH    - Number of call stack frames captured per snapshot
});
```

<Tip>
  **Environment Variable Precedence:** Any environment variable specified (e.g. setting `HYPERPROBE_HITS_PER_SEC=5` inside your server environment) will **automatically override** the code-level option passed to `HyperProbe.start()`.
</Tip>
