<h1 align="center">Optimizely Edge Delivery SDK</h1>

<p align="center">
  Optimizely Edge Delivery lets you execute Optimizely Web experiments on Cloudflare Workers.
  <br>
</p>

<hr>

## Prerequisites

- You must have a [Cloudflare Account](https://dash.cloudflare.com/sign-up/workers-and-pages).
- You must install the [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/).

## Implementing in an existing Worker

You can install the Optimizely Edge Delivery SDK in any existing Cloudflare Worker, whether you already route your incoming traffic through a Cloudflare Worker, or you'd prefer to start from scratch using Cloudflare's [getting started guide](https://developers.cloudflare.com/workers/get-started/guide/).

### Installing the Edge Delivery SDK

Install the Edge Delivery library using npm:

```bash 
npm install @optimizely/edge-delivery
```

### Implementing and executing experiments

The SDK accepts a config object `options`. All properties listed below are members of that object (e.g. `options.environment`). They are grouped by purpose.

#### Required

| Option | Type | Description |
| --- | --- | --- |
| `environment` | `'dev' \| 'prod'` | Defines the environment the worker runs in. Use `'dev'` to enable the local development URL options below. |

#### Experiment configuration

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `snippetId` | `string \| number` | — | The Snippet ID pointing to the generated Edge Delivery configuration file. |
| `accountId` | `number` | — | The Account ID, used when building snippet URLs (e.g. `cdn.optimizely.com/public/{accountId}/s/{snippetId}/web_sdk_v0.json`). |
| `DATA` | `string` | — | The JSON configuration file (as a string) used to execute your experiments. If omitted, it is fetched from `kvNamespace` using `snippetId` when both are provided. |
| `isProd` | `boolean` | `true` | Whether this is a production environment. |
| `isSnippetless` | `boolean` | `false` | Runs Edge Delivery in snippetless mode, injecting no snippet on the page. Only supports experiments with page-level transforms and no browser-level transforms, as it will not compile any browser JavaScript. |
| `useEdgeDeliverySnippet` | `boolean` | `false` | When `true`, injects the Edge Delivery snippet as a `<script>` tag loaded from the Optimizely CDN (along with the inline experiment results), instead of compiling and inlining the full browser JS. |

#### Snippet injection

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `nonce` | `string` | — | A nonce value for the injected snippet `<script>` tag. If not provided, it is derived from the control response's `Content-Security-Policy` header when available. |
| `position` | `string` | `'top'` | Where to place the injected snippet: `'top'` (prepend to `<head>`), `'bottom'` (append to `<body>`), or a CSS id selector starting with `#` (insert immediately after the matched element). |
| `existingSnippet` | `string` | `'keep'` | What to do if an existing snippet is found on the page. `keep`: leave it untouched.<br>`comment`: wrap it in an HTML comment.<br>`remove`: remove it entirely. |
| `fixCSPForOptimizely` | `boolean` | `false` | When `true`, augments the control response's `Content-Security-Policy` header with the directives Optimizely requires. |

#### Caching

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `cacheTTLs` | `object` | `0` | An object containing `dataTTL`, and `browserTTL` (in seconds). |
| `deployId` | `string` | `null` | Used when calculating the cache key. A cache HIT means the BrowserJS is cached and returned immediately. |

#### Error handling

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `fallback` | `string` | `null` | Behavior when the edge rewriter throws. `error`: throw the error (visible in worker logs) before proceeding to `snippet`.<br>`snippet`: return the web-snippet-injected page, bypassing Edge Delivery; if this fails, proceed to `null`.<br>`null`: return the original request. |

#### Advanced / integration

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `control` | `Response` | — | The response from the original page request, before any transformations are applied. See [Other configuration options](#other-configuration-options). |
| `rewriter` | `HTMLRewriter` | new `HTMLRewriter` | A custom `HTMLRewriter` instance to use for transformations. |
| `logLevel` | `'debug' \| 'info' \| 'warning' \| 'error'` | `'error'` | Internal worker log level. |

#### Local development (when `environment` is `'dev'`)

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `dev_host` | `string` | `example.com` | Target request host. |
| `dev_protocol` | `string` | `https` | Target request protocol. |
| `dev_port` | `string` | — | Target request port (e.g. `8080`). |
| `dev_pathname` | `string` | — | Target request pathname (e.g. `hello/world`). If not provided, the pathname of the current request is used. |

#### Webhook configuration

Both options are required for webhook processing.

| Option | Type | Description |
| --- | --- | --- |
| `kvNamespace` | `KVNamespace` | A Cloudflare KV namespace used to fetch the experiment `DATA` config (keyed by `snippetId`) and to persist webhook updates. |
| `webhookSecret` | `string` | Secret used to verify incoming webhook requests. |

#### Basic configuration options

It's recommended to set the development URL options (`dev_host`, and optionally `dev_protocol`/`dev_port`/`dev_pathname`) so the SDK has a target when testing locally or against your worker site directly. These only apply when `environment` is `'dev'`.

```typescript
const options = {
    "environment": "dev",
    "snippetId": "29061560280",
    "dev_host": "example.com"
};
```

#### applyExperiments

The `applyExperiments` method is used to execute experiments. This method uses the request information to make experiment bucketing decisions and apply active experiment variations to the control. Any decisions or changes that cannot be made on the edge are packaged together and added to the `<head>` element for execution on the browser.

```typescript
import { applyExperiments } from '@optimizely/edge-delivery';
...
await applyExperiments(request, ctx, options);
```

#### Other configuration options

Optionally, you may pass a Response object as the control in the `options` parameter. This can be useful if you already have an existing Cloudflare Worker that, for example, makes modifications to the control outside of Optimizely experiments. 

```typescript
let control = await fetch(request);
...
const options: Options = {
    // Other options
    "control": control
};
```
