# Errors and source maps

Visibling groups errors into issues by type and normalized stack, symbolicates minified frames with the source maps you upload, and stitches each occurrence into the affected user's support timeline.

## Browser errors

The browser client captures uncaught errors and unhandled promise rejections by default. Disable that with `captureUnhandledErrors: false`, or report handled errors yourself:

```ts
import { visibling } from "./visibling";

try {
  await submitPayment(order);
} catch (error) {
  visibling.captureException(error, { orderId: order.id, step: "payment" });
  throw error;
}
```

`captureException` sends the error type, message, stack, and the current 20-item breadcrumb trail. Browser errors arrive with `errorSource: "browser"` and `errorLevel: "error"`. Add breadcrumbs around the actions that lead to a failure:

```ts
visibling.addBreadcrumb("checkout", "selected payment method", { method: "card" });
```

Breadcrumbs are capped at 20 entries, each with a 64-character category, a 512-character message, and a small data object.

## Worker errors with a Tail Worker

A Tail Worker observes every invocation of a producer Worker, healthy or not. `@visibling/sdk/tail` filters to failures (uncaught exceptions, any outcome other than `ok`, and HTTP 5xx) and forwards just those to Visibling as `cf_issues` error items. Raw Workers Logs are never re-stored.

```ts
// tail/src/index.ts — a separate Worker
import type { TraceItem } from "@visibling/sdk/tail";
import { createVisiblingTailHandler } from "@visibling/sdk/tail";

interface Env {
  VISIBLING_SERVER_KEY: string;
}

export default {
  async tail(events: readonly TraceItem[], env: Env): Promise<void> {
    const handler = createVisiblingTailHandler({
      serverKey: env.VISIBLING_SERVER_KEY,
      ingestUrl: "https://visibling.com/api/v1/ingest",
    });
    await handler.tail(events);
  },
};
```

```jsonc
// tail/wrangler.jsonc — the Tail Worker itself
{
  "name": "my-app-tail",
  "main": "src/index.ts",
  "compatibility_date": "2025-09-02"
}
```

```jsonc
// the producer Worker's wrangler.jsonc
{
  "tail_consumers": [{ "service": "my-app-tail" }]
}
```

```sh
wrangler secret put VISIBLING_SERVER_KEY --config tail/wrangler.jsonc
```

Set `ingestUrl` to your Visibling origin. When both Workers live in the same Cloudflare account, you can pass a Service Binding instead of a URL:

```ts
import type { VisiblingTailServiceBinding } from "@visibling/sdk/tail";

interface Env {
  VISIBLING_SERVER_KEY: string;
  VISIBLING: VisiblingTailServiceBinding;
}

export default {
  async tail(events, env: Env) {
    await createVisiblingTailHandler({
      serverKey: env.VISIBLING_SERVER_KEY,
      serviceBinding: env.VISIBLING,
    }).tail(events);
  },
};
```

```jsonc
{
  "services": [
    {
      "binding": "VISIBLING",
      "service": "visibling-web",
      "entrypoint": "VisiblingIngestEntrypoint"
    }
  ]
}
```

`createVisiblingTailHandler` throws when the key is not a `vis_srv_` key, and requires `ingestUrl` when no `serviceBinding` is configured. Tail failures are logged and swallowed so the producer Worker is never affected, and one failed partition never drops the rest.

Rethrow errors from your `fetch` handler when you want them grouped. A caught-and-swallowed exception is invisible to a Tail Worker.

## Cloudflare Workers Issues webhook

Cloudflare Notifications can push Workers Issues alerts to Visibling. Create a webhook destination that posts to:

```text
POST https://visibling.com/api/webhooks/cf-issues
x-visibling-key: vis_srv_your_project_server_key
content-type: application/json
```

The endpoint accepts only a **server** key (`vis_srv_`), requires the `INGEST_QUEUE` binding, and answers `202 Accepted` with `{"ok":true,"accepted":1}` once the alert is queued. The webhook normalizes the alert envelope tolerantly: title, error type, message, stack, request URL, `cf-ray`, trace id, release, environment, and timestamp are read when present, and every value is bounded before it reaches the queue.

Failures are retryable: `401` for a missing or invalid key, `403` for a non-server key, `413` for a payload over 64 KB, `429` with `Retry-After: 60` for rate limiting, and `500` when queueing fails. Cloudflare's at-least-once delivery can then retry.

## Source maps

Visibling stores source maps in R2 and symbolicates an error's stack when the occurrence is processed. Upload one `.map` file per request with a `vis_map_` key.

### 1. Build with source maps

If you are using Vite:

```ts
// vite.config.ts
export default defineConfig({
  build: { sourcemap: true },
});
```

Keep the map files until the upload step; do not serve them from your production origin unless you intend to.

### 2. Create a source map key

In **Project settings → Keys**, create a **source map** key. It starts with `vis_map_` and is shown once. Store it in CI as a secret, for example `VISIBLING_MAP_KEY`.

### 3. Upload each map

The release version must match the `release` label your client and proxy attach to events (for example a git SHA or a release tag), and `filename` must match the path embedded in the stack frames. Upload paths relative to the served root, such as `assets/app.js.map`; lookup also falls back to the bare basename, so a flattened upload still resolves.

```sh
VERSION="$(git rev-parse --short HEAD)"

find dist -name '*.map' -print0 | while IFS= read -r -d '' map; do
  filename="${map#dist/}"
  encoded="$(node -p 'encodeURIComponent(process.argv[1])' "$filename")"
  curl --fail-with-body -sS -X POST \
    "https://visibling.com/api/v1/releases/${VERSION}/sourcemaps?filename=${encoded}" \
    -H "x-visibling-key: ${VISIBLING_MAP_KEY}" \
    -H "content-type: application/json" \
    --data-binary "@${map}"
done
```

A successful upload answers `200`:

```json
{
  "ok": true,
  "sourcemap": { "key": "sourcemaps/<project>/<version>/assets/app.js.map", "bytes": 183420 },
  "release": { "version": "a1b2c3d", "sourcemapCount": 4, "sourcemapBytes": 921334 }
}
```

Re-uploading the same version and filename replaces the stored object and adjusts the byte counters rather than double-counting.

### Limits and validation

- The body must be a JSON source map object with `version: 3` and a string `mappings`.
- One file is capped at 10 MB.
- `version` is capped at 100 characters and cannot contain `/` or `\`.
- `filename` is capped at 200 characters; absolute paths, backslashes, empty segments, `.` and `..` segments, and control characters are rejected.
- The organization's plan source map budget is enforced: 50 MB on Free, 500 MB on Starter, and 5 GB on Growth. Self-hosted deployments have no byte cap.
- Status codes: `400` for an invalid version, filename, or map; `401` for a missing or revoked key; `403` when the key is not a `vis_map_` key; `413` for an oversized file or exhausted storage; `429` with `Retry-After: 60` for rate limiting; `500` for transient storage failures.

If no map matches a frame's file name, the frame stays minified in the issue detail; the raw stack and the rest of the occurrence are still stored.

## How errors become issues

On receipt, Visibling fingerprints errors by type and normalized stack, upserts the issue, records the occurrence, and links it to the user (`distinctId`, falling back to `anonId`). A first sighting opens the issue; a resolved issue that fires again regresses. The issue detail page shows the symbolicated stack, breadcrumbs, request context, affected users, and a deep link to Cloudflare Workers Observability when the project has a Cloudflare token configured.
