# `@hamur/scripts`

The first-party module for third-party scripts: analytics, tag managers, chat widgets, maps. It gives every adapter `useScript` and a `Script` component that load a script once per page session, after hydration by default, with a status the page can read. Every tag is added by `injectScript` of `hamur/app`, so it carries the page's CSP nonce and passes Trusted Types. Add it to `modules`.

```ts
// hamur.config.ts
import scripts from "@hamur/scripts"

export default defineConfig({
  modules: [scripts],
})
```

```tsx
import { useScript } from "@hamur/scripts/react"

export default function Page() {
  const widget = useScript("https://cdn.example.com/widget.js")
  return <p>{widget.status}</p>
}
```

### `default`

The module, as `defineModule({ meta: { name: "scripts", configKey: "scripts", hooks: ["scripts:registry"] } })`. Its setup adds a client app plugin that tells the triggers when the app mounted and starts the scripts an html server render recorded. With `scripts.registry`, `scripts.globals`, `scripts.defaultScriptOptions` or `scripts.debug` set it also adds the app plugin that sets the defaults and loads those scripts on every page, before the client app plugin. With `scripts.bundle` in a build, the first of its app plugins hands the app `#hamur/scripts/bundled`, the table of first-party copies (below).

**Hook `scripts:registry`.** `(entries: Record<string, ScriptRegistryEntry>) => void | Promise<void>`, once in `modules:done`, with the built-in entries by name; a module adds an entry or replaces one by assigning its name, with `from` set to the module that default-exports it (an absolute path, as `createResolver(import.meta.url).resolve("./runtime/widget.ts")` gives, or a package specifier), which the client imports when `scripts.registry` names the entry. A value that is not an entry fails the build with `scripts:registry: entries["bad"] must be a registry entry { name, schema, script, use, trigger, hosts }`; an added entry that `scripts.registry` names without `from` fails with `scripts.registry.custom names an entry added by scripts:registry without from; set from to the module that default-exports it, which the client imports`, and a relative `from` with `scripts:registry: entries["custom"].from "./x.ts" must be an absolute path or a package specifier`.

### `ScriptsOptions`, `ScriptsRegistryOptions`, `ScriptConfigTrigger`, `ScriptRegistryInputs`

The `scripts` config key: `{ registry?: ScriptsRegistryOptions; globals?: ScriptsGlobalsOptions; defaultScriptOptions?: ScriptDefaultOptions; bundle?: string[]; bundleFallback?: boolean; privacy?: PrivacyFlags; debug?: boolean }`. `ScriptsRegistryOptions` maps each registry name (the `useScript<Name>` with a lower-case first letter, typed by `ScriptRegistryInputs`) to the entry's input or `[input, { trigger?: ScriptConfigTrigger; privacy?: PrivacyFlags }]` (`privacy`: the collection proxy's flags for this entry, below), with `ScriptConfigTrigger` `"client" | "server" | "manual"` (a promise is not data). Each entry so named loads on every page through an app plugin, with its own trigger unless the tuple names one.

```ts
// hamur.config.ts
import scripts from "@hamur/scripts"

export default defineConfig({
  modules: [scripts],
  scripts: {
    registry: {
      plausibleAnalytics: { domain: "example.com" },
      googleAnalytics: [{ id: "G-ABCDEF1234" }, { trigger: "manual" }],
    },
  },
})
```

The inputs are written to `runtimeConfig.public.scripts.registry.<name>`; the inputs and the trigger are the build's. The client bundle holds only the configured entries' files, so a build that configures Plausible alone ships no other vendor's code.

| Config                                                                 | Fails the build with                                                                                                                          |
| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `scripts: { theme: 1 }`                                                | `scripts.theme is not an option; use registry, globals, defaultScriptOptions, bundle, bundleFallback, privacy, debug`                         |
| `registry: { foo: {} }`                                                | `scripts.registry key "foo" is not a registry script; use one of googleAnalytics, googleTagManager, plausibleAnalytics, … or scripts.globals` |
| `registry: { googleAnalytics: { id: "UA-1" } }`                        | `scripts.registry.googleAnalytics.id "UA-1" is not a GA4 measurement id (G-XXXXXXXXXX)`                                                       |
| `registry: { plausibleAnalytics: {} }`                                 | `scripts.registry.plausibleAnalytics.domain is required`                                                                                      |
| `registry: { googleAnalytics: [{ id: "G-1" }, { trigger: "later" }] }` | `scripts.registry.googleAnalytics[1].trigger "later" is not "client", "server" or "manual"`                                                   |

### `ScriptsGlobalsOptions`

`scripts.globals`: `Record<string, string | [input: string | ScriptInput, options?: { trigger?: ScriptConfigTrigger }]>`, scripts loaded on every page by name, through the same app plugin as `scripts.registry`. A name is letters and digits starting with a letter, and is not also a `scripts.registry` name. A global loads once for the page session, whatever the pages and navigations; its key is the input's `key ?? src`, so a `useScript` of the same URL shares its instance. Without a trigger it takes `defaultScriptOptions.trigger`, else `"client"`.

```ts
// hamur.config.ts
import scripts from "@hamur/scripts"

export default defineConfig({
  modules: [scripts],
  scripts: {
    globals: {
      support: "https://cdn.example.com/widget.js",
      chat: [{ src: "https://chat.example.com/loader.js", defer: true }, { trigger: "manual" }],
    },
  },
})
```

Each global is written to `runtimeConfig.public.scripts.globals.<name>` as `{ src, … }` (the tuple's input, without the trigger, which is the build's).

| Config                                                                                         | Fails the build with                                                                                                                                    |
| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `globals: { a: 5 }`                                                                            | `scripts.globals.a must be a URL or [input, options] (got 5)`                                                                                           |
| `globals: { a: "a.js" }`                                                                       | `scripts.globals.a "a.js" must be an absolute http or https URL, or start with "/"`                                                                     |
| `globals: { a: [{ src: "/a.js", nonce: "x" }] }`                                               | `scripts.globals.a[0].nonce is not a script attribute; use src, async, defer, type, nomodule, integrity, crossorigin, referrerpolicy, key or data-*`    |
| `globals: { a: ["/a.js", { trigger: "later" }] }`                                              | `scripts.globals.a[1].trigger "later" is not "client", "server" or "manual"`                                                                            |
| `globals: { "chat-widget": "/a.js" }`                                                          | `scripts.globals key "chat-widget" must be letters and digits, starting with a letter`                                                                  |
| `registry: { clarity: … }, globals: { clarity: "/a.js" }`                                      | `scripts.globals.clarity is also a scripts.registry name; a name loads one script`                                                                      |
| `globals: { a: "/a.js", b: "/a.js" }` (or one `key`)                                           | `scripts.globals.b loads "/a.js", as scripts.globals.a does; a script is loaded once, under one name`                                                   |
| `registry: { plausibleAnalytics: … }, globals: { stats: "https://plausible.io/js/script.js" }` | `scripts.globals.stats loads "https://plausible.io/js/script.js", as scripts.registry.plausibleAnalytics does; a script is loaded once, under one name` |

### `ScriptDefaultOptions`

`scripts.defaultScriptOptions`: `{ trigger?: ScriptConfigTrigger; warmupStrategy?: false | WarmupStrategy; crossorigin?: "anonymous" | "use-credentials" | false }`, the defaults of every `useScript`, `Script` and global; a call's own option wins, and a registry entry's own trigger counts as the call's. A default `trigger` or `warmupStrategy` changes every `useScript` and `Script` in the app that sets none, including those of components and modules written without it in mind. `crossorigin` applies to a call whose input sets none, before the cross-origin default. A wrong value fails the build: `scripts.defaultScriptOptions.warmupStrategy "now" is not false, "preload", "preconnect" or "dns-prefetch"`, `scripts.defaultScriptOptions.trigger "later" is not "client", "server" or "manual"`, `scripts.defaultScriptOptions.crossorigin "x" is not "anonymous", "use-credentials" or false`, and an unknown key `scripts.defaultScriptOptions.use is not an option; use trigger, warmupStrategy, crossorigin`.

