SparkleTree Docs, full text of the SDK, agents and platform pages. Index: https://docs.sparkletree.io/llms.txt # Add adaptive copy to a page Source: https://docs.sparkletree.io/developers/sdk/quickstart/ Markdown: https://docs.sparkletree.io/developers/sdk/quickstart.md ```bash npm install @sparkletree/core @sparkletree/react npx @sparkletree/cli init --origin https://yoursite.com npx @sparkletree/cli doctor --url https://yoursite.com ``` SparkleTree adapts the words in your page. Point at copy you already have, a button label, a form heading, a paragraph, and it returns a version written for the visiting context: time of day, device, language, referring site, plus anything you declare yourself. You write the copy that ships with your app. SparkleTree replaces it when an adapted version is available and leaves yours alone when it is not. The same provider also plays whole campaign creative, a hero or a CTA, managed from your dashboard. It changes text and a few theme colours. It does not change your markup, your layout, or your CSS, it ships no stylesheet, and it renders no iframe. If every request fails, your page still shows the copy you wrote. No account yet? `npx @sparkletree/cli dev` runs a local mock of the SparkleTree edge, and the [runnable examples](https://docs.sparkletree.io/developers/sdk/examples.md) stream from it with no configuration at all. See [Test without an account](https://docs.sparkletree.io/developers/sdk/testing.md). Sign up at [app.sparkletree.io](https://app.sparkletree.io) when you want real copy. ## Install the packages ```bash npm install @sparkletree/core @sparkletree/react ``` React 18 or later, Node 18 or later, ESM only. ## Set up the project with `init` ```bash npx @sparkletree/cli init --origin https://yoursite.com ``` In a terminal, `init` does what the dashboard steps below would otherwise ask of you: 1. It signs you in through the browser when you are not signed in yet: open the address it prints, check the code, approve. 2. It registers `https://yoursite.com` as a site of your workspace, so a live key works there. Repeat `--origin` for more sites, your staging host and `http://localhost:3000` included. Registering needs the admin role. 3. It picks the campaign: the only one your workspace can serve, or the one you choose when there are several (`--campaign ` chooses up front). 4. It writes four lines into `.env.local` and keeps every other line of the file as it was: ```bash # SparkleTree (written by sparkletree init) NEXT_PUBLIC_SPARKLETREE_KEY=st_pk_test_… NEXT_PUBLIC_SPARKLETREE_API_BASE=https://p.qrtree.ai NEXT_PUBLIC_SPARKLETREE_ORG_ID=6f1c2a4e-… NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID=9b8e7d6c-… ``` The prefix follows your framework, read from `package.json`: `NEXT_PUBLIC_` for Next.js, `VITE_` for Vite, `PUBLIC_` for Astro and SvelteKit, none for Remix and for a project without a framework. `--framework` sets it. The key is the test key, for a page on localhost; the result also prints the same lines with the live key, for your production environment. Both keys are public. The sign-in token is secret and is never written into your project. `init` checks everything that can stop it before it registers a site or writes a file. When `.env.local` is not covered by `.gitignore` it says so; `--yes` adds the line. `--dry-run` shows what it would do and changes nothing. ### From an agent or a script `init --json`, or `init` without a terminal, never opens a browser sign-in and never asks a question. Sign in first, once, in a terminal, or set `SPARKLETREE_TOKEN`: ```bash npx @sparkletree/cli login npx @sparkletree/cli init --json --framework next --origin https://yoursite.com --campaign 9b8e7d6c-5a4f-4e3d-8c2b-1a0f9e8d7c6b ``` Stdout then holds one JSON document. Without a sign-in it is `{"ok":false,"error":"not_signed_in",…}` at once. With several campaigns and no `--campaign` it is `{"ok":false,"error":"choose_campaign","campaigns":[…]}`: run it again with one of those ids. Every failure carries a `reason` and a `remedy`, and the exit code is `0` on success, `1` on an error and `2` on wrong usage. The full output is in [the CLI reference](https://docs.sparkletree.io/developers/sdk/cli.md#init). ## Wrap the part of your app that uses SparkleTree One provider per page view. In Next.js, put it in your root layout. ```tsx import { SparkletreeProvider } from "@sparkletree/react"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` The key alone is enough: it carries your workspace id and API base, and the provider reads them from it. `apiBase` and `organizationId` are optional; when set, they override what the key says. Or let the CLI write the provider: `npx @sparkletree/cli add provider` copies one into `components/sparkletree/provider.tsx`, written for the framework in your `package.json` (`--framework` sets it), that reads the names `init` wrote: | Framework | The provider reads | |---|---| | Next.js | `process.env.NEXT_PUBLIC_SPARKLETREE_KEY` | | Vite | `import.meta.env.VITE_SPARKLETREE_KEY` | | Astro | `import.meta.env.PUBLIC_SPARKLETREE_KEY` | | SvelteKit | `env.PUBLIC_SPARKLETREE_KEY` from `$env/dynamic/public` (SvelteKit's `import.meta.env` carries only `VITE_` names) | | Remix, none | Nothing: there is no public env convention, so the provider takes `publishableKey` as a prop. In Remix, read `SPARKLETREE_KEY` from `process.env` in your root loader and pass it down. `init` prints the same note. | It reads `…_API_BASE` and `…_ORG_ID` the same way and passes them when they are set, so a project set up before `init` wrote the key keeps working with those two alone. Each variable is read by its full name, because Next.js and Vite put a public value into the browser bundle only where the code spells it out. A missing variable stops the page at load with an error that names it and says that `npx @sparkletree/cli init` writes it. In a single-page app, call `pageVariants.reset()` (exported from `@sparkletree/react`) when your router changes route. A route change is a new page view, and the per-page-view experiment pinning needs to know. The publishable key is a signed credential minted in the dashboard. Every stream request must carry it. A test key (`st_pk_test_`) works from a page on localhost (`http://localhost`, `127.0.0.1`, `[::1]`, any port) and from a server; from any other site the site must be registered to your organization, test key or live key (`st_pk_live_`). From localhost a fragments group shows copy that is already written and its fallbacks otherwise: the hosted edge writes no new fragment copy for a loopback origin (see [Test keys are for development](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md#test-keys-are-for-development)). Treat it like any client-side key: it is visible in page source, so protection comes from the origin registry and rate limits; rotate it from the dashboard if it leaks. Self-hosting the API? Pass `apiBase` and `organizationId` explicitly alongside the key (explicit props win for addressing; the key is still sent). [Signed minting](https://docs.sparkletree.io/developers/sdk/signed-minting.md) explains why that is required rather than preferred. ## Adapt copy you already have Name a piece of your own copy, say what it says today, and render the result. There is nothing to create in a dashboard first. The keys and fallback strings you write are the request: ```tsx import { useFragments, FragmentText } from "@sparkletree/react"; function SignupButton() { const f = useFragments({ context: { page: "pricing", intent: "signup" }, fields: { cta: { kind: "cta", fallback: "Start your free trial" } }, }); return ( ); } ``` One `useFragments` call can carry a whole form's worth of fields, written together so they agree with each other. See [Fragments](https://docs.sparkletree.io/developers/sdk/fragments.md) for groups, kinds and swap rules. ## Play a campaign: render a hero and a button Campaign islands play whole creative managed from your dashboard. This is where the campaign id `init` wrote comes in: ```tsx import { Hero, Cta } from "@sparkletree/react"; const campaignId = process.env.NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID!; export function Landing() { return ( <> ); } ``` That is the whole integration. `fallback` is the only required prop besides the campaign id. `npx @sparkletree/cli add hero cta` copies the same two components into your repo instead, if you want to own their markup; see [the CLI](https://docs.sparkletree.io/developers/sdk/cli.md#add). ## Check the setup ```bash npx @sparkletree/cli doctor --url https://yoursite.com ``` `doctor` checks the installed packages, the key in your env file, that the edge accepts the key from your site, that the campaign can be served, and, with `--url`, your page's Content Security Policy. Every problem comes with the fix. See [Check your setup](https://docs.sparkletree.io/developers/sdk/setup-checks.md). ## Write the fallback as copy you would ship on its own The text in `fallback` is what a visitor reads whenever the adapted version is late, missing, or never coming: a slow network, a paused campaign, our service down. Until then the block holds rather than flashing copy the stream is about to replace. Your fallback is there but invisible, occupying its exact space, so nothing moves whichever way the wait ends. There is no skeleton and no spinner. See [What your visitors see](https://docs.sparkletree.io/developers/sdk/what-visitors-see.md). Write it as the only version of the copy. For some visitors it is. ## Check the failure path before the happy path Run the mock edge with a failure: ```bash npx @sparkletree/cli dev --failure offline ``` Put the env lines it prints in your development env file (for example `.env.development.local`), restart your dev server and load the page. You should see your fallback copy, fully readable, with no adapted provenance stamped and no layout shift. That is the behaviour that runs during an incident, so it is the one worth verifying first. Every failure the mock can act out is in [Test without an account](https://docs.sparkletree.io/developers/sdk/testing.md). ## Style it with your own CSS The npm components ship no stylesheet. They render class hooks and CSS custom properties for campaign colours: `.st-hero`, `.st-hero-headline`, `.st-cta`, `.st-stream-text`. Style them like any other element in your design system. ## Without the CLI: the dashboard Everything `init` does can be done by hand: | You need | Where it comes from | |---|---| | A publishable key (`st_pk_live_…` / `st_pk_test_…`) | Settings > Embedding in your dashboard. It encodes your workspace id and API address. | | A campaign id | Campaign islands only. The campaign lives in your dashboard; a surface id (a named screen or placement that decides what plays there) works instead. Fragments need no dashboard object at all. | | Your site's origin, registered | Settings > Embedding > Origins. Requests from an unregistered origin fail CORS. See [Origins, CSP and privacy](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md). | Put the key in `NEXT_PUBLIC_SPARKLETREE_KEY` (or your framework's name for it) and pass it to the provider as above. ## Before you ship Two steps stand between "works on my machine" and production: - **Register your production origin and use the live key there.** `npx @sparkletree/cli init --origin https://yoursite.com` registers it and prints the lines for production. Every request from an unregistered origin fails CORS. See [Origins, CSP and privacy](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md). - **Wire signed minting.** Reading copy is free and unauthenticated; *writing* new copy spends your credits, and workspaces created after 2026-08-09 refuse unsigned mints by default. Without a token endpoint your fragments serve fallbacks forever, silently in production and with a console warning in dev. [Signed minting](https://docs.sparkletree.io/developers/sdk/signed-minting.md) is a ~20-line backend route. ## Where to go from here - [Fragments](https://docs.sparkletree.io/developers/sdk/fragments.md): adaptive copy for anything you can name, under keys you choose. - [What your visitors see](https://docs.sparkletree.io/developers/sdk/what-visitors-see.md): the behaviour rules that change what you write. - [Provider, components and useIsland](https://docs.sparkletree.io/developers/sdk/components.md): every prop. - [The CLI](https://docs.sparkletree.io/developers/sdk/cli.md): every command, with its JSON output. - [When things go wrong](https://docs.sparkletree.io/developers/sdk/when-things-break.md): slow networks, paused campaigns, outages. --- # Check your setup Source: https://docs.sparkletree.io/developers/sdk/setup-checks/ Markdown: https://docs.sparkletree.io/developers/sdk/setup-checks.md ```bash npx @sparkletree/cli doctor --url https://yoursite.com/pricing npx @sparkletree/cli doctor --json # one JSON document, for an agent or CI ``` `doctor` reads your project and asks the edge whether it would accept your key from your site. It generates nothing, spends nothing and changes nothing, and it needs no sign-in. Every check answers `pass`, `warn`, `fail` or `skip`. Every warning and failure comes with a remedy you can act on as written. The command exits `1` when a check fails and `0` otherwise; a warning does not fail. ``` pass node Node 20.11.0 meets >=18, >=18. pass packages @sparkletree/core and @sparkletree/react 0.16.0. pass env-file Read .env.local. pass key NEXT_PUBLIC_SPARKLETREE_KEY is a test key for workspace 6f1c2a4e-…. FAIL origin https://yoursite.com is not allowed for this key. Register it: sparkletree init --origin https://yoursite.com skip csp-frame The served HTML shows no live player. If the page turns on live, frame-src must allow https://*.cloudflarestream.com. ``` | Option | | |---|---| | `--url ` | Also fetch this page: its Content Security Policy and whether it is server-rendered. Redirects are followed. | | `--origin ` | The site to check against the key. Default: the origin of `--url`. | | `--env-file ` | Default: the first that exists of `.env.local`, `.env.development.local`, `.env.development`, `.env`. | | `--campaign ` | Default: `SPARKLETREE_CAMPAIGN_ID` from the env file. | | `--cwd ` | The project root. | | `--json` | `{"ok": …, "checks": [{"id", "status", "message", "remedy"?}, …]}` on stdout. | `doctor` reads the variables `init` writes, with any of the prefixes `NEXT_PUBLIC_`, `VITE_`, `PUBLIC_` or none: `SPARKLETREE_KEY` (or `SPARKLETREE_PUBLISHABLE_KEY`), `SPARKLETREE_API_BASE`, `SPARKLETREE_ORG_ID` and `SPARKLETREE_CAMPAIGN_ID`. With no env file it reads them from the environment, when the key is there. `skip` is never a quiet pass: it means the check could not run, and the message says why. ## Every check The checks run in this order. When an earlier one fails, the ones that need it are skipped with the reason. ### The project | Check | pass | warn or fail, and the remedy | |---|---|---| | `node` | Node meets the `engines` range of the installed `@sparkletree/core` and `@sparkletree/react` (or the CLI's own `>=18` when neither is installed). | **fail**: Node is older. Install a version that meets the range, for example the current LTS. **skip**: the range could not be read. | | `packages` | `@sparkletree/core` and `@sparkletree/react` are installed at the same version. | **fail**: core is not installed (`npm install @sparkletree/core @sparkletree/react`), or the two versions differ (install both at the react version). **warn**: react is not installed; install it at core's version if the site uses React. | | `cli-version` | The CLI and the installed packages are the same version. | **warn**: they differ. Run the matching CLI: `npx @sparkletree/cli@ doctor`. **skip**: core is not installed. | | `env-file` | The env file was read, or the variables were read from the environment. | **fail**: no env file. Run `sparkletree init` (with `--env-file` when you named one). | ### The key and the API base | Check | pass | warn or fail, and the remedy | |---|---|---| | `key` | The key decodes; the message names `live` or `test` and the workspace. | **fail**: no `SPARKLETREE_KEY` variable (run `sparkletree init`, or add `NEXT_PUBLIC_SPARKLETREE_KEY=` with your framework's prefix), or the key does not decode (copy it again from Settings > Embedding, or run `init`). **skip**: no env file, or `@sparkletree/core` could not be loaded. | | `org-id` | Shown only when it warns. | **warn**: `SPARKLETREE_ORG_ID` is not the workspace in the key. Set it to the key's workspace id, or run `init` again. | | `api-base` | The API base (`SPARKLETREE_API_BASE`, else the one in the key) is `https` and a SparkleTree host. | **fail**: it is not `https`. Use the address `sparkletree whoami` shows. **warn**: it is not a SparkleTree host, so facts, slot reads, `ask` and the setup check send nothing to it and new fragment copy is never written, unless the provider gets `apiBase` and `organizationId` as props. Fragment reads, which carry neither the key nor page text, are still sent. Set the address `whoami` shows, or, for a self-hosted edge, pass both props. A loopback API base (`localhost`, `127.0.0.1`, `[::1]`), such as the mock edge of `sparkletree dev`, is a **pass** in a development env file and a **fail** in a production one (a file name with `prod` in it): visitors cannot reach it. **skip**: no API base. | | `key-env` | The kind of key fits the file. | **warn**: a test key in a file whose name contains `prod`. Use the live key there and keep the test key for development. | ### The edge These run only with a key that decodes and a usable API base; otherwise all four are skipped. | Check | pass | warn or fail, and the remedy | |---|---|---| | `edge` | The edge at the API base answers. | **fail**: no answer, or a 5xx. Check the API base and your network, then try again in a few minutes. | | `whoami-key` | The edge accepts the key. | **fail** when the edge enforces the check, **warn** while it only logs: the edge does not accept the key. The remedy is the edge's own sentence for the reason (`missing_key`, `malformed_key`, `unsigned`, `bad_signature`, `no_secret`, `org_mismatch`). | | `origin` | The site is allowed, and the message says by which rule: `registered`, `brand-domain` or `platform`. With a test key the edge answers `test-key` for every site before it looks at the site, so the message says only that the edge accepts this test key from any site, and that whether a page on the site can read the answers is what `browser-read` reports. For a localhost site the message also says that the hosted edge writes no new fragment copy there; against a loopback API base, such as `sparkletree dev`, it does not, because the mock edge writes it. | **fail** when the edge enforces the check, **warn** while it only logs: the site is not allowed. Register it: `sparkletree init --origin `. **skip**: no `--origin` or `--url`, or the edge did not accept the key, so it did not check the site. The key's fix is in `whoami-key`. | | `browser-read` | A page on the site can read the edge's answers. `doctor` sends the edge the request a browser sends before it reads a stream (a CORS preflight, `OPTIONS` on `/api/embed/v1/islands/stream` with the site as `Origin`) and reads `Access-Control-Allow-Origin` from the answer: the site itself, or `*`, is a **pass**. This is what decides it for a test key, which the edge accepts from any site but answers a browser on only when the site is registered, a verified brand domain or localhost. | **fail**: the edge does not answer a browser on the site, so a page there shows only your fallbacks. Register it: `npx @sparkletree/cli init --origin `. For a localhost site, the edge predates the rule that answers localhost: use the mock edge (`npx @sparkletree/cli dev`) or a registered https site. **skip**: no `--origin` or `--url`, no usable API base, or no answer. | | `enforcement` | Always passes. It reports what the edge does with a request that fails the key and site check: refuses it (`required`), logs it and serves it (`log`), or does not check (`off`). | | When the edge has no key check yet, `edge` passes and the other three are skipped. ### The campaign | Check | pass | warn or fail, and the remedy | |---|---|---| | `campaign` | The campaign resolves and can be served. It is read from the edge's cache, so nothing is generated. | **fail**: it does not resolve for this workspace (not in it, not active, or no active variant), the id is not a campaign id, or the edge refused the key for the read. Check the id with `sparkletree whoami`, which lists the campaigns that can be served, and set it with `sparkletree init --campaign `. **warn**: the edge resolved a different campaign, or refused the read for another reason. **skip**: no campaign, no answer, rate limited, or the read ended before it named a campaign; run `doctor` again. | ### The page (with `--url`) | Check | pass | warn or fail, and the remedy | |---|---|---| | `page` | The page answered 2xx. | **fail**: the address is not http or https, the page answered with an error status (check that it is served without signing in), or it could not be fetched (check that the site is running and reachable from this machine). | | `csp-connect` | The page sends no Content Security Policy, no policy restricts `connect-src`, or every policy allows the API base. | **fail**: a policy blocks the API base. The remedy names the policy (header or ``) and the source to add. | | `csp-frame` | Every policy allows `https://*.cloudflarestream.com` in `frame-src`. | **fail**: a policy blocks the live player; the remedy says what to add. **skip**: the served HTML shows no live player. | | `server-rendered` | The served HTML holds the copy markers `data-st-slot` or `data-content-source`: the page is server-rendered. | **warn**: it holds none, so the copy is rendered in the browser only. That is fine for a client-rendered app. To have the copy in the HTML, see [Server-rendered pages](https://docs.sparkletree.io/developers/sdk/server-rendering.md). | Without `--url` these four are skipped. ## The Content Security Policy If your site sends a Content Security Policy, two directives matter: | Directive | Must allow | For | |---|---|---| | `connect-src` | Your API base (`sparkletree whoami` shows it; for the hosted service it is `https://p.qrtree.ai`) | Content, the copy stream, fragments and the events the SDK sends. | | `frame-src` | `https://*.cloudflarestream.com` | Only when you turn on the live player. Its iframe is always `https://.cloudflarestream.com//iframe`. | A policy line you can copy, for the hosted service: ``` connect-src 'self' https://p.qrtree.ai; frame-src https://*.cloudflarestream.com ``` Keep your own sources in each directive; the line above adds SparkleTree's. A directive you do not set falls back to `default-src` (`frame-src` first to `child-src`), so a strict `default-src` blocks SparkleTree too. When a page has several policies, from headers and `` tags, the browser enforces each one, and a request goes through only if all of them allow it. `doctor --url` reads them all the same way. Images, video and audio need their own directives; see [Origins, CSP and privacy](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md#add-three-csp-directives). ## Check a key and a site from code: `checkSetup` ```ts import { checkSetup } from "@sparkletree/core"; const result = await checkSetup({ apiBase: "https://p.qrtree.ai", publishableKey: process.env.NEXT_PUBLIC_SPARKLETREE_KEY, origin: "https://yoursite.com", }); if (!result.ok) console.warn(`SparkleTree: ${result.reason}. ${result.remedy}`); ``` `checkSetup` asks the edge (`GET /api/embed/v1/whoami`) what it would decide for this key and site, without generating or spending anything. It never rejects: when the edge cannot be reached, `reached` is false and `reason` says why. The edge answers with open CORS, so it also works from a page on a site that is not registered yet, which is the case it exists to explain. Without `origin`, the edge reads the request's `Origin` header, so in a browser it checks the page's own site. | Option | | |---|---| | `apiBase` | Required. `https`, or `http` for `localhost`. | | `publishableKey` | `st_pk_…`, sent as `Authorization: Bearer`. | | `organizationId` | When given, it must match the key's workspace. | | `origin` | The site to check, such as `https://yoursite.com`. | | `apiBaseProvenance` | `"explicit"` (the default) or `"key"`. With `"key"`, an API base that is not a SparkleTree host is refused without a request. | | `signal` | An `AbortSignal`. | | `timeoutMs` | Default 10000. Past it the check stops and is not reached, with `reason: "timeout"`. `0` or `Infinity` turns it off. | | `fetchImpl` | A `fetch` to use instead of the platform's, for tests. | | Member | | |---|---| | `reached` | True when the edge answered with a whoami document. | | `ok` | What the edge's key and site check would decide. False when not reached. | | `organizationId` | The key's workspace, or null. | | `key` | `{ present, env, valid }`, with `env` `"live"`, `"test"` or null. | | `origin` | `{ value, allowed, via }`, with `via` `"registered"`, `"brand-domain"`, `"platform"`, `"test-key"` or null. | | `reason` | Null when `ok`. An edge reason (`missing_key`, `malformed_key`, `unsigned`, `bad_signature`, `no_secret`, `org_mismatch`, `missing_origin`, `origin_not_allowed`) or, when not reached, an SDK reason (`insecure_api_base`, `untrusted_api_base`, `network`, `aborted`, `timeout`, `http_error`, `malformed`). | | `remedy` | One sentence that fixes `reason`, or null. | | `enforcement` | `"off"`, `"log"` or `"required"`: what the edge does today with a request that fails the check. Null when not reached. | | `protocol` | `{ supported, current }`: the protocol versions the edge speaks. | | `sdk` | `{ vendored }`: the version of `@sparkletree/core` the edge carries. | | `time` | The edge's clock, ISO 8601. | | `status` | The HTTP status, when the edge answered. | A live key from a server, with no `origin`, answers `missing_origin`: live keys work only from a browser origin. Pass `origin` to check a site from a server. ## From a client you already have: `createClient(...).check()` ```ts import { createClient } from "@sparkletree/core"; const client = createClient({ publishableKey: process.env.NEXT_PUBLIC_SPARKLETREE_KEY! }); const result = await client.check({ origin: "https://yoursite.com" }); if (!result.ok) console.warn(`SparkleTree: ${result.reason}. ${result.remedy}`); ``` `check()` is `checkSetup` with the client's API base, workspace and key, so you do not pass them again. It takes three options, `origin`, `signal` and `timeoutMs`, and answers the same result as `checkSetup`. It never rejects. The API base keeps where it came from: when the client got it from the key rather than from an explicit `apiBase`, an API base that is not a SparkleTree host is refused without a request (`untrusted_api_base`), as with `apiBaseProvenance: "key"`. --- # Fragments Source: https://docs.sparkletree.io/developers/sdk/fragments/ Markdown: https://docs.sparkletree.io/developers/sdk/fragments.md Fragments adapt copy you already have. Name any piece of it, a signup button, a form heading, a paragraph, an empty state, or a group of them together, say what it says today, and SparkleTree returns a version written for where it sits. The keys are yours to choose. ```tsx import { useFragments, FragmentText } from "@sparkletree/react"; function SignupButton() { const f = useFragments({ context: { page: "pricing", intent: "signup" }, fields: { cta: { kind: "cta", fallback: "Start your free trial" } }, }); return ( ); } ``` There is nothing to create in a dashboard first. The keys and the fallback strings you write are the request. ## Your fallbacks are the schema Each entry needs a `kind` and a `fallback`. A bare string is shorthand for `{ kind: "body", fallback: "…" }`. | `kind` | For | |---|---| | `cta` | Buttons | | `label` | Links, small labels | | `headline` | Headings | | `body` | Sentences and paragraphs | | `empty-state` | "Nothing here yet" copy | Every kind follows the same rule: served copy shows only if it arrives while the field is still holding. Once your fallback has landed, it stays. These five kinds are generated copy. Two more kinds read text that is not generated at all: `fact`, a stated fact of a product, and `slot`, a custom slot of a campaign's variant. See [Facts and custom slots in the same group](#facts-and-custom-slots-in-the-same-group). Up to 24 generated fields per call, counted after array expansion. Keys start with a letter and are at most 32 characters. Each fallback is 1 to 2,000 characters, counted as JavaScript's `length` counts them (UTF-16 code units): most characters count as one, and an emoji or another character outside the Basic Multilingual Plane counts as two. These are the validator's numbers, exported from `@sparkletree/core` as `MAX_FRAGMENT_FIELDS` and `MAX_FALLBACK_CHARS`, and development builds warn the moment a declaration crosses one, because production's answer is to quietly serve your fallbacks forever. The 24-field limit is the limit of the generated schema, which is what the write request carries. Fact and slot fields are not part of that schema, so they do not count toward it. They have their own bounds: the facts for one declaration are read for at most 20 distinct products (`MAX_FACT_PRODUCTS`, the most one facts request may name), and fields for further products keep their fallbacks; each slot value is at most 2,000 characters. Development builds are what your bundler marks as development (Vite's dev server, `NODE_ENV=development`). In plain Node, outside a bundler, the SDK warns only when `NODE_ENV` is set to something other than `production` (for example `development` or `test`). With `NODE_ENV` unset it stays silent: the CLI and server code often run that way in production, and a warning there would land in your server logs on every request. ## Declare one group per unit of copy One `useFragments` call is one request, one generation, one draw. Put the fields that belong together in the same call so they are written together. A form's heading and its button should agree with each other. ```tsx const f = useFragments({ context: { page: "login", audience: "returning-user" }, fields: { title: { kind: "headline", fallback: "Welcome back" }, subtitle: { kind: "body", fallback: "Sign in to continue" }, submit: { kind: "cta", fallback: "Sign in" }, forgot: { kind: "label", fallback: "Forgot your password?" }, empty: { kind: "empty-state", fallback: "No account yet? It takes a minute." }, }, }); return (

); ``` `FragmentGroup` stamps the strongest provenance among its fields on the container (`data-content-source`), and `f.$group.marked` reports whether the draw counts as adapted. One call is one draw, so it is the natural unit for a label if your site shows one; the SDK shows none. `FragmentText` renders static copy as bare text with no wrapper element at all. A call site serving fallbacks produces exactly the same DOM as a plain string. Generated copy gets a ``. The SDK adds no visible AI label or icon; if your site labels AI-generated copy, use `$group.marked` for the group decision and `$group.disclosure?.label` for the server's wording. [What your visitors see](https://docs.sparkletree.io/developers/sdk/what-visitors-see.md) covers it. ## Declare a whole section with an array fallback A field whose `fallback` is an array declares one field per paragraph: `intro` with three elements expands to `intro1`, `intro2`, `intro3` before anything is hashed or sent. Each paragraph keeps its own layout budget, which is what lets a whole section adapt without ever shifting your layout, and the whole group is still one draw, so the paragraphs, the heading and the button agree with each other. Read them back in order with `fragmentList`: ```tsx import { useFragments, FragmentText, FragmentGroup, fragmentList } from "@sparkletree/react"; const f = useFragments({ context: { page: "features", intent: "explain" }, fields: { title: { kind: "headline", fallback: "Built for the whole funnel" }, intro: { kind: "body", fallback: [ "First paragraph, written as shipping copy.", "Second paragraph. Your strings are still the schema, per paragraph.", ]}, cta: { kind: "cta", fallback: "Start free" }, }, }); return (

{fragmentList(f, "intro").map((p, i) =>

)}
); ``` Two rules keep this honest: - **The array is a declaration, not data.** Keep it literal in your source. Its length is part of the schema hash, so a different paragraph count is a different construction, and an array fed from a CMS or an API would hash differently between server and client renders. - **The model fills your shape; it never chooses one.** Three paragraphs in, three paragraphs out, each within its budget. Letting the model pick the paragraph count would mean reserving space for the largest answer: a skeleton with extra steps, and the end of layout stability. The fallback's shape is the schema exactly as its length is the budget. ## Facts and custom slots in the same group One declaration takes three kinds of field: generated copy (the kinds above), stated facts (`kind: "fact"`) and custom slots (`kind: "slot"`). They resolve in one round of requests under one hold, into one result: ```tsx const f = useFragments({ context: { page: "product", intent: "convert" }, fields: { pitch: { kind: "body", fallback: "A heavy mug that keeps coffee warm." }, price: { kind: "fact", product: "stoneware-mug", fact: "price", fallback: "249,00 kr" }, stock: { kind: "fact", product: "stoneware-mug", fact: "availability", labels: { in_stock: "In stock", out_of_stock: "Sold out" }, fallback: "In stock", }, promo: { kind: "slot", slot: "promoLine", campaign: CAMPAIGN, fallback: "Delivery in two days" }, }, }); return (

); ``` - **Generated fields** take the path they always took: one read, and a write on a cold context. - **Fact fields** make one request to the facts endpoint for every product the declaration names. An `availability` fact shows the words in its `labels` for the stated state. See [Show prices and other facts](https://docs.sparkletree.io/developers/sdk/facts.md). - **Slot fields** make one `/content` read per distinct campaign or surface. Every rule on this page applies to each of them alike. They hold while the request runs, land once inside the hold, are never replaced once shown, and are refused when they do not fit, which leaves the fallback. Fact and slot fields never enter the schema hash or the write request, so adding one to a group does not change its generated copy or cost a new generation. A slot field changes the page only when its value differs from its fallback. A fact field whose stated value equals its fallback keeps its text and is stamped `stated` (`stated: true`, `data-content-source="stated"`). That stamp needs the value to land: the answer arrives while the field still holds and fits its space. When the hold has already ended, when there is no hold (`holdMs: 0`, or the group was shown earlier in the page view), or when the fit check refuses it, the fallback is shown as your own text, with no stamp. An unknown product, an unstated fact, a slot the variant does not have, a value over its budget or a failed request all leave the fallback as your own copy, and development builds say which. The budget for a fact or slot value is the budget a generated field with the same fallback gets: a `name` fact is sized as a `headline`, a `description` fact and every slot as a `body`, and every other fact as a `label`. Each availability label is held to that budget too, so make the fallback the longest label. ## Custom slots A custom slot is a named piece of text on a campaign's variant, written in the campaign's design (for example a promo line or a delivery note). A `slot` field shows the slot's text from the variant the page is served, in your own markup: ```ts promo: { kind: "slot", slot: "promoLine", campaign: CAMPAIGN, fallback: "Delivery in two days" }, ``` | Member | | |---|---| | `slot` | The slot's name: a letter, then up to 31 letters, digits, `_` or `-`. | | `campaign` | The campaign to read it from. | | `surface` | Or the surface whose campaign to read it from. | | `fallback` | Required. The text when the slot is not there, and its space. | In core, a field that names neither `campaign` nor `surface` reads from the call's `campaignId` or `surfaceId` (options of `fetchFragments` and `client.fragments`). `useFragments` has no such option, so in React name `campaign` or `surface` on the field itself. With neither, the field keeps its fallback. On a `` element, the group's own `campaign` or `surface` attribute is the default. The text comes from the variant's slots on `GET /api/embed/v1/content`: string values only, each at most 2,000 characters. Slot text is labelled the way the edge labels the variant's copy (`meta.contentSource`): `cached` when it was AI-written, `static` when it was authored. A value the edge sends as `static` still lands, and gets a `data-content-source="static"` span, so it is measured against its space like any served copy. **One variant per page view.** A slot read takes part in the page's variant pin, the same one the [islands](https://docs.sparkletree.io/developers/sdk/components.md) use. The first read or island stream for a campaign draws the variant; every other one waits for that draw (up to the time an island waits) and reads pinned to it. So the slot text and the hero around it always come from the same variant, whichever answer arrives first. This pin applies in a browser; on a server, each read stands alone. ## Existing code keeps compiling A declaration of generated fields only takes exactly the path it took before: the same requests, the same hash, the same result. The types grew, they did not change: - `FragmentFieldSpec` is now `string | GeneratedFieldSpec | FactFieldSpec | SlotFieldSpec`. `GeneratedFieldSpec` is the object you have always written. - Each field of the result is a `FragmentFieldState`: a `FieldState` with one optional member, `stated`, which is `true` on a field that shows a stated fact. Its `source` is then `"static"`. Anything that accepts a `FieldState` accepts it. - `source` keeps its three values: `generated`, `cached` and `static`. `FieldSource` is a deprecated name for `ContentSource`. - `FetchFragmentsOptions` gained `campaignId`, `surfaceId`, `language` (the page language for `price` facts) and `signal`, which stops the call's reads; aborted, the call resolves at once with the fallbacks. It also gained `timeoutMs`, default 10000: past it the call resolves with the fallbacks the same way, so a stalled connection never leaves it pending. `0` or `Infinity` turns it off. The React hook and the custom elements abort their request when the hold ends with nothing landed, and on unmount. ## Served copy lands while the field holds, or not at all Once your fallback has landed, that is the field's copy for the page view. A response that arrives afterwards is not shown: replacing words a visitor can see is never done, whether they are a button label or a paragraph. This is `swap: "never"`, the behaviour of every field. Two older values, `"before-paint"` and `"always"`, are deprecated. They are still accepted, so existing code keeps compiling, and they now behave exactly like `"never"`: no late response replaces a landed fallback. Copy landing in the reserved space during the hold lands whole, with one short fade, and only if it fits the space your fallback holds. Before it is painted the field measures it in place. Shorter copy lands and keeps the space your fallback held, so the element never shrinks. Copy that would make your element larger (or, for copy inside a sentence, move the words after it) is not shown: your fallback lands instead, final for the page view. A new declaration (other fields, another context) after copy has been visible changes nothing on screen unless the visitor caused it: call `markVisitorChange()` in the interaction handler before the state update, and the new copy replaces the old with one cross-fade once it is ready. Otherwise the group keeps its copy until it is off screen. `swap` is presentation only: it is never sent, and it never changes which copy gets written. Editing it does re-run the read, exactly as editing a fallback string does, but the request is byte-identical, so it is a cache hit and costs no new generation. ## Your fallback waits behind the served copy The served copy is the first text a reader sees. While the request is in flight your fallback renders invisibly. It occupies its exact space, hidden, so the wait itself never moves the page, and no text is shown that a moment later would be swapped mid-read. While holding, that invisible fallback is a `span` inside your element, so CSS keyed on `:empty` or child selectors will see it for up to the budget. Served copy is written to your fallback's length budget; copy that would still change your element's size is not shown, so write fallbacks that reflect the length of the copy you want there. If nothing adapted has arrived within 2.5 seconds of the group coming into view, your fallback lands in the space it already holds, with zero layout shift and one short fade, and that is then what the visitor reads for the page view. Pass `holdMs` to change the budget (`0` turns the hold off: your fallback shows at once and stays). A response that settles with nothing adapted lands the fallback immediately. The reservation works at every size: a paragraph section holds its full height for the whole wait, so there is no large-group exception anymore, and no section that materializes late. The one trade to know: invisible copy is not a Largest Contentful Paint candidate, so a group that waits out the full budget defers LCP by up to `holdMs`. And because the fallback genuinely has not been seen while it is hidden, a response landing inside the budget shows in groups of any size, buttons and labels included. On the server there are no timers: the HTML carries the same invisible reservation, never your fallback as visible text, so a server-rendered page holds exactly like a client-rendered one. The reservation includes a CSS-only failsafe: if the page's JavaScript has not taken over within 5 seconds your fallback becomes visible on its own (at once with scripting off), and if that happened before hydration, the fallback is final for the page view. ## Layout never shifts, because your fallback sets the budget Each field carries a length budget derived from your own fallback: `max(length × 1.3, floor for the kind)`, where the floors are 24 characters for `cta`, 32 for `label`, 64 for `headline`, and 160 for `body` and `empty-state`. Generated copy is written to fit inside it, and the server recomputes the budget rather than trusting the browser. Write a fallback that reflects the space you actually have and the adapted version will fit the same box. ## The context vocabulary is fixed `context` describes where the copy sits, never who is reading it. | Key | Value | |---|---| | `page` | Your own page class, lowercase letters, digits and hyphens, up to 32 characters. Never a URL or path. | | `intent` | One of `signup`, `signin`, `retain`, `upsell`, `reassure`, `explain`, `browse`, `convert`. | | `audience` | A placement descriptor in the same token format, never a user identifier. | | `notes` | Up to 280 characters of free text describing the placement. | | `custom` | Up to four of your own key/value pairs, both in the token format. | Unknown keys are dropped, and an unrecognised value for a known key is dropped rather than becoming a new bucket. Free text in `notes` is scrubbed of markup and URLs, and the whole field is discarded if it looks like an email address, a phone number or a token. This copy is shared between every visitor in the same context, so nothing about an individual belongs in it. Set page-wide defaults on the provider and override them per call site: ```tsx ``` Every distinct context is a distinct piece of copy to generate, including every distinct `notes` string. Declare the placement, not the visit. Sign-in and checkout page classes may take one extra step: your workspace can require an operator to switch them on and approve the copy before it serves. Until then those call sites render your own strings, exactly as written. ## A cold context is written on the visitor's request A read is one cacheable request that always answers, warm or cold. On a cold read the SDK sends one request to write the copy, once per browser session per context, and the platform generates it right then and streams it back into the hold. Inside the budget, the first visitor sees the generated words; too slow, and their fallback lands and stays (never one and then the other). Either way the read is warm for every view after. `f.$group` reports what happened: | Property | Meaning | |---|---| | `warmth` | `"warm"`: adapted copy was served. `"warming"`: your fallbacks were served, a fill is in flight. `"cold"`: your fallbacks were served. | | `marked` | Whether the group's copy counts as adapted for this viewer. Data only: the SDK renders no label from it. | | `disclosure` | The server's localized label for AI-generated copy (`{ label, locale, status }`), when the read sent one; otherwise `null`. Data only. | | `holding` | The group is waiting out the budget. Every field's `text` is `""`; `FragmentText` reserves each fallback's space invisibly. | | `contextHash` | The identity of this context, if you want it in your own logs. | `holding` is there so the holding window is yours to fill if you want it: ```tsx {f.$group.holding ? : } ``` Take that branch and you take the layout with it: `FragmentText` is what draws the invisible reservation, so whatever you render instead has to hold the space itself. Letting `FragmentText` render throughout is still the default and still what the fields give you on their own. The floor does not move either way: when the budget expires your fallback lands, so `holding` never stays true. ## Every failure renders your own copy Network down, API down, cold cache, credit cap reached, a malformed response: all of them resolve to your fallbacks with `source: "static"`, and `FragmentText` renders them as bare text. The resolver never rejects and never throws. Hitting your credit cap stops new copy being *written*. Copy already written keeps serving, and your fallbacks keep rendering. A limit never takes a page down. ## Use it without React ```ts import { createClient } from "@sparkletree/core"; const client = createClient({ publishableKey: KEY }); const { fields, warmth } = await client.fragments({ context: { page: "pricing", intent: "signup" }, fields: { cta: { kind: "cta", fallback: "Start your free trial" } }, }); button.textContent = fields.cta.text; ``` If you show a label, decide it from `fields.cta.source`: label anything that is not `static`. `fetchFragments` also returns `disclosure`, the server's localized label, when the read sent one. See [Using it without React](https://docs.sparkletree.io/developers/sdk/core.md). ## Brand pages and other sites without a backend A static page, such as a SparkleTree brand page, has no server to sign a mint token, so it writes copy with your live publishable key. Pass the key and the SDK sends it on the write request as `Authorization: Bearer `. The platform writes the copy when the request comes from an origin registered to your organization. Your verified brand host counts as registered. The key is public: it is in your page source. The platform accepts it only from your registered origins, and a browser cannot fake its origin, but a script outside a browser can claim any origin. So anyone who copies the key can spend up to your daily budget for new copy (50 new copies in 24 hours, 1 credit each). That budget is shared by all your sites, including those that sign their writes, so once it is used up your pages show their fallbacks for up to 24 hours. If you have a backend, use a [signed mint token](https://docs.sparkletree.io/developers/sdk/signed-minting.md). ```html

