# Scripts

`@hamur/scripts` loads third-party scripts (analytics, tag managers, chat widgets, maps) without letting them decide when your page is ready. A script loads once per page session, after hydration by default, with a status your page can read. Calls to its API made before it loaded are queued and replayed. Every tag goes in through the same path as your own, so it carries the page's CSP nonce and passes Trusted Types.

```sh
bun add @hamur/scripts
```

````ts [scripts/config.ts]
import { defineConfig } from "hamur"
import scripts from "@hamur/scripts"

export default defineConfig({
  framework: "react",
  modules: [scripts],
  scripts: {
    registry: {
      plausibleAnalytics: { domain: "example.com" },
      googleAnalytics: [{ id: "G-ABCDEF1234" }, { trigger: "manual" }],
    },
    globals: { support: "https://cdn.example.com/widget.js" },
    defaultScriptOptions: { trigger: "client", warmupStrategy: "preload" },
    debug: false,
  },
})
````

Add the module to `modules`; its options live under the `scripts` key. `Script`, `useScript`, `useScripts` and every `useScript<Name>` are imported from the entry of your library: `@hamur/scripts/react`, `/preact`, `/vue`, `/svelte`, `/solid` or `/html`. Every option is in the [reference](/api-reference/scripts).

## Load a script with `useScript`

````tsx [scripts/react/use-script.tsx]
import { useScript } from "@hamur/scripts/react"

interface Widget {
  open(): void
}

export default function Help() {
  const { status, proxy, load } = useScript<Widget>(
    { src: "https://cdn.example.com/widget.js", key: "widget" },
    { trigger: "manual", use: () => (window as unknown as { widget: Widget }).widget },
  )
  return (
    <button
      type="button"
      onClick={() => {
        proxy.open()
        void load()
      }}
    >
      Help ({status})
    </button>
  )
}
````

`useScript(input, options?)` takes a URL or a `ScriptInput` (`src`, `key`, `integrity`, `crossorigin`, `referrerpolicy`, `async`, `defer`, `type`, and `data-*` attributes). It returns `status` (`awaitingLoad`, `loading`, `loaded`, `error`, `removed`), `proxy`, `load()`, `remove()`, `reload()`, `onLoaded()`, `onError()`, `warmup()` and `dispose()`.

- **One script per key.** Calls with the same `key` (default `src`) share one instance for the page session, so two components that call `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`.
- **`proxy`.** A call made on `proxy` while the script is `awaitingLoad` or `loading` is recorded; when the script loads the calls run in order against the object `use()` returns. After that a call goes straight through and returns the SDK's own value. On the server it does nothing. If the script errors or is removed the queue is dropped and nothing throws. `proxy` is typed by the type you give `useScript<T>`.
- **The component form.** `Script` is `useScript` with its callbacks tied to the component, and renders nothing:

````tsx [scripts/react/script-component.tsx]
import { Script } from "@hamur/scripts/react"

export default function Chat() {
  return (
    <>
      <div id="chat" />
      <Script
        src="https://cdn.example.com/widget.js"
        onReady={() => (window as unknown as { widget: { mount(selector: string): void } }).widget.mount("#chat")}
      />
    </>
  )
}
````

`onLoad` runs on a load event while the component is mounted, `onReady` on every mount once the script is loaded (a page that comes back gets it again, while the file runs once), and `onError` on a failure. Vue takes `@load`, `@ready` and `@error`, and its `Script` is named by `src`, since `key` is Vue's own.

## Triggers

`trigger` says when the tag is added:

| `trigger`            | The tag is added                                                                      |
| -------------------- | ------------------------------------------------------------------------------------- |
| `"client"` (default) | in the browser, after the app mounted and the first idle callback                     |
| `"server"`           | in the server's head, with the request's nonce; after hydration the browser adopts it |
| `"manual"`           | when `load()` is called                                                               |
| a `Promise`          | when it resolves                                                                      |

The helpers return a promise for the last row. They are called where the library's hooks are, and on the server their promise never settles, so no tag is written.

````tsx [scripts/react/triggers.tsx]
import { useRef } from "react"
import {
  useScript,
  useScriptTriggerElement,
  useScriptTriggerIdleTimeout,
  useScriptTriggerInteraction,
} from "@hamur/scripts/react"