**`scripts.bundle`, `scripts.bundleFallback`.** `scripts.bundle: string[]` lists third-party files that `hamur build` serves from the app's own origin: an `https:` URL, or the name of a registry entry with `bundle: true` that `scripts.registry` configures, whose URL the build computes from that input (`bundle: ["plausibleAnalytics"]`). The entries that allow it are `googleAnalytics`, `googleTagManager`, `plausibleAnalytics`, `umamiAnalytics`, `cloudflareWebAnalytics`, `metaPixel`, `segment`, `mixpanel`, `leaflet`, `maplibre` and `npm`. In `build:before` each URL is downloaded once (5 MiB at most, 30 s, redirects only to `https:` URLs), kept in `<cacheDir>/scripts/<SHA-256 of the URL>.js`, which never expires (`rm -r <cacheDir>/scripts` renews it; `hamur build --force` does not), and emitted with `emitFile` as `<stem>-<8 hex>.js` below `app.buildAssetsDir`, served `immutable`. `useScript`, `Script`, globals and registry scripts whose `src` is such a URL load the copy with `integrity="sha384-…"` and without the cross-origin defaults, on the server and in the browser; no call changes. Served from `app.cdnURL`, the copy gets `crossorigin` (`app.crossOrigin`, else `"anonymous"`), which its integrity check needs there. `hamur dev` bundles nothing. A copy is a snapshot: the vendor's update reaches the app when the cache is renewed.

```ts
// hamur.config.ts
import scripts from "@hamur/scripts"

export default defineConfig({
  modules: [scripts],
  scripts: {
    registry: { plausibleAnalytics: { domain: "example.com" } },
    bundle: ["plausibleAnalytics", "https://cdn.example.com/widget.js"],
  },
})
```

A failed download fails the build with `scripts.bundle "https://cdn.example.com/widget.js": could not download (503)` (or the reason: `timed out after 30 s`, `larger than 5 MiB`, `redirected to http://…, which is not https`); with `bundleFallback: true` the build logs `[scripts] could not bundle https://cdn.example.com/widget.js: 503; the remote URL is used` and keeps the remote URL.

| Config                                                           | Fails the build with                                                                                              |
| ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `bundle: ["http://x.test/a.js"]`                                 | `scripts.bundle[0] "http://x.test/a.js" must be an https URL or a registry name`                                  |
| `bundle: ["nope"]`                                               | `scripts.bundle[0] "nope" is not a URL or a registry name that can be bundled`                                    |
| `bundle: ["googleAnalytics"]` without `registry.googleAnalytics` | `scripts.bundle[0] "googleAnalytics" needs scripts.registry.googleAnalytics, whose input gives its URL`           |
| `bundle: ["plausibleAnalytics"]` with an `http:` `apiHost`       | `scripts.bundle[0] "plausibleAnalytics" gives "http://stats.example.com/js/script.js", which is not an https URL` |
| `bundleFallback: 1`                                              | `scripts.bundleFallback must be a boolean (got 1)`                                                                |

An empty body or an HTML page answered with 200 counts as a failed download (`200, an empty body`, `200, an HTML page`) and is not cached. An `integrity` that a global or a registry script of the config gives for a bundled URL must match the downloaded file, else the build fails with `scripts.bundle "https://cdn.example.com/widget.js": the downloaded file does not match the integrity "sha384-…"`, with or without `bundleFallback`. An `integrity` a `useScript` call gives wins over the copy's, and a different one logs `[scripts] https://cdn.example.com/widget.js has integrity "sha384-…", not the bundled copy's "sha384-…"; the given one is used, so the browser refuses a copy it does not match`. When an environment variable gives a bundled global or registry script another URL, that URL loads remotely and the server logs once `[scripts] https://cdn.example.com/widget.js is bundled but the configured script now loads https://cdn.example.com/widget-v2.js; the remote URL is used`.

**`scripts.debug`.** `true` logs each status change of a script with `console.info` in the browser under `hamur dev`: `[scripts] /widget.js: awaitingLoad -> loading` (the script's key; a registry entry's is its name). A build for production logs nothing. Another value fails the build with `scripts.debug must be a boolean (got "yes")`.

### `PrivacyFlags`, `ScriptProxy`

**The collection proxy.** An entry with `proxy` that `scripts.registry` names gets the route `<baseURL>_hamur/scripts/p/<vendor>/**` for `GET`, `POST` and `HEAD`, which forwards to the entry's first `upstream` origin with the request's path and query below `<vendor>`: the request never names the host. Its copy in `scripts.bundle` is rewritten by the entry's `rewrite` pairs before its SHA-384, so the integrity matches the served file, and its `data-*` values that start with a pair's `from` (Plausible's `data-api`, Umami's `data-host-url`) get the pair's `to`. The built-in entries with it are `googleAnalytics` (`ga`), `plausibleAnalytics` (`plausible`), `umamiAnalytics` (`umami`) and `mixpanel` (`mixpanel`). The route is public; an app that cares rate-limits it.

```ts
// hamur.config.ts
import scripts from "@hamur/scripts"

export default defineConfig({
  modules: [scripts],
  scripts: {
    registry: { googleAnalytics: [{ id: "G-ABCDEF1234" }, { privacy: { language: false } }] },
    bundle: ["googleAnalytics"],
    privacy: { ip: true },
  },
})
```

`PrivacyFlags` is `{ ip?; userAgent?; language?; screen?; timezone?; hardware? }`, each a boolean; a flag left out is off. Each entry has a default tier (`proxy.privacy`: all six for `googleAnalytics` and `mixpanel`, none for `plausibleAnalytics` and `umamiAnalytics`); a flag `scripts.privacy` gives replaces the tier's, and a flag of the entry's `[input, { privacy }]` replaces both.