Fresh bread every morning

``` Text a visitor can see is never replaced. The element starts with your fallback, invisible but holding its space. Copy that arrives within 2.5 seconds of the page starting lands once; otherwise your fallback shows and stays, and a late response is ignored. Your fallback sets the size: copy that would not fit its box keeps the fallback. Use a block element (`h1` to `h6`, `p`, `div`) for the text. `useFragments` in React does all of this for you. `createClient({ publishableKey })` and `useFragments` under `` send the key the same way. The key goes on the write request only, never on the read. What the key does not do: - A test key (`st_pk_test_`) writes copy only from `localhost`, and only outside production, so never against the hosted edge. On a real site use the live key. - A key for another organization, or a live key from an origin your organization has not registered, is refused. Your fallback stays. - The key does not stop someone who copies it from your page source (see above). What they can spend is bounded by your daily budget for new copy, your quota and your credits. Against the hosted edge, which runs in production, no key writes new copy from `localhost`: a fragments group there shows copy already written for it, and its fallbacks otherwise. To see new copy while developing, use a registered https origin (a preview deployment registered with `sparkletree init --origin`), a signed mint token from your own server, or the mock edge (`sparkletree dev`). An API base that came from a key and is not a SparkleTree host (`*.sparkletree.io`, `*.qrtree.ai`) or loopback is unproven: the browser cannot check the key's signature. For it, facts, the setup check, `ask`, slot reads and the write request are refused without a request (`untrusted_api_base`). The fragments read is still sent, because it carries neither the key nor any text from the page (only the workspace and two hashes), so copy already written still shows. Pass `apiBase` and `organizationId` explicitly for your own edge. A [signed mint token](https://docs.sparkletree.io/developers/sdk/signed-minting.md) is still supported and is still the only credential that resists a spoofed `Origin`. Send both and the token is used. An organization whose admin turned **Signed mints only** on accepts signed tokens only from its other sites, and the key is refused there. Its own brand host, the brand page SparkleTree serves for it, keeps minting with the live key, and that copy counts against the same daily budget. ## Before you ship: pin the spend to your account Writing copy costs credits, and a browser cannot prove it belongs to your account. A live publishable key from a registered origin lets a site with no backend write copy, but the key is public (see above). [Signed minting](https://docs.sparkletree.io/developers/sdk/signed-minting.md) pins the spend to your backend instead, and is required by default for newer workspaces that do not send a key. --- # Show prices and other facts Source: https://docs.sparkletree.io/developers/sdk/facts/ Markdown: https://docs.sparkletree.io/developers/sdk/facts.md A stated fact is a value your workspace has on record: a product's name, its price, whether it is in stock. The SDK reads facts from the edge and never generates or adapts them. Put one in the page with ``: ```tsx import { Fact, SparkletreeProvider } from "@sparkletree/react";

``` `product` is the product's id or its shop handle. `fallback` is the text the page shows when the fact is not stated or cannot be read, and it sets the space the fact may take. There are three ways to show facts: | Way | Use it for | |---|---| | A `fact` field in a fragments declaration | A fact next to adapted copy, under the same hold and in the same draw. | | `` (React) or `` (any framework) | One fact on its own, inside your own element. | | `fetchFacts`, or `useFacts` in React | The whole facts document as data, for markup you render yourself or for a server. | ## A fact next to adapted copy A fragments declaration takes `kind: "fact"` fields next to generated ones. All of them resolve under one hold, in one round of requests: ```tsx import { FragmentGroup, FragmentText, useFragments } from "@sparkletree/react"; function MugCard() { const f = useFragments({ context: { page: "product", intent: "convert" }, fields: { pitch: { kind: "body", fallback: "A heavy mug that keeps coffee warm." }, name: { kind: "fact", product: "stoneware-mug", fact: "name", fallback: "Stoneware mug" }, price: { kind: "fact", product: "stoneware-mug", fact: "price", fallback: "249,00 kr" }, }, }); return (

); } ``` `` is exactly this with one field. Every rule of [fragments](https://docs.sparkletree.io/developers/sdk/fragments.md) applies to a fact field: it holds with its fallback keeping its space, it lands once if it arrives inside the hold and fits, and text the visitor has seen is never replaced. When a stated value is the same text as its fallback, nothing on the page changes: the text stays exactly as it is. The field still counts as stated, so it carries `stated: true` and `data-content-source="stated"`, because the workspace stated that value. That stamp needs the value to land: the answer arrives while the field still holds and fits its space. When the hold has already ended, when there is no hold (`holdMs: 0`, or the group was shown earlier in the page view), or when the fit check refuses it, the fallback is shown as your own text, with no stamp. When a fact is not stated, the fallback stays and is your own copy (`source: "static"`, no `stated`). ## The facts you can name | `fact` | Returns | |---|---| | `name` | The product's name. | | `price` | The amount formatted with its currency for the page language, for example `249,00 kr` for `sv-SE`. | | `amount` | The amount as stored, as a decimal string, for example `249.00`. Never formatted. | | `currency` | The ISO 4217 code, for example `SEK`. | | `availability` | Your words for the stated state, from `labels` (see below). `unknown` counts as not stated, so the fallback stays. | | `sku` | The stock keeping unit. | | `description` | The product's description as stored. | A fact the workspace has not stated leaves the fallback in place. The edge reports availability as `in_stock` or `out_of_stock` only when the product's inventory is tracked; otherwise it is `unknown`. ## Availability in your own words The edge states availability as a code, `in_stock` or `out_of_stock`. A code is not text for a visitor, so an availability field shows the words you give it for each state: ```tsx