export default function Page() {
  const map = useRef<HTMLDivElement>(null)
  useScript("https://cdn.example.com/chat.js", { trigger: useScriptTriggerIdleTimeout({ timeout: 4000 }) })
  useScript("https://cdn.example.com/ads.js", {
    trigger: useScriptTriggerInteraction({ events: ["scroll", "pointerdown"] }),
    warmupStrategy: "preconnect",
  })
  useScript("https://cdn.example.com/map.js", { trigger: useScriptTriggerElement({ trigger: "visible", el: map }) })
  return <div ref={map} style={{ height: 320 }} />
}
````

`useScriptTriggerIdleTimeout({ timeout })` resolves after an idle callback or `timeout` ms (default 3000). `useScriptTriggerInteraction({ events, target })` resolves on the first `scroll`, `pointerdown` or `keydown` (the default `events`) on `window`. `useScriptTriggerElement({ trigger, el })` resolves when `el` is `"visible"`, on `"mouseover"`, or on the events you list. Without `IntersectionObserver` a `"visible"` trigger resolves at once, so a script is never held back by a missing API. `scripts.defaultScriptOptions.trigger` changes the default for every `useScript` and `Script` that sets none, including those of components and modules that did not expect it.

**Warmup.** `warmupStrategy` writes one `<link rel="preload" | "preconnect" | "dns-prefetch" fetchpriority="low">` into the server's head for the script. It defaults to `"preload"` for `"client"` and `false` for the other triggers; `false` turns it off. A preload carries the script's `crossorigin` and `integrity`, so the browser reuses it for the tag. `warmup(strategy)` adds one later, which a facade does on hover.

## Registry scripts

A **registry script** is a script Hamur knows: it checks its input, knows its URL and its default trigger, and types its API. There are 44, one `useScript<Name>` each, and each has a page that lists its keys, its trigger, whether it can be bundled or proxied, and an example. See the [registry](/scripts/registry).

````tsx [scripts/react/registry.tsx]
import { useScriptGoogleAnalytics, useScriptPlausibleAnalytics } from "@hamur/scripts/react"

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

`useScriptGoogleAnalytics({ id })` is `useScript` with the entry's URL, trigger and `use` filled in, after the entry's schema checked `id`; a wrong value throws `scripts: googleAnalytics.id "UA-1" is not a GA4 measurement id (G-XXXXXXXXXX)`. The key is the entry's name, so a `useScript<Name>` call and the `scripts.registry` config share one instance.

`scripts.registry` loads an entry on every page. The value is the entry's input, or `[input, { trigger?, privacy? }]`, fixed by the build. The `scripts:registry` hook adds an entry or replaces one, with `from` set to the module that default-exports it.

## Globals and `useScripts`

`scripts.globals` names scripts to load on every page, by URL or `[input, { trigger }]`. A global loads once across pages and navigations. `useScripts()` returns the global and registry instances by name, so a component can call `proxy` or `load()` on a script the app plugin started:

````tsx [scripts/react/globals.tsx]
import { useScripts } from "@hamur/scripts/react"

interface Named {
  status: string
  load(): Promise<unknown>
}

export default function Help() {
  const support = (useScripts() as Record<string, Named | undefined>).support
  return (
    <button type="button" onClick={() => void support?.load()}>
      {support?.status ?? "off"}
    </button>
  )
}
````

`.hamur/types/scripts.d.ts` writes each name into `HamurScripts` (a registry entry with its SDK type, any other name as `unknown`), so after `hamur typegen` `useScripts().support` is typed and the cast in the sample is not needed. A name is letters and digits starting with a letter.

## Page events

`useScriptEventPage(callback)` runs `callback({ title, path })` after each client navigation, once the new page's head is applied. It never runs for the first load, which the script's own `config` call covers.

````tsx [scripts/react/page-view.tsx]
import { useScriptEventPage, useScriptGoogleAnalytics } from "@hamur/scripts/react"

export default function Tracker() {
  const { proxy } = useScriptGoogleAnalytics({ id: "G-ABCDEF1234" })
  useScriptEventPage(({ title, path }) => proxy.gtag("event", "page_view", { page_title: title, page_path: path }))
  return null
}
````

It registers on the app hook `page:rendered` and ends with the component (in html, when the next navigation starts). The `GoogleAnalytics` and `GoogleTagManager` components send this page view for you.

## Consent