| Flag        | What reaches the vendor                                                                                                                                                            |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ip`        | the client address (`getRequestIP`, so `server.requestIP` decides) in `x-forwarded-for` as IPv4 /24 (`203.0.113.0`) or IPv6 /48 (`2001:db8:85a3::`); without it, the whole address |
| `userAgent` | `user-agent` as the family and major version (`Chrome/128`, `Other` for one it does not know); the parameters `params.userAgent` names are removed                                 |
| `language`  | `accept-language` and the named parameters as the primary tag (`en`)                                                                                                               |
| `screen`    | the named parameters with each number rounded to hundreds (`1920x1080` → `1900x1100`)                                                                                              |
| `timezone`  | a minute offset rounded to the hour; a zone name removed                                                                                                                           |
| `hardware`  | the named parameters removed                                                                                                                                                       |

`cookie`, `authorization` and every other header stay behind: only `accept`, `content-type`, `dnt` and `sec-gpc` pass as sent. The answer carries no `set-cookie`. `ScriptProxy` is `{ vendor: string; upstream: string[]; privacy: PrivacyFlags; params: Partial<Record<keyof PrivacyFlags, string[]>>; rewrite?: Array<[string, string]> }`; a name in `params` is a query parameter, a JSON body's dotted path, or a parameter of a body of `a=1&b=2` lines; `rewrite` defaults to each upstream origin to the route.

| Request                                                         | Answer (text)                                                                  |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| a vendor no configured entry proxies                            | 404 `scripts: no collection proxy for "foo"`                                   |
| `PUT`, …                                                        | 405 `scripts: method not allowed`                                              |
| an empty, `.` or `..` segment, or an escaped slash or backslash | 400 `scripts: "//evil.example/x" is not a collection path`                     |
| a body above `server.maxBodySize`                               | 413 `scripts: request body is larger than server.maxBodySize`                  |
| the vendor answers 5xx or a redirect (never followed)           | 502 `scripts: ga answered 500`                                                 |
| no answer, or one above 1 MiB                                   | 502 `scripts: ga could not be reached`, `scripts: ga answered more than 1 MiB` |
| no answer in 10 s                                               | 504 `scripts: ga timed out after 10 s`                                         |

On a static preset the proxy is not built, the copy is not rewritten, and the build logs `[scripts] the collection proxy needs a server preset`. A wrong flag fails the build: `scripts.privacy.ip must be a boolean (got "yes")`, `scripts.privacy.cookie is not a flag; cookie and authorization are always removed`, `scripts.privacy.fonts is not a flag; use ip, userAgent, language, screen, timezone, hardware`.

### `HamurScripts`, `UseScripts`, `ScriptRegistryApis`

`useScripts()` returns `UseScripts<S> = { readonly [Name in keyof HamurScripts]?: UseScript<HamurScripts[Name], S> }`. `HamurScripts` is empty in the package; `.hamur/types/scripts.d.ts` adds each `scripts.globals` and `scripts.registry` name, a built-in registry entry with its SDK type from `ScriptRegistryApis` (the `Api` type of each entry by its config key, as `ScriptRegistryInputs` has its input) and any other name as `unknown`. Each name is optional, as an environment variable can drop it.

### `ScriptRegistryEntry`, `ScriptRegistryConsent`, `ScriptRegistryOptions`

A registry script: one file under `src/registry/` default-exporting a `ScriptRegistryEntry<I, T>`.

| Member                  | What                                                                                                                                                                                                                                                                                                 |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`                  | the config key, `"googleAnalytics"`                                                                                                                                                                                                                                                                  |
| `schema`                | a Standard Schema of the input `I`, written by Hamur; an issue's message starts with its key, so the error reads `scripts: googleAnalytics.id "UA-1" is not …` at run time and `scripts.registry.googleAnalytics.id …` in the config. An unknown key fails with `<key> is not an option; use <keys>` |
| `script(input)`         | the `ScriptInput`: the URL and its attributes (`data-domain`, …); its `key` defaults to `name`                                                                                                                                                                                                       |
| `setup?(input, window)` | in the browser, once per page session before the tag is added: a dataLayer, a queue function                                                                                                                                                                                                         |
| `use(input)`            | the SDK once loaded, `T`: what `proxy` replays against and `load()` resolves to                                                                                                                                                                                                                      |
| `trigger`               | the default trigger: `"client"`, `"server"` or `"manual"`                                                                                                                                                                                                                                            |
| `hosts`                 | the hosts the script and its requests reach: what a `server.csp` without `strict-dynamic` lists in `script-src` and `connect-src`                                                                                                                                                                    |
| `bundle?`               | `true` when `scripts.bundle` may name the entry: its file works served from the app's origin                                                                                                                                                                                                         |
| `consent?(input)`       | a `ScriptRegistryConsent` `{ default(window), accept(categories, window), revoke(window) }`, used when the trigger is `useScriptTriggerConsent`'s object or a `for(category)` of it                                                                                                                  |
| `proxy?`                | a `ScriptProxy` (below): the app forwards the script's collection requests                                                                                                                                                                                                                           |
| `from?`                 | an entry `scripts:registry` adds: the module that default-exports it (an absolute path or a package specifier), which the client imports when `scripts.registry` names it; a built-in entry has none                                                                                                 |

`ScriptRegistryOptions<T>` is `UseScriptOptions<T>` without `use`: the second argument of `useScript<Name>`.

### `ScriptInput`

`string | ScriptInput` is the first argument of `useScript`; a string is the `src`.

| Key                    | Type                                        | Default                                                                                                                               |
| ---------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `src`                  | `string`                                    | required: an absolute `http` or `https` URL, or a path starting with `/`                                                              |
| `key`                  | `string`                                    | `src`: the name of the one instance of the session                                                                                    |
| `async`                | `boolean`                                   | `true`                                                                                                                                |
| `defer`, `nomodule`    | `boolean`                                   | unset                                                                                                                                 |
| `type`                 | `string`                                    | unset (`"module"`, …)                                                                                                                 |
| `integrity`            | `string`                                    | unset: written as given                                                                                                               |
| `crossorigin`          | `"anonymous" \| "use-credentials" \| false` | `"anonymous"` for a cross-origin `src` (an absolute URL or one starting with `//`); `false` writes none                               |
| `referrerpolicy`       | `ReferrerPolicy`                            | `"no-referrer"` for a cross-origin `src`                                                                                              |
| `` `data-${string}` `` | `string`                                    | written on the tag as given (`"data-domain": "example.com"`); `data-hamur-script` is the module's own and is not taken from the input |

A missing `src` throws `scripts: src must be a non-empty string (got undefined)`, a relative one `scripts: "a.js" must be an absolute http or https URL, or start with "/"`.

### `UseScriptOptions`, `ScriptTrigger`, `WarmupStrategy`

`{ trigger?: ScriptTrigger; use?: () => T | undefined; warmupStrategy?: false | WarmupStrategy }`, with `WarmupStrategy` `"preload" | "preconnect" | "dns-prefetch"`. `use` returns the SDK once loaded (`() => window.gtag`): `load()` resolves to it and `onLoaded` gets it.

