# @git.zone/tsrepo/tapbundle_serverside

> 🔧 Server-side testing utilities for Node.js runtime tests

## Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.

## Installation

```bash
# tapbundle_serverside is part of @git.zone/tsrepo
pnpm add -D @git.zone/tsrepo
```

This is the former `@git.zone/tstest/tapbundle_serverside` of tstest 8.0.0, unchanged apart from its import path; `@git.zone/tstest/tapbundle_serverside` now re-exports this module.

## Overview

`@git.zone/tsrepo/tapbundle_serverside` provides server-side testing utilities exclusively for Node.js runtime. These tools make it trivial to spin up test infrastructure — free ports, HTTPS certificates, ephemeral databases, S3 storage, a headless browser, shell commands, and environment variable management.

## Key Features

- 🌐 **Network Utilities** — Find free ports and port ranges for test servers
- 🔒 **HTTPS Certificates** — Generate self-signed certificates for testing
- 💻 **Shell Commands** — Execute bash commands during tests
- 🔐 **Environment Variables** — On-demand environment variable loading with qenv
- 🗄️ **MongoDB-Wire Testing** — Create ephemeral, memory-backed NoSQLDB nodes
- 📦 **S3 Storage Testing** — Create local S3-compatible storage
- 🖥️ **Browser Testing** — Launch a headless Chromium and drive it with puppeteer against your own test server
- 📁 **Test File Management** — Download and manage test assets

## Basic Usage

```typescript
import { tap, expect } from '@git.zone/tsrepo/tapbundle';
import { TapNodeTools } from '@git.zone/tsrepo/tapbundle_serverside';

// Create an instance and pass `tap` so cleanup is automatic
const tapNodeTools = new TapNodeTools(tap);

tap.test('should start server on free port', async () => {
  const port = await tapNodeTools.findFreePort();
  // start your server on `port`
});

export default tap.start();
```

### How cleanup works

`TapNodeTools` accepts any object with a `registerCleanup()` method (the `tap` instance). On construction, it registers a cleanup callback that stops long-lived background processes (e.g. the SmartNetwork Rust bridge, storage servers and browsers the helpers created). When `tap.start()` finishes running all tests, it calls all registered cleanup functions automatically, so the Node.js event loop can drain and the process exits cleanly.

## API Reference

### TapNodeTools

Construct with a `tap` instance to enable automatic cleanup:

---

### 🌐 Network Utilities

#### `findFreePort(options?)`

Find a single free port on the local machine.

```typescript
// Default: random free port in range 3000–60000
const port = await tapNodeTools.findFreePort();

// Custom range
const port = await tapNodeTools.findFreePort({
  startPort: 8000,
  endPort: 9000,
});

// With exclusions and sequential scan
const port = await tapNodeTools.findFreePort({
  startPort: 3000,
  endPort: 60000,
  randomize: false,   // default: true
  exclude: [8080, 8443],
});
```

**Options:**
| Option | Type | Default | Description |
|---|---|---|---|
| `startPort` | `number` | `3000` | Start of port range (inclusive) |
| `endPort` | `number` | `60000` | End of port range (inclusive) |
| `randomize` | `boolean` | `true` | Pick a random port vs first available |
| `exclude` | `number[]` | `[]` | Ports to skip |

**Returns:** `Promise<number>` — Throws if no free port is found.

#### `findFreePorts(count, options?)`

Find multiple distinct free ports. Each found port is automatically excluded from subsequent searches, guaranteeing all returned ports are unique.

```typescript
const [httpPort, wsPort, adminPort] = await tapNodeTools.findFreePorts(3);

// With custom range
const ports = await tapNodeTools.findFreePorts(2, {
  startPort: 10000,
  endPort: 20000,
});
```

**Parameters:**
- `count` — Number of ports to find
- `options` — Same as `findFreePort()`

**Returns:** `Promise<number[]>` — Array of distinct free ports.

#### `findFreePortRange(count, options?)`

Find consecutive free ports (e.g., `[4000, 4001, 4002]`). Useful when you need a contiguous block.

```typescript
const ports = await tapNodeTools.findFreePortRange(3, {
  startPort: 20000,
  endPort: 30000,
});
// ports = [N, N+1, N+2] where all three are free
```

**Options:**
| Option | Type | Default | Description |
|---|---|---|---|
| `startPort` | `number` | `3000` | Start of search range |
| `endPort` | `number` | `60000` | End of search range |
| `exclude` | `number[]` | `[]` | Ports to skip |

**Returns:** `Promise<number[]>` — Array of consecutive free ports.

---

### 🔒 HTTPS Certificates

#### `createHttpsCert(commonName?, allowSelfSigned?)`