`useScriptTriggerConsent()` returns the app's one consent object. It is a `Promise<void>` that `accept()` resolves, so it is a `trigger`, with `accept(categories?)`, `revoke()` and `for(category)`. A script names its category, `useScript(src, { trigger: consent.for("analytics") })`, or takes the object itself.

| Call                                            | Does                                                                                                                |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `accept()`                                      | grants every category                                                                                               |
| `accept({ analytics: true, marketing: false })` | the whole choice: `for("analytics")` resolves, `for("marketing")` stays pending, a category left out is not granted |
| `revoke()`                                      | stops later loads; a script that already loaded stays, since no browser API unloads a script's effects              |
| `for(category)`                                 | resolves while the category is granted                                                                              |

Hamur stores nothing: the app keeps the choice and calls `accept()` at start. On the server consent is never granted, so a gated script is not in the server HTML. `googleAnalytics` and `googleTagManager` are told as well: before consent they push Consent Mode v2 `default` with `analytics_storage`, `ad_storage`, `ad_user_data` and `ad_personalization` set to `denied`, and `accept({ analytics: true, marketing: false })` pushes an `update` that grants `analytics_storage` and denies the rest (`analytics` maps to `analytics_storage`, `marketing` to the other three).

**A banner recipe per adapter.** No banner ships; you draw it. Each recipe below reads a stored choice when it mounts, calls `accept()` for a "yes", shows the banner when there is no choice, and saves the answer. They share this helper, which keeps the choice in `localStorage` and does not fail when storage is blocked:

````ts [scripts/consent-choice.ts]
const KEY = "consent"

export function readChoice(): "yes" | "no" | undefined {
  try {
    const value = localStorage.getItem(KEY)
    return value === "yes" || value === "no" ? value : undefined
  } catch {
    return undefined
  }
}

export function saveChoice(choice: "yes" | "no"): void {
  try {
    localStorage.setItem(KEY, choice)
  } catch {
    return
  }
}
````

React:

````tsx [scripts/react/consent-banner.tsx]
import { useEffect, useState } from "react"
import { useScript, useScriptTriggerConsent } from "@hamur/scripts/react"
import { readChoice, saveChoice } from "../consent-choice.ts"

export default function ConsentBanner() {
  const consent = useScriptTriggerConsent()
  const [asked, setAsked] = useState(true)
  useScript("https://cdn.example.com/analytics.js", { trigger: consent.for("analytics") })
  useScript("https://cdn.example.com/ads.js", { trigger: consent.for("marketing") })

  useEffect(() => {
    const choice = readChoice()
    if (choice === "yes") consent.accept()
    setAsked(choice !== undefined)
  }, [consent])

  if (asked) return null
  const answer = (choice: "yes" | "no") => {
    saveChoice(choice)
    if (choice === "yes") consent.accept()
    setAsked(true)
  }
  return (
    <div role="dialog" aria-label="Cookies">
      <p>We use analytics and advertising cookies.</p>
      <button type="button" onClick={() => answer("yes")}>
        Accept
      </button>
      <button type="button" onClick={() => answer("no")}>
        Decline
      </button>
    </div>
  )
}
````

Preact:

````tsx [scripts/preact/consent-banner.tsx]
import { useEffect, useState } from "preact/hooks"
import { useScript, useScriptTriggerConsent } from "@hamur/scripts/preact"
import { readChoice, saveChoice } from "../consent-choice.ts"

export default function ConsentBanner() {
  const consent = useScriptTriggerConsent()
  const [asked, setAsked] = useState(true)
  useScript("https://cdn.example.com/analytics.js", { trigger: consent.for("analytics") })

  useEffect(() => {
    const choice = readChoice()
    if (choice === "yes") consent.accept()
    setAsked(choice !== undefined)
  }, [consent])

  if (asked) return null
  const answer = (choice: "yes" | "no") => {
    saveChoice(choice)
    if (choice === "yes") consent.accept()
    setAsked(true)
  }
  return (
    <div role="dialog" aria-label="Cookies">
      <p>We use analytics cookies.</p>
      <button type="button" onClick={() => answer("yes")}>
        Accept
      </button>
      <button type="button" onClick={() => answer("no")}>
        Decline
      </button>
    </div>
  )
}
````

Solid:

````tsx [scripts/solid/consent-banner.tsx]
import { Show, createSignal, onSettled } from "solid-js"
import { useScript, useScriptTriggerConsent } from "@hamur/scripts/solid"
import { readChoice, saveChoice } from "../consent-choice.ts"