``` In a fragments declaration the same field is `{ kind: "fact", product: "stoneware-mug", fact: "availability", labels: { in_stock: "In stock", out_of_stock: "Sold out" }, fallback: "In stock" }`. In the custom elements the words are attributes on the text: `In stock`. The field lands the label for the stated state. It keeps its fallback when there is no label for that state, when it has no labels at all, and when the state is `unknown`. Development builds warn once when an availability field has no labels. `labels` is read only for `availability`. Each label must fit the fallback's space like any other value: it is held to the fallback's character budget and measured in place. Make the fallback the longest label, so every state fits. As with any fact, a label equal to the fallback changes no text on the page; the field is still stamped `stated`. The code itself is still data: `useFacts` and `fetchFacts` return it as `product.availability`. ## Prices and the page language `price` is formatted with `Intl.NumberFormat(language, { style: "currency", currency })`. The same amount reads differently per language: | Language | `249.00` in `SEK` | |---|---| | `en` | `SEK 249.00` | | `sv-SE` | `249,00 kr` | | `de-DE` | `249,00 SEK` | Where the language comes from: - **React:** the provider's language. That is the `language` in the provider's `context` when you set one, else the language of the server read (`serverContext`), else the browser's (`navigator.language`). - **Custom elements:** the nearest `lang` attribute, else the document's, else `en`. - **Core:** the `language` option of `fetchFragments` or `client.fragments`. Core never reads it from the browser and defaults to `en`, so a server and a browser that pass the same value format the same string. When the currency is not known, the amount is not a plain decimal, or the runtime cannot format the language or currency, `price` is the raw amount. Write the fallback as the formatted price will read for the page language, at least as long. The fallback sets the space: a formatted price longer than its fallback can be refused (see below). ## Unknown products and values that do not fit Every failure leaves the fallback in place, and development builds say why: - **A product the workspace does not have** (by id or by handle, matched without regard to case): the edge leaves it out of its answer, and the field keeps its fallback. - **A value longer than its budget.** A fact gets the same character budget a generated field with that fallback gets: `name` is sized as a `headline`, `description` as a `body`, every other fact as a `label`. A longer value is refused. - **A value that would not fit the space.** As with every fragment, the renderer measures the value in place before it is painted. In React, shorter text lands pinned to the box the fallback held, and text that would make the element larger is refused. The custom elements are stricter; see [Use it in any framework](https://docs.sparkletree.io/developers/sdk/elements.md). - **More than 20 products in one declaration.** One facts request names at most 20 products. Fields for the others keep their fallbacks. - **The request fails** (network, an error status, a malformed answer, an aborted request): every fact field keeps its fallback. `fetchFacts` resolves `{ ok: false, reason }` and never rejects. ## A fact is never adapted copy A landed fact has `source: "static"` and `stated: true`. The renderers stamp it `data-content-source="stated"`, so it can be told apart from your own copy (`static`) and from adapted copy (`generated`, `cached`). `source` keeps its three values, so a fact never makes a group count as adapted: `$group.marked` stays false for a group whose only landed text is facts, and `FragmentGroup` stamps the group with the strongest source among its other fields. If your site labels AI-generated copy, a fact needs no label. ## Facts requests made together are sent as one Fact fields that start in the same frame share one request to `GET /api/embed/v1/facts`, when they use the same API base, workspace, key and page language. A product card with `` for the name, the price and the availability makes one request, not three. Each request names at most 20 products; more start a second request. `fetchFacts` and `useFacts` make their own request each time. ## The whole document as data `useFacts` returns the facts document for a campaign, a surface or named products: ```tsx import { useFacts } from "@sparkletree/react"; function LowStockNote() { const { facts } = useFacts({ products: ["stoneware-mug"] }); const soldOut = facts?.products[0]?.availability === "out_of_stock"; // A fixed box: the note appearing later cannot move the page. return ( {soldOut ? "Back in stock soon" : ""} ); } ``` `useFacts` holds nothing and renders nothing. While its request runs, `facts` is `null`, `ok` is false and `reason` is undefined. The request runs in the browser after mount and again when the options change. Markup you render from it is yours, and so is its layout: give it a fixed space, or render it where text appearing later cannot move the page. For text in the page flow, use ``. | Option | | |---|---| | `campaignId` | The campaign whose products and legal lines to read. | | `surfaceId` | The surface whose current campaign to read. | | `products` | Product ids or handles, at most 20. Without them, the campaign's or surface's own products. | It returns `{ facts, ok, reason, verify }`. `verify()` checks the signature (see below). Outside React, `fetchFacts` reads the same document: ```ts import { fetchFacts } from "@sparkletree/core"; const result = await fetchFacts({ apiBase: "https://p.qrtree.ai", organizationId: ORG, publishableKey: KEY, campaignId: CAMPAIGN, // or surfaceId, or products products: ["stoneware-mug"], }); if (result.ok) { const mug = result.facts!.products[0]; } ``` `createClient({ publishableKey }).facts({ products })` does the same with the client's API base, workspace and key. Both take `signal` and `timeoutMs`: the call stops after 10 seconds without a complete answer unless you pass another value. `result` is `{ ok, facts, reason?, status?, url? }`. `facts` is the document exactly as the edge sent it, unknown members kept, so it still verifies. `reason` is one of: | `reason` | | |---|---| | `insecure_api_base` | `apiBase` is not https (http is allowed for localhost only). No request was made. | | `untrusted_api_base` | `apiBase` came from a publishable key and is not a SparkleTree host. No request was made. | | `missing_organization` | No `organizationId`. No request was made. | | `network`, `aborted` | The request did not complete. | | `timeout` | No complete answer within `timeoutMs` (default 10000 ms; `0` or `Infinity` turns it off). | | `http_error` | The edge answered with another status; see `status`. | | `malformed` | The edge answered 200 with something that is not a facts document. | `factText(product, fact, language, labels)` and `findFactProduct(facts, product)` read one fact out of a document the same way a declaration does. `labels` is used only for `availability`; without it, `factText` returns undefined for that fact. ## What the document contains ```json { "facts": 1, "organization": { "id": "…", "name": "Kiln & Co", "url": "https://kiln.example" }, "campaign": { "id": "…", "name": "Autumn firing", "url": "https://p.qrtree.ai/c/…/autumn-firing", "legalLines": ["Prices include VAT."] }, "products": [ { "id": "…", "handle": "stoneware-mug", "name": "Stoneware mug", "price": "249.00", "currency": "SEK", "availability": "in_stock", "sku": "MUG-01", "url": "https://kiln.example/mug" } ], "ask": { "url": "https://p.qrtree.ai/ask", "campaign": "…" }, "source": "stated", "asOf": "2026-11-19T10:00:00Z", "signature": { "alg": "ed25519", "keyId": "a1b2c3d4", "value": "…" } } ``` - Values the workspace has not stated are left out, never sent as empty strings. - The products are the ones you named, or the campaign's own when you named none. They come from campaigns the edge serves. - `campaign` is `null` when no campaign resolved. Its `legalLines` follow the viewer's market (the request's `Accept-Language` and country), verbatim. - `organization.url` is the website on record, or on a brand host that host. It is left out when there is neither. Some members are sent only for campaigns that are public on the edge: - `campaign.url`, the campaign's public page. - `ask`, where to send questions about the campaign. It is also `null` when the workspace has switched its assistant off. - A product's `url`, its page on your site. - A product's `handle`, unless your request named the product by that handle. The answer is cached for 60 seconds per viewer (`Cache-Control: private, max-age=60`). ## Check the signature When the edge has a signing key, the document carries an Ed25519 signature over the canonical JSON of the whole document without its `signature` member. Anyone can check it against the public keys at `/.well-known/sparkletree-keys.json` on the edge: ```ts import { fetchFacts, verifyFacts } from "@sparkletree/core"; const { facts } = await fetchFacts({ apiBase, organizationId, publishableKey, products: ["stoneware-mug"] }); const check = await verifyFacts(facts, { apiBase }); // { valid: true, keyId: "a1b2c3d4" }, or { valid: false, keyId?, reason } ``` `verifyFacts` fetches the keys document from `apiBase`, which must be a SparkleTree host over https: keys from any other host prove nothing about who signed. Pass `keys` instead to verify against keys you already have, and nothing is fetched. It uses WebCrypto, so it works in browsers and in Node where `crypto.subtle` supports Ed25519. It never rejects. | `reason` | | |---|---| | `unsigned` | The document has no signature: the edge has no signing key. | | `malformed` | Not a facts document, or a malformed signature. | | `unsupported_alg` | The signature names an algorithm other than `ed25519`. | | `unsupported` | Ed25519 is not available in this runtime. | | `no_keys` | No `keys` and no `apiBase`. | | `untrusted_key_source` | `apiBase` is not a SparkleTree host, or not https. | | `keys_unavailable` | The keys document could not be read. | | `unknown_key` | No key has the signature's `keyId`. | | `bad_signature` | The signature does not match the document. | The keys document is a list of JWKs: ```json { "keys": [{ "kty": "OKP", "crv": "Ed25519", "kid": "a1b2c3d4", "x": "…", "use": "sig", "alg": "EdDSA" }] } ``` `signature.keyId` names the key's `kid`; `x` is the raw 32-byte public key, base64url. The list is empty when no key is configured. To check a signature without the SDK, remove `signature`, write the rest as canonical JSON, and verify `signature.value` (base64url, no padding) over its UTF-8 bytes. Canonical JSON is RFC 8785 for the values a facts document holds: object members sorted by the UTF-16 code units of their names, no whitespace, and strings that escape only `"`, `\` and U+0000 to U+001F (`\b \f \n \r \t` where they exist, lower-case `\u00xx` otherwise). `canonicalJson(value)` from `@sparkletree/core` writes exactly this. ## From a server `fetchFacts` and `verifyFacts` run on a server as they do in a browser. A server sends no `Origin`, so the edge reads facts for a server caller only with a valid publishable key: pass `publishableKey`. ```ts // A server component, an API route or a build step. import { fetchFacts } from "@sparkletree/core"; const result = await fetchFacts({ apiBase: "https://p.qrtree.ai", organizationId: process.env.SPARKLETREE_ORG!, publishableKey: process.env.SPARKLETREE_KEY!, products: ["stoneware-mug"], }); ``` On a server, a fact field in `fetchFragments` formats `price` with the `language` you pass. Pass the same value the browser will use, and both write the same string. To put the facts in your page's head for visiting agents and search engines, use `getAgentSurface` or ``; see [Be readable by visiting agents](https://docs.sparkletree.io/developers/sdk/agents.md). --- # Register your origin, set your CSP, know what is sent Source: https://docs.sparkletree.io/developers/sdk/origins-and-privacy/ Markdown: https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md ## Register your site's origin or every request fails ```bash npx @sparkletree/cli init --origin https://yoursite.com --origin https://staging.yoursite.com npx @sparkletree/cli doctor --origin https://yoursite.com ``` The publishable key is a signed credential minted in the dashboard. Every stream request must carry it. A test key (`st_pk_test_`) works from a page on localhost and from a server; from any other site the site must be registered to your organization, test key or live key (`st_pk_live_`). Treat it like any client-side key: it is visible in page source, so protection comes from the origin registry and rate limits; rotate it from the dashboard if it leaks. So for a live key, your site's origin has to be registered against your organization. `sparkletree init --origin ` registers it. Repeat `--origin` for each site; a site already registered is reported, not added twice. Registering needs the admin role in the workspace. A site the app refuses is listed with the reason, and the command exits `1`. `sparkletree doctor --origin ` then asks the edge whether the live key is accepted from that site, and `sparkletree whoami` lists every registered site. See [the CLI](https://docs.sparkletree.io/developers/sdk/cli.md#init). The dashboard (Settings → Embedding → Origins) does the same. On a phone the same list is under Settings → Embedding, where it is called Sites. The API works too, authenticated as your organization. The endpoint refuses any session that does not belong to the org, so nobody can register an origin against your organization id from the outside: ```bash curl -X POST "https:///api/organizations//embed-origins" \ -H "Content-Type: application/json" \ -H "Cookie: " \ -d '{"origin":"https://yoursite.com"}' ``` Until it is, every request fails CORS and your visitors read your fallback copy. Register each origin you actually serve from, including staging and your local dev server. Wildcards are rejected: a browser never sends one, so such an entry would look like coverage while covering nothing. Plaintext `http` is accepted for `localhost` only. A workspace can register up to 20 sites. ## Test keys are for development A test key (`st_pk_test_…`) works from a page on localhost (`http://localhost`, `127.0.0.1` or `[::1]`, any port) and from a server, which sends no origin at all. That is what it is for: your local dev server and a test run in CI. From any other site the site must be registered, test key or not. The edge sends the header that lets a browser read its answer (`Access-Control-Allow-Origin`) only to registered sites, verified brand domains and localhost, so a page anywhere else cannot read it. A preview deployment needs its address registered (`sparkletree init --origin`). From localhost, against the hosted edge, a test key works for the hero, CTA and live streams (`Hero`, `Cta`, `Live`, ``), `/content` (cards and slot fields), facts, `ask` with a campaign, the setup check, fragments that are already warm, and events (`track`, impressions). Two things stay closed from localhost whatever the key: - **Writing new fragment copy.** The hosted edge refuses a mint from a loopback origin. A fragments group on localhost shows copy another site already wrote for it, and its fallbacks otherwise. To see new fragment copy while developing, use a registered https origin (a preview deployment registered with `init --origin`), a signed mint token from your own server ([signed minting](https://docs.sparkletree.io/developers/sdk/signed-minting.md)), or the mock edge (`sparkletree dev`). Development builds say so in the console when a mint is refused this way. - **The voice token route**, which needs the origin registered to the workspace. `init` writes the test key into `.env.local` by default, and prints the lines with the live key for production. Use the live key on your production site, where the origin registry protects it; `doctor` warns when an env file whose name contains `prod` holds a test key. Only the admin and editor roles get the test key from the CLI; for other roles `init` writes the live key and tells you to register your development address. ## What a signed-in CLI can do `sparkletree login` asks for one scope, `sdk:setup`. A sign-in with it can: - read the workspace's publishable keys, its API base, its registered sites and the campaigns that can be served; - add sites to the workspace's allowed list (with the admin role); - read campaign results. It cannot change campaigns, copy, billing or members. The browser approval page shows the requested access and says "It can read this workspace's SDK keys and add sites to its allowed list." The token is stored only on your machine, readable only by you, is sent only to the app that issued it, and is never written into your project. `sparkletree logout` revokes it. See [Sign-in](https://docs.sparkletree.io/developers/sdk/cli.md#sign-in). ## Add three CSP directives If you run a Content Security Policy (`doctor --url` checks `connect-src` and `frame-src` on the served page; see [Check your setup](https://docs.sparkletree.io/developers/sdk/setup-checks.md#the-content-security-policy)): ``` connect-src https:// # content and the copy stream img-src https:// # campaign artwork, if any media-src https:// # video creatives ``` The SDK loads no script from anywhere. The one exception is audio playback: if you call `mountAudio` with a Spotify track, Spotify's own iframe API script is injected into your page, which needs: ``` script-src https://open.spotify.com frame-src https://open.spotify.com ``` Treat that call as an explicit decision to bring in a third party. The live player is the other one. If you turn on `live` on a `Hero` or render `Live`, a running channel's player is an iframe from Cloudflare Stream, which needs: ``` frame-src https://*.cloudflarestream.com ``` The visitor's browser then connects to Cloudflare to play the stream. Nothing loads from there unless you turned the player on and a channel is running. See [Show a live stream](https://docs.sparkletree.io/developers/sdk/live.md). ## Exactly what leaves the browser All of this goes to your SparkleTree API and nowhere else. Disclosing it to your visitors is your obligation, so here it is plainly: | Sent | Where it comes from | |---|---| | Time of day, day of week, timezone | The device clock. | | Language, coarse mobile/desktop flag | `navigator` and a media query. | | Referring origin | `document.referrer`, reduced to its origin. | | A per-tab session id | Random, kept in `sessionStorage`. | | One page view per page load | With the campaign. No page path, no variant. | | Impressions and clicks | With the campaign, the version served, where the copy came from, and whether adapted copy was on screen. | | Anything you pass as `context` | Yours. | Only the origin of the referrer is sent, never the full URL. Referrer paths and query strings routinely carry session tokens and personal data, and that value would end up in server and CDN logs. Your page content is not in that list and the API takes no parameter for it: nothing is read out of your DOM, so the copy on your page stays yours alone. There is also no geolocation prompt, no fingerprinting, no third-party analytics, and no cross-site identifier. When the browser sends Global Privacy Control or Do Not Track, none of the events above leave the browser; only the requests that load copy do. ## Drop a signal you do not want to send Your `context` is merged over the collected signals and wins, so overriding one with `undefined` removes it: ```tsx ``` ## What the `storage` prop gates `storage` controls where the visitor's "show me the standard version" preference is kept. Pass your own store if a consent manager gates `localStorage`, or if your test environment does not provide one. That preference is its whole scope. The per-tab session id and the impression and click events are sent regardless; to stop those, do not render the components. ## Fragment reads are public and cacheable The fragment read request carries no credentials and no prose from your page, only three identifiers: your organization id, the context hash, and the schema hash. That is why it can be served from a shared cache. Your fallback strings never appear in a URL. The write request, which spends credits, is the one that takes a [signed token](https://docs.sparkletree.io/developers/sdk/signed-minting.md). --- # Run the example apps Source: https://docs.sparkletree.io/developers/sdk/examples/ Markdown: https://docs.sparkletree.io/developers/sdk/examples.md Two runnable apps live in the repository, both Vite + React. The recipes app works without a SparkleTree account, streaming from the mock edge in `@sparkletree/core/testing`; the one-page integration wants real ids from your dashboard. A third, [`example-nextjs`](https://gitlab.com/sparkletree/sparkletree-sdk/-/tree/main/example-nextjs), shows live copy in server-rendered Next.js pages; see [Live copy in server-rendered pages](https://docs.sparkletree.io/developers/sdk/server-rendering.md). ## A one-page integration you can read in a sitting [`example`](https://gitlab.com/sparkletree/sparkletree-sdk/-/tree/main/example) is one page: a provider, a hero, a button. Read it in a sitting. ```bash cd example cp .env.example .env.local # fill in from your dashboard pnpm dev # http://localhost:4322 ``` ## Eleven recipes, no backend required [`examples`](https://gitlab.com/sparkletree/sparkletree-sdk/-/tree/main/examples) is the same SDK dressed for eleven very different pages. With no configuration it runs against the mock edge, served from the Vite dev server by the `mockEmbedApi` plugin with the recipes' own campaigns added as scenarios. It replays recorded responses as real network traffic, and every page is badged "mock stream" so a replay can never be mistaken for live adaptation. Any recipe can be made to fail on purpose: add `?st-mock=` to a request, or use a campaign id `st-mock-`. See [Test without an account](https://docs.sparkletree.io/developers/sdk/testing.md). ```bash cd examples pnpm dev # http://localhost:4323 ``` | Recipe | Route | What it shows | |---|---|---| | Editorial hero | `#/editorial` | Serif display type, art direction, light and dark. The SDK owns the words; your CSS owns everything they wear. | | The storefront | `#/shop` | A whole shop: a promo ribbon on the degraded path, a live seasonal hero, product cards whose prices stay facts and stay unlabelled, a brand story written as one fragment group, reviews the SDK never touches, and a generated checkout button. | | Guided dealer campaign | `#/dealer` | Your own `context` beating the SDK's guesses, and a button whose destination the campaign decides. | | The restaurant | `#/restaurant` | Tonight's menu: dishes and prices never adapt; the one adapted thing is the kitchen's note card. The quietest the SDK gets, and provenance still travels with generated copy. | | SaaS pricing page | `#/pricing` | Plans and prices are facts that never adapt; the hero's cached copy types into the held canvas in one paced entrance; one adapted sentence per plan, one label for the grid. | | Continuity page | `#/continuity` | Three blocks down a long page; later ones open when reached, carrying what the visit observed on the way. | | Water | `#/water` | A WebGL2 fluid simulation poured over a live hero and button, proving the page underneath stays ordinary clickable DOM. | | Live stream | `#/live` | A studio opens its kiln on camera. One prop on the hero shows a running live channel's player in a slot that is there from the first frame, and a second slot placed by hand shows what stands in when nothing is live. | | The product card | `#/product-card` | An adapted pitch, the product's stated name, price and stock, and a custom slot from the campaign's variant, in one card under one hold. The facts share one request and are never marked as adapted. | | Custom elements | `#/elements` | The same campaign built only from the custom elements, the way a plain HTML, Astro, Svelte or Liquid page serves it. | | The parts drawer | `#/components` | The component library: seven premade, self-contained parts. Announcement bar, split hero, product card, pricing card, FAQ block, newsletter signup, testimonial. Copy a function, keep the label. | ## Point them at your own API Set the publishable key and a campaign id (the other variables are optional) and every recipe streams from your account instead of the mock: ```bash cp .env.example .env.local ``` | Variable | | |---|---| | `VITE_SPARKLETREE_KEY` | Your publishable key. Every recipe passes it to the provider. It also carries the API base and workspace id. | | `VITE_SPARKLETREE_API_BASE` | Your embed API host. Optional with a key; when set, it wins over the key's. | | `VITE_SPARKLETREE_ORG_ID` | Your workspace id. Optional with a key; when set, it wins over the key's. | | `VITE_SPARKLETREE_CAMPAIGN_ID` | The campaign every streaming recipe plays. | | `VITE_SPARKLETREE_CONTENT_CAMPAIGN_ID` | Optional, for the card recipes. | | `VITE_SPARKLETREE_LIVE_SURFACE_ID` | Optional, for the Live stream recipe: the surface a live channel is routed to. | Without a key, live mode needs both `VITE_SPARKLETREE_API_BASE` and `VITE_SPARKLETREE_ORG_ID`. `init` writes the key, the API base, the workspace id and the campaign id with Vite's names, and registers the dev server's origin: ```bash cd examples npx @sparkletree/cli init --framework vite --origin http://localhost:4323 --campaign ``` Plaintext `http` is accepted for `localhost` only. Add the optional variables by hand. Vite reads environment variables at startup, so restart `pnpm dev` after editing `.env.local`. ## The publishable key Requests to the edge carry the workspace's publishable key (`st_pk_test_…` or `st_pk_live_…`). It is public: it sits in the browser bundle, so it is not a secret to protect. What it does is tie each request to your workspace. A test key works from a page on localhost (`http://localhost`, `127.0.0.1`, `[::1]`, any port) and from a server. From any other site the site must be registered to your workspace, test key or live key, which is why registering your origin is the step that matters for production. On localhost the examples' fragments show copy that is already written, and their fallbacks otherwise: the hosted edge writes no new fragment copy for a loopback origin. Run them against the mock edge (`sparkletree dev`) to see every kind of copy land. The edge checks the key in one of three modes, and `sparkletree doctor` reports which one is on: | Mode | A request without a valid key, or with a live key from a site that is not registered | |---|---| | `off` | Is served. The edge does not check. | | `log` | Is served, and the edge logs the reason. This is the default. | | `required` | Is refused with `401`, and the page keeps its fallback copy. | Every recipe here passes `VITE_SPARKLETREE_KEY` to the provider as `publishableKey`, and the custom elements recipe passes it to `defineSparkletreeElements`. With the key set, the recipes keep streaming when the edge requires keys. Without it, they stream only while the mode is not `required`. See [the quickstart](https://docs.sparkletree.io/developers/sdk/quickstart.md) and [Register your origin](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md). --- # What your visitors see Source: https://docs.sparkletree.io/developers/sdk/what-visitors-see/ Markdown: https://docs.sparkletree.io/developers/sdk/what-visitors-see.md These rules govern what appears on screen. They are worth ten minutes, because each one explains why an API you might reach for does not exist. Throughout, an **island** is one block of SparkleTree-managed copy on your page: a hero, or a call-to-action button. `useIsland` is the hook behind both. ## Your own copy is what a visitor reads when the stream does not deliver Your `fallback` prop is the text on screen whenever the adapted version is late, missing, or never coming. A block either shows real copy or waits over your artwork with your fallback held invisible in the space it will occupy; there is no skeleton and no spinner. This is true on a fast connection and a slow one, on the first visit and the hundredth. So the fallback is never throwaway text. It is the copy a real person reads whenever the stream does not arrive. ## Text a visitor can see is never replaced A visitor is never shown something and then has it replaced, removed, or pushed around, with one exception: a line the stream did not finish (see [below](#one-deliberate-exception-one-fade)). Every copy slot follows the same four rules: 1. **The slot holds, reserved.** When a block comes into view and live copy is coming, its text slots stay blank for a short hold, with your fallback drawn invisibly in the exact space it would take, so nothing moves. Art, background and chrome are never held; only the text waits. 2. **Live copy lands in the reserved space.** Generated copy types in as it arrives. Copy already generated for an earlier visitor in the same context lands whole, with one short fade. Either way it is the first text the visitor reads in that slot. 3. **If the hold runs out, your fallback lands, and it is final.** It fades in once, in the space it already held. Adapted copy that arrives afterwards is not shown in that page view. 4. **The server HTML never shows a fallback a stream may follow.** Server and first client render carry the same invisible reservation, so a server-rendered page holds exactly like a client-rendered one. The hold lasts 2.5 seconds and restarts once if the stream proves it is alive: when the stream starts writing a field the block shows, the hold starts again with a full 2.5 seconds. When the stream starts writing a field your fallback leaves out (the hero stream opens with the greeting, which a block without a greeting never shows), that is proof of life too: the hold then lasts at least 2.5 seconds from that moment, and the one restart is kept for the first field the block shows. Either way the longest wait is 5 seconds. On a server-rendered page that is one clock from first paint: time spent waiting for the page's JavaScript counts against the same 2.5 and 5 seconds. It starts when the block is in view: a block below the fold keeps its slot reserved and lets the stream work in the background, and when it scrolls into view finished copy is already there (or the hold starts then). A block that never scrolls into view never shows anything changing. `state.rewrites` counts replacements of visible text. Within one stream it is `0` unless a line the stream started was not finished; each such line replaced by your fallback counts one. ## Your fallback sets the size Each field's fallback defines that field's slot: its shape and its length. The slot is exactly the size your fallback takes, from the first paint to the end of the page view, whatever lands in it, so nothing around it ever moves. - **Live copy is written to fit.** Each field's fallback length is sent with the request as that field's length budget, and the platform writes copy to it. - **Copy that would not fit is not shown.** Before copy that arrives whole is painted, the slot measures it. If it would not fit the box your fallback sets, your fallback lands instead, final for the view, and the impression reports your fallback. - **Typed copy never grows the slot.** Copy that types in is clipped to the box rather than pushing the page. - **A field your fallback does not have is never shown.** There is no slot for it. Give a field a fallback to give it a place on the page. Write each fallback as long as the copy you want in that place. A slot remembers, for the page view, what it showed: per field, the text and its provenance. If the block mounts again (a suspended section resolving, a re-keyed parent), it shows exactly that again, and records no second impression. ## Visible copy changes only when the visitor causes it Copy on screen does not change because something changed behind it: the clock, a location or context value resolving, a re-render, a provider update. A change to what an island or a fragment group would show (its campaign, its context, its fallback) is handled like this: - **Nothing visible yet** (the slot is still holding): the change applies at once, under the same clock. - **The visitor caused it**: your interaction handler calls `markVisitorChange()` before the state update. The old copy stays until the new copy is ready, then one cross-fade replaces it. Your fallback is never shown in between; if the new stream fails, the new fallback arrives through that same single cross-fade. This is the change `state.rewrites` counts. - **A new page view**: the same single cross-fade, for a provider that outlives page views and is given a new `viewKey` (or a new `serverContext` from the next server read). - **Anything else** waits: the copy on screen stays until the block is off screen, and the change applies there, where nobody sees it. ```tsx import { markVisitorChange } from "@sparkletree/react"; ``` ### One deliberate exception, one fade - **A line the stream did not finish ends on your fallback.** When the stream fails while writing a line (an error, a dropped connection), or a line gets no new text for 5 seconds, the half line is replaced once by your fallback, with one cross-fade, in the space the fallback reserved. That is one change of text the visitor may be reading, and it ends on a whole sentence. It happens at most once per field, the fallback is final for the page view, and the field is marked `static`. A line that finished is never replaced. A line that was still held, so nobody saw it, and a line the stream never started simply show your fallback. The custom elements show no typing, so they land only finished lines. Time with the page hidden does not count toward the 5 seconds: when the visitor comes back, a line being written gets a fresh 5 seconds. A block that mounts again in the same page view shows your fallback for a line that was half written, never the half line. - **Keeping a typed line instead** is possible only with `openStream` in core: pass `unfinishedCopy: keepUnlessClearlyError`. React's `useIsland` builds its own choreographer and takes no such option, so a page built with `Hero`, `Cta` or `useIsland` cannot opt out today. That policy is close to 0.16.1 but not the same: a line that started and then sent no text for 5 seconds gets your fallback under either policy when nothing is held and a fallback is set (a blank slot is not text to keep); text that is clearly an error is replaced at the stall, not only at the end of the stream; and `state.rewrites` counts that replacement. See [When things go wrong](https://docs.sparkletree.io/developers/sdk/when-things-break.md#a-line-the-stream-did-not-finish). ## If the page's JavaScript is late or missing The reservation in the server HTML carries a CSS-only failsafe: if the page's JavaScript has not taken over within 5 seconds, your fallback becomes visible on its own, and visitors with scripting turned off see it at once. When the JavaScript does arrive it takes over the hold; if the failsafe had already shown your fallback, that fallback is final for the page view. A held call-to-action is invisible as a whole, not just its label, and inert: it cannot be focused, clicked or followed until its label lands. In the server HTML it carries the same failsafe instead, so without JavaScript it reveals itself, label and all, as a working link. The deadline holds when timers do not: in a background tab, or on a page restored from the browser's back/forward cache, copy that arrives after the hold ran out is not shown, even if the page's timer has not fired yet. ## Finished creative: `serverRendered` `serverRendered` is for copy that is not a fallback at all: finished campaign creative your server already rendered from the platform. It renders visibly from the first frame, nothing holds, and the stream's copy for those fields is ignored (theme, media and the button action still apply). ```tsx ``` Leave it unset for an ordinary fallback. ## Live copy in server-rendered HTML: `initialCopy` A page rendered on your server can read the live copy already cached for the visitor's context and render it as final text, so a returning context never waits at all. Pass it as `initialCopy`: visible from the first frame, settled, stamped with its provenance, and the island's whole copy (the stream writes no text into it). When the read finds nothing, the island renders its reservation and holds as usual. See [Live copy in server-rendered pages](https://docs.sparkletree.io/developers/sdk/server-rendering.md). The one trade of the hold: invisible copy is not a Largest Contentful Paint candidate, so a block that waits out the full budget defers LCP by up to that long. ## One timer, and it is yours The arrival of real text is what moves a block forward, so timing takes care of itself and a block behaves the same on a fast office connection as on a train. The one number you set is the hold budget, and every entry point takes it: `holdMs` on `Hero`, `Cta`, `useIsland` and `useFragments`, and on `openStream` in core. It defaults to 2.5 seconds. `holdMs={0}` turns the hold off: your fallback shows at once, on the server too, and stays. Whatever you set, your fallback is the floor when the budget runs out. If you draw text yourself instead of through `StreamText` or `FragmentText`, reserve the space a holding field will take: `heldReserve(field)` returns the text to reserve, and `useFragments` reports `$group.holding` while it lasts. The one presentational knob is `smooth`, which turns the typing pace and the fades on or off. It changes nothing about state or timing, and reduced-motion visitors always get the final text at once. ## Adapted copy always carries its provenance Every non-static field is stamped `data-content-source` in the DOM: machine-readable, auditable, and never applied to copy the server declared static. Copy served from cache counts as adapted too — it was generated, just for an earlier visitor in the same context; calling it authored would be an untruth in the other direction. ## The SDK never adds a visible AI label No component, hook or helper in the SDK puts an AI label or icon on your page. Provenance is in the data, and what your visitors see is up to you. Some jurisdictions require AI-generated content to be labelled; whether and how to label is the site owner's choice. If you want a label, `decideChrome` tells you when a field counts as adapted for this viewer, and the label is your own markup: ```tsx import { StreamText, useSparkletree } from "@sparkletree/react"; import { decideChrome } from "@sparkletree/core"; function Headline({ field }) { const { prefersStandard } = useSparkletree(); const chrome = decideChrome(field.source, prefersStandard); return ( <>

{chrome.marked ? AI-generated content : null} ); } ``` `decideChrome` keeps the claim honest either way: it never calls your own copy AI-generated. ## The two cases where `marked` is false - **The copy was not adapted.** Your fallback, a product name, a price: anything whose `source` is `static`, because there is nothing to disclose. Claiming authored copy is AI-written is treated as the worse error. - **The visitor asked for the standard version.** Any viewer can switch the preference for themselves; give them the control from the provider: ```tsx import { useSparkletree } from "@sparkletree/react"; function StandardVersionToggle() { const { prefersStandard, setPrefersStandard } = useSparkletree(); return ( ); } ``` The preference is stored per browser and honoured by every SparkleTree block on the page. Fragments aggregate naturally at the group: one `useFragments` call is one draw, so `fragments.$group.marked` is one decision for everything written together, and the `FragmentGroup` container is stamped with the strongest provenance among its fields. When the server sends a localized label with the fragments, `fragments.$group.disclosure?.label` carries it ("AI-generated content" in English), so a group label can use the server's wording: ```tsx {f.$group.marked && f.$group.disclosure ? ( {f.$group.disclosure.label} ) : null} ``` The package also exports `InlineMark`, an optional helper that renders an unstyled `` holding its `markLabel` as plain text. Nothing renders it unless you do. ## Pass the field, not the string ```tsx // Renders the copy with its provenance and paced entrance. // Renders AI-written copy with no provenance stamp. Do not do this.