`warmupStrategy` writes one `<link rel="<strategy>" fetchpriority="low">` in the server's head, with the key `hamur-script-warmup:<key>` so any number of callers write one. It defaults to `"preload"` for the `"client"` trigger and `false` for the others. `preload` writes `as="script"` and `href="<src>"` with the script's `crossorigin` and `integrity`, so the browser reuses it for the tag: the SSR head of `useScript("https://x.test/a.js")` has `<link rel="preload" as="script" href="https://x.test/a.js" crossorigin="anonymous" fetchpriority="low">`. `preconnect` (with the script's `crossorigin`) and `dns-prefetch` take the origin of `src` only, and `preconnect` to the app's own origin, which a relative `src` always is, writes nothing. Another value throws `scripts: warmupStrategy must be false, "preload", "preconnect" or "dns-prefetch" (got "now")`.

| `trigger`            | The tag is added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `"client"` (default) | in the browser, after the app mounted (hydration done) and the first idle callback (`requestIdleCallback` with a 2000 ms timeout; `setTimeout(…, 1)` where there is none)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `"server"`           | in the server's head, before the entry script, through `useServerHead`, with `data-hamur-script="<key>"`; the document writes the request's nonce on it. After hydration the browser adopts that tag by the Resource Timing entry of its URL: `loaded` when the entry ended with a status under 400 (or `use()` has a value), `error` for any other entry (the fetch finished without a load; a later `load()` adds a fresh tag), and with no entry yet `loading` until its `load` or `error` event. The tag is never replaced while it may still run. A page the server did not render (a client navigation) has no such tag, and the script loads as `"client"` |
| `"manual"`           | when `load()` is called                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| a `Promise`          | when it resolves; a rejection leaves it `awaitingLoad`. The trigger helpers below return one                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |

Another value throws `scripts: trigger must be "client", "server", "manual" or a Promise (got "later")`.

### `ScriptStatus`

`"awaitingLoad" | "loading" | "loaded" | "error" | "removed"`. A script starts `awaitingLoad` (`loading` with `"server"`), is `loading` once its tag is added, then `loaded` on its `load` event or `error` on its `error` event; `remove()` makes it `removed`. `load()` after `removed` or `error` adds the tag again. On the server it never changes: the server records and adds nothing.

### `ScriptActions`, `UseScript`

What `useScript` returns, `UseScript<T, S> = ScriptActions<T> & { readonly status: S; readonly proxy: T }`, with `S` the library's form of `ScriptStatus`:

| Member               | What                                                                                                                                                                                                                                        |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`             | React and Preact `ScriptStatus` (the component re-renders), Vue `Readonly<Ref<ScriptStatus>>`, Svelte `{ readonly current: ScriptStatus }`, Solid `Accessor<ScriptStatus>`, html `{ get(): ScriptStatus; subscribe(callback): () => void }` |
| `proxy`              | `T`, the SDK type `use` declares; see below                                                                                                                                                                                                 |
| `load()`             | adds the tag now; resolves to `use()`'s value once loaded (at once when it is), the same promise while `loading`; rejects with `scripts: "/s.js" failed to load`, or `scripts: "/s.js" was removed before it loaded`                        |
| `remove()`           | removes the tag for every caller and sets `removed`; `false` when there was no tag                                                                                                                                                          |
| `reload()`           | `remove()`, then `load()`: a loaded script runs again. While `loading` it is `load()`, so an in-flight file is not added twice                                                                                                              |
| `onLoaded(callback)` | at once when loaded, and on each later load; returns its remover                                                                                                                                                                            |
| `onError(callback)`  | at once when the script already failed, and on each later failure; returns its remover                                                                                                                                                      |
| `warmup(strategy)`   | adds the `<link>` of `"preload"`, `"preconnect"` or `"dns-prefetch"` to `document.head` now (a facade calls it on hover); once per strategy, not again when the server already wrote that link, and a no-op on the server                   |
| `dispose()`          | drops the callbacks this caller registered; the script stays                                                                                                                                                                                |

**`proxy`.** With `useScript<Gtag>(src, { use: () => window.gtag as Gtag })`, `proxy.gtag("event", "x")` type-checks against `Gtag`. A call at any depth (`proxy.a.b.c()`) made while the script is `awaitingLoad` or `loading` is recorded; when it loads, the calls run against `use()`'s value in order, once, with the SDK object as `this`. After `loaded` a call goes straight to the SDK and returns its value; before, it returns `undefined`. On the server a call is a no-op. When the script errors or is removed the queue is dropped, nothing throws, and the calls that follow are no-ops until a later `load()`. A replayed call that throws is logged in development (`[scripts] proxy call "gtag" threw: <message>`) and does not stop the rest. The queue holds 1000 calls: past that the oldest is dropped, with one development warning `[scripts] the proxy queue holds 1000 calls and the script has not loaded; the oldest calls are dropped`. A property read gives a proxy before load, and after load the SDK's value for anything but an object or a function; `then`, `toJSON` and symbols read as `undefined`, so `await proxy` does not wait. All callers of one key share one queue.

**One instance per key.** `useScript` calls of one `key ?? src` share one instance for the page session (per request on the server), so two components calling `useScript("/s.js")` add one `<script>`. The same key with another `src` throws `scripts: key "chat" is used for "https://a.test/a.js" and "https://b.test/b.js"; a key names one script`. The callbacks of a caller end with its component (React and Preact on unmount, Vue with the component's scope, Svelte on destroy, Solid with the owner); in html, a call made while a page renders in the browser keeps its callbacks until the next navigation starts.

### `ScriptTriggerIdleTimeoutOptions`, `ScriptTriggerInteractionOptions`, `ScriptElementTrigger`, `ScriptTriggerElementOptions`

The arguments of the trigger helpers (below).

| Type                                                    | Shape                                                                                                                       |
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `ScriptTriggerIdleTimeoutOptions`                       | `{ timeout?: number }`: milliseconds, default `3000`                                                                        |
| `ScriptTriggerInteractionOptions<Target = EventTarget>` | `{ events?: string[]; target?: Target }`: `events` defaults to `["scroll", "pointerdown", "keydown"]`, `target` to `window` |
| `ScriptElementTrigger`                                  | `"visible" \| "mouseover" \| string[]`: the names of the events on the element                                              |
| `ScriptTriggerElementOptions<El>`                       | `{ trigger: ScriptElementTrigger; el: El }` with `el` the library's element ref                                             |

### `ScriptConsent`, `ScriptTriggerConsentOptions`, `PostConsentTrigger`

The consent object and the options of `useScriptTriggerConsent` (below).

| Type                                           | Shape                                                                                                                                                                                |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ScriptConsent`                                | a `Promise<void>` (a trigger, resolved by `accept()`) with `accept(categories?: true \| Record<string, boolean>): void`, `revoke(): void` and `for(category: string): Promise<void>` |
| `ScriptTriggerConsentOptions<Consent = never>` | `{ consent?: Promise<boolean> \| Consent; postConsentTrigger?: PostConsentTrigger }` with `Consent` the library's reactive boolean                                                   |
| `PostConsentTrigger`                           | `"onIdle" \| Promise<unknown>`: what the load waits for after consent                                                                                                                |

### `ScriptPage`

What `useScriptEventPage` (below) hands its callback.

| Type         | Shape                                                                                                              |
| ------------ | ------------------------------------------------------------------------------------------------------------------ |
| `ScriptPage` | `{ title: string; path: string }`: `document.title` and `location.pathname + location.search` after the navigation |

### `FacadeTriggerName`, `YouTubeFacadeProps`, `VimeoFacadeProps`, `MapsFacadeProps`, `IntercomFacadeProps`, `CrispFacadeProps`, `LatLng`

The props of the facade components below besides the slots and `trigger`, which each adapter types in its own idiom.

| Type                  | Shape                                                                                                               |
| --------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `FacadeTriggerName`   | `"click" \| "visible" \| "mouseover"`                                                                               |
| `YouTubeFacadeProps`  | `{ videoId: string; title?: string; playerVars?: Record<string, string \| number>; ratio?: number; host?: string }` |
| `VimeoFacadeProps`    | `{ videoId: string \| number; title?: string; ratio?: number }`                                                     |
| `MapsFacadeProps`     | `{ apiKey: string; center: LatLng; zoom: number; markers?: LatLng[]; ratio?: number }`                              |
| `IntercomFacadeProps` | `{ appId: string }`                                                                                                 |
| `CrispFacadeProps`    | `{ websiteId: string }`                                                                                             |
| `LatLng`              | `{ lat: number; lng: number }`                                                                                      |

### `ScriptProps`

The props of `Script`: `src`, `trigger`, `onLoad`, `onReady`, `onError` and the other keys of `ScriptInput`. `onLoad` runs on a load event while the component is mounted; `onReady` runs on every mount once the script is loaded, also when it already was, so a page that comes back gets it again while the file runs once; `onError` runs on a failure.

## `@hamur/scripts/devtools`

The view of the `scripts` tab of `@hamur/devtools`, which the module registers with `addDevtoolsTab` (so with the module absent there is no tab); an app never imports it. In `hamur dev` the page holds a registry at `window.__hamur_scripts` that the tab reads: each script of the page with its `key`, `src`, trigger (`client`, `server`, `manual`, `idle`, `interaction`, `visible`, `consent` or `consent: <category>`, `promise` for any other), status and the time of each status change, and the consent object's state (`all granted`, or each category granted or denied). A script that waits for a consent category that is not granted shows as `blocked`. A production client holds no registry.

## `@hamur/scripts/react`, `@hamur/scripts/vue`, `@hamur/scripts/preact`, `@hamur/scripts/svelte`, `@hamur/scripts/solid`, `@hamur/scripts/html`

Each exports `useScript`, `useScripts`, `Script` and every `useScript<Name>` for its library; the app imports them from the entry of its library, with the module in `modules`.

### `useScript`

`useScript<T = unknown>(input: string | ScriptInput, options?: UseScriptOptions<T>): UseScript<T, S>`, called where the library's hooks are (a component's render or setup; anywhere in an html page function).