export default function ConsentBanner() {
  const consent = useScriptTriggerConsent()
  const [asked, setAsked] = createSignal(true)
  useScript("https://cdn.example.com/analytics.js", { trigger: consent.for("analytics") })

  onSettled(() => {
    const choice = readChoice()
    if (choice === "yes") consent.accept()
    setAsked(choice !== undefined)
  })

  const answer = (choice: "yes" | "no") => {
    saveChoice(choice)
    if (choice === "yes") consent.accept()
    setAsked(true)
  }
  return (
    <Show when={!asked()}>
      <div role="dialog" aria-label="Cookies">
        <p>We use analytics cookies.</p>
        <button type="button" onClick={() => answer("yes")}>
          Accept
        </button>
        <button type="button" onClick={() => answer("no")}>
          Decline
        </button>
      </div>
    </Show>
  )
}
````

Vue:

````vue [scripts/vue/consent-banner.vue]
<script setup lang="ts">
import { onMounted, ref } from "vue"
import { useScript, useScriptTriggerConsent } from "@hamur/scripts/vue"
import { readChoice, saveChoice } from "../consent-choice.ts"

const consent = useScriptTriggerConsent()
const asked = ref(true)
useScript("https://cdn.example.com/analytics.js", { trigger: consent.for("analytics") })

onMounted(() => {
  const choice = readChoice()
  if (choice === "yes") consent.accept()
  asked.value = choice !== undefined
})

function answer(choice: "yes" | "no") {
  saveChoice(choice)
  if (choice === "yes") consent.accept()
  asked.value = true
}
</script>

<template>
  <div v-if="!asked" role="dialog" aria-label="Cookies">
    <p>We use analytics cookies.</p>
    <button type="button" @click="answer('yes')">Accept</button>
    <button type="button" @click="answer('no')">Decline</button>
  </div>
</template>
````

Svelte:

````svelte [scripts/svelte/consent-banner.svelte]
<script lang="ts">
  import { onMount } from "svelte"
  import { useScript, useScriptTriggerConsent } from "@hamur/scripts/svelte"
  import { readChoice, saveChoice } from "../consent-choice.ts"

  const consent = useScriptTriggerConsent()
  let asked = $state(true)
  useScript("https://cdn.example.com/analytics.js", { trigger: consent.for("analytics") })

  onMount(() => {
    const choice = readChoice()
    if (choice === "yes") consent.accept()
    asked = choice !== undefined
  })

  function answer(choice: "yes" | "no") {
    saveChoice(choice)
    if (choice === "yes") consent.accept()
    asked = true
  }
</script>