{state.fields.headline.text}

``` ## Two blocks of one campaign always tell the same story A campaign can be running an experiment with several versions. Within one page view, every block of that campaign is served the same version, so your hero cannot come from one arm and your button from another. A client-side navigation counts as a new page view only when the last provider unmounts. A provider at your app root survives route changes, so call `pageVariants.reset()`, exported from `@sparkletree/react`, when your router changes route. ## Check which stage a block has reached `state.phase` tells you where an island is, and it is stable enough to key styling off: | `state.phase` | On screen | |---|---| | `idle` | Before the stream exists: your fallback, reserved invisibly (or visible with `serverRendered`, `enabled={false}` or `holdMs={0}`). | | `holding` | Your artwork, with the text slots held for a moment, their space reserved by your invisible fallback. | | `live` | Adapted copy, arriving. | | `settled` | Final copy for this page view. | | `failed` | Finished copy stands. A line the stream did not finish is replaced once by your fallback; a blank or still-held slot gets your fallback. | `Hero` and `Cta` stamp it on the element as `data-phase`, alongside `data-typing`, `data-settled` and `data-content-source` on each piece of text. --- # Live copy in server-rendered pages Source: https://docs.sparkletree.io/developers/sdk/server-rendering/ Markdown: https://docs.sparkletree.io/developers/sdk/server-rendering.md Text a visitor can see is never replaced, so live copy is decided before a slot is shown. A page rendered in the browser decides it with the hold: the slot waits blank for a moment, then live copy or your fallback lands once. A page rendered on your server can do better for visitors whose context has been seen before: it can read the live copy already cached for that context and put it in the HTML as final text. When there is nothing cached, the island renders its reservation exactly as before, and the browser's stream and hold take over. First paint is never blocked on the read. ## What the read is `getIslandCopy`, from `@sparkletree/react/server` (or `@sparkletree/core/server`), is a server-only function: ```ts import { getIslandCopy } from "@sparkletree/react/server"; const read = await getIslandCopy({ publishableKey: process.env.SPARKLETREE_PUBLISHABLE_KEY!, campaignId: "cmp_123", // or surfaceId islands: ["hero", "cta"], fallbacks: { hero: heroFallback, cta: ctaFallback }, // the islands' own fallbacks declared: { page: "home" }, // the same values as the provider's context headers: requestHeaders, // a Headers object or a plain record budgetMs: 250, // the default; 1000 at most }); read.islands.hero; // { copy, contentSource: "cached", freshness, variantId, campaignId } or null read.islands.cta; // the same, or null read.context; // pass to read.elapsedMs; // how long the read took, for your logs ``` - **Strictly a read.** Nothing is generated and nothing is counted. The impression records in the browser when the island is seen, with the copy's variant and provenance (`cached`, or `cached-stale` for copy past its freshness window). - **Never throws, never waits past the budget.** A miss, an error, a timeout, a malformed key or a call in a browser all return `null` islands. The budget is the total wait, network included. - **One read, one variant.** Name every island you render in one call. In the App Router, wrap the call in React's `cache` so islands in separate Suspense boundaries share it. - **Live or test key.** The read takes your publishable key from the server, so no origin is involved: a live key (`st_pk_live_`) in production, a test key (`st_pk_test_`) in local development. - **Pass the islands' fallbacks.** Each fallback sets its slot's size, and its length goes with the request as that field's length budget, exactly as the island's stream in the browser sends it, so the read finds the copy the stream cached. A field a fallback does not have is left out of the result. ### What it sends Only an allow-list of the visitor's request headers is read: | Header | Becomes | |---|---| | `Accept-Language` | The language (well-formed entries only). | | `Sec-CH-UA-Mobile`, else `User-Agent` | The device bucket: `mobile` for phones, `desktop` for everything else, tablets included, as in the browser. | | `x-vercel-ip-timezone`, else `cf-timezone` | The time zone, and from it the time of day, bucketed exactly as the browser does. Pass `fallbackTimezone` for hosts that send neither. | The visitor's IP address, cookies, full user agent, referrer and location are never read or sent. The key travels as an `Authorization` header, never in the URL. ## The browser adopts the server's context Copy is cached per context. For the browser's stream to replay the entry the server read, or to fill the one it missed, it has to send the same values. Pass `read.context` to the provider: ```tsx ``` For that page view the browser then sends the server's device type, time of day, time zone and language instead of reading its own (a value the server left out is left out), and pins the variant the server decided before any island's stream opens. Values in the provider's `context` still win, so keep the declared placement the same on both sides; custom dimensions (`custom: { tier: "pro" }`) are sent as `x.tier` by both. Without `serverContext` nothing changes. Each read names its page view. A provider that stays mounted across navigations (an app-root layout) starts a new page view when it is given the next read's context: pins, slot memory and impressions start fresh, before any island below opens its stream, and copy from the new read is shown with one cross-fade. Copy for the same page view is never swapped: a different `initialCopy` with the same `serverContext` is not shown until the next view. ## Islands with and without copy ```tsx ``` - **A hit** renders visibly from the first byte, settled and final, stamped `data-content-source="cached"`, in the slots your fallback sets. It is the island's whole copy: the stream still brings theme, media and the button's action, but writes no text. A field the cached copy has no text for shows your fallback; a field your fallback does not have is not shown. - **A miss** (`undefined`) renders the reservation: your fallback, invisible, holding its space. In the browser the hold runs as usual. ## Next.js App Router Stream the shell first and each island when its read is back. Never await the read above a Suspense boundary; that would hold the whole page on it. ```tsx // app/page.tsx import { IslandReservation } from "@sparkletree/react"; import { Suspense } from "react"; export default function Page() { return (
}>
); } ``` ```tsx // app/live-hero.tsx (a server component) import { Hero, SparkletreeProvider } from "@sparkletree/react"; import { getIslandCopy } from "@sparkletree/react/server"; import { headers } from "next/headers"; import { cache } from "react"; const readCopy = cache(async () => getIslandCopy({ publishableKey: KEY, campaignId: CAMPAIGN, islands: ["hero", "cta"], fallbacks: { hero: heroFallback, cta: ctaFallback }, headers: await headers(), }), ); export async function LiveHero() { const read = await readCopy(); return ( ); } ``` `IslandReservation` renders the island's reservation as static markup: the same elements and the same invisible fallback, so the slot owns its space from first paint, and a hit arriving makes text appear without replacing anything. Give it the same `fallback`, `className`, `style` and (for a `cta`) `href` as the island. The reservation and the island are one slot, with one clock. The reservation holds blank for at most 5 seconds from its first paint, then shows your fallback. When the island arrives inside that time, its copy lands in the blank slot, and a miss holds only what is left of the 2.5 second budget. When it arrives later, its copy is not shown: your fallback stays, final for the view. This works before the page's JavaScript has loaded too: the reservation and the island each carry a small inline script. If your Content Security Policy requires a nonce for inline scripts, pass it as `nonce` to `IslandReservation`, `Hero` and `Cta`. Reading `headers()` makes the route dynamic, and the read is `cache: "no-store"`: the HTML is per request and never shared between visitors. Do not put a page that reads copy behind a shared cache. ## Next.js Pages Router `getServerSideProps` finishes before any HTML is sent, so the read's budget adds to the time to first byte. Keep it small; a slow read simply returns no copy. ```tsx export const getServerSideProps = async ({ req, res }) => { const read = await getIslandCopy({ publishableKey: KEY, campaignId: CAMPAIGN, islands: ["hero", "cta"], fallbacks: { hero: heroFallback, cta: ctaFallback }, headers: req.headers, budgetMs: 150, }); res.setHeader("Cache-Control", "private, no-store"); return { props: { read } }; }; ``` The result is plain JSON and passes through props as is. ## Static pages, ISR and static export Do not call `getIslandCopy` for HTML that is built once and served to everyone. There is no visitor at build time, and one visitor's copy baked into shared HTML would be shown to all of them. Render the islands without `initialCopy`: they carry the reservation, and in the browser they hold while the stream brings live copy, or your fallback lands and stays. That is an explicit choice, not a degraded mode: it is exactly how a client-rendered page behaves. ## Stated facts on the server Facts are not adapted copy, so a server can read them for any page, static pages included, and render them as final text: they are the workspace's records, the same for every visitor. Read them with `fetchFacts` and your publishable key (a server sends no `Origin`, so the edge reads facts for a server caller only with a valid key): ```tsx // app/products/mug/page.tsx (a server component) import { fetchFacts } from "@sparkletree/core"; export default async function MugPage() { const { facts } = await fetchFacts({ apiBase: "https://p.qrtree.ai", organizationId: ORG, publishableKey: process.env.SPARKLETREE_PUBLISHABLE_KEY, products: ["stoneware-mug"], }); const mug = facts?.products[0]; return

{mug?.name ?? "Stoneware mug"}