```vue
<script setup lang="ts">
import { useScript } from "@hamur/scripts/vue"

const { status, onLoaded } = useScript(
  { src: "https://cdn.example.com/widget.js", key: "widget" },
  { trigger: "manual" },
)
onLoaded(() => console.log("widget ready"))
</script>

<template>
  <p>{{ status }}</p>
</template>
```

### `useScripts`

`useScripts(): UseScripts<S>`, called where the library's hooks are: the `scripts.globals` and `scripts.registry` scripts by name, each as `useScript` returns it, with this caller's callbacks (they end with the component; in html with the next navigation). The app plugin has already loaded them; `useScripts` adds no tag and starts nothing.

```tsx
import { useScripts } from "@hamur/scripts/react"

export default function Help() {
  const { support } = useScripts()
  return <button onClick={() => support?.load()}>{support?.status ?? "off"}</button>
}
```

### `Script`

`useScript` with its callbacks tied to the component; it renders nothing. React, Preact, Svelte and Solid take `onLoad`, `onReady` and `onError` as props, Vue as `@load`, `@ready` and `@error` (Vue keeps `key` for itself, so its `Script` is named by `src`). html: `Script(props): string` returns `""`; a `"server"` tag goes in the head as in the other libraries, and the server records the others in `app.modulePayload.scripts`, which the module's client app plugin starts after hydration (the page does not run in the hydrating browser). When the page renders in the browser (a client navigation) its callbacks run after the page is painted; on the first load of a document they do not run, as the page does not.

```tsx
import { Script } from "@hamur/scripts/react"

;<Script src="https://cdn.example.com/widget.js" onReady={() => window.widget.mount("#chat")} />
```

### `HtmlScriptStatus`

`@hamur/scripts/html` only: `{ get(): ScriptStatus; subscribe(callback: (status: ScriptStatus) => void): () => void }`, the `status` of html's `useScript`.

### `useScriptTriggerIdleTimeout`, `useScriptTriggerInteraction`, `useScriptTriggerElement`

Each returns a `Promise<void>` for `useScript`'s `trigger`: the script loads when it resolves. Call them where the library's hooks are, in the component that calls `useScript`. They return the same promise on each render (a changed `timeout`, `events` or `trigger` makes a new one). On the server the promise never settles, so no tag is written. A rejected trigger never loads the script, which stays `awaitingLoad`. The listeners and the observer start after the component mounted, and go when the promise resolves or the component unmounts (Vue with the scope, Svelte on destroy, Solid with the owner).

| Helper                                              | Resolves                                                                                                                                                                         |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `useScriptTriggerIdleTimeout({ timeout? })`         | after `requestIdleCallback`, or `timeout` ms (default 3000)                                                                                                                      |
| `useScriptTriggerInteraction({ events?, target? })` | on the first of `events` (default `["scroll", "pointerdown", "keydown"]`) on `target` (default `window`); the listeners are passive and once, and all are removed when one fires |
| `useScriptTriggerElement({ trigger, el })`          | `"visible"`: when `el` enters the viewport (`IntersectionObserver`, `rootMargin: "100px"`; with none the script loads at once); `"mouseover"`; or a list of event names on `el`  |

`el` follows the library: React and Preact `RefObject<Element | null>`, Vue `Ref<Element | null | undefined>`, Svelte `() => Element | undefined`, Solid `Accessor<Element | undefined>`. An `el` that is `null` when the component mounted never fires.

```tsx
import { useRef } from "react"
import { useScript, useScriptTriggerElement } from "@hamur/scripts/react"

export default function Page() {
  const map = useRef<HTMLDivElement>(null)
  useScript("https://cdn.example.com/map.js", { trigger: useScriptTriggerElement({ trigger: "visible", el: map }) })
  return <div ref={map} />
}
```

**html.** The page function does not run again in the hydrating browser, so the server records the helper's trigger in `app.modulePayload.scripts` and the module's client app plugin rebuilds it after hydration. For that, `el` is a CSS selector (or an `Element` when the page renders in the browser) and `target` is a selector, an `EventTarget` (browser render only) or unset for `window`; a selector is looked up once the page is in the document. A page rendered in the browser (a client navigation) starts its helpers after the navigation committed and stops them when the next one starts.