{#if !asked}
  <div role="dialog" aria-label="Cookies">
    <p>We use analytics cookies.</p>
    <button type="button" onclick={() => answer("yes")}>Accept</button>
    <button type="button" onclick={() => answer("no")}>Decline</button>
  </div>
{/if}
````

html. An html page function runs on the server, and in the browser only when a client navigation renders the page; the browser's first load of a document does not run it. So on a first load the banner is in the HTML but its buttons do nothing until a navigation renders the page, and a document's first load has no way to call `accept()` yet. The recipe below works from the first client navigation on and ends its click listener when the next navigation starts:

````ts [scripts/html/consent-banner.ts]
import { useApp } from "@hamur/adapter-html"
import { useScript, useScriptTriggerConsent } from "@hamur/scripts/html"
import { readChoice, saveChoice } from "../consent-choice.ts"

export default function ConsentBanner(): string {
  const consent = useScriptTriggerConsent()
  useScript("https://cdn.example.com/analytics.js", { trigger: consent.for("analytics") })
  if (typeof document !== "undefined") {
    const choice = readChoice()
    if (choice === "yes") consent.accept()
    const listener = new AbortController()
    useApp().hooks.hookOnce("page:start", () => listener.abort())
    document.addEventListener(
      "click",
      (event) => {
        const answer = (event.target as Element).closest<HTMLElement>("[data-consent]")?.dataset.consent
        if (answer !== "yes" && answer !== "no") return
        saveChoice(answer)
        if (answer === "yes") consent.accept()
        document.querySelector("[data-banner]")?.remove()
      },
      { signal: listener.signal },
    )
    if (choice !== undefined) return ""
  }
  return `<div data-banner role="dialog" aria-label="Cookies"><p>We use analytics cookies.</p><button type="button" data-consent="yes">Accept</button><button type="button" data-consent="no">Decline</button></div>`
}
````

`useScriptTriggerConsent` also takes `consent`, the stored choice, as a promise or the library's reactive boolean, and `postConsentTrigger` (`"onIdle"` or a promise) to delay the load after consent. See the [reference](/api-reference/scripts#usescripttriggerconsent).

## Bundle a script into your build

`scripts.bundle` lists third-party files the build serves from your own origin: an `https:` URL, or the name of a registry script that allows it and that `scripts.registry` configures.

````ts [scripts/bundle-config.ts]
import { defineConfig } from "hamur"
import scripts from "@hamur/scripts"

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

`hamur build` downloads each file once (5 MiB at most, 30 s, redirects only to `https:`), keeps it in `<cacheDir>/scripts`, hashes it with SHA-384 and emits it as `<stem>-<hash>.js` below `app.buildAssetsDir`, served `immutable`. No call changes: a `useScript`, a global or a registry script whose `src` is a listed URL loads the copy with an `integrity` attribute and, being same-origin, no `crossorigin`. Under `app.cdnURL` the copy is cross-origin and gets `crossorigin`, which its integrity check needs.

- A bundled script is a snapshot. The vendor's update reaches you when you renew the cache: `rm -r <cacheDir>/scripts`; `hamur build --force` does not.
- A script that loads more scripts (a tag manager) is bundled as the one file. What it fetches is the vendor's.
- `hamur dev` bundles nothing and uses the remote URL.
- A failed download fails the build with `scripts.bundle "https://cdn.example.com/widget.js": could not download (503)`. With `bundleFallback: true` it logs `[scripts] could not bundle https://cdn.example.com/widget.js: 503; the remote URL is used` and keeps the remote URL. A `200` with an empty body or an HTML page counts as a failed download.
- An `integrity` you pin for a bundled URL is checked against the file, and a file that does not match fails the build whatever `bundleFallback` says.

The scripts that allow it are `googleAnalytics`, `googleTagManager`, `plausibleAnalytics`, `umamiAnalytics`, `cloudflareWebAnalytics`, `metaPixel`, `segment`, `mixpanel`, `leaflet`, `maplibre` and `npm`: plain libraries, or files that send to fixed hosts. Stripe and PayPal require their file from their own host, and a map, a captcha or a player is a loader tied to its host.

## The privacy proxy

A registry script with `proxy` lets the app forward its collection requests, so the browser talks to your origin and the vendor sees your server. With the script bundled, the copy is rewritten before its hash so it sends to `/_hamur/scripts/p/<vendor>`, and that route forwards to the vendor with the privacy flags applied. The host comes from the entry, never from the request, and redirects are not followed. The entries are `googleAnalytics` (`ga`), `plausibleAnalytics` (`plausible`), `umamiAnalytics` (`umami`) and `mixpanel` (`mixpanel`).

````ts [scripts/privacy-config.ts]
import { defineConfig } from "hamur"
import scripts from "@hamur/scripts"

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

`scripts.privacy` sets six flags for every proxied script and `[input, { privacy }]` overrides them for one; a flag left out falls back to the entry's own tier:

| Flag        | What reaches the vendor                                                                 |
| ----------- | --------------------------------------------------------------------------------------- |
| `ip`        | the client address as IPv4 `/24` or IPv6 `/48`                                          |
| `userAgent` | the family and major version (`Chrome/128`), and the parameters the entry names removed |
| `language`  | the primary tag of `accept-language` (`en`)                                             |
| `screen`    | the named parameters rounded to hundreds                                                |
| `timezone`  | a minute offset rounded to the hour; a zone name removed                                |
| `hardware`  | the named parameters removed                                                            |

`cookie` and `authorization` are always removed, and only `accept`, `content-type`, `dnt` and `sec-gpc` pass as sent. The route is public: rate-limit it if you care. The body is bounded by `server.maxBodySize` (413), and the vendor must answer in 10 s (504). On a static preset the proxy is not built and the build logs `[scripts] the collection proxy needs a server preset`. A flag that is not one of the six, such as `cookie`, fails the build.

## Facades

A **facade** renders a placeholder in the server HTML and loads the script when the user acts, so the page makes no request to the vendor before. The set is `YouTubePlayer`, `VimeoPlayer`, `GoogleMaps`, `IntercomFacade` and `CrispFacade`, plus `GoogleAnalytics` and `GoogleTagManager`, which render nothing and load by `trigger`.

````tsx [scripts/react/facades.tsx]
import { CrispFacade, 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>}
      />
      <CrispFacade websiteId="00000000-0000-4000-8000-000000000000" />
    </>
  )
}
````