; } ``` `fetchFacts` never throws; on any failure `facts` is `null` and your own text renders. A page built once and served to everyone shows what the facts said at build time: rebuild or revalidate it when your prices change. The edge caches a facts answer for 60 seconds. A `` in the same page holds on the server like every fragment: the HTML carries its fallback as the reservation, and the browser reads the fact. Use `fetchFacts` for text the server should decide, and `` for a fact that should be read fresh in the browser. ## Describe the page for agents: `` ``, from `@sparkletree/react/server`, reads the facts on the server and renders a schema.org `` + surface.links.map((l) => ``).join("") : ""; ``` | Option | | |---|---| | `apiBase` | Required. The edge. | | `organizationId` | Required. Your workspace id. | | `publishableKey` | Your `st_pk_` key. Pass it: a server sends no `Origin`, so the edge reads facts for a server caller only with a valid key. Development builds warn without it. | | `campaignId`, `surfaceId`, `products` | What to read, as for `fetchFacts`. | | `signal`, `fetchImpl` | As elsewhere. | The result is `{ facts, jsonLd, links, reason? }`. `facts` is the facts document, or `null` with `reason` when it could not be read; `jsonLd` and `links` are then `null` and empty. `getAgentSurface` never rejects. `serializeJsonLd` writes `<`, `>`, `&`, U+2028 and U+2029 as `\u` escapes, so no stated value can close the script element. The result parses to the same value. `buildAgentJsonLd(facts)` builds the graph from a facts document you already have. ## The JSON-LD For a campaign with one product, the graph reads: ```json { "@context": "https://schema.org", "@graph": [ { "@type": "Organization", "@id": "https://kiln.example#organization", "name": "Kiln & Co", "url": "https://kiln.example" }, { "@type": "Product", "name": "Stoneware mug", "description": "A heavy mug, fired twice.", "sku": "MUG-01", "url": "https://kiln.example/mug", "image": "https://kiln.example/mug.jpg", "brand": { "@id": "https://kiln.example#organization" }, "offers": { "@type": "Offer", "price": "249.00", "priceCurrency": "SEK", "availability": "https://schema.org/InStock", "url": "https://kiln.example/mug" } }, { "@type": "AskAction", "name": "Ask about this campaign", "target": { "@type": "EntryPoint", "urlTemplate": "https://p.qrtree.ai/ask", "httpMethod": "POST", "contentType": "application/json" } } ] } ``` - The `Organization` is identified by its website on record, or by `urn:sparkletree:organization:{id}` when there is none. - Each product is a `Product` with the members the workspace has stated. Its `Offer` carries the price only when it is a plain decimal, `priceCurrency`, and `availability` only for `in_stock` (`InStock`) and `out_of_stock` (`OutOfStock`). A product with none of these has no offer. - The `AskAction` is there only when the facts document has an `ask` entry: the campaign is public on the edge and the workspace's assistant is on. ## The links | `rel` | `href` | When | |---|---|---| | `describedby` | The facts URL that was read, `application/json`. | Always, with facts. | | `alternate` | `{apiBase}/c/{campaign-id}/manifest.json`, `application/json`. | When the campaign is public on the edge. | | `alternate` | `{apiBase}/llms.txt`, `text/plain`. | Always, with facts. | ## How an agent checks the facts The JSON-LD in your page is a copy, and a copy can be edited by anyone who serves the page. The signed original is the facts document the `describedby` link points to. An agent checks it like this: 1. Fetch the facts URL. The document's `signature` names a `keyId`. 2. Fetch `/.well-known/sparkletree-keys.json` from the SparkleTree host that served the facts, and find the key whose `kid` is that `keyId`. 3. Remove `signature`, write the rest as canonical JSON (RFC 8785), and verify `signature.value` with Ed25519 against the key's `x`. `verifyFacts` from `@sparkletree/core` does steps 2 and 3: ```ts import { fetchFacts, verifyFacts } from "@sparkletree/core"; const { facts } = await fetchFacts({ apiBase: "https://p.qrtree.ai", organizationId, publishableKey, campaignId }); const { valid, keyId, reason } = await verifyFacts(facts, { apiBase: "https://p.qrtree.ai" }); ``` It fetches keys only from a SparkleTree host over https (or loopback); keys from any other host prove nothing about who signed. To verify against keys you hold, pass `keys` and nothing is fetched. When the edge has no signing key, `signature` is `null` and `verifyFacts` resolves `{ valid: false, reason: "unsigned" }`. ## How an agent asks The `AskAction` and the facts document's `ask` entry name the edge's `/ask`. An agent posts `{ "question": "…", "campaign": "{campaign-id}" }` and gets `{ answer, campaign, links, homeCampaignId, session }` back; it sends `session` with the next question to continue. The rules are on [Let visitors ask](https://docs.sparkletree.io/developers/sdk/ask.md). ## What it does not do - **No `llms.txt`, agent card or sitemap on your host.** The links point at the edge's documents, which describe the edge's own pages, not your site. - **No signature on your page.** The JSON-LD is unsigned; the signed facts are at the `describedby` URL. - **No copy, and nothing generated.** Only stated facts go in. Adapted copy on your page is not described. - **No reviews, ratings, prices in other currencies or offers you did not state.** The graph has the members the facts have, and no others. - **No refresh.** It is what the facts said when your server rendered the page. A page cached for a day says what was true when it was cached; the facts endpoint itself is cached for 60 seconds. - **No answers on your own host.** Questions go to the edge's `/ask`. --- # Provider, components and useIsland Source: https://docs.sparkletree.io/developers/sdk/components/ Markdown: https://docs.sparkletree.io/developers/sdk/components.md An **island** is one block of SparkleTree-managed copy: a hero, or a call-to-action. `Hero` and `Cta` are thin wrappers over the `useIsland` hook; when their layout does not suit you, call the hook and write your own. ## Wrap the page once with `SparkletreeProvider` Everything else must render inside it, or it throws with a message telling you so. ```tsx {children} ``` | Prop | What it does | |---|---| | `publishableKey` | `st_pk_live_…` or `st_pk_test_…` from the dashboard. A signed credential sent on every request as `st-key`; the server refuses requests without it. Also decoded locally to an organization id and API host. | | `apiBase` | API host, if you self-host. Wins over the key. | | `organizationId` | Your organization id. Wins over the key. | | `context` | Extra context merged over what the SDK collects. Yours wins on conflict. Must be JSON-serializable. | | `serverContext` | The visitor context and variant your server read copy with: pass `getIslandCopy(...).context`. For this page view the browser sends the same device type, time of day, time zone and language, and keeps the server's variant. See [Live copy in server-rendered pages](https://docs.sparkletree.io/developers/sdk/server-rendering.md). | | `mintToken` | A signed token, or a function receiving the write (`{ context, schema, contextHash, schemaHash }`) and returning a token bound to it, for [fragment minting](https://docs.sparkletree.io/developers/sdk/signed-minting.md). | | `storage` | Where the visitor's "standard version" preference is kept. Defaults to `window.localStorage`; pass your own if a consent manager gates it. | | `fetchImpl` | Replacement `fetch`, for tests. | Pass `publishableKey`, or both `apiBase` and `organizationId`. With neither, the provider throws at render. A misconfigured integration is a setup error, not something to silently degrade around. An inline `context={{ … }}` object is fine. Identity is compared by content, so re-creating the object each render does not re-request anything. ### What the provider collects on its own Time of day, day of week, timezone, language, a coarse mobile/desktop flag, and the origin of the referring page, never the full referrer URL. No permission prompt, no geolocation, no fingerprinting. Each signal is optional: missing ones cost a less well-adapted creative, not a working page. Override any of them, or drop one entirely: ```tsx ``` One exception: time of day. The server derives the daypart from the timezone itself, so a `timeOfDay` override is ignored for island copy — override the `timezone` if you need a different clock. ## `Hero` renders a greeting, headline and body ```tsx ``` Fields you leave out of `fallback` are not rendered. The component draws the campaign's background image behind the copy when there is one, and applies the campaign's colours as CSS custom properties on the section. Add `live` and the hero shows a running live channel's player in a 16:9 slot it holds from the first frame. See [Show a live stream](https://docs.sparkletree.io/developers/sdk/live.md). ### Legal lines The stream sends the campaign's legal lines for the viewer's market, and they reach your code as data: `parts.legal` in a `Hero` layout, `useIsland(...).legal`, and `state.legal`. Each is a list of strings, verbatim and in the author's order, empty until the stream sends them and when the campaign has none. They are not copy: no hold, no mark, and the stream never replaces them. The default layout does not render them, because lines that arrive after the first paint would move the page. A layout that shows them puts them in a space it reserves itself, rendered whether or not lines have arrived: ```tsx ( <> {parts.headline} {parts.body}
{(parts.legal ?? []).map((line, i) => {line})}
), }} /> ``` Render each line exactly as given. `legal` is optional on the types so parts and results built by hand (a test, a story) still compile: read it as `parts.legal ?? []`. ## `Cta` renders one button label ```tsx ``` It renders an `` when a destination survives vetting: the campaign's own if it supplies one, otherwise your `href`. With neither it renders a non-interactive `` instead. Clicks are reported automatically, and your `onClick` still runs. While its label holds, the whole button keeps its space but is invisible and inert: it cannot be focused, clicked or followed. It appears, usable, when its label lands. Your own button gets the same with `useHeldControl`: ```tsx const control = useHeldControl(state.fields.cta); … ``` ## Props shared by `Hero` and `Cta` | Prop | What it does | |---|---| | `campaignId` | The campaign to play. | | `surfaceId` | Use instead of `campaignId` when a screen or placement decides what plays. Pass one or the other. | | `fallback` | Required. Your copy: `{ greeting?, headline?, body?, cta? }`. Each field's fallback sets that field's slot, its shape and its length: live copy is written to its length, whole copy that would not fit is not shown, and a field without a fallback is never shown. | | `serverRendered` | Finished campaign creative your server already rendered from the platform, not an authored `fallback`. It renders visibly from the first frame and is final: nothing holds, and the stream's copy for those fields is ignored. Omit it for an ordinary fallback, which is reserved invisibly (in the server HTML too) until live copy or the end of the hold. | | `initialCopy` | Copy already produced for this view, such as `getIslandCopy(...).islands.hero`. It renders visibly from the first frame, settled and final, with its provenance; it is the island's whole copy, and the impression records when the island is seen. Pass `undefined` when there is none. | | `heldBeforeMs` | How long the slot already held blank before this render. Spent from the hold and the 5 second maximum. Not needed after an `IslandReservation`: the island measures that wait from the reservation's first paint. | | `slot` | Tells apart two blocks with the same campaign (or surface) on one page. A block remembers what it showed for the page view, so mounting it again shows the same copy and records no second impression; blocks with the same campaign and `slot` share that memory. | | `nonce` | A nonce for the small inline script in the server HTML, for pages whose Content Security Policy requires one. | | `enabled` | `false` skips the network entirely and renders your fallback visibly. For Storybook, previews and tests. | | `sessionId` | Keeps copy continuous for a returning visitor on an individual screen. Omit and each page view is independent. | | `pin` | Defaults to `true`: this block shares the page's campaign version. Set `false` for a block that is meant to say something different for the same campaign. | | `smooth` | Defaults to `true`: live copy types in at a steady pace, copy that lands whole fades in once, and a deliberate replacement cross-fades once. Pass `false` for text verbatim. Presentation only. | | `holdMs` | How long the text slots hold, once the block is in view, waiting for live copy before your `fallback` lands. While holding, the fallback occupies its space invisibly, so nothing moves when copy lands. Defaults to 2500, and restarts once when the stream proves it is alive. Whatever lands is final for the page view. `0` turns the hold off: the fallback shows at once and stays. | | `className`, `style` | Passed through. | | `layouts` (Hero only) | Named render functions the campaign may choose between. | | `live` (Hero only) | `true` holds a 16:9 slot after the body and shows the player there when a live channel is running. Off by default. See [Show a live stream](https://docs.sparkletree.io/developers/sdk/live.md). | ## Give the campaign a choice of layouts A campaign can ask for a named layout; you decide which names you draw. The layout arrives with the stream, so the block starts in the default arrangement and the component swaps when it lands. An undeclared name falls through to the built-in arrangement, so a campaign can never ask for markup you did not write. ```tsx (
{headline}{body}
), }} /> ``` ## Build your own markup with `useIsland` ```tsx import { useIsland, heldReserve, StreamText } from "@sparkletree/react"; function CustomHero() { const fallback = { headline: "Software that meets the moment" }; const { state, ref } = useIsland({ campaignId: "camp_123", island: "hero", fallback }); // The hold reserves, and useIsland does the reserving: while the canvas // waits, each blank field arrives already carrying its held copy, and // StreamText keeps the geometry invisibly. Nothing to wire. The one // question left to your markup is heldReserve's: a blank field with a // reserve still occupies its space, so keep its element mounted. return (
{state.fields.body.text || heldReserve(state.fields.body) ? ( ) : null}
); } ``` `island` is `"hero"` or `"cta"`; there are no other kinds. Every other option is the same as the props above. **Attach `ref` to the element that has to be visible.** It is how impressions are counted. Leave it off and your campaign renders perfectly while reporting zero traffic. See [Impressions and clicks](https://docs.sparkletree.io/developers/sdk/analytics.md). ### What `useIsland` gives you back `state.fields.greeting`, `.headline`, `.body` and `.cta`, each carrying: | Field property | Meaning | |---|---| | `text` | What to render right now. Never a placeholder. | | `source` | `"generated"`, `"cached"` or `"static"` (your own copy). | | `typing` | Live text is currently landing. | | `settled` | This text is final for the page view. | | `mode` | The delivery mode the server declared. | `state.rewrites` counts replacements of text the visitor could see this page view. Copy landing in a blank slot is not one, so a stream that finishes its lines counts `0`. One is added when your fallback replaces a line the stream did not finish (it failed, or the line got no new text for 5 seconds), and one per cross-fade after a campaign or context change the visitor caused. The phase values are tabled in [When things go wrong](https://docs.sparkletree.io/developers/sdk/when-things-break.md). Also on `state`: `phase`, `theme`, `layout`, `backgroundImage`, `videoUrl`, `live` (the [live player's block](https://docs.sparkletree.io/developers/sdk/live.md), or `null`), `legal` (the [legal lines](#legal-lines), also returned as `legal` beside `state`), `ctaAction`, `ctaStyle`, `sequence`, `contentSource`, `degraded`, `variantId`, `error`, `rewrites`, `meta`, and `held`. `held` is the copy the hold pulled off the canvas per field, whatever was actually painted there, `/content` copy or your fallback. `useIsland` attaches it back onto each holding field so a blank field keeps occupying its exact space; `heldReserve(field)` reads the reservation when your markup needs to know. An island carries four copy fields today. For copy of your own naming, any keys you like anywhere in your UI, reach for [fragments](https://docs.sparkletree.io/developers/sdk/fragments.md). ## `StreamText` renders one field ```tsx ``` | Prop | What it does | |---|---| | `field` | The field object from `state.fields.*`. Not `field.text`. | | `as` | Element to render. Defaults to `span`. | | `smooth` | Live typing at a steady pace, one fade for whole landings and deliberate replacements. Defaults to `true`; pass `false` for text verbatim. | | `className`, `style` | Passed through. | It stamps `data-typing`, `data-settled`, `data-holding` and `data-content-source` on the element for styling and auditing. While a field holds it draws the reservation (invisibly, in the server HTML too) and sets `aria-busy`, so screen readers announce the copy once, when it lands. It never wipes and retypes visible text. ## Stated facts: `Fact` and `useFacts` `Fact` shows one stated fact of one product, as text inside your own element. It is a one-field fragments group, so it holds, lands once and reserves its space like every fragment: ```tsx

``` | Prop | | |---|---| | `product` | The product's id or handle. | | `fact` | `name`, `price`, `amount`, `currency`, `availability`, `sku` or `description`. | | `labels` | With `fact="availability"`: your words for each state, `{ in_stock, out_of_stock }`. The label for the stated state is shown; without one the fallback stays. | | `fallback` | Required. The text when the fact is not stated or cannot be read. It sets the fact's space; for availability, make it the longest label. | ```tsx

