# @convertics/script

Lightweight visitor analytics + identify script for Convertics. Ships as an
npm package and as a single minified IIFE file for dropping straight into a
page via `<script>` (e.g. served from the `convertics` R2 bucket / a CDN in
front of it).

## Usage

### As an npm package

```ts
import { init } from "@convertics/script";

const convertics = init("your-public-key");
```

### As a `<script>` tag

```html
<script src="https://scripts.convertics.ai" data-public-key="your-public-key"></script>
```

That's it — no second script block needed. On load, the script reads the
`data-public-key` attribute off its own `<script>` tag (via
`document.currentScript`, or by matching `script[data-public-key]` if that's
unavailable), caches it, and calls `init()` automatically.

If you need to call `init()` yourself (e.g. from an npm import, or to grab
the returned instance for manual tracking / identify), the IIFE build
exposes a `Convertics` global:

```html
<script src="https://scripts.convertics.ai" data-public-key="your-public-key"></script>
<script>
  // Auto-init already ran off `data-public-key` above — this is only needed
  // if you want the returned instance (e.g. to call `.identify()`).
  const convertics = Convertics.init("your-public-key");

  // Once you know who the visitor is (e.g. after login/checkout), attach
  // their email or phone to the anonymous visitor record already tracked:
  convertics.identify("email", "person@example.com");
</script>
```

Calling `init()` explicitly on a page that also auto-initialized starts a
second, independent tracking instance — don't do both.

### API

`init(publicKey: string, options?: InitOptions)` immediately sends a
page-view beacon and keeps tracking client-side route changes in
single-page apps by patching `history.pushState`/`replaceState` and
listening for `popstate`/`hashchange`. It returns:

```ts
{
  // With no arguments, manually record a page view (e.g. after a navigation autoTrack can't
  // see). With an eventName, record a custom product event instead - never deduped, unlike a
  // page view - e.g. track("signup_clicked", { plan: "pro" }).
  track: (eventName?: string, properties?: Record<string, unknown>) => void;
  identify: (key: "email" | "phone", value: string) => Promise<void>; // attach an identifier to the current visitor
  visitorId: () => string | undefined; // id for checkout metadata; also the `_convertics_visitor_id` cookie
}
```

```ts
interface InitOptions {
  type?: "website" | "extension"; // defaults to "website" - see "Adding the tracking script to a Chrome extension" below
  surface?: "content-script" | "popup" | "options" | "devtools" | "unknown"; // only meaningful when type is "extension"
}
```

```ts
// Identify a visitor once you know who they are (e.g. after login/checkout)
convertics.identify("email", "person@example.com");

// Record a custom product event, e.g. from a click handler
convertics.track("signup_clicked", { plan: "pro" });
```

Each page-view beacon carries `public_key`, an anonymous `visitor_id`
(persisted in `localStorage`), the current path, referrer/UTM params, and an
AES-encrypted fingerprint payload. `init({ type: "extension" })` also sends
`context: "extension"`, the surface (`content-script`, `popup`, `options`,
`devtools`), the Chrome extension id, the manifest version, and the page host
(`location.hostname`). Harbor stores those on the event so a project can
count website and extension traffic separately, and can filter by version.
It's sent with `navigator.sendBeacon` to
`${VITE_HARBOR_URI}/events/visitor`. A custom `track(eventName, properties)`
call reuses the same beacon, just carrying an event name and a JSON
`properties` object instead of always being a page view. `identify()` posts
to `${VITE_HARBOR_URI}/events/update` via `fetch`.

### Sending events from your backend

To record an event from your own server (e.g. `purchase_completed` after a
webhook fires) rather than the browser, POST directly to Harbor's
authenticated ingestion endpoint instead of using the npm package:

```
POST ${VITE_HARBOR_URI}/events/track
Content-Type: application/json
x-api-key: <your project's secret key>

{
  "public_key": "your-public-key",
  "visitor_id": "12345",              // OR "email"/"phone" below - all optional
  "email": "person@example.com",
  "event_name": "purchase_completed",
  "properties": { "amount": 49.0, "currency": "usd" }
}
```

- `x-api-key` is your project's own secret key (distinct from
  `public_key`, which is safe to expose client-side) — find it in your
  project settings.
- Pass `visitor_id` if you already have it (e.g. returned from a prior
  `/events/visitor` call), or `email`/`phone` if the visitor was previously
  identified via `identify()` — Harbor looks up the matching visitor by that
  hint. An event with none of these is still recorded, just not tied to a
  particular visitor.