**Facade click.** A trigger list that has `"click"` writes, once through `useServerHead`, one small static inline script (it gets the request's nonce, or its hash is recorded for a hash policy):

```js
document.addEventListener(
  "click",
  function (e) {
    var t = e.target instanceof Element && e.target.closest("[data-hamur-facade]")
    if (t) t.__hamurClicked = true
  },
  true,
)
```

An element with `data-hamur-facade` that was clicked before the app hydrated has `__hamurClicked` set, and `useScriptTriggerElement` with `"click"` in `trigger` resolves at once when it arms. No other early event is replayed: a widget that does not exist yet cannot take one.

### `useScriptTriggerConsent`

`useScriptTriggerConsent(options?: ScriptTriggerConsentOptions<Consent>): ScriptConsent` returns the app's one consent object (one per request on the server, one in the browser): every call gets the same object, and the first call's `postConsentTrigger` is the one kept. A script without a category takes the object as its `trigger`, one with a category takes `for(category)`:

```tsx
import { useScript, useScriptTriggerConsent } from "@hamur/scripts/react"

export default function Banner() {
  const consent = useScriptTriggerConsent()
  useScript("https://cdn.example.com/analytics.js", { trigger: consent.for("analytics") })
  useScript("https://cdn.example.com/ads.js", { trigger: consent.for("marketing") })
  return <button onClick={() => consent.accept({ analytics: true, marketing: false })}>Analytics only</button>
}
```

| Call                                            | Does                                                                                                                                                                                       |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `accept()`, `accept(true)`                      | grants every category: the object and every `for(category)` resolve                                                                                                                        |
| `accept({ analytics: true, marketing: false })` | the whole choice: `for("analytics")` and the object resolve, `for("marketing")` stays pending, and a category left out is not granted. A record with no `true` does not resolve the object |
| `revoke()`                                      | stops later loads: a trigger read after it (a script that mounts later) waits for the next `accept()`. A script that is loaded stays; no browser API unloads a script's effects            |
| `for(category)`                                 | resolves while `category` is granted; the same promise for each call with that name                                                                                                        |

**`consent`** is the choice the app stored (a cookie, `localStorage`): Hamur stores nothing, so the app hands it back at start. It is applied only until the app calls `accept()` or `revoke()`: from then on the user's choice wins. A promise is read once (React and Preact read the first one a component gets): `true` accepts every category, `false` or a rejection changes nothing, and a `true` that arrives after consent changed is dropped. The reactive form is followed, shared by every caller: `true` accepts every category, and `false` after `true` revokes; a first `false` changes nothing. It is React and Preact a `boolean`, Vue a `Ref<boolean>`, Svelte a getter `() => boolean`, Solid an `Accessor<boolean>`, html `{ get(): boolean; subscribe(callback: (value: boolean) => void): () => void }` (followed until the next navigation starts). An app with categories calls `accept(record)` itself.

**`postConsentTrigger`** delays the load after consent: `"onIdle"` until the first idle callback (`requestIdleCallback` with a 2000 ms timeout), a promise until it resolves (a rejected one never loads). A `revoke()` before it fires keeps the scripts waiting. Another value throws `scripts: postConsentTrigger must be "onIdle" or a Promise (got "later")`.

**Server.** Consent is never granted on the server: `accept()` and `revoke()` do nothing and the triggers never settle, so no gated script is written in the SSR head, and a consent trigger writes no warmup link by default. html records a gated script as `{ kind: "consent", category? }` in `app.modulePayload.scripts`, and the client app plugin binds it to the browser's consent object.

No banner UI ships: the page draws its own and calls `accept()` and `revoke()`.

### `useScriptEventPage`

`useScriptEventPage(callback: (page: ScriptPage) => void): void` runs `callback({ title, path })` after each client navigation, once the new page's head is applied, so `title` is the new `document.title` and `path` is `location.pathname + location.search`. It registers on the app hook `page:rendered`, so it never runs for the first load.

```tsx
import { useScriptEventPage } from "@hamur/scripts/react"

export default function Tracker() {
  useScriptEventPage(({ title, path }) => {
    ;(window as { gtag?: (...args: unknown[]) => void }).gtag?.("event", "page_view", {
      page_title: title,
      page_path: path,
    })
  })
  return null
}
```

The callback ends when the component unmounts (React and Preact: the effect, Vue: the scope, Solid: the owner, Svelte: the component). html has no unmount: the callback ends when the next navigation starts, and the page that is rendered next registers it again. On the server it does nothing.

### `YouTubePlayer`, `VimeoPlayer`, `GoogleMaps`

Facade components: the server HTML has a placeholder and a play button in a box whose `aspect-ratio` is reserved (`ratio`, default `16 / 9`, width over height), and nothing is requested from the vendor until the trigger fires. Then the vendor's script loads (the `youtubePlayer`, `vimeoPlayer` or `googleMaps` entry), and the player or map replaces the placeholder in the same box, so the layout does not shift.

| Component       | Placeholder                                                                                                               | Props                                                                                                                                                                      |
| --------------- | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `YouTubePlayer` | the thumbnail `https://i.ytimg.com/vi/<videoId>/hqdefault.jpg`                                                            | `videoId` (11 characters of `A-Z a-z 0-9 _ -`, checked before it goes into a URL), `title?`, `playerVars?`, `ratio?`, `host?` (default `https://www.youtube-nocookie.com`) |
| `VimeoPlayer`   | none of its own (Vimeo gives a thumbnail only through an `oEmbed` request): the placeholder you give, or a plain dark box | `videoId` (numeric), `title?`, `ratio?`                                                                                                                                    |
| `GoogleMaps`    | a Static Maps image of `center`, `zoom` and `markers` (`https://maps.googleapis.com/maps/api/staticmap?…&key=<apiKey>`)   | `apiKey`, `center`, `zoom` (0 to 21), `markers?`, `ratio?`                                                                                                                 |

Every facade also takes:

- `trigger`: `"click"` (default), `"visible"`, `"mouseover"` or a `Promise` that resolves when the script should load. A click loads on every name but a `Promise`, so a touch screen needs no hover. A click before the app hydrated is replayed. The player starts at once after a click or a hover, and waits for its own button after `"visible"` or a `Promise`.
- A placeholder that replaces the default image, and `loading` and `error` content, shown while the script loads and when it fails. React and Preact: `children`, `loading` and `error` props (nodes). Vue: the default slot, `#loading` and `#error`. Svelte: `children`, `loading` and `error` snippets. Solid: the same props as React in JSX. html: `placeholder`, `loading` and `error` strings in the props, markup as given.
- `aria-busy="true"` on the root while the script loads. The play button is a `<button type="button">` named `Play video: <title>` (`Play video` without a title, `Load interactive map` for the map); the thumbnail has an empty `alt`.

The map key is public and in the image URL; restrict it to the site's referrers. The interactive map takes `center` and `markers` as coordinates, so an address needs a geocoding call of your own.

```tsx
import { GoogleMaps, YouTubePlayer } from "@hamur/scripts/react"

export default function Page() {
  return (
    <>
      <YouTubePlayer videoId="dQw4w9WgXcQ" title="Demo" />
      <GoogleMaps
        apiKey="<key>"
        center={{ lat: 41.0082, lng: 28.9784 }}
        zoom={12}
        trigger="visible"
        loading={<p>Loading the map</p>}
      />
    </>
  )
}
```

In `@hamur/scripts/html` each is a function returning markup (`YouTubePlayer({ videoId, title })`) that carries its own description in `data-hamur-facade-source`; a client app plugin, loaded only when a facade is in the document, binds it after hydration and after each navigation. Pass `trigger` as a name there: a `Promise` throws `scripts: YouTubePlayer trigger must be "click", "visible" or "mouseover" in html (got a Promise)`. A bad prop throws while rendering (`scripts: YouTubePlayer videoId must be an 11-character YouTube video id (got "../x")`).

### `IntercomFacade`, `CrispFacade`

Chat bubbles: the server HTML has a round `<button type="button" aria-label="Open chat">` fixed at the bottom right of the window (`right: 20px; bottom: 20px`), as the vendor's own bubble sits, and nothing is requested from the vendor until the trigger fires. Then the widget loads (the `intercom` or `crisp` entry), opens, and the bubble is removed. A bubble reserves no space in the page, so it shifts nothing.

| Component        | Prop                                               | Opens with                         |
| ---------------- | -------------------------------------------------- | ---------------------------------- |
| `IntercomFacade` | `appId`, checked by the `intercom` entry's schema  | `Intercom("show")`                 |
| `CrispFacade`    | `websiteId`, checked by the `crisp` entry's schema | `$crisp.push(["do", "chat:open"])` |

Both take `trigger`, a placeholder, `loading`, `error` and set `aria-busy` as the facades above do. The widget opens after a click or a hover; after `"visible"` or a `Promise` it only loads and the vendor's own launcher shows. A bad id throws while rendering (`scripts: IntercomFacade appId must be a non-empty string (got "")`, `scripts: CrispFacade websiteId is required`). In `@hamur/scripts/html` each is a function returning markup, as the facades above.

```tsx
import { CrispFacade } from "@hamur/scripts/react"

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <>
      {children}
      <CrispFacade websiteId="<website id>" />
    </>
  )
}
```

### `GoogleAnalytics`, `GoogleTagManager`

`GoogleAnalytics({ id, trigger? })` and `GoogleTagManager({ id, trigger? })` load the `googleAnalytics` or `googleTagManager` entry by `trigger` (`"client"` by default, or any trigger of `useScript`) and render nothing. After each client navigation they send one page view through `useScriptEventPage`: GA4 `gtag("event", "page_view", { page_title, page_path, page_location })`, GTM a `{ event: "page_view", page_title, page_path, page_location }` push to `dataLayer` (a container's trigger on that event reads it). The first load's page view is the `config` call's own. In html the page view is sent for pages rendered in the browser (a client navigation) that include the component, and on a document's first load the tag loads without the entry's setup (no `config` call, see the html note of the entries below), so an html app that tracks its first page lists `googleAnalytics` in `scripts.registry`.

```vue
<GoogleAnalytics id="G-ABCDEF1234" />
```

### `useScriptGoogleAnalytics`, `useScriptGoogleTagManager`, `useScriptPlausibleAnalytics`, `useScriptUmamiAnalytics`, `useScriptFathomAnalytics`, `useScriptCloudflareWebAnalytics`, `useScriptVercelAnalytics`, `useScriptPosthog`, `useScriptMatomoAnalytics`, `useScriptClarity`, `useScriptHotjar`, `useScriptMetaPixel`, `useScriptStripe`, `useScriptIntercom`, `useScriptCrisp`, `useScriptYoutubePlayer`, `useScriptVimeoPlayer`, `useScriptGoogleMaps`, `useScriptGoogleRecaptcha`, `useScriptAhrefsAnalytics`, `useScriptBingUet`, `useScriptBlueskyEmbed`, `useScriptCalendly`, `useScriptDatabuddy`, `useScriptGoogleAdsense`, `useScriptGoogleSignIn`, `useScriptInstagramEmbed`, `useScriptLeaflet`, `useScriptLemonSqueezy`, `useScriptLinkedinInsight`, `useScriptMaplibre`, `useScriptMixpanel`, `useScriptNpm`, `useScriptPaypal`, `useScriptRedditPixel`, `useScriptRybbit`, `useScriptSegment`, `useScriptSnapchatPixel`, `useScriptSpeedcurve`, `useScriptTiktokPixel`, `useScriptTawk`, `useScriptUsercentrics`, `useScriptXEmbed`, `useScriptXPixel`

`useScript<Name>(input, options?: ScriptRegistryOptions<Api>): UseScript<Api, S>` is `useScript(entry.script(input), { trigger: entry.trigger, use: () => entry.use(input), ...options })` once the entry's schema accepted `input`; an invalid input throws the schema's message (`scripts: googleAnalytics.id "UA-1" is not a GA4 measurement id (G-XXXXXXXXXX)`). The key is the entry's name, so every caller and the `scripts.registry` config share one instance, and a second input with another URL throws the key error. `proxy` is typed by the entry's API.

```tsx
import { useScriptGoogleAnalytics, useScriptPlausibleAnalytics } from "@hamur/scripts/react"

export default function Page() {
  const { proxy } = useScriptGoogleAnalytics({ id: "G-ABCDEF1234" })
  useScriptPlausibleAnalytics({ domain: "example.com" })
  return <button onClick={() => proxy.gtag("event", "signup")}>Sign up</button>
}
```

| Function                          | Input                                                                                           | Default trigger | Script                                                                                                                                                                                                                 | Before load                                                                                    | `proxy`                                                                 |
| --------------------------------- | ----------------------------------------------------------------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `useScriptGoogleAnalytics`        | `id` (`G-…`), `l?`                                                                              | `client`        | `https://www.googletagmanager.com/gtag/js?id=<id>` (`&l=<l>`)                                                                                                                                                          | `window[l]` and `gtag("js")`, `gtag("config", id)`                                             | `{ gtag, dataLayer }`                                                   |
| `useScriptGoogleTagManager`       | `id` (`GTM-…`), `l?`, `auth?`, `preview?`                                                       | `client`        | `https://www.googletagmanager.com/gtm.js?id=<id>` (`&l`, `&gtm_auth`, `&gtm_preview`, `&gtm_cookies_win=x`)                                                                                                            | the `gtm.js` event on `window[l]`                                                              | `{ dataLayer }`                                                         |
| `useScriptPlausibleAnalytics`     | `domain`, `extensions?`, `apiHost?`                                                             | `client`        | `<apiHost>/js/script[.<extension>…].js`, `data-domain`, `data-api` (`<apiHost>/api/event`)                                                                                                                             | the `plausible` queue                                                                          | `{ plausible }`                                                         |
| `useScriptUmamiAnalytics`         | `websiteId` (a UUID), `hostUrl?`, `domains?`                                                    | `client`        | `<hostUrl>/script.js` (default `https://cloud.umami.is`), `data-website-id`, `data-domains`                                                                                                                            |                                                                                                | `{ umami }`                                                             |
| `useScriptFathomAnalytics`        | `site`, `spa?` (`"auto"`, `"history"`, `"hash"`), `honorDNT?`                                   | `client`        | `https://cdn.usefathom.com/script.js`, `data-site`, `data-spa`, `data-honor-dnt`                                                                                                                                       |                                                                                                | `{ fathom }`                                                            |
| `useScriptCloudflareWebAnalytics` | `token`, `spa?`                                                                                 | `client`        | `https://static.cloudflareinsights.com/beacon.min.js`, `data-cf-beacon`                                                                                                                                                |                                                                                                | `{ __cfBeacon }`                                                        |
| `useScriptVercelAnalytics`        | `mode?` (`"auto"`, `"development"`, `"production"`), `debug?`                                   | `client`        | `/_vercel/insights/script.js`; in `"development"` `https://va.vercel-scripts.com/v1/script.debug.js`                                                                                                                   | the `va` queue                                                                                 | `{ va }`                                                                |
| `useScriptPosthog`                | `apiKey`, `region?` (`"us"`, `"eu"`), `apiHost?`, `config?`                                     | `client`        | `https://<region>-assets.i.posthog.com/static/array.js`                                                                                                                                                                | `posthog._i` with the `init` call                                                              | `{ posthog }`                                                           |
| `useScriptMatomoAnalytics`        | `matomoUrl`, `siteId`, `trackerUrl?`                                                            | `client`        | `<matomoUrl>matomo.js`                                                                                                                                                                                                 | `_paq`: `trackPageView`, `enableLinkTracking`, `setTrackerUrl`, `setSiteId`                    | `{ _paq }`                                                              |
| `useScriptClarity`                | `id`                                                                                            | `client`        | `https://www.clarity.ms/tag/<id>`                                                                                                                                                                                      | the `clarity` queue                                                                            | `{ clarity }`                                                           |
| `useScriptHotjar`                 | `id`, `sv?` (6)                                                                                 | `client`        | `https://static.hotjar.com/c/hotjar-<id>.js?sv=<sv>`                                                                                                                                                                   | `_hjSettings` and the `hj` queue                                                               | `{ hj }`                                                                |
| `useScriptMetaPixel`              | `id`                                                                                            | `client`        | `https://connect.facebook.net/en_US/fbevents.js`                                                                                                                                                                       | the `fbq` queue with `init` and `PageView`                                                     | `{ fbq }`                                                               |
| `useScriptStripe`                 | none                                                                                            | `client`        | `https://js.stripe.com/v3/`                                                                                                                                                                                            |                                                                                                | `{ Stripe }`                                                            |
| `useScriptIntercom`               | `appId`, `apiBase?`                                                                             | `manual`        | `https://widget.intercom.io/widget/<appId>`                                                                                                                                                                            | `intercomSettings` and the `Intercom` queue                                                    | `{ Intercom }`                                                          |
| `useScriptCrisp`                  | `id`                                                                                            | `manual`        | `https://client.crisp.chat/l.js`                                                                                                                                                                                       | `$crisp` and `CRISP_WEBSITE_ID`                                                                | `{ $crisp }`                                                            |
| `useScriptYoutubePlayer`          | none                                                                                            | `manual`        | `https://www.youtube.com/iframe_api`                                                                                                                                                                                   |                                                                                                | `{ YT }`                                                                |
| `useScriptVimeoPlayer`            | none                                                                                            | `manual`        | `https://player.vimeo.com/api/player.js`                                                                                                                                                                               |                                                                                                | `{ Vimeo }`                                                             |
| `useScriptGoogleMaps`             | `apiKey`, `libraries?`, `language?`, `region?`                                                  | `manual`        | `https://maps.googleapis.com/maps/api/js?key=<apiKey>&loading=async…`                                                                                                                                                  |                                                                                                | `{ maps }`                                                              |
| `useScriptGoogleRecaptcha`        | `siteKey`, `version?` (`"v3"`, `"v2"`), `hl?`                                                   | `manual`        | `https://www.google.com/recaptcha/api.js` (`?render=<siteKey>` for v3)                                                                                                                                                 |                                                                                                | `{ grecaptcha }`                                                        |
| `useScriptAhrefsAnalytics`        | `key`                                                                                           | `client`        | `https://analytics.ahrefs.com/analytics.js`, `data-key`                                                                                                                                                                |                                                                                                | none                                                                    |
| `useScriptBingUet`                | `id`                                                                                            | `client`        | `https://bat.bing.com/bat.js`                                                                                                                                                                                          | the `uetq` queue; once loaded `new UET({ ti, enableAutoSpaTracking: true, q })` and `pageLoad` | `{ uetq }`                                                              |
| `useScriptBlueskyEmbed`           | none                                                                                            | `manual`        | `https://embed.bsky.app/static/embed.js`                                                                                                                                                                               |                                                                                                | none                                                                    |
| `useScriptCalendly`               | none                                                                                            | `manual`        | `https://assets.calendly.com/assets/external/widget.js`                                                                                                                                                                |                                                                                                | `{ Calendly }`                                                          |
| `useScriptDatabuddy`              | `clientId`                                                                                      | `client`        | `https://cdn.databuddy.cc/databuddy.js`, `data-client-id`                                                                                                                                                              |                                                                                                | `{ databuddy }`                                                         |
| `useScriptGoogleAdsense`          | `client` (`ca-pub-…`)                                                                           | `client`        | `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=<client>`                                                                                                                                       | the `adsbygoogle` array                                                                        | `{ adsbygoogle }`                                                       |
| `useScriptGoogleSignIn`           | `clientId` (`….apps.googleusercontent.com`)                                                     | `manual`        | `https://accounts.google.com/gsi/client`                                                                                                                                                                               |                                                                                                | `{ google }`, whose `accounts.id.initialize` adds `client_id: clientId` |
| `useScriptInstagramEmbed`         | none                                                                                            | `manual`        | `https://www.instagram.com/embed.js`                                                                                                                                                                                   |                                                                                                | `{ instgrm }`                                                           |
| `useScriptLeaflet`                | `version?` (`1.9.4`)                                                                            | `manual`        | `https://unpkg.com/leaflet@<version>/dist/leaflet.js`                                                                                                                                                                  |                                                                                                | `{ L }`                                                                 |
| `useScriptLemonSqueezy`           | none                                                                                            | `manual`        | `https://assets.lemonsqueezy.com/lemon.js`                                                                                                                                                                             | once loaded `createLemonSqueezy()`                                                             | `{ createLemonSqueezy, LemonSqueezy }`                                  |
| `useScriptLinkedinInsight`        | `id`                                                                                            | `client`        | `https://snap.licdn.com/li.lms-analytics/insight.min.js`                                                                                                                                                               | `_linkedin_partner_id`, `_linkedin_data_partner_ids` and the `lintrk` queue                    | `{ lintrk }`                                                            |
| `useScriptMaplibre`               | `version?` (`5.6.0`)                                                                            | `manual`        | `https://unpkg.com/maplibre-gl@<version>/dist/maplibre-gl.js`                                                                                                                                                          |                                                                                                | `{ maplibregl }`                                                        |
| `useScriptMixpanel`               | `token`, `apiHost?`                                                                             | `client`        | `https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js`                                                                                                                                                                  | `mixpanel._i` with the `init` call                                                             | `{ mixpanel }`                                                          |
| `useScriptNpm`                    | `packageName`, `file?`, `version?` (`latest`), `registry?` (`"jsdelivr"`, `"unpkg"`, `"cdnjs"`) | `client`        | `https://cdn.jsdelivr.net/npm/<packageName>@<version>/<file>`, `https://unpkg.com/<packageName>@<version>/<file>`, `https://cdnjs.cloudflare.com/ajax/libs/<packageName>/<version>/<file>` (version and file required) |                                                                                                | none                                                                    |
| `useScriptPaypal`                 | `clientId`, `currency?`, `components?`                                                          | `manual`        | `https://www.paypal.com/sdk/js?client-id=<clientId>` (`&currency`, `&components`)                                                                                                                                      |                                                                                                | `{ paypal }`                                                            |
| `useScriptRedditPixel`            | `id` (`a2_…`)                                                                                   | `client`        | `https://www.redditstatic.com/ads/pixel.js`                                                                                                                                                                            | the `rdt` queue with `init` and `PageVisit`                                                    | `{ rdt }`                                                               |
| `useScriptRybbit`                 | `siteId`, `host?`                                                                               | `client`        | `<host>/api/script.js` (default `https://app.rybbit.io`), `data-site-id`                                                                                                                                               |                                                                                                | `{ rybbit }`                                                            |
| `useScriptSegment`                | `writeKey`                                                                                      | `client`        | `https://cdn.segment.com/analytics.js/v1/<writeKey>/analytics.min.js`                                                                                                                                                  | `window.analytics` as a queue with a `page` call                                               | `{ analytics }`                                                         |
| `useScriptSnapchatPixel`          | `id` (a UUID)                                                                                   | `client`        | `https://sc-static.net/scevent.min.js`                                                                                                                                                                                 | the `snaptr` queue with `init` and `PAGE_VIEW`                                                 | `{ snaptr }`                                                            |
| `useScriptSpeedcurve`             | `id`                                                                                            | `client`        | `https://cdn.speedcurve.com/js/lux.js?id=<id>`                                                                                                                                                                         | `window.LUX`                                                                                   | `{ LUX }`                                                               |
| `useScriptTiktokPixel`            | `id`                                                                                            | `client`        | `https://analytics.tiktok.com/i18n/pixel/events.js?sdkid=<id>&lib=ttq`                                                                                                                                                 | the `ttq` queue with a `page` call                                                             | `{ ttq }`                                                               |
| `useScriptTawk`                   | `propertyId`, `widgetId`                                                                        | `manual`        | `https://embed.tawk.to/<propertyId>/<widgetId>`                                                                                                                                                                        | `Tawk_API` and `Tawk_LoadStart`                                                                | `{ Tawk_API }`                                                          |
| `useScriptUsercentrics`           | `id`                                                                                            | `client`        | `https://web.cmp.usercentrics.eu/ui/loader.js`, `data-settings-id`                                                                                                                                                     |                                                                                                | `{ UC_UI }`                                                             |
| `useScriptXEmbed`                 | none                                                                                            | `manual`        | `https://platform.twitter.com/widgets.js`                                                                                                                                                                              | `twttr.ready` queue                                                                            | `{ twttr }`                                                             |
| `useScriptXPixel`                 | `id`                                                                                            | `client`        | `https://static.ads-twitter.com/uwt.js`                                                                                                                                                                                | the `twq` queue with `config`                                                                  | `{ twq }`                                                               |

Every id, key and version is checked against the shape the vendor documents before it reaches a URL or an attribute (`scripts: leaflet.version "1.9.4/../x" is not a release (1.9.4)`). Leaflet and MapLibre load only their script: add `leaflet.css` or `maplibre-gl.css` of the same release with `useHead`, as the popup and badge widgets of Calendly need `widget.css`. `useScriptNpm` has one instance per app (its key is `npm`), so a second package needs `useScript`.

The entries write no `crossorigin` (a vendor's script is not checked with SRI, and not every vendor sends CORS headers); Google Maps and reCAPTCHA send the page's origin as referrer (`strict-origin-when-cross-origin`), which a key restricted to the site's referrers needs.

**Consent.** With a trigger from `useScriptTriggerConsent` (the object or `for(category)`), `useScriptGoogleAnalytics` and `useScriptGoogleTagManager` first call `gtag("consent", "default", { analytics_storage: "denied", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" })`, then follow the app's consent object: `accept({ analytics: true, marketing: false })` calls `gtag("consent", "update", { analytics_storage: "granted", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" })` (`analytics` → `analytics_storage`, `marketing` → the three ad keys), `revoke()` the update with all four `"denied"`. `gtag` is Google's shim `function gtag() { window[l].push(arguments) }` (gtag.js reads only `arguments` objects from the dataLayer, not arrays): for `dataLayer` the page's `window.gtag`, made when missing; for another `l` a shim of its own, so GA4 on `dataLayer` and GTM on `l: "gtmLayer"` each get their own consent. `l` must be a JavaScript identifier that is not an `Object.prototype` key nor something on `window` other than an array: `scripts: googleTagManager.l "location" is already on window and is not an array`.

```tsx
const consent = useScriptTriggerConsent()
useScriptGoogleAnalytics({ id: "G-ABCDEF1234" }, { trigger: consent.for("analytics") })
```

**html.** A page rendered in the browser runs the entry's setup; on a document's first load an html page does not run there, so the recorded script is started without the entry's setup and `use`. An entry that needs its setup on the first load of an html app goes in `scripts.registry`.