``` `useFacts({ campaignId?, surfaceId?, products? })` returns the whole facts document as data, `{ facts, ok, reason, verify }`, and holds nothing. See [Show prices and other facts](https://docs.sparkletree.io/developers/sdk/facts.md). ## Questions: `useAsk` `useAsk({ campaignId?, organizationId? })` keeps a conversation with the workspace's assistant and renders nothing: `{ ask, answer, status, links, followUps, error, reset }`. See [Let visitors ask](https://docs.sparkletree.io/developers/sdk/ask.md). ## Server only: `@sparkletree/react/server` `getIslandCopy` and `deriveServerContext` (see [Live copy in server-rendered pages](https://docs.sparkletree.io/developers/sdk/server-rendering.md)), ``, `getAgentSurface`, `buildAgentJsonLd` and `serializeJsonLd` (see [Be readable by visiting agents](https://docs.sparkletree.io/developers/sdk/agents.md)), and `getResults`, a campaign's results read with a secret API key. They are the functions of `@sparkletree/core/server`, re-exported so a React project imports from one package. Never import this entry from a client component. ## Cards for copy that does not stream `CopyCard` and `ProductCard` render copy you already have, from your own CMS, catalogue or API call, and route it through the same provenance logic. ```tsx ``` Set `contentSource` from where the copy actually came from, never a guess; it defaults to `static`. Product names and prices are always treated as authored facts and never claim adapted provenance. ## Style it with class hooks and custom properties No CSS ships with the package. Campaign colours arrive as `--st-*` custom properties on the rendered element, so your stylesheet can consume them: ```css .st-hero { background: var(--st-background, #fff); } .st-cta { background: var(--st-primary); color: var(--st-cta-text); } .st-stream-text[data-typing="true"]::after { content: "▍"; } ``` Outside React, `themeStyle(state.theme)` returns the same properties as a style object and `applyTheme(element, state.theme)` sets them on a node, returning a function that undoes it. --- # Use it in any framework Source: https://docs.sparkletree.io/developers/sdk/elements/ Markdown: https://docs.sparkletree.io/developers/sdk/elements.md `@sparkletree/core/elements` is a set of custom elements. They do what the React components do, on any page that can write HTML: plain HTML, Astro, Svelte, Liquid, Vue. The text you serve inside them is the fallback. It is there before any script runs, it sets the layout, and it is what a reader without scripts sees. ## A complete page ```html

God morgon

Stoneware for slow mornings

Fired twice and glazed by hand in our studio.

Not live right now

Stoneware mug

A heavy mug that keeps coffee warm.

249,00 kr

Slutsåld

Delivery in two days

Buy the mug ``` `/sparkletree.js` is one module: ```js import { defineSparkletreeElements } from "@sparkletree/core/elements"; defineSparkletreeElements(); ``` Build it with your bundler. Without one, serve the package's `dist/` folder from your site and import `dist/elements/index.js` from it by a relative path; the folder has no other dependencies. What happens on this page: - The hero island streams live copy for its greeting, headline and body. The CTA island streams its button label, puts the campaign's checked destination on your link, and records the click. Both islands show the same variant of the campaign. - The fragments group writes `pitch` for its declared placement, reads the mug's stated name, price and availability (shown in the page's words, "I lager" or "Slutsåld"), and reads the `promoLine` custom slot of the variant the hero drew. One hold covers all five texts. - The live slot shows the player when a live channel is running, in the box your CSS reserved. ## The same markup in other frameworks The markup is the same everywhere. Each snippet below changes only what its framework requires. Load `/sparkletree.js` with the same tag in the page head in every case. **Astro.** A script tag with attributes other than `src` is left as written, so the render-blocking tag goes in the layout's `` with `is:inline`: ```astro --- const { handle } = Astro.props; ---

A heavy mug that keeps coffee warm.

249,00 kr

``` **Svelte.** Write the elements as they are. Use `slot-name`, not `slot`: Svelte reserves the `slot` attribute. ```svelte

A heavy mug that keeps coffee warm.

249,00 kr

``` **Liquid.** ```liquid

{{ product.description | strip_html | truncate: 120 }}

{{ product.price | money }}

``` **Vue.** Tell Vue the elements are not components: ```ts // vite.config.ts vue({ template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith("sparkletree-") } } }) ``` ```vue ``` This works the same with Vue on the server (Nuxt, for example). **React.** In a React app, use the [React components](https://docs.sparkletree.io/developers/sdk/components.md). If you write the elements in JSX instead, write them as they are: React passes every attribute shown here to the element. In TypeScript, declare the tags in `JSX.IntrinsicElements` first. ## The elements ### `` One island stream for the `` elements inside it. | Attribute | | |---|---| | `campaign` | The campaign to play. | | `surface` | Use instead of `campaign` when a screen or placement decides what plays. | | `island` | `hero` (the default: `greeting`, `headline`, `body`) or `cta` (`cta`). | | `hold-ms` | How long the texts hold, once in view, before the served text is final. Defaults to 2500. `0` turns the hold off. | | `pin` | `false` lets this island draw its own variant instead of sharing the page's. | | `name` | Tells apart two islands of the same campaign on one page. | Each field of the island takes one text with served text in it. A text for another field, a second text for the same field, or an empty one shows as served, and development builds say so. In a `cta` island, the campaign's destination is checked and set as the `href` of the `` around the text or inside it, and a click on it is recorded. An island records one page view, and one impression when it has been seen, with what the visitor was shown. ### `` One fragments group for the `` elements inside it: one request, one hold, one draw. | Attribute | | |---|---| | `page`, `intent`, `audience`, `notes` | The declared context, as in [fragments](https://docs.sparkletree.io/developers/sdk/fragments.md). | | `campaign`, `surface` | The default campaign or surface for slot texts that name none. | | `hold-ms` | As on the island. Defaults to 2500. `0` turns the hold off. | ### `` One text. Its served text is the fallback. When it holds a single element and no text of its own (`Start`), the copy is written into that element, so your link or emphasis stays and only its words change. | Attribute | | |---|---| | `field` | In an island: `greeting`, `headline`, `body` or `cta`. In a fragments group: the field's name, which is its key in the request. | | `key` | In a fragments group: an older name for `field`, still read. When both are set, `field` wins. Vue and React keep `key` for themselves and do not write it to the element, so use `field`. | | `kind` | In a fragments group: `cta`, `label`, `headline`, `body` or `empty-state` for generated copy (`body` when absent); `fact` or `slot`. | | `product`, `fact` | With `kind="fact"`: the product's id or handle, and the fact (`name`, `price`, `amount`, `currency`, `availability`, `sku`, `description`). | | `in-stock`, `out-of-stock` | With `fact="availability"`: your words for each state. The words for the stated state land; without them the served text stays. | | `slot-name` | With `kind="slot"`: the custom slot's name. `slot` is read too, but some frameworks reserve it. | | `campaign`, `surface` | With `kind="slot"`: where to read the slot, over the group's. | A text with no field name, an unknown fact, a slot with no name or no served text takes no part: it shows as served. Two texts with the same field name in one group are one field: they show the same copy. ### `` One stated fact on its own, with no group around it. It is a fragments group of one text, the element itself, so it follows the same rules. ```html

Price: 249,00 kr

In stock

``` | Attribute | | |---|---| | `product` | The product's id or handle. | | `fact` | `name`, `price`, `amount`, `currency`, `availability`, `sku` or `description`. | | `in-stock`, `out-of-stock` | With `fact="availability"`: your words for each state. Without a label for the stated state the served text stays, so availability needs them. Make the served text the longest label. | | `hold-ms` | As on the island. | Facts that start within the same frame share one facts request: a name, a price and an availability for one product make one request. `price` is formatted for the language of the nearest `lang` attribute, else the document's, else `en`. See [Show prices and other facts](https://docs.sparkletree.io/developers/sdk/facts.md). ### `` The live player's slot. Inside a `` it shows the island's player. On its own, with a `campaign` or `surface` attribute, it opens a stream of its own for the player only, pinned to the variant the page already shows for that campaign. Its children show while there is no player. The SDK builds the iframe itself from the stream's checked address and never inserts markup from the stream. A player for the channel that is already playing leaves the iframe alone, so it does not reload. A page with a Content Security Policy needs `frame-src https://*.cloudflarestream.com`. ## Configuration Each value is read from the first place that has it: 1. a `data-sparkletree-key`, `data-sparkletree-api-base` or `data-sparkletree-organization` attribute on the element or any element around it, for example ``; 2. the config passed to `defineSparkletreeElements`; 3. a `` tag, or `sparkletree-api-base` and `sparkletree-organization`. As everywhere in the SDK, an explicit organization and API base win over the key's own for addressing, and the key is still sent as the credential. An element with no working configuration (no key and no organization with an API base, a malformed key, an insecure API base) keeps its served text, and development builds say what to add. ```js defineSparkletreeElements({ publishableKey: "st_pk_live_…", // or from the page, as above context: { deviceType: "kiosk" }, // merged over what the browser collects, for island streams mintToken: async ({ context, schema }) => getToken(context, schema), // for fragment writes }); ``` Every member is optional: `publishableKey`, `apiBase`, `organizationId`, `context`, `fetchImpl` and `mintToken`. Call it once, as early as you can. Calling it again is safe: elements already defined are left alone, and the first config passed is the one used. Where there is no `customElements` (server rendering, a worker) it does nothing and returns `false`, so the import is safe in code that also runs on a server. The island streams send the same signals the React provider collects: time of day, day of week, time zone, language, a mobile or desktop flag and the referring origin. A fragments group sends only its declared context. ## When copy lands, and when the served text stays - **While copy is coming, the texts hold.** Each text is hidden with `visibility: hidden`, its served text in place, so its space is kept and nothing is blanked. - **The hold starts when a text is in view** and lasts `hold-ms`, 2500 ms by default. It restarts once when the stream proves it is alive (an island) or when the server starts writing copy for this view (a fragments group), never past twice the budget. - **Copy lands once, inside the hold.** An island's copy lands whole when the stream finishes; a field still being written when the hold runs out, when the stream breaks, or when it stops getting text, is not shown, and its served text stays. The elements never show typing, so the one case where React replaces visible text (a half line it typed) does not arise here. A fragments group lands when its response arrives. Each text lands only if it fits (see the next section); a text that does not fit keeps its served text. - **When the hold runs out, the served text is the copy**, final for the page view. Copy that arrives later is not shown. A fragments request still running is stopped; an island's stream runs on for the theme, the live player and the destination, but writes no text. - **Text the visitor has seen is never replaced.** When an attribute changes (another `campaign`, another `page`), copy that nobody has seen yet is read again at once. Visible copy changes only when the visitor caused it: call `markVisitorChange()` from `@sparkletree/core` in the event handler before you change the attribute, and the new copy replaces the old once, whole. Otherwise the change waits until the group is off screen. - **A group that is created again** in the same page view (a client-side navigation, for example) shows what it showed before, with nothing held. ### Why the script must run before the first paint The hold works only on text no one has seen. When the module runs before the browser first paints, every text is held from the moment it is parsed, and nothing a visitor reads is ever replaced. That is what the tag in `` does: ```html ``` `type="module"` lets the parser go on while the module loads. `blocking="render"` keeps the browser from painting until it has run. Browsers that do not support `blocking` ignore it. When the module runs after the first paint, the elements already on the page are checked as they are defined. If the page has painted and any of a group's texts is in the viewport, or the page has been scrolled, the visitor may have read them: they do not hold, and the served text is final for that group. A group whose texts are all out of view holds as usual. Nothing ever moves either way; the page just shows fewer adapted texts above the fold. ## The fit rule is stricter than in React The elements write no styles on your markup, so they cannot pin a box the way React's `FragmentText` pins its span to the space the fallback held. Instead the copy is written, the layout is read in the page's own layout engine, and the served text is put back before the browser paints if anything moved. Copy lands only when all of these stay exactly as the served text set them: - the box of the nearest block-level element around the text (the text itself when your CSS made it block-level): all four edges; - the text's lines: how many, and each line's top and height; - the position of the first content after the text inside that block. So copy that wraps differently, spills out of a fixed-height box, moves the words after it or changes the width of a block that sizes to its content is refused. Shorter copy that would remove a line is refused too, where React would land it in the space it holds. Write served text that is close to the length of the copy you expect there. ## The live slot needs a box from your CSS ```css sparkletree-live { display: block; aspect-ratio: 16 / 9; } ``` An unknown element lays out inline, and an inline box has no height for a player to fill. The element never writes `display`. When it is defined before the first paint and your CSS sets no aspect ratio, it writes `aspect-ratio: 16 / 9` inline, which still needs `display: block` from you. When a player would mount after the page has painted and the slot has no box of its own (no height, or an inline box), no player mounts: the slot stays as served, and development builds name the CSS to add. ## What a page script can read ```js document.addEventListener("sparkletree:settled", (event) => { const { source, variantId } = event.detail; console.log(event.target, source, variantId); }); ``` `sparkletree:settled` is dispatched, bubbling, by an island or fragments group (and a ``) when its copy is final. It goes out after the current task's code has run, so a listener added by the same script still hears it. `detail.source` is the strongest source among the group's texts (`generated`, `cached` or `static`; a stated fact is `static`), and `detail.variantId` is the variant for island copy, `null` otherwise. From that moment the group also carries `data-st-settled` with the same source, so a script that runs later can check instead of waiting. The constants are exported as `SETTLED_EVENT` and `SETTLED_ATTRIBUTE`. | Where | Attribute | | |---|---|---| | Each text | `data-content-source` | `static` until copy lands, then `generated`, `cached`, `static` or `stated`. | | Each text | `data-st-reserve`, `data-holding="true"` | While it holds. | | Island | `data-phase` | The stream's phase. | | Island | `data-st-slot` | The slot id React stamps for the same island and served text. | | Group | `data-st-settled` | Once its copy is final: the source. | | Live slot | `data-live` | `waiting` or `playing`. | | Live slot | `data-live-channel` | The playing channel's id. | Read-only properties: | Element | Property | | |---|---|---| | `` | `state` | The island's state, as `openStream` gives it: `theme`, `ctaAction`, `live`, `legal`, `variantId` and the rest. `null` before it opens. | | `` | `result` | The last fragments response. `null` before it arrives. | | `` | `marked` | Whether the copy on screen counts as adapted for this visitor. | | `` | `disclosure` | The server's label for AI-generated copy, when it sent one. | | `` | `result` | As on a fragments group. | ## What the elements do not do - **No typing and no fades.** Copy replaces the served text in one step. - **No shadow DOM and no stylesheet.** Your CSS styles the text. The only inline property written on your markup is `visibility`, while a text holds, and it is removed after. The live slot may get `aspect-ratio` before the first paint. - **No theme.** The campaign's colours are data on `island.state.theme`. Apply them yourself with `applyTheme(element, state.theme)` from `@sparkletree/core` if you want them. - **No AI label.** As everywhere in the SDK. Provenance is in `data-content-source`, `marked` and `disclosure`. - **No legal lines on the page.** They are data on `island.state.legal`. Render them in a space your page reserves for them. - **No layouts, background image or video.** The words are the only part of the campaign the elements write. `state.backgroundImage` and `state.videoUrl` are data. - **No server reads.** There is no `initialCopy` or `serverRendered`: the served text is the fallback, and live copy comes from the stream in the browser. - **No session continuity** (`sessionId`) and no audio. For any of these, use [`@sparkletree/core`](https://docs.sparkletree.io/developers/sdk/core.md) directly, or the React components. --- # Let visitors ask Source: https://docs.sparkletree.io/developers/sdk/ask/ Markdown: https://docs.sparkletree.io/developers/sdk/ask.md `ask` sends one question to the edge's `POST /ask` and resolves with the answer, written from your workspace's live campaigns. `useAsk` keeps a conversation in React. Both are headless: they give you text and state, and render nothing. The form, the answer's space and its look are yours. ```tsx import { useAsk } from "@sparkletree/react"; import { useState } from "react"; function AskBox({ campaignId }: { campaignId: string }) { const { ask, answer, status, links, followUps, error } = useAsk({ campaignId }); const [question, setQuestion] = useState(""); return (
{ event.preventDefault(); void ask(question); }}> setQuestion(event.target.value)} maxLength={1000} />
{/* The answer grows as it is written: give it a space of its own. */}
{status === "error" ?

No answer right now ({error?.reason}).

:

{answer}

} {links.map((link) => {link.label})} {followUps.map((next) => )}
); } ``` ## `useAsk` | Option | | |---|---| | `campaignId` | Answer about this campaign. It must be public on the edge. | | `organizationId` | Answer from the workspace's whole live roster. Defaults to the provider's workspace when no `campaignId` is given. | It returns: | Member | | |---|---| | `ask(question)` | Ask. A question still running is stopped first. Resolves with core's `AskResult` and never rejects. | | `answer` | The answer so far while it streams, the whole answer when done. After an error, the text received before it stopped. | | `status` | `idle` before the first question and after `reset()`; `asking` until the first piece arrives; `streaming` while it is written; `done`; `error` when no answer could be written. | | `links` | Links the answer points to: `{ label, url }`. | | `followUps` | Suggested next questions. | | `error` | `{ reason, status?, message? }` when `status` is `error`, else `null`. | | `reset()` | Stop a running question, forget the conversation and go back to `idle`. | The answer always streams with `useAsk`. The conversation's session is kept between questions, so a follow-up continues the thread; `reset()` starts a new one. A question stopped by a newer one, by `reset()` or by unmount resolves with `reason: "aborted"` and changes no state. Where you render the answer, give it a space of its own, a panel or a dialog, below everything it could push. It grows as it is written. ## `ask` without React ```html
``` | Option | | |---|---| | `apiBase` | Required. The edge, for example `https://p.qrtree.ai`. | | `question` | Required. Trimmed; at most 1,000 characters, counted in code points (an emoji counts as one). Fallback limits elsewhere in the SDK count UTF-16 code units instead. | | `campaignId` | Answer about this public campaign. | | `organizationId` | Without a campaign: the workspace whose live roster answers. | | `publishableKey` | Your live key, sent as `Authorization: Bearer`. Needed for a workspace-wide question from your own site. | | `session` | The `session` from an earlier answer, to continue that conversation. | | `onChunk(piece, soFar)` | Called with each piece as it is written. Giving it makes the request a stream. | | `signal` | Stops the question. | | `idleTimeoutMs` | Default 30000. The call stops when no bytes arrive from the edge for this long; each piece starts it again. With text received the result is `ok` with `truncated: true`; with none, `reason: "timeout"`. `0` or `Infinity` turns it off. | `createClient({ publishableKey }).ask({ question, campaignId, session, onChunk })` does the same with the client's API base, workspace and key. `AskResult` is: | Member | | |---|---| | `ok` | An answer was written. | | `answer` | The answer, or the text received before the call stopped. | | `links` | `{ label, url }[]`. | | `followUps` | Suggested next questions; empty when there are none. | | `session` | Send it back as `session` to continue. Empty when there is none. | | `campaign` | `{ id, name, url }`, the campaign the answer is about, when there is one. | | `homeCampaignId` | The campaign the conversation is grounded in. | | `truncated` | The answer was cut off upstream: usable, but it may be incomplete. | | `reason`, `status`, `error` | Why `ok` is false, the HTTP status, and the edge's message. | `ask` never rejects. Every failure resolves with `ok: false` and a reason. ## Streaming Without `onChunk`, the edge answers with one JSON document. With it, the request asks for `text/event-stream` and the answer arrives in pieces: | Event | | |---|---| | `chunk` | `{ text }`, a piece of the answer while it is written. `onChunk` gets it with the text so far. | | `done` | The whole response. Its `answer` replaces the pieces. | | `followups` | `{ questions }`, suggested next questions, after `done`. | | `error` | No answer was written. | A stream that ends before `done` with text received resolves `ok: true` with that text and `truncated: true`. An answer the edge had ready may come back as one `done` event, or as JSON; `ask` reads whichever was sent. ## Sessions and follow-ups Each answer carries a `session`. Send it with the next question and the edge answers with the conversation's history. Only values the edge handed out are accepted. An answer the edge served from its store of first answers comes without a session, and the next question then starts a new conversation. With a campaign, the answer may recommend another campaign of the same workspace. `campaign` and `links` then describe the recommended campaign, and `homeCampaignId` keeps naming the campaign the conversation is grounded in. To continue the thread, keep asking with the same `campaignId` and the `session`, never the recommended campaign's id. `useAsk` does this for you. Without a campaign, the question runs against the workspace's whole live roster. `campaign` and `links` are there only when the answer recommends a campaign, and there is no `homeCampaignId`. ## When the edge refuses a question | What | Status | `reason` | |---|---|---| | An empty question. No request is made. | none | `invalid_request` | | A question over 1,000 characters (counted in code points, as the edge counts them). No request is made. | none | `question_too_long` | | A malformed request: a campaign or workspace id that is not a UUID, a `session` the edge did not hand out, neither a campaign nor a workspace. | 400 | `bad_request` | | A campaign that does not exist, is not being served, or is not public on the edge; a workspace-wide question for a workspace with no live public campaigns. | 404 | `not_found` | | A campaign whose conversations are not switched on. | 403 | `forbidden` | | A workspace-wide question without proof of the workspace (see below). | 403 | `forbidden` | | Too many questions. The edge sends `Retry-After: 60`. | 429 | `rate_limited` | | No answer could be written. | 502, or an `error` event | `conversation_failed` | | Any other status. | other | `http_error` | A question about one campaign needs no other proof: the campaign must be public on the edge. A workspace-wide question spends the workspace's answers, so the edge answers it only when the request proves the workspace: - it is sent to the workspace's own verified brand host, or - it carries the workspace's **live** publishable key (`st_pk_live_`) from an origin registered for the workspace. Test keys are not accepted for workspace-wide questions. From your own site, pass your live key (`useAsk` sends the provider's) and register the origin; see [Origins, CSP and privacy](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md). ## Limits - A question is at most 1,000 characters; a request body at most 8 KB. - The edge limits requests per visitor IP address and answers 429 with `Retry-After: 60` when the limit is reached. - Every answer is written by the workspace's assistant from its live campaigns. A campaign that is not public on the edge cannot be asked about. --- # Show a live stream Source: https://docs.sparkletree.io/developers/sdk/live/ Markdown: https://docs.sparkletree.io/developers/sdk/live.md When a live channel is running and routed to the surface a hero asks for, the hero's stream says so, and the SDK can show the channel's player. The same happens when a campaign carries a live block of its own. Two parts do the work. `Hero` takes a `live` prop, and `Live` is the player's slot as a component you place yourself. Both ship in the release after 0.15.0. ## Turn it on in a `Hero` ```tsx ``` With `live`, the hero has a 16:9 slot after the body. The slot is there from the first frame, in the server HTML too, whether or not a channel is running. When the stream reports a running channel, the player fills the slot. Nothing on the page moves, because the space was already taken. Without `live`, a hero never shows a player and keeps no space for one. That is the default, so an existing page does not change when you upgrade. A live channel is routed to a surface, so pass `surfaceId`. A `campaignId` shows a player only when that campaign carries its own live block. ## Place the player yourself with `Live` `useIsland` puts the live block on `state.live`. Hand it to `Live` wherever the player belongs in your markup: ```tsx import { Live, StreamText, useIsland } from "@sparkletree/react"; function LiveEvent({ surfaceId }: { surfaceId: string }) { const { state, ref } = useIsland({ surfaceId, island: "hero", fallback: { headline: "Tonight we open the kiln" }, }); return (
Not live right now
); } ``` | Prop | What it does | |---|---| | `live` | The block to play: `state.live` from `useIsland`, or `parts.live` in a `Hero` layout. `null` keeps the slot empty. | | `children` | Shown in the slot while there is no player: a poster, a line of text, or nothing. | | `className`, `style` | Passed to the slot. `style` is merged over the slot's own, so another ratio or a fixed size is yours to set. | A `Hero` layout gets the same block as `parts.live`: ```tsx (
{headline}{body}
), }} /> ``` The `live` prop does not apply to a layout you wrote: you place the player. ## The slot is there first `Live` always renders its slot, a `
` with `aspect-ratio: 16 / 9` set inline. The player is an iframe that fills it. The slot's width comes from your layout, and its height follows from the ratio, so the space is reserved before any player exists. While no channel is running the slot stays, empty or showing its children. It does not collapse, because collapsing would move the page. If you would rather have no slot at all when nothing is live, render `Live` only when there is a block, and accept that the page moves when the player appears: ```tsx {state.live ? : null} ``` Style the two states with the slot's attributes: ```css .st-live { background: #111; border-radius: 10px; overflow: hidden; } .st-live[data-live="waiting"] { /* no player yet, or none running */ } .st-live[data-live="playing"] { /* the player is in the slot */ } ``` `Hero` adds the class `st-hero-live` to its slot. An `IslandReservation` for a hero takes the same `live` prop, so a Suspense fallback holds the slot too. ## A playing channel is never reloaded The player is kept by its channel. If the hero asks again during the same view of the page (the visitor changed something, or your context changed) and the same channel is still running, the iframe on the page is left exactly as it is. It does not reload and playback does not restart. | The next stream says | What happens | |---|---| | The same channel | Nothing. The iframe stays. | | Another channel | One new player replaces the old one, in the same slot. | | No live block | The player goes. The slot stays. | | Nothing, because it failed | The player that was playing stays. | ## What the SDK puts on your page The stream describes the player as markup. The SDK does not insert that markup. It reads the player's address and title out of it and builds the iframe itself, and only for an address of this exact shape: ``` https://.cloudflarestream.com//iframe ``` Of the address's query, only the player switches `autoplay`, `muted` and `controls` are kept. Anything else in the markup is dropped. An address that does not match yields no player at all. The iframe is a Cloudflare Stream player, so it loads from Cloudflare and the visitor's browser connects to Cloudflare to play it. It starts muted, which is the only way browsers allow a video to start by itself. If you run a Content Security Policy, allow the player's frame: ``` frame-src https://*.cloudflarestream.com ``` ## Without React `openStream` reports the same block on `state.live`: `{ channelId, src, title }`, or `null`. Build your iframe from `src`, and keep it while `channelId` stays the same. To carry a playing channel into the next stream, pass the block you have as `initialLive`: ```ts const next = openStream({ target, initial, initialLive: previous.live }); ``` `parseLiveReady` and `safeLiveSrc` are exported from `@sparkletree/core` if you read the stream yourself. ## Try it The cookbook's Live stream recipe (`#/live`) runs with no backend. See [Run the example apps](https://docs.sparkletree.io/developers/sdk/examples.md). --- # The sparkletree CLI Source: https://docs.sparkletree.io/developers/sdk/cli/ Markdown: https://docs.sparkletree.io/developers/sdk/cli.md ```bash npx @sparkletree/cli init --origin https://yoursite.com # sign in, register the site, write .env.local npx @sparkletree/cli doctor --url https://yoursite.com # check the setup and the served page npx @sparkletree/cli add hero cta # copy component source into your repo ``` The CLI is the npm package `@sparkletree/cli`; its command is `sparkletree`. Run it with `npx @sparkletree/cli `, or install it in the project (`npm install -D @sparkletree/cli`) and run `sparkletree ` through your package manager. Never run `npx sparkletree`: that name belongs to an unrelated npm package. Node 18 or later, ESM only. | Command | What it does | Changes | |---|---|---| | [`login`](#login) | Sign in through the browser with a device code. | Writes the sign-in file. | | [`logout`](#logout) | Revoke the sign-in and delete it from this machine. | Deletes the sign-in file. | | [`whoami`](#whoami) | Show the workspace, role, API base, keys, sites and campaigns. | Nothing. | | [`init`](#init) | Register sites and write the SparkleTree lines of the env file. | Registers sites; writes the env file; with `--yes`, `.gitignore`. | | [`doctor`](#doctor) | Check the setup. Every problem comes with a fix. | Nothing. | | [`dev`](#dev) | Run the local mock edge. | Nothing. | | [`results`](#results) | How a campaign's variants did. | Nothing. | | [`docs`](#docs) | Print the docs shipped with the installed packages. | Nothing. | | [`add`](#add) | Copy component source into your project. | Writes component files. | | [`upgrade`](#upgrade) | Port copied components to the current template wiring. | Rewrites copied files. | | `list` | List the components `add` can copy. | Nothing. | | `help` | Print the usage. Also `--help` and `-h` on any command. | Nothing. | `--version` prints the CLI version from any position. ## For agents and scripts: `--json` and exit codes The setup commands (`login`, `logout`, `whoami`, `init`, `doctor`, `dev`, `results`, `docs`) take `--json`. Then stdout holds one JSON document and nothing else; the human text goes to stderr. `login --json` is the one exception: it prints a `{"event":"verification",…}` line first and the result last. Nothing prompts with `--json` or `--yes`, or when stdin is not a terminal. Where `init` would ask which campaign to use, it stops with the list in the result instead, and you run it again with `--campaign `. Every failure has the same three members, so a script can act on it as written: ```json {"ok":false,"error":"not_signed_in","reason":"Not signed in.","remedy":"Run `sparkletree login`, or set SPARKLETREE_TOKEN."} ``` | Exit code | Meaning | |---|---| | `0` | Success. For `doctor`: no check failed (warnings are allowed). | | `1` | A failed check or an error. The document says which. | | `2` | Wrong usage: an unknown option, a missing or extra argument, a bad value (such as a `--port` out of range, a `--cwd` that is not a directory, or a `dev --failure` name the mock does not have). The document has `"error": "usage"`, except for a `--failure` name, which answers `"error": "unknown_failure"` with the names in its `remedy`. | | `130` | `login` or `init` was stopped with Ctrl+C. A final document is still printed, `{"ok":false,"error":"interrupted",…}`. | An unexpected error ends with `"error": "unexpected"` and exit code `1`. `--version --json` prints `{"ok":true,"version":"…"}`, in any position, so `sparkletree --version --json` works too. The component commands (`add`, `upgrade`, `list`) print text only. They exit `1` for an unknown command, an unknown option, a missing component name or an argument a command does not take (`sparkletree list extra`). ## Sign-in `login` stores the sign-in in `$XDG_CONFIG_HOME/sparkletree/sdk.json` (default `~/.config/sparkletree/sdk.json`). The directory is created with mode `0700` and the file with mode `0600`, so only you can read it. The file holds the token, the app that issued it, when it was saved and when it expires. The token is valid for 90 days. The token is secret. The CLI never prints it, never logs it, never puts it in an error message, and never writes it into your project: `init` writes only the publishable key, the API base, the workspace id and the campaign id, all of which are public. What a sign-in can do: read the workspace's SDK setup (its publishable keys, API base, registered sites and the campaigns that can be served), add sites to the workspace's allowed list, and read campaign results. Nothing else. The browser approval page names the client, `sparkletree-sdk-cli`, shows the requested access `sdk:setup`, and says: > It can read this workspace's SDK keys and add sites to its allowed list. ### Which app the token goes to | Variable or option | Effect | |---|---| | `SPARKLETREE_TOKEN` | A token to use instead of the stored sign-in. It is used first and never written anywhere. It goes to the default app, `https://app.sparkletree.io`, unless `--app` or `SPARKLETREE_APP` names another one. | | `SPARKLETREE_APP` | The app address, for every command. | | `--app ` | The app address, for this command. Wins over `SPARKLETREE_APP`. | | `XDG_CONFIG_HOME` | Where the sign-in file lives. | A stored sign-in is sent only to the app that issued it. When `--app` or `SPARKLETREE_APP` names a different app, the command stops with `"error": "app_mismatch"`, sends nothing, and tells you to sign in there with `sparkletree login --app
`. Every app address must be `https`; plain `http` is accepted only for `localhost`, `127.0.0.1` and `[::1]`. An address that is neither stops the command with `"error": "bad_app"` before anything is sent. No request follows a redirect. ## login ``` sparkletree login [--app ] [--json] ``` Asks the app for a device code with the scope `sdk:setup` and prints an address and a code: ``` Open https://app.sparkletree.io/cli/activate?user_code=WXYZ-1234 and enter the code WXYZ-1234 (valid for 10 minutes). Waiting for approval... ``` Open the address, check the code, approve. The CLI asks for the token at the interval the server names and stores it when you approve. If `SPARKLETREE_TOKEN` is set, `login` says that it is used before the stored sign-in. With `--json`, stdout holds two lines: the code, then the result. ```json {"event":"verification","url":"https://app.sparkletree.io/cli/activate?user_code=WXYZ-1234","userCode":"WXYZ-1234","expiresIn":600} {"ok":true,"status":"approved","appBase":"https://app.sparkletree.io","expiresAt":"2027-02-17T10:00:00.000Z","configPath":"/home/you/.config/sparkletree/sdk.json","tokenSource":"file"} ``` `status` is `approved`, or on failure `denied` (refused in the browser), `expired` (the code ran out before approval), `error` or `interrupted` (Ctrl+C, exit code `130`). Nothing is stored unless the status is `approved`. ## logout ``` sparkletree logout [--app ] [--json] ``` Revokes the stored token at the app that issued it, then deletes the sign-in file. The file is deleted even when the app cannot be reached; `revoked` says whether the app confirmed it. When `--app` or `SPARKLETREE_APP` names another app, nothing is changed and the command exits `1`. ```json {"ok":true,"revoked":true,"removed":true,"configPath":"/home/you/.config/sparkletree/sdk.json","envTokenRemains":false,"message":"Signed out."} ``` `envTokenRemains` is true when `SPARKLETREE_TOKEN` is still set; unset it to stop using it. With no stored sign-in, `logout` says so and exits `0`. ## whoami ``` sparkletree whoami [--app ] [--json] ``` Reads the workspace setup with the sign-in. Changes nothing. ```json { "ok": true, "workspace": { "id": "6f1c2a4e-0b7d-4c1e-9a52-3d8e7f0a1b2c", "name": "Kiln & Co" }, "role": "admin", "apiBase": "https://p.qrtree.ai", "apiBaseConfigured": true, "appBase": "https://app.sparkletree.io", "tokenSource": "file", "keys": { "live": "st_pk_live_eyJ…", "test": "st_pk_test_eyJ…" }, "sites": [{ "id": "a1", "origin": "https://kiln.example", "label": "Shop", "verified": false, "devOnly": false }], "campaigns": [{ "id": "9b8e7d6c-5a4f-4e3d-8c2b-1a0f9e8d7c6b", "name": "Autumn firing", "status": "active", "public": true }] } ``` | Member | | |---|---| | `apiBase` | The address the SDK talks to. | | `apiBaseConfigured` | False when the server has no embed address for the workspace, so `apiBase` does not serve the embed API. That is for SparkleTree support to fix; `init` stops until it is fixed. | | `tokenSource` | `env` (`SPARKLETREE_TOKEN`) or `file` (the stored sign-in). | | `keys` | The publishable keys. They are public, so they are shown to be copied. `test` is present only for the admin and editor roles. | | `sites` | The registered sites. | | `campaigns` | The campaigns that can be served now, newest first, at most 50. | ## init ``` sparkletree init [options] ``` | Option | | |---|---| | `--origin ` | Register a site. Repeat it for several. A site already registered is reported as such, not added twice. `http://` is accepted for `localhost` only. | | `--campaign ` | The campaign the page plays. | | `--env-file ` | The file to write, relative to the project. Default `.env.local`. Created when missing. | | `--framework ` | `next`, `vite`, `astro`, `sveltekit`, `remix` or `none`. Default: read from `package.json`. | | `--dev-key` / `--no-dev-key` | Write the test key (the default) or the live key. | | `--dry-run` | Show what would be written. Registers nothing and writes nothing. | | `--yes`, `-y` | Do not ask; also add the env file to `.gitignore` when it is not covered. | | `--cwd ` | The project root. Default: the current directory. | | `--app ` | The app to sign in at. | | `--json` | One JSON document on stdout. | What `init` does, in order: 1. **Signs in** when there is no token. Only for a person at a terminal: with `--json`, or without a terminal, it never starts a browser sign-in and stops at once with `"error": "not_signed_in"`. Run `login` first, or set `SPARKLETREE_TOKEN`. 2. **Reads the workspace setup**: keys, API base, sites and campaigns. 3. **Picks the campaign.** `--campaign` wins; an id the workspace cannot serve now is written anyway, with a warning. Without it, the only campaign that can be served is used. With several, a terminal asks, and otherwise `init` stops with `"error": "choose_campaign"` and the list in `campaigns`. With none, no campaign is written and a warning says so; [fragments](https://docs.sparkletree.io/developers/sdk/fragments.md) work without a campaign. 4. **Registers each `--origin`**, five per request. This needs the admin role in the workspace (a workspace's only member counts as admin). A site the app refuses is reported in `origins` with the reason, and the rest of `init` still runs. 5. **Writes the env file.** Everything that can stop `init` is checked before it registers a site or writes a file: the sign-in, the setup (including whether the server has the workspace's embed address), the campaign, the key and the values for the env file. Two stops can still happen after a site was registered, a refused env file write (`env_write_failed`) and Ctrl+C (`interrupted`); both list the sites already registered in `registered`. Run the same command again: those sites are then reported as already registered. ### What it writes Four variables, with your framework's public prefix: | Framework | Prefix | |---|---| | `next` | `NEXT_PUBLIC_` | | `vite` | `VITE_` | | `astro`, `sveltekit` | `PUBLIC_` | | `remix`, `none` | none | | Variable (Next.js names) | Value | |---|---| | `NEXT_PUBLIC_SPARKLETREE_KEY` | The publishable key: the test key by default, the live key with `--no-dev-key`. | | `NEXT_PUBLIC_SPARKLETREE_API_BASE` | The API base. | | `NEXT_PUBLIC_SPARKLETREE_ORG_ID` | The workspace id. | | `NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID` | The campaign, when there is one. | An existing assignment is updated in place, keeping `export ` and a trailing comment. A missing one is added at the end under the line `# SparkleTree (written by sparkletree init)`. Every other line, its line ending included, stays as it was. The test key works from a page on localhost (`http://localhost`, `127.0.0.1`, `[::1]`, any port) and from a server. Any other site must be registered, test key or not; `doctor --origin` asks the edge the way a browser on that site would and fails `browser-read` when a page there cannot read the answers. From localhost the hosted edge writes no new fragment copy, so fragments show copy already written and their fallbacks otherwise; `init` prints this under the env lines (`envFile.keyNote`). If your role cannot use a test key, `init` writes the live key and warns: a live key works only from a registered site, so register your development address too (`--origin http://localhost:3000`). When the env file is not covered by `.gitignore`, `init` warns and names the line to add; with `--yes` it adds the line to the project's `.gitignore`. An env file outside the project is never added, because this project's `.gitignore` cannot cover it. When you register a site, the result also holds the same lines with the live key, under `production`, for your host's environment settings. The live key is public and works only from the registered sites. ### Output ```json { "ok": true, "dryRun": false, "workspace": { "id": "6f1c2a4e-0b7d-4c1e-9a52-3d8e7f0a1b2c", "name": "Kiln & Co" }, "role": "admin", "apiBase": "https://p.qrtree.ai", "framework": "next", "frameworkSource": "package.json", "campaign": { "id": "9b8e7d6c-5a4f-4e3d-8c2b-1a0f9e8d7c6b", "name": "Autumn firing", "source": "only" }, "origins": [{ "origin": "https://shop.kiln.example", "status": "created" }], "envFile": { "path": ".env.local", "created": true, "written": true, "keyEnv": "test", "keyNote": "The test key works from a page on localhost (http://localhost, 127.0.0.1, [::1], any port) and from a server. Any other site must be registered, test key or not. From localhost the hosted edge writes no new fragment copy, so fragments show copy already written and their fallbacks otherwise; to see new copy, use a registered https site, a signed mint token, or the mock edge (sparkletree dev).", "changes": [ { "name": "NEXT_PUBLIC_SPARKLETREE_KEY", "action": "added" }, { "name": "NEXT_PUBLIC_SPARKLETREE_API_BASE", "action": "added" }, { "name": "NEXT_PUBLIC_SPARKLETREE_ORG_ID", "action": "added" }, { "name": "NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID", "action": "added" } ], "lines": [ "NEXT_PUBLIC_SPARKLETREE_KEY=st_pk_test_eyJ…", "NEXT_PUBLIC_SPARKLETREE_API_BASE=https://p.qrtree.ai", "NEXT_PUBLIC_SPARKLETREE_ORG_ID=6f1c2a4e-0b7d-4c1e-9a52-3d8e7f0a1b2c", "NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID=9b8e7d6c-5a4f-4e3d-8c2b-1a0f9e8d7c6b" ] }, "gitignore": { "covered": true, "added": false, "path": "/home/you/shop/.gitignore" }, "warnings": [], "next": ["sparkletree add provider hero", "sparkletree doctor --url https://shop.kiln.example"], "production": { "key": "st_pk_live_eyJ…", "lines": ["NEXT_PUBLIC_SPARKLETREE_KEY=st_pk_live_eyJ…", "…"], "note": "Set these in your production environment (your host's environment settings). The live key is public and works only from the registered sites." } } ``` | Member | Values | |---|---| | `ok` | False when a site was rejected. The env file is still written; the exit code is `1`. | | `campaign.source` | `flag` (`--campaign`), `only` (the one campaign that can be served) or `chosen` (picked at the prompt). `campaign` is null when there is none. | | `origins[].status` | `created`, `already_registered`, `would_register` (with `--dry-run`) or `rejected` (with `reason`). | | `envFile.changes[].action` | `added`, `updated` or `unchanged`. | | `envFile.written` | False with `--dry-run`, or when nothing changed. | | `gitignore.outsideProject` | Present and true when the env file is outside the project. | | `next` | The commands to run next. | | `providerNote` | Remix and `none` only. These have no public env convention, so the provider `add` copies takes the values as props; the note says where to pass them. The text output prints it under "Provider". | The errors that stop `init` before any change: `not_signed_in`, `bad_app`, `app_mismatch`, `bad_stored_app`, `api_base_not_configured`, `choose_campaign` (with `campaigns`), `no_key` (the workspace has no publishable key yet; an admin creates them in Settings > Embedding), and the app's own errors when the setup cannot be read (`network`, an HTTP status, `insufficient_scope`). ## doctor ``` sparkletree doctor [options] ``` | Option | | |---|---| | `--url ` | Also fetch this page and check its Content Security Policy and whether it is server-rendered. | | `--origin ` | The site to check against the key. Default: the origin of `--url`. One only. | | `--env-file ` | Default: the first that exists of `.env.local`, `.env.development.local`, `.env.development`, `.env`. | | `--campaign ` | Default: `SPARKLETREE_CAMPAIGN_ID` from the env file, with any framework prefix. | | `--cwd ` | The project root. | | `--json` | One JSON document on stdout. | `doctor` needs no sign-in. It reads the project, asks the edge whether it accepts the key and the site, sends the edge the preflight a browser on the site would send (`browser-read`: can a page there read the answers), reads the campaign from the edge's cache without generating anything, and, with `--url`, fetches the page. It changes nothing and spends nothing. It exits `1` when a check fails and `0` otherwise; a warning does not fail. The edge accepts a test key from any site, so with a test key the `origin` check passes without calling the site allowed: `browser-read` says whether a page there can read the answers. When the edge does not accept the key, `origin` is a skip and `whoami-key` gives the fix. ```json {"ok":true,"checks":[{"id":"node","status":"pass","message":"Node 20.11.0 meets >=18, >=18."},{"id":"key","status":"pass","message":"NEXT_PUBLIC_SPARKLETREE_KEY is a test key for workspace 6f1c2a4e-0b7d-4c1e-9a52-3d8e7f0a1b2c."},{"id":"page","status":"skip","message":"Pass --url to check a served page."}]} ``` (Shortened: the real document has every check.) Each check has `id`, `status` (`pass`, `warn`, `fail` or `skip`), `message`, and for a warning or a failure a `remedy`. Every check, what each status means for it and its fix: [Check your setup](https://docs.sparkletree.io/developers/sdk/setup-checks.md). ## dev ``` sparkletree dev [--port ] [--failure ] [--framework ] [--cwd ] [--json] ``` Runs the mock edge from `@sparkletree/core/testing` on `127.0.0.1`, port `4330` by default (`--port 0` takes any free port, shown in the output), and prints the env lines that point a project at it, with the framework's prefix (`--framework`, or read from `package.json`). It needs no account and no network. It runs until Ctrl+C and then exits `0`. `--failure ` makes every request act out one failure; the names and what each does are in [Test without an account](https://docs.sparkletree.io/developers/sdk/testing.md). Each event the mock receives and each failure it acts out is logged on stderr. ```json {"ok":true,"url":"http://127.0.0.1:4330","port":4330,"failure":null,"lines":["NEXT_PUBLIC_SPARKLETREE_KEY=st_pk_test_eyJ…","NEXT_PUBLIC_SPARKLETREE_API_BASE=http://127.0.0.1:4330","NEXT_PUBLIC_SPARKLETREE_ORG_ID=00000000-0000-4000-8000-000000000001","NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID=00000000-0000-4000-8000-000000000002"]} ``` With `--json` the document is printed once the mock is running, and the command keeps running. The errors: `port_in_use` (the remedy names the next free port, checked, and `--port 0`), `unknown_failure` (the remedy lists the names), `testing_unavailable` (the CLI's `@sparkletree/core` has no mock edge; run `npx @sparkletree/cli@latest dev`) and `start_failed`. ## results ``` sparkletree results [--days ] [--app ] [--json] ``` How a campaign's variants did over the last `--days` days (1 to 90, default 30), read with the sign-in. The variants are listed leader first. Without `--json` it prints a table: ``` Autumn firing (9b8e7d6c-5a4f-4e3d-8c2b-1a0f9e8d7c6b), 2026-10-20 to 2026-11-19 (30 days) Total: 4120 impressions, 310 clicks, 7.5% CTR, 22 conversions Variant Impressions Clicks CTR Conversions Share leader Warm kiln 2100 190 9.0% 15 51.0% Plain 2020 120 5.9% 7 49.0% Site activity: 800 page views, 40 clicks, 3 conversions ``` With `--json` the document is `{"ok":true, …}` followed by every member of the results, described in [Read results back](https://docs.sparkletree.io/developers/sdk/results.md). A campaign that is not in the signed-in workspace answers `"error": "not_found"`. ## docs ``` sparkletree docs [topic] [--list] [--path] [--cwd ] [--json] ``` Prints the docs that ship inside the installed packages, so you read the docs for the version the project has. It looks for `@sparkletree/core`, `@sparkletree/react` and `@sparkletree/cli` in the project's `node_modules` (and its parents), and falls back to the copies that come with the CLI. | Form | Prints | |---|---| | `docs` | Each package's `llms.txt`: the list of its docs. | | `docs ` | One page. The topic is the file name without `.md`, such as `quickstart`. `react/quickstart` or `react:quickstart` names the package. | | `docs --list` | Every topic and the package it is in. | | `--path` | The file paths instead of the content. | ```json {"ok":true,"kind":"topic","topic":"quickstart","package":"@sparkletree/core","path":"/home/you/shop/node_modules/@sparkletree/core/docs/quickstart.md","content":"# Add adaptive copy to a page\n…"} ``` `kind` is `index`, `topic` or `list`. With `--path`, `content` is left out. The errors: `no_docs`, `bad_topic` and `unknown_topic` (with `topics`, every topic name). See [Docs for coding agents](https://docs.sparkletree.io/developers/sdk/docs-for-agents.md). ## add ``` sparkletree add [--dir ] [--cwd ] [--framework ] [--force] [--dry-run] ``` Two ways to use the components. Import them from `@sparkletree/react` and we own the markup. Or copy the source into your project and you own it. Pick one: doing both leaves you with two components called `Hero`. Files are written under `components/sparkletree/` by default, and dependencies are resolved for you: asking for `hero` also writes `provider` if you do not have it. | Component | What it is | |---|---| | `provider` | The `SparkletreeProvider` wrapper, written for your framework. It passes the publishable key, and the API base and workspace id when they are set, read under the names `init` writes. See below. | | `hero` | Streaming hero: greeting, headline, body, artwork. | | `cta` | Streaming call to action with a stable hit area. | | `copy-card` | A card for copy you already have. | | `product-card` | A product card with image, name, description and price. | ### The provider, per framework `add` finds the framework in `package.json` the same way `init` does, so the provider reads exactly the names `init` wrote. `--framework` sets it. | Framework | The provider reads | |---|---| | `next` | `process.env.NEXT_PUBLIC_SPARKLETREE_KEY`, `…_API_BASE`, `…_ORG_ID` | | `vite` | `import.meta.env.VITE_SPARKLETREE_KEY`, `…_API_BASE`, `…_ORG_ID` | | `astro` | `import.meta.env.PUBLIC_SPARKLETREE_KEY`, `…_API_BASE`, `…_ORG_ID` | | `sveltekit` | `env.PUBLIC_SPARKLETREE_KEY`, `…_API_BASE`, `…_ORG_ID`, from `$env/dynamic/public`. SvelteKit's `import.meta.env` carries only `VITE_` names. | | `remix`, `none` | Nothing. There is no public env convention, so the provider takes `publishableKey`, `apiBase` and `organizationId` as props, at a place marked in the file. In Remix, read `SPARKLETREE_KEY` from `process.env` in your root loader and pass it down. `init` prints the same note. | Each variable is read by its full name: Next.js and Vite put a public value into the browser bundle only where the code spells out `process.env.NEXT_PUBLIC_…` or `import.meta.env.VITE_…`. With the key, the API base and workspace id come from the key, and the other two override it when set. Without the key, the API base and workspace id alone still work, as in a project set up before `init` wrote the key. A missing variable throws at load with an error that names it and says that `npx @sparkletree/cli init` writes it. The Vite provider reads `import.meta.env`, so TypeScript needs Vite's client types: a `create vite` project has them, and any other adds `"types": ["vite/client"]` to `tsconfig.json`. A provider copied by version 0.15.0 or earlier reads the environment through `globalThis`, which neither Next.js (webpack or Turbopack) nor Vite replaces with the values. It works during server rendering and throws at load in the browser. Run `sparkletree upgrade` to replace it with the current provider for your framework (see [upgrade](#upgrade)). | Option | | |---|---| | `--dir ` | Where files are written. Default `components`. | | `--cwd ` | Project root. Default: the current directory. | | `--framework ` | The framework the provider is written for: `next`, `vite`, `astro`, `sveltekit`, `remix` or `none`. Default: read from `package.json`. | | `--force` | Overwrite files that already exist. | | `--dry-run` | Print what would happen and write nothing. | Existing files are never overwritten without `--force`; they are listed as skipped and the command still exits `0`, so running it again in CI is safe. The tool prints the packages to install and does not run your package manager. The default class names assume Tailwind CSS. Swap them for anything; the files are yours. ## upgrade ``` sparkletree upgrade [--dir ] [--cwd ] [--framework ] [--dry-run] ``` Copies drift as the templates improve, and they are your files: nothing can patch them at runtime. `upgrade` ports what your copies are missing. It takes no component names; it upgrades every copied `provider`, `hero` and `cta` it finds under `--dir`. It works one generation at a time and decides what a copy is missing by its content, never by guessing which release wrote it: - **0.4.0** changed the hold from blanking to reserving: a holding field is invisible but still occupies its exact space. A 0.3.0 copy without this wiring collapses during the hold and shifts the page when copy lands. - **0.6.1** moved URL vetting to the one `safeActionUrl` in `@sparkletree/core`. A copy carrying the old inline helper still works, but it is frozen: a future fix to the vetting rules would never reach it. The upgrade deletes the local copy and imports the shared one. A 0.3.0 copy gets both, in order; a 0.4.0 or 0.5.0 copy gets only the second. The provider has one generation. Every release up to 0.15.0 copied the same provider, which reads the environment through `globalThis` and so throws in the browser. `upgrade` replaces it with the provider `add` writes now for your framework: it reads the variables `init` writes by their full names and passes the publishable key. With only the API base and workspace id set, as in a project set up before `init` wrote the key, it still works. The framework is read from `package.json` the same way `init` and `add` read it; `--framework` sets it. A provider you edited is left alone and the command names the part that did not match (`imports`, `env reads and checks` or `SparkleTree component`). How it stays safe in your repository: - **Exact matches, all or nothing per file.** Every part of every needed generation must match exactly. One miss means you edited the file where the upgrade has to land, so nothing is written and the command names which parts did not match, for you to port by hand. - **Line endings do not matter.** A file checked out with CRLF line endings (git's `core.autocrlf` on Windows) matches as it would with LF, and is written back with its own line endings. - **Your styling survives.** The parts it rewrites avoid the Tailwind class names the templates invite you to change. - **Running it twice changes nothing.** A generation whose wiring is already in the file is skipped; a copy missing none is reported up to date and never touched. - **It checks your install first.** The rewritten source must compile against your installed `@sparkletree/react` and `@sparkletree/core`. Against an older install the run names the version it needs, reports what it *would* write, and writes nothing. Update the packages, then run it again. Files that do not match are a report, not a failure: the command exits `0` either way, so it is safe in CI. When it ported or left alone a file, the output ends with a short reason for each generation; a run with everything up to date prints only the list. ## Upgrades still reach the copied files The copied components contain layout and nothing else: no endpoints, no event names, no version numbers, no timing values. Everything that talks to SparkleTree stays in `@sparkletree/core` and `@sparkletree/react`, which the copies import from. So a change to how SparkleTree delivers copy is a version bump for you, not a migration. Edit the copied files freely. Two things to keep: - **Attach the `ref`** that `useIsland` returns to the element that has to be visible, or the block reports no impressions. - **Pass fields to `StreamText`**, not `field.text`, or adapted copy renders without its provenance stamp and paced entrance. --- # When things go wrong Source: https://docs.sparkletree.io/developers/sdk/when-things-break/ Markdown: https://docs.sparkletree.io/developers/sdk/when-things-break.md ```bash npx @sparkletree/cli doctor --url https://yoursite.com/the-page ``` Nothing here throws, and no failure blanks copy a visitor is reading. Copy that already landed stays. A slot that was still blank gets what you wrote. A line the stream was still writing ends on what you wrote too: your fallback replaces the half line once, in the same space. If the half line was never painted, nothing is replaced: your fallback takes the blank slot. ## Run `doctor` before you check anything by hand When the page shows only your fallback copy, the cause is usually in the setup: a key that does not decode, a site that is not registered, a campaign that cannot be served, or a Content Security Policy that blocks the API. `doctor` checks each of these against the edge, without generating or spending anything, and prints the fix for every problem. Start there; every check and its remedy is in [Check your setup](https://docs.sparkletree.io/developers/sdk/setup-checks.md). To see how your page behaves in each failure below, run it against the mock edge: [Test without an account](https://docs.sparkletree.io/developers/sdk/testing.md). ## If our service is down, your copy stays on the page The request fails and `state.phase` becomes `failed`. Fields that finished keep the copy they delivered. A field still blank gets your `fallback`. A field the stream was writing when it failed is covered in [A line the stream did not finish](#a-line-the-stream-did-not-finish). `state.error` carries a readable message you can log. No exception reaches your render tree, no element collapses, nothing shifts. There is no retry loop and no reconnection storm: one attempt per block per page view. ## On a slow network, the visitor reads your copy On an ordinary client-side mount nothing is on screen yet. The hold arms the moment the block mounts, before the browser ever paints, covering even a wait that precedes the request itself, such as a pinned sibling waiting on the page's variant draw. The block waits over your artwork rather than flashing copy it is about to replace: 2.5 seconds, restarted once if the stream proves it is alive, so up to 5 seconds. The wait reserves rather than blanks: your fallback is drawn invisibly in its exact space, so nothing collapses while it lasts. A connect that hangs or never answers is the same case: at the end of the budget your fallback lands in the space it already holds, with one short fade, and that is then what the visitor reads for the page view. A stream that arrives after that is not shown. Server-rendered pages hold the same way: the server HTML carries the invisible reservation, not your fallback as text. If the page's JavaScript is late, a CSS-only failsafe reveals your fallback after 5 seconds (at once with scripting off), and that fallback is then final. ## A line the stream did not finish A line the stream started and did not finish counts as failed in two cases: the stream ends without finishing it (an `error` event, the connection closing before `done`, a failed request, a timeout), or the line gets no new text for 5 seconds (`TYPING_STALL_MS`) while the rest of the stream may carry on. What the visitor sees depends on the renderer: - **React (`Hero`, `Cta`, `useIsland`), a line the visitor watched being typed:** your fallback replaces the half line once, with one cross-fade (700 ms; no motion under reduced motion), in the box your fallback reserved, so nothing around it moves. The field becomes `source: "static"`, `data-content-source="static"`, and the fallback is final: later text for that line, and a late close of it, are not shown. `state.rewrites` counts the replacement. This is the one case where text a visitor can see is replaced: a half sentence is not worth keeping, and the replacement ends on a whole one. - **React, a line that started but was still blank on screen** (the failure came in the same network read as the half line, so the half line was never painted): nothing is replaced. Your fallback is typed into the slot at the typing pace, two characters a frame (about 300 ms for a 36-character headline; no motion under reduced motion), in the box your fallback reserved. The field becomes `source: "static"`, there is no `crossfade`, and `state.rewrites` stays 0. The mock edge at the default pace sends the failure one chunk step after the half line, as on a real connection, so there the half line is shown and replaced. Over HTTP at `pace: 0` the mock's whole stream, the line's start included, arrives in one read: the line was still held, so the next case applies and your fallback appears at once. - **React, a line that was still held** (out of view, or waiting to land whole after a campaign or context change): it was never shown, so it gets your fallback with no replacement. A line that stalled while out of view is never typed in when it scrolls into view; your fallback lands instead. - **React, a server-rendered field:** it is final from the start, so the stream writes nothing over it and it stays as it was. - **`openStream` in `@sparkletree/core`:** the same rules, because React uses the same choreographer: `state.fields` carries the outcome, with `crossfade: true` on a field whose visible line was replaced, and your renderer draws it. To keep a typed line instead, as before 0.16.2, pass `unfinishedCopy: keepUnlessClearlyError`: it keeps the line at the end of the stream and at a stall, and replaces only text that is clearly an error. It is close to 0.16.1, not the same: a line that started and sent no text for 5 seconds gets your fallback under either policy when nothing is held, clearly-error text is replaced at the stall too, and `state.rewrites` counts it. The React components do not take this option, so a React page cannot opt out. - **The custom elements (``):** they never show typing, so only a line the stream finished lands. The line it was writing keeps your served text, after a failure and after a stall alike. A line that finished is never replaced, whatever happens to the rest of the stream. A stream the page closes itself (an unmount, a new stream replacing it, `close()`) is not a failure: nothing is replaced. Time with the page hidden does not count toward the 5 seconds: when the visitor comes back, a line being written gets a fresh 5 seconds. After a stall with the connection still open, `state.phase` stays `live` (`data-phase="live"`) until the stream ends, even though the line already shows your fallback. The hosted edge ends a stream after 30 seconds. The impression is recorded then, with what the visitor was shown. ## If the campaign is paused or out of budget, real copy still renders The server can serve a fixed, pre-decided version instead of generating one. That is not an error: the words are real, they were simply not adapted for this visitor. `state.degraded` names the reason and `state.contentSource` says `static`, so nothing claims adapted provenance. Correctly, because nothing was generated. `Hero` puts it on the element as `data-degraded`, if you want to annotate it. ## Every state a visitor can be in | `state.phase` | On screen | |---|---| | `idle` | Before the stream exists: your fallback, reserved invisibly. | | `holding` | Your artwork, the text slots held for a moment, their space reserved by your invisible fallback. | | `live` | Adapted copy, arriving. | | `settled` | Final copy for this page view. | | `failed` | Finished copy stands. A line the stream did not finish is replaced once by your fallback; a blank or still-held slot gets your fallback. | ## Test the outage in one line Point the provider at a host that cannot answer: ```tsx ``` Expect: your fallback, readable; `state.rewrites === 0` (nothing was typed, so nothing was replaced); no adapted provenance; no layout shift. Verify this before you verify the happy path. It is the behaviour that runs during an incident. The mock edge acts out the other failures too, one name each: `npx @sparkletree/cli dev --failure slow`, `stall`, `error-mid-stream`, `http-500`, `quota`, `unauthorized`, `over-long` or `empty`. What the page should show for each is in [Test without an account](https://docs.sparkletree.io/developers/sdk/testing.md#what-the-page-should-show). For previews, Storybook and unit tests, skip the network instead of faking a broken host: ```tsx useIsland({ campaignId, island: "hero", fallback, enabled: false }); ``` ## The one failure you have to fix yourself: a missing `ref` `useIsland` returns a `ref` that must be attached to the element which has to be visible for the view to count. Forget it and the campaign renders perfectly while reporting zero impressions. Because the SDK tells the server it owns the count, nothing else counts it either. ```tsx const { state, ref } = useIsland({ … }); return
…
; ``` `Hero` and `Cta` attach it for you. There is no warning when a custom component does not. ## Failures the SDK absorbs without telling you - **A blocked or throwing `localStorage`.** The visitor's "standard version" preference cannot be stored; copy keeps counting as adapted (`decideChrome` stays honest), which is the safe default. Pass your own `storage` if a consent manager gates it. - **A missing `IntersectionObserver`.** The impression fires immediately instead of waiting for visibility. Over-counting is visible in your numbers; under-counting would be a silent bias in figures you are billed on. - **Missing context signals.** A hardened browser or in-app webview may withhold language, device or timezone. The creative adapts less well; nothing breaks. - **An API version your deployment does not implement.** Your first paint stands and no retry happens. - **A self-hosted `apiBase` that arrived through a `publishableKey`.** Facts, the setup check, `ask`, slot reads and the request that writes new fragment copy are not sent (`untrusted_api_base`). The fragments read is still sent, because it carries neither the key nor any text from the page, so copy that is already written still shows; nothing new is ever written, so fragments otherwise serve your fallbacks and never warm up. This is the one entry here that does not resolve itself with time. Pass `apiBase` and `organizationId` to the provider explicitly. A dev build warns once in the console; see [signed minting](https://docs.sparkletree.io/developers/sdk/signed-minting.md). ## What a failure leaves untouched Finished text stays painted, your artwork stays, your DOM keeps its order, your scripts keep running, and no spinner is left spinning. A line the stream stopped part way through is replaced once by your fallback, in the same space, so the visitor ends on a whole sentence. A line nobody saw is never shown part-written: it gets your fallback. --- # Test without an account Source: https://docs.sparkletree.io/developers/sdk/testing/ Markdown: https://docs.sparkletree.io/developers/sdk/testing.md ```bash npx @sparkletree/cli dev # mock edge on http://127.0.0.1:4330 npx @sparkletree/cli dev --failure offline # every request fails ``` ```ts import { startMockEdge, mockEmbedApi, mockFetch } from "@sparkletree/core/testing"; ``` `@sparkletree/core/testing` is a mock of the SparkleTree edge for tests and local development. It answers the same endpoints as the real edge, with the same shapes and statuses: the islands stream, islands/copy, content, fragments and their mint, track, whoami, facts, the signing keys document and `/ask`. The streams replay the recorded fixtures the real edge is tested against, bundled in the package. You need no account, no keys and no network. Never deploy it. It answers CORS for any origin and accepts unsigned keys. Out of the box it serves one workspace, one campaign and one surface, with these ids (`MOCK_IDS`): | | Id | |---|---| | `organizationId` | `00000000-0000-4000-8000-000000000001` | | `campaignId` | `00000000-0000-4000-8000-000000000002` | | `surfaceId` | `00000000-0000-4000-8000-000000000003` | | `variantId` | `00000000-0000-4000-8000-000000000004` | The campaign has the products `stoneware-mug` (249.00 SEK, in stock) and `linen-cloth` (out of stock), and its variant the custom slots `eyebrow`, `note` and `promoLine`: the names the examples in these pages use, so they show a value landing when run against the mock. Any other campaign or surface id is unknown, as it would be on the real edge, so a test for a wrong id means something. Add your own campaigns, content and fragments with the `scenarios` option. ## From the terminal: `sparkletree dev` ```bash npx @sparkletree/cli dev ``` ``` Mock edge running at http://127.0.0.1:4330 Point your project at it, for example in .env.development.local: NEXT_PUBLIC_SPARKLETREE_KEY=st_pk_test_eyJ… NEXT_PUBLIC_SPARKLETREE_API_BASE=http://127.0.0.1:4330 NEXT_PUBLIC_SPARKLETREE_ORG_ID=00000000-0000-4000-8000-000000000001 NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID=00000000-0000-4000-8000-000000000002 Press Ctrl+C to stop. ``` Put those lines in your development env file and restart your dev server. The names follow your framework (`--framework`, or read from `package.json`), as with `init`. The values depend only on the port, so the same lines work every time. `--port ` picks another port; `--failure ` makes every request act out one failure. Each event the mock receives is logged on stderr. Ctrl+C stops it. ## In a Vitest test: `mockFetch` `mockFetch()` is a `fetch` answered in process, with no server and no ports. Pass it to the provider as `fetchImpl`. It carries a test key and the mock's ids, so the provider needs nothing else. ```tsx // hero.test.tsx (Vitest, environment "jsdom", with @testing-library/react) import { cleanup, render, waitFor } from "@testing-library/react"; import { afterEach, expect, it } from "vitest"; import { Hero, SparkletreeProvider } from "@sparkletree/react"; import { mockFetch, type MockFetch } from "@sparkletree/core/testing"; const fallback = { headline: "Handmade stoneware", body: "Fired in small batches." }; function renderHero(fetchImpl: MockFetch) { const { container } = render( , ); return container.querySelector(".st-hero")!; } // Testing Library unmounts after each test by itself only under `globals: true`. afterEach(cleanup); it("plays the streamed copy and counts the impression", async () => { const fetchImpl = mockFetch({ pace: 0 }); const hero = renderHero(fetchImpl); await waitFor(() => expect(hero.getAttribute("data-phase")).toBe("settled")); expect(hero.textContent).toContain("This headline streamed from the mock edge"); // The impression is sent after the copy settles: wait for it to arrive. await waitFor(() => expect(fetchImpl.events().map((event) => event.eventType)).toContain("impression")); fetchImpl.close(); }); it("keeps the fallback when the edge is down", async () => { const fetchImpl = mockFetch({ failure: "offline" }); const hero = renderHero(fetchImpl); await waitFor(() => expect(hero.getAttribute("data-phase")).toBe("failed")); expect(hero.textContent).toContain(fallback.headline); expect(hero.querySelector('[data-content-source="generated"]')).toBeNull(); fetchImpl.close(); }); ``` `afterEach(cleanup)` unmounts what a test rendered. Testing Library does this by itself only when Vitest runs with `globals: true`; without it the first test's `Hero` stays mounted and decides what the second one shows. `pace: 0` sends every stream frame at once, so the test does not wait for copy to be paced the way a generation lands. Relative URLs resolve against `apiBase` (default `http://127.0.0.1:4330`); absolute URLs are answered whatever their host. `close()` stops every delay and open stream. ## In a Playwright test: `startMockEdge` `startMockEdge()` runs the mock as an HTTP server on `127.0.0.1`. Node only. Start it on a fixed port and give the app under test the env lines `sparkletree dev` prints for that port. ```ts // e2e/hero.spec.ts import { expect, test } from "@playwright/test"; import { expectNoLayoutShift, installLayoutShiftObserver, layoutShift, startMockEdge, type MockEdge, } from "@sparkletree/core/testing"; let edge: MockEdge; test.beforeAll(async () => { edge = await startMockEdge({ port: 4330 }); }); test.afterAll(async () => { await edge.close(); }); test.beforeEach(() => { edge.reset(); edge.setFailure(null); }); test("copy lands without moving the page", async ({ page }) => { await installLayoutShiftObserver(page); await page.goto("/"); await expectNoLayoutShift(page); expect((await layoutShift(page)).total).toBe(0); expect(edge.events().some((event) => event.eventType === "impression")).toBe(true); }); test("a slow edge: the fallback lands and nothing moves", async ({ page }) => { edge.setFailure("slow"); await installLayoutShiftObserver(page); await page.goto("/"); await expectNoLayoutShift(page); await expect(page.locator(".st-hero")).toContainText("Handmade stoneware"); }); ``` `startMockEdge` resolves to the server's `url` and `port`, a `publishableKey` whose API base is that server, the mock's ids (`organizationId`, `campaignId`, `surfaceId`, `variantId`), `events()`, `reset()`, `setFailure()` and `close()`. Without `port` it takes any free port. `host` sets the interface. ## In the Vite dev server: `mockEmbedApi` The Vite plugin serves the mock from the dev server (and `vite preview`) at the page's own origin. Paths the mock does not serve go on to Vite. ```ts // vite.config.ts import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { mockEmbedApi } from "@sparkletree/core/testing"; export default defineConfig({ plugins: [react(), mockEmbedApi()], }); ``` ```tsx ``` The plugin runs in Vite's Node process and adds nothing to your build. It logs each event it receives to the console. `plugin.handler` is the shared handler, for reading events or setting a failure from your own dev setup. The [runnable examples](https://docs.sparkletree.io/developers/sdk/examples.md) are built this way. ## Make it fail on purpose | Failure | What the mock does | |---|---| | `offline` | Drops the connection. | | `slow` | Holds back the first byte for `slowMs` (default 3000 ms, longer than the SDK's hold). | | `stall` | Sends part of the response and then nothing. | | `error-mid-stream` | Breaks the response part way. On the islands stream it ends with an `error` event, one chunk step after the last chunk (none at `pace: 0`). | | `http-500` | Answers 500. | | `quota` | Serves the stored copy as static, with `degraded: "quota"`. | | `unauthorized` | Answers 401 with an embed auth reason (`unauthorizedReason`, default `origin_not_allowed`) where the edge checks a key, and whoami answers `ok: false` with the same reason and its remedy. Fragment reads are not checked, on the real edge either, so they still serve. islands/copy checks no origin, so it refuses only for a key reason or `org_mismatch`. | | `over-long` | Sends copy far longer than the slot's length budget. | | `empty` | Sends no copy. | Pick one in any of these ways. A choice for one request wins over a choice for the whole mock. | For | How | |---|---| | The whole mock | The `failure` option, `setFailure(name)` (`null` clears it), or `sparkletree dev --failure `. | | One request | The query parameter `?st-mock=` or the header `x-st-mock: `. An unknown name answers 400 with the list. | | One campaign or surface | The id `st-mock-`, made by `failureCampaignId(name)`. Every request that names it fails that way. | `fixtureCampaignId(name)` (`st-fixture-`) replays one recorded fixture exactly as recorded; `FIXTURES` lists them. ## What the page should show When the integration is right, every failure ends with readable copy and no layout shift. Check this with `expectNoLayoutShift` for each one. | Failure | On the page | |---|---| | `offline`, `http-500`, `unauthorized` | `data-phase="failed"`. Your fallback, readable, with no adapted provenance (`data-content-source` is `static`). | | `slow` | The block holds, its space reserved by your invisible fallback, then your fallback lands with one short fade when the hold runs out. The late stream is not shown: the fallback is final for the page view. | | `stall` | The same as `slow`: the stream opened, so the hold restarts once (at most 5 seconds in all), then your fallback lands and nothing replaces it. The mock types no text before it goes quiet. A real stream that types part of a line and then goes quiet has that line replaced once by your fallback 5 seconds after its last text. | | `error-mid-stream` | `data-phase="failed"`. React (`Hero`, `Cta`, `useIsland`): the mock sends the `error` one chunk step after the half headline, so at the default pace the page shows the half line first. That half line is then replaced once by your fallback, with one cross-fade in the space it reserved, and the headline reads `data-content-source="static"`. When the error arrives before the half line was painted, nothing is replaced, the headline reads `data-content-source="static"`, and `rewrites` stays 0. There are two such cases. If the line started in an earlier network read and the chunk and the error came together in a later one, your fallback is typed into the slot that was still blank, at the typing pace (two characters a frame, about 300 ms for a 36-character headline; no motion under reduced motion). If the whole stream came in one read, as it does from the mock over HTTP at `pace: 0`, the headline was still held, so your fallback appears at once with no typing. A field that was still held (out of view) or that it never started gets your fallback, and a fallback already on screen stays. The custom elements (``) show no typing, so only a field the stream finished lands; the field it was writing and any it never started keep your served text. | | `quota` | `data-phase="settled"` and `data-degraded="quota"` on `Hero`. Real copy, the stored version, marked `static`, so nothing claims adapted provenance. | | `over-long` | Your fallback. Copy that does not fit the space your fallback reserved is not shown, so the slot neither grows nor moves the page. | | `empty` | `data-phase="settled"` with your fallback in every field. | The reason is the same each time: the fallback sets the slot's size, and visible text is never replaced, except a line the stream did not finish, which ends on your fallback once. See [When things go wrong](https://docs.sparkletree.io/developers/sdk/when-things-break.md) and the [layout doctrine](https://gitlab.com/sparkletree/sparkletree-sdk/-/blob/main/LAYOUT-DOCTRINE.md). ## Read back what was tracked Every event the mock's `/track` received, oldest first: ```ts edge.events(); // startMockEdge fetchImpl.events(); // mockFetch plugin.handler.events(); // mockEmbedApi ``` Over HTTP, from any of them: `GET /__sparkletree/events` answers `{ "events": [...] }`, `?type=impression` filters by event type, and `DELETE /__sparkletree/events` clears the list. `reset()` forgets the events and the minted fragments. | Member | | |---|---| | `receivedAt` | When the mock received it, ISO 8601. | | `eventType` | `impression`, `click`, `conversion` or `custom` (the page view is a `custom` event). | | `organizationId`, `campaignId`, `variantId` | When the event named them. | | `eventData` | What the SDK sent with it, such as `context.island`. | | `body` | The request body as sent. | ## The layout helpers They take a Playwright `page` (anything with `addInitScript` and `evaluate`) and import nothing from Playwright. Layout shifts are reported by Chromium only; elsewhere `expectNoLayoutShift` throws and says so. | Helper | What it does | |---|---| | `installLayoutShiftObserver(page)` | Records layout shifts from the start of every document the page loads. Call it before `page.goto()`. | | `layoutShift(page)` | The shift recorded so far on this document: `total`, `totalExcludingInput`, `entries` (each with `value`, `startTime`, `hadRecentInput` and the `nodes` it moved), `scrollHeight`, `supported`, `documentId`. | | `waitForSettled(page, selector?, options?)` | Waits until the copy in `selector` (default: the whole page) has settled: nothing still reserved, holding or live, and something there stamped as settled. Then waits two frames, so late shift entries are in. Throws a readable error naming what is still pending. | | `expectNoLayoutShift(page, action?, options?)` | Runs `action`, waits for the copy to settle, and throws when anything moved: a layout shift, a change of `document.documentElement.scrollHeight`, or a change of a landmark element's box. The error names each shift and each element that moved. Resolves to `{ shift, entries, scrollHeight, landmarks }`. | The action must not navigate: navigate first, then check what follows. Without an action, `expectNoLayoutShift` checks from the moment it is called until the copy settles; `layoutShift(page).total` covers the whole load. | Option | Default | | |---|---|---| | `selector` | the whole page | Wait for the copy in this selector to settle. | | `timeoutMs` | 10 000 | How long to wait for the settle. | | `tolerance` | 0 | The total shift allowed. | | `ignoreInputShifts` | false | Leave out shifts the browser flagged as following input, as web-vitals CLS does. Chromium flags shifts for about 500 ms after a click, so by default they count. | | `landmarks` | `DEFAULT_LANDMARKS`, the direct children of `body` and of `main` | CSS selectors for the elements whose boxes must not change. `[]` skips the comparison. They catch a page shorter than the viewport, where content can move without the scroll height changing. | | `newSettle` | true | After an action, wait for a new settle. Pass false when the action changes no SparkleTree copy. | `waitForSettled` takes `timeoutMs`, `after` (an action to run first, after which the settle must be a new one) and `newSettle`. ## Options `startMockEdge`, `mockEmbedApi` and `mockFetch` share these options. | Option | Default | | |---|---|---| | `scenarios` | the defaults | Extra or replacement streams, content and fragments, merged over the defaults id by id. | | `failure` | none | A failure for every request. | | `slowMs` | 3000 | How long `slow` holds back the first byte. | | `pace` | 1 | Multiplies every delay between stream frames. 0 sends every frame at once. | | `enforcement` | `"log"` | The key and site check: `log` serves every request and stamps `x-st-auth` with the reason a key failed; `required` answers 401; `off` checks nothing. | | `origins` | any loopback origin | Origins registered for live keys. | | `strictKeys` | false | Check key signatures the way the real edge does. Needs `keySecret`; sign keys with `signPublishableKey`. | | `keySecret` | none | The secret `strictKeys` checks against. A test value, never a real secret. | | `unauthorizedReason` | `origin_not_allowed` | The reason the `unauthorized` failure reports, on whoami too. | | `organization` | | The workspace `/facts` describes. | | `signFacts` | true | Sign `/facts` with a throwaway key. | | `mintText` | the field's fallback | The text a fragment mint writes. | | `answer` | a fixed sentence | The answer `/ask` gives. | | `livePlayback` | none | A real Cloudflare Stream player, `