Generate a self-signed HTTPS certificate for testing secure connections.

```typescript
const { key, cert } = await tapNodeTools.createHttpsCert('localhost', true);

// Use with Node.js https module
const server = https.createServer({ key, cert }, handler);
server.listen(port);
```

**Parameters:**
- `commonName` (default: `'localhost'`) — Certificate common name
- `allowSelfSigned` (default: `true`) — Sets `NODE_TLS_REJECT_UNAUTHORIZED=0`

**Returns:** `Promise<{ key: string; cert: string }>` — an unencrypted PKCS#8 `PRIVATE KEY` PEM and a self-signed `CERTIFICATE` PEM (RSA-2048, SHA-256, subject and issuer `CN=<commonName>`, valid for 365 days from now, no subject alternative names).

---

### 💻 Shell Commands

#### `runCommand(command)`

Execute a bash command and return the result: `exitCode`, `stdout` and `stderr` as separate streams, `combinedOutput` with both in arrival order, and `timedOut`.

```typescript
const result = await tapNodeTools.runCommand('ls -la');
console.log(result.exitCode);
console.log(result.stdout);
console.log(result.stderr);
```

---

### 🔐 Environment Variables

#### `getQenv()`

Get the [qenv](https://code.foss.global/push.rocks/qenv) instance of the project under test: it reads `qenv.yml` from the working directory (when there is one; a missing file is accepted and its `required:` list is not enforced) and the env file `env.json`, `env.yml` or `env.yaml` from `.nogit/`.

```typescript
const qenv = await tapNodeTools.getQenv();
```

#### `getEnvVarOnDemand(envVarName)`

Read an environment variable through that qenv instance: the process environment first, then the `.nogit/` env file, systemd credentials and Docker secrets. It resolves to `undefined` when no source has the variable; it does not prompt and stores nothing.

```typescript
const apiKey = await tapNodeTools.getEnvVarOnDemand('GITHUB_API_KEY');
if (!apiKey) throw new Error('GITHUB_API_KEY is not set');
```

---

### 🗄️ Database Testing

#### `createSmartmongo()`

Create an ephemeral, single-node NoSQLDB instance with partial MongoDB wire-protocol compatibility. It is automatically started and ready to use.

[@push.rocks/smartmongo](https://code.foss.global/push.rocks/smartmongo) is an optional peer dependency of `@git.zone/tsrepo` (`^9.0.3`): tsrepo does not install it, so a project that uses this helper installs it itself:

```bash
pnpm install --save-dev @push.rocks/smartmongo
```

```typescript
const mongo = await tapNodeTools.createSmartmongo();
const { mongoDbUrl, mongoDbName } = await mongo.getMongoDescriptor(); // mongoDbUrl starts with mongodb://
// ... run database tests ...
await mongo.stop();
```

The helper returns an `ITapSmartmongo`, the started SmartMongo instance described by the members tests use (tsrepo's published types do not import smartmongo):

| Member | Description |
| --- | --- |
| `readyPromise` | Resolves once the instance has started; the helper starts it before it returns. |
| `getMongoDescriptor()` | The connection descriptor: `mongoDbUrl` (a `mongodb://` URL) and `mongoDbName`. |
| `stop()` | Stops the instance and cleans up after it. |
| `stopAndDumpToDir(dir, nameFunction?, emptyDir?)` | Like `stop()`, but stores the database on disk in `dir`. |

Without the package installed, the helper throws before loading anything:

```
TapNodeTools.createSmartmongo() needs @push.rocks/smartmongo, an optional peer dependency of @git.zone/tsrepo, and it is not installed. Install it in the project under test: pnpm install --save-dev @push.rocks/smartmongo
```

smartmongo uses memory-backed NoSQLDB storage. It downloads no MongoDB binary, does not provide replication or complete MongoDB API parity, and uses NoSQLDB binaries published for Linux and macOS on x64 and arm64.

---

### 📦 Storage Testing

#### `createObjectStorage()`

Create a local S3-compatible storage instance for testing.

This helper requires GNU/Linux on amd64 or arm64 with glibc 2.34 or later,
the matching dynamic loader, `libm.so.6` and `libgcc_s.so.1`. Musl-only
systems such as a default Alpine installation are unsupported by ObjectStorage 10.

```typescript
const s3 = await tapNodeTools.createObjectStorage();
// ... run storage tests ...
await s3.stop();
```

Default config: a port the operating system assigns when the server binds
(port 0), clean slate enabled in an independent private temporary directory for
each instance. Read the bound port from `s3.port` or the storage descriptor; no
other process can take it between choosing and binding. Uses
standalone [@lossless.org/objectstorage](https://code.foss.global/lossless.org/objectstorage)
10.5.0. `PutObject` and `CompleteMultipartUpload` honor `If-None-Match: *`:
conflicts return `412 PreconditionFailed` without replacing the existing object.
`ListParts` supports verifying multipart abort cleanup. Callers can await `stop()`
to close a server early. Helper cleanup waits for admitted creation and stops
remaining servers before removing its temporary directories. Failed cleanup
retains its resources for a later retry; new storage creation is rejected while
cleanup is running. Existing storage directories remain untouched. This helper
creates disposable test storage; it does not migrate production storage roots.

---

### 🖥️ Browser Testing

#### `createBrowser()`

Launch a headless Chromium and return its puppeteer
[`Browser`](https://pptr.dev/api/puppeteer.browser). Start your own server in a
`*.node.ts` test and drive the browser against it; pages, evaluation, reloads,
service workers and worker targets are the plain puppeteer API.

```typescript
import { tap, expect } from '@git.zone/tsrepo/tapbundle';
import { TapNodeTools, type TTapNodeBrowser } from '@git.zone/tsrepo/tapbundle_serverside';

const tapNodeTools = new TapNodeTools(tap);
let browser: TTapNodeBrowser;

tap.test('registers the service worker', async () => {
  // your test server listens on `port`
  browser = await tapNodeTools.createBrowser();
  const page = await browser.newPage();
  await page.goto(`http://127.0.0.1:${port}/`);
  await page.evaluate(async () => {
    await navigator.serviceWorker.register('/sw.js');
    await navigator.serviceWorker.ready;
  });
  await page.reload({ ignoreCache: true });
  const workerTarget = await browser.waitForTarget(
    (target) => target.type() === 'service_worker',
  );
  expect(workerTarget.url()).toEqual(`http://127.0.0.1:${port}/sw.js`);
});

export default tap.start();
```

**Returns:** `Promise<TTapNodeBrowser>` — the puppeteer `Browser`. The exported
`TTapNodeBrowser` type names it, so a test can type the handle without
depending on puppeteer itself.

The browser is launched through `getEnvAwareBrowserInstance()` from
`@push.rocks/smartbrowser/automation`
([@push.rocks/smartbrowser](https://code.foss.global/push.rocks/smartbrowser)):
it uses a `google-chrome`, `chromium` or `chromium-browser` binary from the
`PATH` and falls back to puppeteer's default browser when none is found, and it
disables the Chromium sandbox when `CI` is set or the tests run as root. Callers
can `close()` a browser early. Helper cleanup waits for launches that are still
starting and closes every browser that is still open, so the test process can
exit; new browser launches are rejected while cleanup is running.

---

### 📁 Test File Provider

#### `testFileProvider.getDockerAlpineImageAsLocalTarball()`

Download the Alpine Linux Docker image as a tarball for testing.

```typescript
const tarballPath = await tapNodeTools.testFileProvider.getDockerAlpineImageAsLocalTarball();
// Path: ./.nogit/testfiles/alpine.tar
```

## Runtime Requirements

⚠️ **Node.js only.** All utilities in this module require Node.js. Import only in `.node.ts` test files. Deno is unsupported and untested.

```
test/mytest.node.ts          ✅ Correct — Node.js only
test/mytest.ts               ✅ Correct — defaults to Node.js
test/mytest.all.ts           ❌ Will fail in Chromium and Bun
```

## Dependencies

- [@push.rocks/smartnetwork](https://code.foss.global/push.rocks/smartnetwork) — Port discovery
- [@push.rocks/qenv](https://code.foss.global/push.rocks/qenv) — Environment variable management
- [@push.rocks/smartshell](https://code.foss.global/push.rocks/smartshell) — Shell command execution
- [@push.rocks/smartcrypto](https://code.foss.global/push.rocks/smartcrypto) — Certificate generation
- [@push.rocks/smartmongo](https://code.foss.global/push.rocks/smartmongo) — Single-node NoSQLDB-backed MongoDB-wire testing; an optional peer dependency (`^9.0.3`) the project under test installs itself
- [@lossless.org/objectstorage](https://code.foss.global/lossless.org/objectstorage) — S3 storage testing
- [@push.rocks/smartbrowser](https://code.foss.global/push.rocks/smartbrowser) — Headless Chromium through puppeteer
- [@push.rocks/smartfile](https://code.foss.global/push.rocks/smartfile) — File operations
- [@push.rocks/smartrequest](https://code.foss.global/push.rocks/smartrequest) — HTTP requests

## License and Legal Information

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](../license.md) file.

**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

### Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

### Company Information

Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