- Unlike the public browser routes, `/events/track` requires no `Origin`
  header — it's meant for server-to-server calls.

`VITE_HARBOR_URI` must be set at build time — this package only builds and
sends the beacon; wiring up a receiving endpoint (Harbor) is out of scope
here.

## Adding the tracking script to a website

Below are drop-in examples for common setups. Swap in your real project id
and CDN URL. Unless noted, `init()` is only needed if you want to call
`.identify()` later — the `data-public-key` attribute alone is enough for
page-view tracking.

### Plain HTML

```html
<!doctype html>
<html>
  <head>
    <script src="https://scripts.convertics.ai" data-public-key="your-public-key"></script>
  </head>
  <body>
    ...
  </body>
</html>
```

### Vue.js

Add the tag to `public/index.html` (Vue CLI) or `index.html` at the project
root (Vite):

```html
<!-- index.html -->
<head>
  <script src="https://scripts.convertics.ai" data-public-key="your-public-key"></script>
</head>
```

Or install the package and init from your app entry (`src/main.ts`):

```ts
import { init } from "@convertics/script";
import { createApp } from "vue";
import App from "./App.vue";

init("your-public-key");
createApp(App).mount("#app");
```

### Nuxt.js

Use Nuxt's `app.head` config in `nuxt.config.ts` so the tag is rendered on
every page (Nuxt 3):

```ts
// nuxt.config.ts
export default defineNuxtConfig({
  app: {
    head: {
      script: [{ src: "https://scripts.convertics.ai", "data-public-key": "your-public-key" }],
    },
  },
});
```

Or, for manual `init()`/`identify()` access, add a client-side plugin:

```ts
// plugins/convertics.client.ts
import { init } from "@convertics/script";

export default defineNuxtPlugin(() => {
  const convertics = init("your-public-key");
  return { provide: { convertics } };
});
```

### Next.js

Use `next/script` in your root layout (App Router) so it loads after the
page is interactive:

```tsx
// app/layout.tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script src="https://scripts.convertics.ai" data-public-key="your-public-key" strategy="afterInteractive" />
      </body>
    </html>
  );
}
```

Pages Router equivalent goes in `pages/_app.tsx` with the same `<Script>`.

### Svelte / SvelteKit

Add the tag to `src/app.html`, inside `<head>`:

```html
<!-- src/app.html -->
<head>
  %sveltekit.head%
  <script src="https://scripts.convertics.ai" data-public-key="your-public-key"></script>
</head>
```

Or, from the npm package in `src/routes/+layout.svelte`:

```svelte
<script>
  import { onMount } from "svelte";
  import { init } from "@convertics/script";

  onMount(() => {
    init("your-public-key");
  });
</script>

<slot />
```

### WordPress

Without a plugin, add it via **Appearance → Theme File Editor → header.php**
(or a child theme) just before `</head>`:

```php
<script src="https://scripts.convertics.ai" data-public-key="your-public-key"></script>
</head>
```

If you'd rather not edit theme files, use a "header/footer scripts" plugin
(e.g. Insert Headers and Footers) and paste the same `<script>` tag into
its "Scripts in Header" field.

### Wix

Wix doesn't allow editing raw HTML `<head>` directly, but you can inject
custom code from the dashboard:

1. Go to **Settings → Custom Code** (or **Marketing & SEO → Tracking & Analytics** on newer sites).
2. Click **Add Custom Code**, paste:
   ```html
   <script src="https://scripts.convertics.ai" data-public-key="your-public-key"></script>
   ```
3. Set it to load on **All pages**, in the **Head** section, and choose
   **Load once** so it's not re-injected on every route change.

## Adding the tracking script to a Chrome extension

Manifest V3's "no remote code" policy means an extension can't load the
CDN-hosted `<script src="...">` build the way a website does — the script
has to be bundled into the extension itself. Install the npm package and
call `init()` with `{ type: "extension" }` from whichever surface(s) you
want tracked:

Register your extension's id in your project settings first (the same
allowlist role `domains` plays for a website) — a popup/options/devtools
page's own origin is `chrome-extension://<extension-id>`, and the backend
rejects calls from an id it doesn't recognize for your project. Find your
id at `chrome://extensions` (with Developer Mode on) once the extension is
loaded, or in the Chrome Web Store dashboard for a published one.

```sh
pnpm add @convertics/script
```

```ts
import { init } from "@convertics/script";

init("your-public-key", { type: "extension" });
```

Passing `type: "extension"` changes two things versus the website path
described above:

- **Identity storage.** Cookies/`localStorage`/IndexedDB are scoped to
  whatever _site_ a content script happens to be injected into, so using
  them would fragment one visitor's id per-site instead of giving one id
  shared across all your extension's surfaces. With `type: "extension"`,
  the visitor id is stored in `chrome.storage.local` instead — extension-
  scoped, shared by every surface below, and requires the `"storage"`
  permission in `manifest.json`.
- **Lifecycle.** Popups and devtools panels can close within a fraction of
  a second of opening, often before an `unload` event gets a chance to
  fire. For those surfaces the script also flushes a beacon on
  `visibilitychange` turning `"hidden"`, so a quick open-and-close still
  gets tracked.
- **Source.** The beacon is stored as an extension event, with the surface,
  extension id, manifest version, and page host, separate from website page
  views on the same project. Content-script events use the site's hostname
  so the dashboard can list the sites the extension ran on.
- **Installs and uninstalls.** The first `init({ type: "extension" })` on
  that browser records one install. Later page views and extension updates
  do not count again. A reinstall does, because Chrome clears extension
  storage on uninstall. The same call sets the uninstall URL, and refreshes
  it once the visitor id exists. Chrome only allows that URL from an
  extension page, so call `init` from the popup, options page, or devtools
  panel as well as the content script. `"storage"` is the only permission
  this needs.

### Uninstall redirect

Chrome keeps only one uninstall URL per extension, and Convertics sets it to
record the uninstall. If you have your own goodbye or feedback page, give it
to Convertics instead: the uninstall is recorded first, then the user is sent
on to your page.

```ts
import { init, setUninstallRedirect } from "@convertics/script";

init("your-public-key", {
  type: "extension",
  uninstallRedirect: "https://your-site.com/bye",
});

// Later, e.g. after sign-in, when the page needs to know who left:
await setUninstallRedirect(`https://your-site.com/bye?uid=${user.uid}`);

// After sign-out, go back to the init() value:
await setUninstallRedirect(null);
```

- **Convertics must be the only code calling `chrome.runtime.setUninstallURL`.**
  Remove your own call and pass your page through `uninstallRedirect` /
  `setUninstallRedirect` instead. Whichever call runs last wins, so keeping
  yours either stops uninstalls being recorded or drops your page.
- Only absolute `https://` URLs are accepted. Anything else is ignored.
- The page's host must be one of your project's registered domains (the same
  list used for website tracking), or Convertics shows its own plain page
  instead of redirecting.
- The value is kept in `chrome.storage.local`, so it is shared by every
  surface and survives service worker restarts. A `setUninstallRedirect`
  value wins over the `init()` option until you pass `null`.
- Chrome rejects uninstall URLs longer than 1023 characters. If your page
  would push it past that, the uninstall is still recorded but the user is
  not redirected, so keep the URL short.

Supported surfaces — content script, popup, options page, devtools panel:

### Content script

Runs against the page it's injected into, so it's tracked exactly like a
website page view (including SPA route changes via the same
`pushState`/`hashchange` patching). The surface is auto-detected.

```json
// manifest.json
{
  "manifest_version": 3,
  "permissions": ["storage"],
  "content_scripts": [
    {
      "matches": ["https://your-site.com/*"],
      "js": ["content-script.js"],
      "run_at": "document_start"
    }
  ]
}
```

```ts
// content-script.ts, bundled to content-script.js
import { init } from "@convertics/script";

init("your-public-key", { type: "extension" });
```

### Popup / options page

Both are plain extension-owned HTML pages, so bundle the same call into
whichever entry script `popup.html` / `options.html` loads. The surface is
auto-detected (`popup` vs. `options`) — no `surface` option needed.

```json
// manifest.json
{
  "manifest_version": 3,
  "permissions": ["storage"],
  "action": { "default_popup": "popup.html" },
  "options_page": "options.html"
}
```

```ts
// popup.ts / options.ts
import { init } from "@convertics/script";

init("your-public-key", { type: "extension" });
```

### Devtools panel

Devtools panel pages don't get a reliable in-page signal to distinguish
themselves from other extension pages, so pass `surface: "devtools"`
explicitly:

```ts
// panel.ts, the page passed to chrome.devtools.panels.create()
import { init } from "@convertics/script";

init("your-public-key", { type: "extension", surface: "devtools" });
```

## Development

```sh
pnpm dev      # vite dev server (dev harness at index.html)
pnpm build    # tsc + vite build -> dist/index.es.js, dist/index.iife.js, dist/index.d.ts
```