- `trigger` is `"click"` (default), `"visible"`, `"mouseover"` or a `Promise`. A click before the app hydrated is not lost: the facade loads at once when it hydrates.
- The player or map replaces the placeholder in the same box, with `aspect-ratio` reserved by `ratio` (`16 / 9` by default), so the layout does not shift.
- `loading` and `error` content shows while the script loads and when it fails, and the root has `aria-busy="true"` while it loads.
- The chat bubbles reserve no space: they sit fixed at the bottom right of the window and are removed once the vendor's widget opens.
- In html each facade is a function that returns markup, and the trigger is a name.

The slot names and props in every library are in the [reference](/api-reference/scripts#youtubeplayer-vimeoplayer-googlemaps). The [video recipe](#video) below uses `YouTubePlayer` too.

## `crossorigin`, SRI and CSP

A script with a cross-origin `src` gets `crossorigin="anonymous"` and `referrerpolicy="no-referrer"` unless the call sets them, so an `integrity` check can run. Not every vendor sends CORS headers. A script that does not fails to load with `crossorigin="anonymous"`, and in `hamur dev` the browser's error is explained once per `src`: `[scripts] https://x.test/a.js failed to load; it may not send CORS headers; set crossorigin: false`. The registry scripts already write `crossorigin: false`, since their vendor files carry no `integrity`.

````tsx [scripts/react/cors.tsx]
import { useScript } from "@hamur/scripts/react"

export default function Page() {
  useScript({ src: "https://cdn.example.com/widget.js", crossorigin: false })
  useScript({
    src: "https://cdn.example.com/lib.js",
    integrity: "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC",
  })
  return null
}
````

`crossorigin: false` writes no attribute. A script with an `integrity` and `crossorigin: false` throws `scripts: "https://x.test/a.js" has integrity and crossorigin: false; a cross-origin script is checked only with CORS`, since the browser would not check it. A bundled copy is same-origin and always has `integrity`.

**CSP.** A tag the module adds carries the request's nonce, and `'strict-dynamic'` lets a nonced script's own children run. If your `server.csp` does not use `strict-dynamic`, list the vendor's hosts in `script-src`, and always in `connect-src` for the requests the script makes. `hosts` on each registry page says which. See [Sessions and security](/sessions-and-security#content-security-policy).

````ts [scripts/csp-config.ts]
import { defineConfig } from "hamur"
import scripts from "@hamur/scripts"

export default defineConfig({
  framework: "react",
  modules: [scripts],
  scripts: { registry: { googleAnalytics: { id: "G-ABCDEF1234" } } },
  server: {
    csp: {
      mode: "auto",
      directives: {
        "script-src": ["'self'", "https://www.googletagmanager.com"],
        "connect-src": ["'self'", "https://www.google-analytics.com", "https://region1.google-analytics.com"],
      },
    },
  },
})
````

## Why there is no worker strategy

`@hamur/scripts` has no `worker` strategy and runs no script in a web worker in the Partytown manner. A worker has no DOM. To run a script there, every `document` or `window` read becomes a synchronous message to the main thread, through a `SharedArrayBuffer` that needs cross-origin isolation (which blocks every embed that sends no CORP header), or a service worker that answers synchronous requests. Only the scripts someone tested against that proxy work, and a tag manager, a chat widget or a payment form breaks in a way only its vendor can fix.

The costs that motivate it are met on the main thread: a late `trigger`, a facade that loads on the user's action, and a first-party copy with `scripts.bundle`.

## Video

Two ways to put a video on a page, and neither loads the video before the visitor asks for it.

**Your own file.** Put the video, its captions and a poster in `public/media/`. The poster is an image, so `@hamur/image` makes it: `getImage` gives the URL of the right size and format.

````tsx [video/react/video.tsx]
import { getImage } from "@hamur/image/react"

export default function Intro() {
  const poster = getImage("/media/intro-poster.jpg", { width: 1280 }).url
  return (
    <video controls preload="none" width={1280} height={720} poster={poster}>
      <source src="/media/intro.mp4" type="video/mp4" />
      <track kind="captions" src="/media/intro.en.vtt" srcLang="en" label="English" default />
    </video>
  )
}
````

- `preload="none"` makes the browser fetch no video bytes until the visitor plays. The poster and the `width` and `height` reserve the space, so the layout does not shift.
- `<track kind="captions">` takes a WebVTT file. Hamur serves `.vtt` as `text/vtt` and `.mp4` as `video/mp4`.
- A browser plays and seeks a video with `Range` requests, and Hamur's static server answers them: `accept-ranges: bytes` on every file, `206` with a `content-range` for a range, and `416` with `content-range: bytes */<size>` for one past the end. A prebuilt route never holds an audio or video file, so a range always reaches the handler that can answer it. A CDN in front must pass `Range` through. Write the file with its index first (`ffmpeg -movflags +faststart`), so the browser can start without reading to the end. The test `apps/web/video.test.ts` requests a file with `Range: bytes=100-199` and gets 206.

**YouTube.** `YouTubePlayer` is a facade: the server HTML has a thumbnail and a play button in a box of the right ratio, the page makes no request to `youtube.com` before the click, and the layout does not shift after it.

````tsx [video/react/youtube.tsx]
import { Img } from "@hamur/image/react"
import { YouTubePlayer } from "@hamur/scripts/react"

export default function Talk() {
  return (
    <YouTubePlayer videoId="dQw4w9WgXcQ" title="Hamur in ten minutes" trigger="click">
      <Img
        src="/media/talk-thumb.jpg"
        width={1280}
        height={720}
        alt=""
        style={{ width: "100%", height: "100%", objectFit: "cover" }}
      />
    </YouTubePlayer>
  )
}
````

The player loads from `https://www.youtube-nocookie.com` unless you set `host`. Without children the thumbnail is YouTube's `hqdefault.jpg`, a request to Google's image host; the `Img` of `@hamur/image` in the sample serves it from your app instead. The `videoId` is checked (11 characters of `A-Z a-z 0-9 _ -`) before it goes into a URL. Vimeo has no thumbnail without an `oEmbed` request, so `VimeoPlayer` takes the placeholder you give.

## Warnings and errors

| Message                                                                                                                | Cause                                                                 |
| ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `scripts: src must be a non-empty string (got undefined)`                                                              | `useScript` with no `src`                                             |
| `scripts: "a.js" must be an absolute http or https URL, or start with "/"`                                             | a relative `src`                                                      |
| `scripts: trigger must be "client", "server", "manual" or a Promise (got "later")`                                     | a wrong trigger                                                       |
| `scripts: key "chat" is used for "https://a.test/a.js" and "https://b.test/b.js"; a key names one script`              | one key, two `src`                                                    |
| `scripts: "https://x.test/a.js" has integrity and crossorigin: false; a cross-origin script is checked only with CORS` | an integrity the browser cannot check                                 |
| `[scripts] https://x.test/a.js failed to load; it may not send CORS headers; set crossorigin: false`                   | development, once per `src`                                           |
| `[scripts] proxy call "gtag" threw: <message>`                                                                         | development: a call replayed from the queue threw; the rest still run |
| `[scripts] the collection proxy needs a server preset`                                                                 | build: the proxy on a static preset                                   |
| `[scripts] could not bundle <url>: <status>; the remote URL is used`                                                   | build, with `bundleFallback`                                          |
| `scripts.bundle "<url>": could not download (<status>)`                                                                | build error                                                           |

Every config key is checked when the config loads and a wrong value fails with a message that names it, such as `scripts.registry.plausibleAnalytics.domain is required` or `scripts.defaultScriptOptions.warmupStrategy "now" is not false, "preload", "preconnect" or "dns-prefetch"`.

## Not in v1

Partytown-style execution in a worker, a consent banner and a stored consent state, blocking a third-party tag that you wrote in HTML, bundling a script's own run-time subresources and bundling in `hamur dev`, inline scripts through `useScript` (they are `useHead({ script: [{ innerHTML }] })`), a service worker for the collection proxy, and unloading a script's effects on `revoke()`. A Gravatar entry is not built: it loads an image, not a script, so use an `Img` of `@hamur/image` with the Gravatar host in `image.domains`.
