@nordhavnhq/beacon 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cache.ts","../src/errors.ts","../src/version.ts","../src/client.ts","../src/chart.ts","../src/chart-fence.ts","../src/index.ts"],"names":["version"],"mappings":";;;AAiGA,IAAM,OAAA,GAAU,CAAA;AAGT,IAAM,mBAAN,MAA6C;AAAA,EAGlD,WAAA,CAAoB,aAAa,GAAA,EAAK;AAAlB,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAFpB,IAAA,IAAA,CAAQ,GAAA,uBAAU,GAAA,EAAwB;AAAA,EAEH;AAAA,EAEvC,IAAI,GAAA,EAAqC;AACvC,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,GAAG,CAAA;AAAA,EACzB;AAAA,EAEA,GAAA,CAAI,KAAa,KAAA,EAAyB;AAExC,IAAA,IAAA,CAAK,GAAA,CAAI,OAAO,GAAG,CAAA;AACnB,IAAA,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACvB,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,GAAO,IAAA,CAAK,UAAA,EAAY;AACtC,MAAA,MAAM,SAAS,IAAA,CAAK,GAAA,CAAI,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AACtC,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,IAAA,CAAK,GAAA,CAAI,OAAO,MAAM,CAAA;AAAA,IACxB;AAAA,EACF;AAAA,EAEA,OAAO,GAAA,EAAmB;AACxB,IAAA,IAAA,CAAK,GAAA,CAAI,OAAO,GAAG,CAAA;AAAA,EACrB;AAAA,EAEA,IAAA,GAAyB;AACvB,IAAA,OAAO,IAAA,CAAK,IAAI,IAAA,EAAK;AAAA,EACvB;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAA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AE,EAAA,EAAI,KAAA,EAAO,OAAO,mBAAA,EAAoB;AAC1D,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACvB,SACO,GAAA,EAAK;AACV,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,gBAAA,EAAmB,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA,CAAA,EAAG;AAAA,EACnG;AACA,EAAA,IAAI;AACF,IAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,KAAA,EAAO,UAAA,CAAW,GAAG,CAAA,EAAE;AAAA,EAC5C,SACO,GAAA,EAAK;AACV,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA,EAAE;AAAA,EAC9E;AACF;;;AChEO,SAAS,aAAa,OAAA,EAA0C;AACrE,EAAA,OAAO,IAAI,YAAY,OAAO,CAAA;AAChC","file":"index.cjs","sourcesContent":["/**\n * Read caching for the content client. GET responses (schema, record lists,\n * single records, queries) are cached by request key and kept fresh by\n * conditional revalidation: each entry stores the studio's `ETag`, which the\n * client sends back as `If-None-Match`. A cheap project-wide stamp gates whether\n * a revalidation is even attempted, so a stable site serves straight from cache.\n *\n * Swap in a custom `CacheStore` to share a cache across client instances or to\n * back it with something persistent.\n */\n\nexport interface CacheEntry {\n value: unknown\n /**\n * The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`\n * to revalidate: a `304` means the stored value is still current.\n */\n etag?: string\n /**\n * The project stamp this entry was last confirmed current against. When it\n * equals the client's latest known stamp, the entry is served without any\n * network call at all.\n */\n validatedVersion?: string\n /** Epoch ms when the entry expires. `0` means it never expires. */\n expiresAt: number\n /**\n * Epoch ms before which a failed refetch is not retried: until then the entry\n * is served as-is. Set after a transient error, cleared by a fresh value or a\n * `304`.\n */\n retryAt?: number\n}\n\n/** Pluggable backing store. The default is an in-memory, insertion-ordered map. */\nexport interface CacheStore {\n get(key: string): CacheEntry | undefined\n set(key: string, entry: CacheEntry): void\n delete(key: string): void\n /** Iterate current keys (used for prefix invalidation). */\n keys(): Iterable<string>\n clear(): void\n}\n\nexport interface CacheOptions {\n /** Master switch. Default `true`. */\n enabled?: boolean\n /**\n * How long a cached entry survives, in ms. Default `604800000` (7 days).\n *\n * This is NOT how long until content refreshes - revalidation keeps entries\n * current within `revalidate` (seconds) whenever the studio is reachable. The\n * TTL only decides when an entry stops being served blindly and the next read\n * must refetch it. If that refetch fails transiently (studio down, 5xx,\n * network), the expired value is served anyway, so a studio outage degrades\n * to \"slightly stale\" rather than \"site errors\" however long it lasts.\n *\n * The one case where it bounds staleness directly is when revalidation is off\n * (`revalidate: false`) or the server has no `/version` endpoint: then content\n * can be up to `ttl` old while the studio is reachable. `0` = never expire.\n */\n ttl?: number\n /**\n * Minimum ms between two project-stamp checks. Default `60000` (1 minute) -\n * this is the freshness window for PUBLIC visitors (an edit is picked up on\n * the next check after it lands); an editor viewing a surface preview bypasses\n * the cache entirely and always sees changes instantly.\n *\n * The check fires only on a read and is throttled, so a quiet site barely\n * checks at all; the interval only caps the busy case. Each check costs the\n * studio a small API-key lookup, so raise it (a few minutes) if you run many\n * frontends; lower it for a tighter public window. `false` disables checking\n * and leaves you with pure TTL expiry.\n */\n revalidate?: number | false\n /**\n * How long a read that already holds a cached value waits on the studio for a\n * fresher one, in ms. Default `1000`. Past it the read gets the cached value\n * and the refresh finishes in the background, so the next read has it.\n *\n * It keeps a slow or hanging studio from slowing your pages down: without it\n * every read after an edit waits for as long as the studio takes, up to\n * `timeout`. The price is that on a slow studio an edit shows one read later.\n *\n * `0` never waits (always serve the cached value, refresh in the background).\n * `false` waits for the studio; choose it where work cannot outlive the\n * request, as on serverless platforms that freeze the process once the\n * response is out. A read with nothing cached always waits.\n */\n waitForFresh?: number | false\n /** Soft cap on entries; oldest are evicted first. Default `500`. */\n maxEntries?: number\n /** Custom backing store. Defaults to an in-memory store. */\n store?: CacheStore\n}\n\n/** An `expiresAt` that is always in the past (`0` would mean \"never expires\"). */\nconst EXPIRED = 1\n\n/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */\nexport class MemoryCacheStore implements CacheStore {\n private map = new Map<string, CacheEntry>()\n\n constructor(private maxEntries = 500) {}\n\n get(key: string): CacheEntry | undefined {\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n // Re-insert so recently written keys are considered newest.\n this.map.delete(key)\n this.map.set(key, entry)\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.map.delete(oldest)\n }\n }\n\n delete(key: string): void {\n this.map.delete(key)\n }\n\n keys(): Iterable<string> {\n return this.map.keys()\n }\n\n clear(): void {\n this.map.clear()\n }\n}\n\n/**\n * Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation\n * bookkeeping (etag + validated stamp), and prefix invalidation, so the client\n * only deals in cache keys.\n */\nexport class ContentCache {\n readonly enabled: boolean\n private ttl: number\n /** Pause after a failed refetch: the `revalidate` interval, or 1 minute without one. */\n private retryDelay: number\n private store: CacheStore\n\n constructor(opts: CacheOptions = {}) {\n this.enabled = opts.enabled ?? true\n this.ttl = opts.ttl ?? 604_800_000\n this.retryDelay = typeof opts.revalidate === 'number' && opts.revalidate > 0 ? opts.revalidate : 60_000\n this.store = opts.store ?? new MemoryCacheStore(opts.maxEntries ?? 500)\n }\n\n /**\n * The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the\n * whole entry (value + etag + validated stamp) so the client can decide\n * whether to serve it, revalidate it, or fall back to it on error.\n *\n * An expired entry is left in the store (the refetch overwrites it, or\n * `maxEntries` evicts it) so `stale` can still fall back to it.\n */\n peek(key: string, now: number): CacheEntry | undefined {\n const entry = this.stale(key)\n if (!entry) return undefined\n if (entry.expiresAt !== 0 && entry.expiresAt <= now) return undefined\n return entry\n }\n\n /**\n * The entry for `key` whether or not its TTL has run out: the last good value\n * to serve when a refetch fails transiently.\n */\n stale(key: string): CacheEntry | undefined {\n if (!this.enabled) return undefined\n return this.store.get(key)\n }\n\n /** Store a freshly fetched value with its validator and the stamp it is current against. */\n set(key: string, value: unknown, opts: { etag?: string, version?: string }, now: number): void {\n if (!this.enabled) return\n this.store.set(key, {\n value,\n etag: opts.etag,\n validatedVersion: opts.version,\n expiresAt: this.ttl === 0 ? 0 : now + this.ttl,\n })\n }\n\n /**\n * Record that an existing entry is still current as of `version` (after a\n * `304`), refreshing its TTL without touching the value. No-op if it is gone.\n */\n confirm(key: string, version: string | undefined, now: number): void {\n const entry = this.store.get(key)\n if (!entry) return\n entry.validatedVersion = version\n entry.expiresAt = this.ttl === 0 ? 0 : now + this.ttl\n delete entry.retryAt\n this.store.set(key, entry)\n }\n\n /**\n * Record that refetching `key` from `from` just failed transiently, so reads\n * serve it as-is for a while instead of each waiting on an unreachable studio.\n * Returns the entry to serve: `from`, or the newer one a concurrent read stored\n * in the meantime (left unpaused, since its own fetch succeeded).\n */\n backoff(key: string, from: CacheEntry, now: number): CacheEntry {\n const entry = this.store.get(key)\n if (!entry) return from\n // Compare fields, not identity: a custom store may hand back copies.\n if (entry.etag !== from.etag || entry.expiresAt !== from.expiresAt) return entry\n entry.retryAt = now + this.retryDelay\n this.store.set(key, entry)\n return entry\n }\n\n /**\n * Mark `key` as due for a refetch while keeping its value to fall back on:\n * the next read asks the studio again whatever the stamp says, and still\n * serves this value if the studio does not answer. For when the stored value\n * may be outdated but there is no telling - dropping it would throw away the\n * only thing left to show during an outage. No-op for a key that is not held.\n */\n expire(key: string): void {\n const entry = this.store.get(key)\n if (!entry) return\n entry.expiresAt = EXPIRED\n delete entry.retryAt\n this.store.set(key, entry)\n }\n\n /** `expire` for every key that starts with `prefix`. */\n expirePrefix(prefix: string): void {\n for (const key of [...this.store.keys()]) {\n if (key.startsWith(prefix)) this.expire(key)\n }\n }\n\n /** Drop one exact key. */\n delete(key: string): void {\n this.store.delete(key)\n }\n\n /** Drop every key that starts with `prefix`. */\n deletePrefix(prefix: string): void {\n for (const key of [...this.store.keys()]) {\n if (key.startsWith(prefix)) this.store.delete(key)\n }\n }\n\n clear(): void {\n this.store.clear()\n }\n}\n","/**\n * Error thrown for any non-2xx response from the content API. `status` carries\n * the HTTP status code so callers can branch (401 bad key, 403 out of scope,\n * 404 missing node/dataset/record, 422 query failed).\n */\nexport class HavenError extends Error {\n readonly status: number\n /** The raw parsed response body, when the server returned one. */\n readonly body: unknown\n\n constructor(message: string, status: number, body?: unknown) {\n super(message)\n this.name = 'HavenError'\n this.status = status\n this.body = body\n // Restore prototype chain for `instanceof` when transpiled to ES5.\n Object.setPrototypeOf(this, HavenError.prototype)\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401\n }\n\n get isForbidden(): boolean {\n return this.status === 403\n }\n\n get isNotFound(): boolean {\n return this.status === 404\n }\n}\n","/**\n * Project-stamp tracker: the cheap gate in front of conditional revalidation.\n *\n * The cache lives in YOUR process, so the studio cannot push an invalidation\n * into it. Instead it publishes a stamp per project at `GET /api/content/version`\n * that changes on every content edit. This tracker fetches that stamp at most\n * once per interval (one tiny request regardless of read volume) and exposes the\n * latest value it has seen.\n *\n * The client uses it as a gate: while the stamp is unchanged, cached entries are\n * served with no network at all; when it moves, entries revalidate individually\n * with `If-None-Match` (a `304` keeps the cached value, a `200` replaces it). If\n * the stamp check itself fails - studio down, network blip - the last known\n * stamp stands, so the cache keeps serving instead of hammering a dead endpoint.\n */\n\nexport type VersionProbe = () => Promise<string>\n\n/** How long a server without the version route silences the check. */\nexport const UNSUPPORTED_PAUSE_MS = 15 * 60_000\n\nexport class VersionTracker {\n private lastChecked = 0\n private version: string | null = null\n private inFlight: Promise<void> | null = null\n /**\n * Epoch ms before which we do not ask again, after the server turned out\n * to have no version route. A pause and not a final verdict: an old server\n * costs one request per pause, and one that gains the route is picked up\n * without a restart.\n */\n private pausedUntil = 0\n\n constructor(\n private readonly probe: VersionProbe,\n /** Minimum ms between two probes. `0` disables checking entirely. */\n private readonly interval: number,\n /**\n * Whether a probe failure means \"this server has no version route\", as\n * opposed to \"could not be reached\". The caller decides, as only it can\n * tell the server's own `404` from the one a proxy answers with while\n * the server is away - and that one must not pause anything: the server\n * is back in seconds, and freshness would stay off for the whole pause.\n */\n private readonly isUnsupported: (err: unknown) => boolean = (err) => (err as { status?: number } | null)?.status === 404,\n ) {}\n\n /** The most recent stamp seen, or `null` before the first successful probe. */\n current(): string | null {\n return this.version\n }\n\n /**\n * Refresh the stamp if we are due. Resolves once the answer is in, so the\n * read that triggered it sees an up-to-date stamp. A failed probe leaves the\n * last known stamp in place (serve-from-cache rather than thrash).\n *\n * A failed probe counts towards the interval like any other, also when no\n * stamp has ever come in. Otherwise a process that starts while the studio\n * is down (with a persisted cache to serve from) would probe on every read,\n * and against a hanging studio make each of them wait out the probe.\n */\n async refresh(now: number): Promise<void> {\n if (this.interval <= 0 || now < this.pausedUntil) return\n if (this.inFlight) return this.inFlight\n if (now - this.lastChecked < this.interval) return\n\n this.lastChecked = now\n this.inFlight = this.run(now)\n try {\n await this.inFlight\n }\n finally {\n this.inFlight = null\n }\n }\n\n private async run(now: number): Promise<void> {\n try {\n this.version = await this.probe()\n }\n catch (err) {\n // A server that predates the version route: ask again only after a\n // long pause. Any other failure is transient - keep the last stamp\n // so the cache keeps serving, and try again next interval.\n if (this.isUnsupported(err)) {\n this.pausedUntil = now + Math.max(this.interval, UNSUPPORTED_PAUSE_MS)\n }\n }\n }\n}\n","import { ContentCache, type CacheEntry, type CacheOptions } from './cache'\nimport { HavenError } from './errors'\nimport type { ContentLocale, ContentRecord, ContentSchema, QueryResult, SchemaNode } from './types'\nimport { VersionTracker } from './version'\n\n/**\n * Query parameter Nordhavn OS appends when it loads your site in a\n * surface preview. Its presence means \"an editor is looking at this right now\",\n * which is exactly when caching must get out of the way - see `forRequest`.\n */\nexport const PREVIEW_PARAM = 'sl-preview'\n\n/** Hosted Nordhavn OS platform. Used when no `baseUrl` is provided. */\nexport const DEFAULT_BASE_URL = 'https://beacon.nordhavn.ai'\n\n/** Default request timeout in ms (`timeout` option). */\nconst DEFAULT_TIMEOUT = 10_000\n/** Ceiling for the stamp check, which every concurrent read waits on. */\nconst VERSION_TIMEOUT = 3_000\n/** Default for `cache.waitForFresh`, in ms. */\nconst DEFAULT_WAIT_FOR_FRESH = 1_000\n/** The longest delay a timer holds; beyond it `setTimeout` fires after 1 ms. */\nconst MAX_TIMER = 2_147_483_647\n/** How many keys `storedBy` remembers before it starts over. */\nconst STORED_LIMIT = 5_000\n/** How long a failed read of the project's locales is not repeated. */\nconst LOCALES_RETRY_MS = 60_000\n/** Default for `gatewayRetry`, in ms. */\nconst DEFAULT_GATEWAY_RETRY = 200\n/** The longest `gatewayRetry` honoured; a larger value is cut back to this. */\nconst MAX_GATEWAY_RETRY = 60_000\n\n/** A studio failure the client absorbed, handed to `onError`. */\nexport interface StudioFailure {\n /**\n * What failed: the periodic `stamp-check`, or the `read` that refreshes one\n * cache entry (its cached value was served instead).\n */\n during: 'stamp-check' | 'read'\n /** Cache key of the entry that could not be refreshed. Only for `read`. */\n key?: string\n /** What went wrong: a `HavenError`, a `TimeoutError`, a network error. */\n error: unknown\n}\n\nexport interface HavenClientOptions {\n /**\n * Project API key, `slk_...`. Mint one in the project's settings under\n * \"API keys\". Its reach is the union of its per-node read/write scopes.\n */\n apiKey: string\n /**\n * Base URL of your Nordhavn OS server, without a trailing `/api/content`\n * (that path is appended automatically). Defaults to the hosted platform at\n * `https://beacon.nordhavn.ai`; override it for a self-hosted instance.\n */\n baseUrl?: string\n /**\n * Default locale for reads, e.g. `nl` or `fr-BE`. When set, records are\n * returned in that language, with untranslated fields falling back to the\n * project default. Override per call with `opts.locale`. Omit for the default\n * locale. Discover available locales with `client.locales()`.\n */\n locale?: string\n /** Read caching. Pass `false` to disable, or an options object to tune it. */\n cache?: boolean | CacheOptions\n /** Custom `fetch` implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch\n /**\n * Give up on a request after this many ms, body included. Default `10000`.\n * `0` disables it, as does `Infinity`.\n *\n * Without one, a studio that accepts the connection but never answers holds\n * every read until the runtime gives up (minutes, in Node). A timed-out read\n * counts as transient, like a `5xx`: the last good value is served. The\n * once-a-minute stamp check uses at most 3 seconds of it, as every read in\n * that moment waits on the check.\n *\n * It covers writes too. A write that times out may still have reached the\n * studio, so do not blindly send it again: you could store it twice.\n */\n timeout?: number\n /**\n * A read with nothing cached that gets a `502` or `503` tries once more after\n * this many ms, plus up to as many again at random (so the reads of one page\n * do not all come back at once). Default `200`. `false` turns it off.\n *\n * Often one bad moment, such as a proxy switching to a new studio container;\n * and with nothing cached the error is all the caller would get. Never for a\n * read with a value cached (that value is served), a preview or\n * `cache: false` read, a write, or an answer carrying `Retry-After`.\n */\n gatewayRetry?: number | false\n /**\n * Called for every studio failure the client absorbs: a failed stamp check,\n * or a read answered from the cache because its refresh failed. These never\n * reach your code as an error, so this is the only place to notice that the\n * site is running on cached content. Errors that are thrown to the caller\n * (a read with nothing cached, a write) are not repeated here.\n *\n * At most one call per stamp check and one per cache entry per retry pause,\n * so it is safe to log or alert from. Without it the client logs one\n * `console.warn` per outage.\n */\n onError?: (failure: StudioFailure) => void\n /** Extra headers merged into every request. */\n headers?: Record<string, string>\n /**\n * Force preview behaviour: every read bypasses the cache and refreshes it.\n * Usually you do not set this by hand - use `client.forRequest(req)`, which\n * turns it on only for requests that carry the studio's preview marker.\n */\n preview?: boolean\n}\n\n/** Per-call read options. */\nexport interface ReadOptions {\n /** Set `false` to bypass the cache for this call and always hit the network. */\n cache?: boolean\n /**\n * Locale for this read, overriding the client-level `locale`. Pass an empty\n * string to force the project default even when a client locale is set;\n * `undefined` or `null` (a missing header, from `headers.get()`) leaves the\n * client locale in place. Untranslated fields fall back to the default\n * locale. Only record reads use it (`listRecords`, `getRecord`, a dataset's\n * `list` and `get`); `query()`, `schema()`, `nodes()` and `locales()` ignore it.\n */\n locale?: string | null | undefined\n}\n\ntype Method = 'GET' | 'POST' | 'PATCH'\n\n/**\n * Typed client for the Nordhavn OS content API: read and write a project's node\n * datasets from any website or app. Reads are cached (see the `cache` option);\n * writes invalidate the affected cache entries automatically.\n *\n * ```ts\n * const studio = new HavenClient({ apiKey: 'slk_...', baseUrl: 'https://studio.example.com' })\n * const posts = await studio.dataset<Post>('blog', 'posts').list()\n * ```\n */\nexport class HavenClient {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly fetchImpl: typeof fetch\n private readonly headers: Record<string, string>\n private readonly cache: ContentCache\n private readonly versionTracker: VersionTracker\n /**\n * `false` on a preview view (see `forRequest`), so reads bypass the cache by\n * default. The one field such a view has of its own; all the rest is shared.\n */\n private readDefault: boolean\n /** Client-level default locale for reads (undefined = project default). */\n private readonly locale?: string\n /** Request timeout in ms, `0` for none. */\n private readonly timeout: number\n /** `cache.waitForFresh` in ms, `Infinity` to wait for the studio. */\n private readonly waitForFresh: number\n /** `gatewayRetry` in ms, `undefined` when it is off. */\n private readonly gatewayRetry: number | undefined\n /**\n * The refresh under way per cache key, so concurrent reads of one key share\n * one request, with the ticket it left on (see `state.ticket`).\n */\n private readonly inflight = new Map<string, { job: Promise<unknown>, ticket: number }>()\n /**\n * Per cache key, the ticket of the request whose answer the cache holds.\n * Emptied on every invalidation, capped by `STORED_LIMIT`. See `storable`.\n */\n private readonly storedBy = new Map<string, number>()\n private readonly onError?: (failure: StudioFailure) => void\n /**\n * Everything that changes while the client runs and is not a collection of\n * its own. One object, so that a preview view - which shares this client's\n * fields through its prototype - changes the same values and never a copy.\n */\n private readonly state = {\n /**\n * Numbers the requests in the order they leave. Answers come back in any\n * order, and the cache must never go back in time: a request takes a\n * ticket when it leaves, and `storable` compares it on the way back.\n */\n ticket: 0,\n /** The last ticket handed out when the cache was last invalidated. */\n invalidatedAt: 0,\n /** Set by an absorbed failure, cleared by the next answer: one warning per outage. */\n unreachable: false,\n /**\n * The project's locales as last read. Kept here and not only in the cache,\n * where the entry can be evicted: without the list a requested locale\n * cannot be mapped onto the key its content is cached under, and that\n * content would be out of reach for as long as the studio is away.\n */\n locales: undefined as ContentLocale[] | undefined,\n /** Epoch ms before which the locales are not asked for again, after that failed. */\n localesRetryAt: 0,\n }\n\n constructor(options: HavenClientOptions) {\n if (!options.apiKey) throw new Error('HavenClient: `apiKey` is required')\n\n this.apiKey = options.apiKey\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n const resolvedFetch = options.fetch ?? globalThis.fetch\n if (!resolvedFetch) {\n throw new Error('HavenClient: no `fetch` available; pass one via options.fetch')\n }\n this.fetchImpl = resolvedFetch.bind(globalThis)\n this.headers = options.headers ?? {}\n this.locale = options.locale || undefined\n this.readDefault = options.preview !== true\n this.timeout = normalizeTimeout(options.timeout)\n this.onError = options.onError\n\n const cacheOpt = options.cache\n const cacheOptions: CacheOptions\n = cacheOpt === false ? { enabled: false }\n : cacheOpt === true || cacheOpt === undefined ? {}\n : cacheOpt\n this.cache = new ContentCache(cacheOptions)\n this.waitForFresh = normalizeWait(cacheOptions.waitForFresh)\n this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry)\n\n const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false\n ? 0\n : cacheOptions.revalidate ?? 60_000\n // The stamp check is tiny, and every read arriving while it runs waits on it,\n // so it gets a tighter budget than a full read.\n const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT)\n this.versionTracker = new VersionTracker(\n async () => {\n try {\n const res = await this.request<{ version?: unknown }>('GET', '/version', undefined, probeTimeout)\n // Anything but a stamp (a maintenance page answering 200) is no\n // answer: the last known stamp stands.\n if (typeof res?.version !== 'string') throw unexpectedBody(`${this.baseUrl}/api/content/version`)\n this.state.unreachable = false\n return res.version\n }\n catch (err) {\n // A studio without the route is up and answering: nothing to report.\n if (isMissingRoute(err)) this.state.unreachable = false\n else this.report({ during: 'stamp-check', error: err })\n throw err\n }\n },\n revalidate,\n isMissingRoute,\n )\n }\n\n // ── Preview scoping ─────────────────────────────────────────────────────────\n\n /**\n * A per-request view of this client that skips the cache when the request\n * comes from a Nordhavn OS surface preview, and behaves exactly like this\n * client otherwise. Reads still refresh the shared cache, so an editor\n * refreshing the preview also warms what real visitors get.\n *\n * Accepts whatever your framework hands you: a `Request`, a URL string or\n * `URL`, `URLSearchParams`, or a plain searchParams object.\n *\n * ```ts\n * // Next.js app router\n * export default async function Page({ searchParams }) {\n * const posts = await studio.forRequest(await searchParams).dataset('blog', 'posts').list()\n * }\n * ```\n *\n * Note this only bypasses the SDK's own cache. If the page itself sits behind\n * a CDN or framework data cache, that layer needs the same treatment (e.g.\n * `cache: 'no-store'` when the preview marker is present) or the editor keeps\n * seeing a stale page no matter what this client returns.\n */\n forRequest(input: PreviewInput): HavenClient {\n if (!this.readDefault) return this // already a preview client\n if (!isPreviewRequest(input)) return this\n\n // A view on this client, not a second one: it inherits every field through\n // its prototype - the cache, the stamp, the requests under way, the options -\n // and differs in the one it sets here. The preview must refresh what the\n // public site reads, not keep a second universe of its own; and built this\n // way there is no list of fields to hand over that a new one could be\n // missing from.\n const view = Object.create(this) as HavenClient\n view.readDefault = false\n return view\n }\n\n /** Whether this client bypasses the cache (i.e. came from a preview request). */\n get isPreview(): boolean {\n return !this.readDefault\n }\n\n // ── Introspection ─────────────────────────────────────────────────────────\n\n /** The full content shape this key can reach: nodes, datasets, field schemas. */\n async schema(opts?: ReadOptions): Promise<ContentSchema> {\n return this.cachedGet<ContentSchema>('schema', '/schema', opts, has('nodes', Array.isArray))\n }\n\n /** Shorthand for `schema()` then `.nodes`. */\n async nodes(opts?: ReadOptions): Promise<SchemaNode[]> {\n return (await this.schema(opts)).nodes\n }\n\n /**\n * The locales this project's content can be requested in (default first). Use\n * a locale `code` as the client `locale` option or a per-call `opts.locale`.\n */\n async locales(opts?: ReadOptions): Promise<ContentLocale[]> {\n const res = await this.cachedGet<{ locales: ContentLocale[] }>('locales', '/locales', opts, has('locales', Array.isArray))\n return res.locales\n }\n\n /**\n * Resolve the locale for a read: per-call override, else the client default.\n * Only a value overrides: `{ locale: undefined }` (or `null`) is what a site\n * passes when the visitor sent no language, and must leave the client locale standing.\n * `''` is the one way to ask for the project default.\n */\n private resolveLocale(opts?: ReadOptions): string | undefined {\n // `!= null`: from plain JavaScript a missing header arrives as `null`\n // (`headers.get()`), and means the same as `undefined`.\n const l = opts?.locale != null ? opts.locale : this.locale\n return l || undefined\n }\n\n /**\n * The locale a read is requested and cached under: the requested one mapped\n * onto a locale the project is configured with (see `matchLocale`).\n *\n * Sites pass on whatever language the visitor's browser asks for, and the\n * studio answers all of `nl`, `nl-NL` and `nl-BE` with the same content. Keyed\n * by the raw value, each spelling would be its own cache entry and its own\n * request - and a stream of made-up ones would push every real entry out of\n * the cache, the last good values for an outage among them. Mapped first,\n * the cache holds one entry per configured locale, whatever is asked for.\n *\n * Without the list of locales (caching off, an older studio without the\n * route, studio unreachable and never read) the requested value goes to the\n * studio as it is, and the studio resolves it.\n */\n private async readLocale(opts?: ReadOptions): Promise<string | undefined> {\n const requested = this.resolveLocale(opts)?.trim() || undefined\n if (requested === undefined || !this.cache.enabled) return requested\n\n // A preview or `cache: false` read is never tried twice (`gatewayRetry`),\n // and neither is the lookup it may have to wait for.\n const bypass = !(opts?.cache ?? this.readDefault)\n const configured = await this.configuredLocales(!bypass)\n return configured ? matchLocale(requested, configured) : requested\n }\n\n /**\n * The project's locales, or `undefined` when they have never been read and\n * cannot be now. An empty list is an answer like any other: the project has\n * no locales, the studio serves the same content whatever language is asked\n * for, and `matchLocale` then maps every request onto the default.\n *\n * Once the list is known this does not wait for anything: the read maps from\n * the list as it stands, and the list is brought up to date on the side. A\n * read therefore spends its `waitForFresh` on its content alone, and keeps\n * finding that content under the same key while the studio is away. Only\n * the very first localized read waits here, as it has nothing to map from.\n *\n * The exception is `waitForFresh: false`. That setting promises that a read\n * waits for the studio and leaves nothing running when it returns - what a\n * host needs that freezes the process once the response is out. So there\n * the list is brought up to date first, like the content after it.\n */\n private async configuredLocales(retry: boolean): Promise<ContentLocale[] | undefined> {\n const state = this.state\n if (Date.now() >= state.localesRetryAt) {\n // Always through the cache, also on a preview view: this runs on every\n // localized read, and a new locale shows up when the stamp moves.\n const lookup = this.cachedGet<{ locales: ContentLocale[] }>(\n 'locales',\n '/locales',\n { cache: true },\n has('locales', Array.isArray),\n retry,\n ).then(\n (res) => {\n state.locales = res.locales\n },\n () => {\n // Leave the list as it is, and the studio alone for a while.\n state.localesRetryAt = Date.now() + LOCALES_RETRY_MS\n },\n )\n if (state.locales === undefined || this.waitForFresh === Infinity) await lookup\n }\n return state.locales\n }\n\n // ── Records ───────────────────────────────────────────────────────────────\n\n /** List every record in a dataset (references inflated). Requires read scope. */\n async listRecords<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n opts?: ReadOptions,\n ): Promise<ContentRecord<T>[]> {\n const locale = await this.readLocale(opts)\n const res = await this.cachedGet<{ records: ContentRecord<T>[] }>(\n recordsKey(nodeSlug, datasetSlug, locale),\n datasetPath(nodeSlug, datasetSlug) + localeQuery(locale),\n opts,\n has('records', Array.isArray),\n )\n return res.records\n }\n\n /** Read one record by uid. Requires read scope. Throws 404 if it does not exist. */\n async getRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n recordUid: string,\n opts?: ReadOptions,\n ): Promise<ContentRecord<T>> {\n const locale = await this.readLocale(opts)\n const res = await this.cachedGet<{ record: ContentRecord<T> }>(\n recordKey(nodeSlug, datasetSlug, recordUid, locale),\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}${localeQuery(locale)}`,\n opts,\n has('record', isObject),\n )\n return res.record\n }\n\n /** Create a record. Requires write scope. Invalidates cached reads of the dataset. */\n async createRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n data: Record<string, unknown>,\n ): Promise<ContentRecord<T>> {\n const res = await this.write<{ record: ContentRecord<T> }>(\n 'POST',\n datasetPath(nodeSlug, datasetSlug),\n { data },\n nodeSlug,\n datasetSlug,\n )\n return res.record\n }\n\n /**\n * Partially update a record. The patch is merged onto the stored data (omitted\n * top-level fields are preserved). Requires write scope. Invalidates cached\n * reads of the dataset and of this record.\n */\n async updateRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n recordUid: string,\n data: Record<string, unknown>,\n ): Promise<ContentRecord<T>> {\n const res = await this.write<{ record: ContentRecord<T> }>(\n 'PATCH',\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}`,\n { data },\n nodeSlug,\n datasetSlug,\n )\n return res.record\n }\n\n /**\n * Sends a write and settles the cached reads of its dataset with the outcome.\n *\n * Stored: they are dropped. Refused (an answered 4xx): they are still right\n * and stay. Anything else - a timeout, a dropped connection, a 5xx - leaves\n * open whether the studio carried the write out, so they are marked for a\n * recheck: the next read asks the studio again, and keeps the cached value to\n * fall back on if the studio is in fact down.\n */\n private async write<T>(method: Method, path: string, body: unknown, nodeSlug: string, datasetSlug: string): Promise<T> {\n let res: T\n try {\n res = await this.request<T>(method, path, body)\n }\n catch (err) {\n if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, 'recheck')\n throw err\n }\n this.invalidateDataset(nodeSlug, datasetSlug)\n return res\n }\n\n // -- Queries --\n\n /** Run a saved query (`queries.<slug>`) and return its result. Requires read scope. */\n async query<V = unknown>(querySlug: string, opts?: ReadOptions): Promise<QueryResult<V>> {\n return this.cachedGet<QueryResult<V>>(\n `query:${querySlug}`,\n `/queries/${encodeURIComponent(querySlug)}`,\n opts,\n // Recognised by `shape`, never by `value`: that may be anything, and a\n // query without a result can come back with no `value` at all.\n has('shape', (shape) => typeof shape === 'string'),\n )\n }\n\n // ── Fluent dataset handle ───────────────────────────────────────────────────\n\n /**\n * A fluent, type-parameterised handle to one dataset:\n * `client.dataset<Post>('blog', 'posts').list()`.\n */\n dataset<T = Record<string, unknown>>(nodeSlug: string, datasetSlug: string): DatasetHandle<T> {\n return new DatasetHandle<T>(this, nodeSlug, datasetSlug)\n }\n\n // ── Cache control ───────────────────────────────────────────────────────────\n\n /**\n * Clear cached reads. With no argument, clears everything. Pass a scope to\n * clear just part of it: a node slug, or `{ node, dataset }` for one dataset.\n * A scoped clear also drops every saved query result, as any of them may\n * aggregate the content that was cleared.\n */\n clearCache(scope?: string | { node: string, dataset?: string }): void {\n if (scope === undefined) {\n this.cache.clear()\n this.invalidated()\n return\n }\n const node = typeof scope === 'string' ? scope : scope.node\n const dataset = typeof scope === 'string' ? undefined : scope.dataset\n if (dataset) {\n this.invalidateDataset(node, dataset)\n return\n }\n this.dropPrefix(`records:${node}/`)\n this.dropPrefix(`record:${node}/`)\n this.dropPrefix('query:')\n }\n\n /**\n * Invalidate cached record reads for a dataset (every locale), plus all query\n * results (which may aggregate it). `drop` removes them; `recheck` keeps each\n * value as a fallback but makes the next read ask the studio again.\n */\n private invalidateDataset(nodeSlug: string, datasetSlug: string, how: 'drop' | 'recheck' = 'drop'): void {\n const one = how === 'drop' ? (key: string) => this.drop(key) : (key: string) => this.recheck(key)\n const all = how === 'drop' ? (prefix: string) => this.dropPrefix(prefix) : (prefix: string) => this.recheckPrefix(prefix)\n // Default-locale list key + every `::<locale>` variant of it.\n one(recordsKey(nodeSlug, datasetSlug))\n all(`${recordsKey(nodeSlug, datasetSlug)}::`)\n // All single-record keys under the dataset (every uid, every locale).\n all(`${recordKey(nodeSlug, datasetSlug, '')}`)\n all('query:')\n }\n\n /** Drop one key from the cache. */\n private drop(key: string): void {\n this.cache.delete(key)\n this.invalidated()\n }\n\n /** `drop` for every key that starts with `prefix`. */\n private dropPrefix(prefix: string): void {\n this.cache.deletePrefix(prefix)\n this.invalidated()\n }\n\n /** Like `drop`, but the value stays as a fallback (see `ContentCache.expire`). */\n private recheck(key: string): void {\n this.cache.expire(key)\n this.invalidated()\n }\n\n /** `recheck` for every key that starts with `prefix`. */\n private recheckPrefix(prefix: string): void {\n this.cache.expirePrefix(prefix)\n this.invalidated()\n }\n\n /**\n * Called by everything that invalidates cached reads. Every request that is\n * under way at this moment left before it, so its answer may show the\n * content as it was: none of them may store what they come back with\n * (`storable`), and no later read may join one of them (hence the cleared\n * `inflight`). They still answer the reads that were already waiting on them.\n *\n * Deliberately not narrowed to the keys that were invalidated. The price is\n * that an unrelated answer now and then is served without being stored, and\n * asked for once more; what it buys is one rule without exceptions.\n */\n private invalidated(): void {\n this.state.invalidatedAt = this.state.ticket\n this.storedBy.clear()\n this.inflight.clear()\n }\n\n /**\n * Whether the answer to the request that left on `ticket` may change what\n * the cache holds for `key`. The single gate in front of every cache write\n * that follows a request - cached read or bypass, a new value, a `304`, a\n * deletion or a retry pause alike. It keeps the cache from going back in time:\n *\n * - not when the cache was invalidated after the request left: the answer\n * may show the content from before (a write, `clearCache`);\n * - not when the cache already holds the answer to a request that left\n * later: that one is newer, whichever of the two came back first.\n */\n private storable(key: string, ticket: number): boolean {\n return ticket > this.state.invalidatedAt && ticket >= (this.storedBy.get(key) ?? 0)\n }\n\n /**\n * Settles the cache with the studio's own definitive \"no\" for `key` (deleted,\n * forbidden), in answer to the request that left on `ticket`: the entry goes.\n * The one place this happens, for a cached read and a bypass alike.\n *\n * The deletion is noted like any other answer. Without that, a request that\n * left earlier and comes back later would pass the gate and put the deleted\n * content straight back.\n */\n private gone(key: string, ticket: number): void {\n if (!this.storable(key, ticket)) return\n this.cache.delete(key)\n this.stored(key, ticket)\n }\n\n /**\n * Notes that the cache now reflects, for `key`, the answer to the request\n * that left on `ticket` - a value, a `304`, or the studio's own \"this does\n * not exist\", after which the cache holds nothing for it. A refresh of that\n * key that left earlier and is still under way is retired: a read arriving\n * now must not join it for an older answer than the cache already reflects.\n */\n private stored(key: string, ticket: number): void {\n // Unbounded growth is cut off the blunt, safe way: forget everything and\n // bar every request under way from storing, as an invalidation does.\n if (this.storedBy.size >= STORED_LIMIT) this.invalidated()\n this.storedBy.set(key, ticket)\n const running = this.inflight.get(key)\n if (running && running.ticket < ticket) this.inflight.delete(key)\n }\n\n // ── Transport ───────────────────────────────────────────────────────────────\n\n /**\n * The read path, with conditional revalidation.\n *\n * Steady state (project stamp unchanged since we last confirmed this entry):\n * served straight from cache, zero network. After a content change the stamp\n * moves, so the entry is revalidated once with `If-None-Match` - a `304` keeps\n * the cached value, a `200` replaces it - and then it is fast again.\n *\n * Five rules hold for every read, whatever the studio does. Each is enforced\n * in exactly one place, named here, so that it cannot hold for one kind of\n * read and not for another:\n *\n * 1. A failure that is not the studio's own definitive answer never costs a\n * cached value: it is served instead, and stays cached (`refresh`).\n * 2. Only what is recognisably this endpoint's answer is ever stored\n * (`conditionalGet`).\n * 3. The cache never goes back in time: an answer is not stored when the\n * cache was invalidated, or filled with a newer answer, after its request\n * left (`storable`, in front of every write to the cache).\n * 4. A read that already holds a value waits on the studio for `waitForFresh`\n * at most, stamp check and refresh together (here); the refresh then\n * finishes on the side.\n * 5. One request per key at a time (`refresh`).\n */\n private async cachedGet<T>(\n cacheKey: string,\n path: string,\n opts: ReadOptions | undefined,\n isExpected: BodyCheck,\n /** Whether a `502`/`503` with nothing cached may be tried again (`gatewayRetry`). */\n retry = true,\n ): Promise<T> {\n const useCache = opts?.cache ?? this.readDefault\n\n // Preview / explicit bypass: always fetch fresh and never fall back, but\n // still refresh the shared cache so real visitors benefit from the warm entry.\n if (!useCache) {\n // The stamp as it stands before asking, like the cached path below. Read\n // after the answer it can be newer than the content that came back (an\n // edit landed in between, and another read's stamp check saw it), and\n // that older content would then count as current until the next edit.\n const version = this.versionTracker.current() ?? undefined\n const ticket = ++this.state.ticket\n let res: Awaited<ReturnType<HavenClient['conditionalGet']>>\n try {\n res = await this.conditionalGet(path, undefined, isExpected)\n }\n catch (err) {\n // Never falls back - but the studio's own \"this does not exist\" is an\n // answer for the cache as well, here as on the cached path.\n if (isDefinitive(err)) this.gone(cacheKey, ticket)\n throw err\n }\n if (this.storable(cacheKey, ticket)) {\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n this.stored(cacheKey, ticket)\n }\n return res.value as T\n }\n\n // With something to serve, expired or not, the studio gets a budget.\n const started = Date.now()\n const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity\n\n // Cheap, throttled: at most one tiny stamp request per `revalidate` window.\n // A check that outlasts the budget carries on; this read uses the stamp we had.\n await within(this.versionTracker.refresh(started), budget)\n const version = this.versionTracker.current() ?? undefined\n const entry = this.cache.peek(cacheKey, Date.now())\n\n if (entry) {\n // Serve from cache when we cannot see a newer stamp (tracking off, first\n // probe not in yet, or studio unreachable) or the stamp is unchanged since\n // this entry was last confirmed.\n if (version === undefined || entry.validatedVersion === version) {\n return entry.value as T\n }\n }\n\n // Revalidate (the stamp moved) or refetch (miss / TTL expired). An expired\n // entry still has its etag, so an unchanged value comes back as a `304`.\n const last = entry ?? this.cache.stale(cacheKey)\n // A refetch failed moments ago: serve the last good value until the pause\n // is over, rather than making every read wait on an unreachable studio.\n if (last?.retryAt !== undefined && Date.now() < last.retryAt) {\n return last.value as T\n }\n\n const refresh = this.refresh<T>(cacheKey, path, last, version, isExpected, retry)\n if (!last) return refresh\n const outcome = await within(refresh, budget - (Date.now() - started))\n return outcome.settled ? outcome.value : last.value as T\n }\n\n /**\n * Fetches `cacheKey` from the studio and settles the cache with the answer.\n * One per key at a time: reads that arrive while it runs get the same promise,\n * so a slow studio sees one request for a key and not one per visitor.\n *\n * Resolves with the value to serve: the fresh one, or a cached one when the\n * studio failed transiently. Rejects on a definitive answer, or when there is\n * nothing cached to serve in its place.\n */\n private refresh<T>(\n cacheKey: string,\n path: string,\n last: CacheEntry | undefined,\n version: string | undefined,\n isExpected: BodyCheck,\n retry: boolean,\n ): Promise<T> {\n const running = this.inflight.get(cacheKey)\n if (running) return running.job as Promise<T>\n\n let ticket = ++this.state.ticket\n // Whether the slot for this key is still this refresh's own: once retired\n // it is empty, or belongs to the refresh that came after.\n const registered = (): boolean => this.inflight.get(cacheKey)?.job === job\n const register = (): void => {\n this.inflight.set(cacheKey, { job, ticket })\n }\n const job: Promise<T> = (async () => {\n try {\n let res: Awaited<ReturnType<HavenClient['conditionalGet']>>\n try {\n res = await this.conditionalGet(path, last?.etag, isExpected)\n }\n catch (err) {\n // A `502` or `503` is often one bad moment (a proxy switching to a\n // new studio container), and with nothing cached it is all the caller\n // would get. So once more, a moment later. A read is safe to repeat;\n // with a value to fall back on it is served instead, as below.\n const pause = this.gatewayRetry\n if (!retry || pause === undefined || last || this.cache.stale(cacheKey) || !isGatewayHiccup(err)) throw err\n await sleep(pause + Math.random() * pause)\n\n // Another request may have stored a value meanwhile: serve that.\n const meanwhile = this.cache.stale(cacheKey)\n if (meanwhile) return meanwhile.value as T\n // Or the slot went to a refresh that started during the pause, after\n // a newer answer retired this one's: that refresh left later, so its\n // answer is the one to have, and asking alongside it would break the\n // one request per key.\n const slot = this.inflight.get(cacheKey)\n // Returned as it is, not awaited: its outcome is that refresh's own,\n // already settled with the cache there, not a failure of this one.\n if (slot && !registered()) return slot.job as Promise<T>\n\n // The second try leaves now, after anything that left during the\n // pause, so it takes a ticket of its own: under the first one its\n // answer, newer than theirs, would count as older (`storable`). The\n // slot carries it, so an older answer does not retire it (`stored`);\n // emptied meanwhile (an invalidation), it is taken again, so that\n // reads arriving now join this request instead of sending their own.\n // And it reads the stamp as it stands now, before leaving: the\n // answer is at least as new as that.\n ticket = ++this.state.ticket\n if (slot) slot.ticket = ticket\n else register()\n version = this.versionTracker.current() ?? undefined\n res = await this.conditionalGet(path, undefined, isExpected)\n }\n // A `304` is only ever accepted in answer to an etag, so `last` is there.\n if (res.notModified && last) {\n if (this.storable(cacheKey, ticket)) {\n this.cache.confirm(cacheKey, version, Date.now())\n this.stored(cacheKey, ticket)\n }\n return last.value as T\n }\n if (this.storable(cacheKey, ticket)) {\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n this.stored(cacheKey, ticket)\n }\n return res.value as T\n }\n catch (err) {\n // Definitive answer from the studio itself (deleted/forbidden): drop the\n // entry and surface it.\n if (isDefinitive(err)) {\n this.gone(cacheKey, ticket)\n throw err\n }\n // Anything else is transient: studio down, 5xx, timeout, rate limit,\n // network, a body that is not what this endpoint returns, or a 4xx from\n // whatever stands in front of the studio while it is gone. Serve a\n // cached value, even an expired one, and keep it.\n //\n // What the cache holds *now*, not only what it held when this request\n // left: every read that joined gets this same outcome, and one of them\n // may hold a value that was stored in the meantime (by a preview read,\n // say) while the read that started the request had none. Failing that\n // one with an error it had the content for is exactly what rule 1 forbids.\n const held = this.cache.stale(cacheKey) ?? last\n if (!held) throw err\n this.report({ during: 'read', key: cacheKey, error: err })\n return (this.storable(cacheKey, ticket) ? this.cache.backoff(cacheKey, held, Date.now()) : held).value as T\n }\n finally {\n if (registered()) this.inflight.delete(cacheKey)\n }\n })()\n this.inflight.set(cacheKey, { job, ticket })\n return job\n }\n\n /**\n * Hands an absorbed failure to `onError`, or without one warns once per\n * outage. Never throws and never leaves a rejection behind: a broken hook\n * must not turn a served read into an error, and an `async` hook whose own\n * work fails (an alert that cannot be delivered, during the very outage it\n * reports) must not become the unhandled rejection that stops the process.\n */\n private report(failure: StudioFailure): void {\n const first = !this.state.unreachable\n this.state.unreachable = true\n try {\n if (this.onError) {\n const outcome: unknown = this.onError(failure)\n if (isThenable(outcome)) outcome.then(undefined, () => {})\n }\n else if (first) {\n const reason = failure.error instanceof Error ? failure.error.message : String(failure.error)\n const what = failure.during === 'read' ? `could not refresh \"${failure.key}\"` : 'stamp check failed'\n console.warn(`[@nordhavnhq/beacon] ${what} (${reason}); cached content keeps being served.`)\n }\n }\n catch {\n /* the hook's own problem */\n }\n }\n\n /**\n * A GET that understands conditional requests: sends `If-None-Match` when an\n * etag is supplied, and reports a `304` as `notModified` rather than a value.\n *\n * The one place that decides what counts as an answer, for every read:\n *\n * - A `2xx` whose body fails `isExpected` is rejected, not returned. A\n * maintenance page or a captive portal can answer `200` with JSON of its\n * own; storing that would replace the last good value with nothing, at the\n * very moment the studio is away.\n * - A `304` is only an answer to a request that sent an etag. Unasked for,\n * it says \"keep what you have\" to a caller that has nothing, and there is\n * no value to return or store.\n */\n private async conditionalGet(\n path: string,\n ifNoneMatch: string | undefined,\n isExpected: BodyCheck,\n ): Promise<{ notModified: boolean, value?: unknown, etag?: string }> {\n const url = `${this.baseUrl}/api/content${path}`\n return withTimeout(url, this.timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(ifNoneMatch ? { 'If-None-Match': ifNoneMatch } : {}),\n ...this.headers,\n },\n signal,\n })\n\n if (res.status === 304) {\n if (!ifNoneMatch) throw unexpectedBody(url)\n this.state.unreachable = false\n return { notModified: true, etag: res.headers.get('etag') ?? ifNoneMatch }\n }\n if (!res.ok) throw await this.toError(res)\n const etag = res.headers.get('etag') ?? undefined\n const value: unknown = res.status === 204 ? undefined : await res.json()\n if (!isExpected(value)) throw unexpectedBody(url)\n this.state.unreachable = false\n return { notModified: false, value, etag }\n })\n }\n\n private async request<T>(method: Method, path: string, body?: unknown, timeout = this.timeout): Promise<T> {\n const url = `${this.baseUrl}/api/content${path}`\n return withTimeout(url, timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...this.headers,\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal,\n })\n\n if (!res.ok) throw await this.toError(res)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n })\n }\n\n /** Parse a non-2xx response into a `HavenError`, preferring its message. */\n private async toError(res: Response): Promise<HavenError> {\n let message = res.statusText || `Request failed with status ${res.status}`\n let parsed: unknown\n try {\n parsed = await res.json()\n const m = parsed as { message?: unknown, statusMessage?: unknown }\n if (typeof m?.message === 'string') message = m.message\n else if (typeof m?.statusMessage === 'string') message = m.statusMessage\n } catch {\n /* non-JSON error body; keep the status text */\n }\n const err = new HavenError(message, res.status, parsed)\n if (res.headers.has('retry-after')) askedToWait.add(err)\n return err\n }\n}\n\n/** Fluent, dataset-scoped view returned by `client.dataset()`. */\nexport class DatasetHandle<T = Record<string, unknown>> {\n constructor(\n private readonly client: HavenClient,\n private readonly nodeSlug: string,\n private readonly datasetSlug: string,\n ) {}\n\n list(opts?: ReadOptions): Promise<ContentRecord<T>[]> {\n return this.client.listRecords<T>(this.nodeSlug, this.datasetSlug, opts)\n }\n\n get(recordUid: string, opts?: ReadOptions): Promise<ContentRecord<T>> {\n return this.client.getRecord<T>(this.nodeSlug, this.datasetSlug, recordUid, opts)\n }\n\n create(data: Record<string, unknown>): Promise<ContentRecord<T>> {\n return this.client.createRecord<T>(this.nodeSlug, this.datasetSlug, data)\n }\n\n update(recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>> {\n return this.client.updateRecord<T>(this.nodeSlug, this.datasetSlug, recordUid, data)\n }\n\n /** Clear cached reads for this dataset. */\n clearCache(): void {\n this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug })\n }\n}\n\n// ── Preview detection ─────────────────────────────────────────────────────────\n\n/** Anything a framework might hand you that could carry the preview marker. */\nexport type PreviewInput\n = | string\n | URL\n | URLSearchParams\n | { url: string }\n | Record<string, string | string[] | undefined>\n | null\n | undefined\n\n/**\n * True when the request was opened from a Nordhavn OS surface preview, i.e. it\n * carries the `sl-preview` query parameter the studio appends to the iframe URL.\n */\nexport function isPreviewRequest(input: PreviewInput): boolean {\n if (!input) return false\n\n if (typeof input === 'string') {\n // Either a full URL or a bare query string (\"?a=1\" / \"a=1\").\n const query = input.includes('?') ? input.slice(input.indexOf('?') + 1) : input\n return new URLSearchParams(query).has(PREVIEW_PARAM)\n }\n if (input instanceof URLSearchParams) return input.has(PREVIEW_PARAM)\n if (input instanceof URL) return input.searchParams.has(PREVIEW_PARAM)\n if (typeof (input as { url?: unknown }).url === 'string') {\n return isPreviewRequest((input as { url: string }).url)\n }\n return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM)\n}\n\n// ── Timeout ───────────────────────────────────────────────────────────────────\n\n/**\n * Runs `run` with an abort signal that fires after `ms`, and rejects with a\n * `TimeoutError` at that moment whether or not `run` listens to the signal: a\n * custom `fetch` may ignore it. The timer spans the whole of `run`, so a studio\n * that sends headers and then stalls the body is caught too.\n *\n * The error is a plain `Error`, not a `HavenError`: the read path treats\n * anything without an HTTP status as transient and serves the cache.\n */\nasync function withTimeout<T>(url: string, ms: number, run: (signal?: AbortSignal) => Promise<T>): Promise<T> {\n if (ms <= 0) return run(undefined)\n\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const expired = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const err = new Error(`The studio did not answer within ${ms}ms: ${url}`)\n err.name = 'TimeoutError'\n controller.abort(err)\n reject(err)\n }, ms)\n })\n\n try {\n return await Promise.race([run(controller.signal), expired])\n }\n finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * The `timeout` option as a usable number of ms, `0` for none. `Infinity`, or\n * more than a timer can hold, means \"no timeout\" - handed to `setTimeout` as\n * it is, it would fire after 1 ms and fail every request.\n */\nfunction normalizeTimeout(value: number | undefined): number {\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT\n return value > MAX_TIMER ? 0 : value\n}\n\n/** `gatewayRetry` in ms, `undefined` when the second try is off. */\nfunction normalizeGatewayRetry(value: number | false | undefined): number | undefined {\n if (value === false) return undefined\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY\n return Math.min(value, MAX_GATEWAY_RETRY)\n}\n\n/** `cache.waitForFresh` in ms, `Infinity` when a read should wait for the studio. */\nfunction normalizeWait(value: number | false | undefined): number {\n if (value === false) return Infinity\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH\n // More than a timer can hold is no budget at all: `within` already waits\n // such a value out, so it is made to mean `false` everywhere, in one place.\n return value > MAX_TIMER ? Infinity : value\n}\n\ntype Settled<T> = { settled: true, value: T } | { settled: false }\n\n/**\n * Waits on `promise` for at most `ms`. Past that it reports \"not settled\" and\n * lets the promise run on; a later rejection is swallowed here, as whoever\n * started the work deals with its outcome. A rejection within `ms` is thrown.\n */\nasync function within<T>(promise: Promise<T>, ms: number): Promise<Settled<T>> {\n if (ms > MAX_TIMER) return { settled: true, value: await promise }\n if (ms <= 0) {\n promise.catch(() => {})\n return { settled: false }\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined\n const late = new Promise<Settled<T>>((resolve) => {\n timer = setTimeout(() => resolve({ settled: false }), ms)\n })\n try {\n return await Promise.race([promise.then((value): Settled<T> => ({ settled: true, value })), late])\n }\n finally {\n clearTimeout(timer)\n }\n}\n\n// ── Response shape ────────────────────────────────────────────────────────────\n\n/** Whether a value is a promise, or anything else that settles later. */\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null | undefined)?.then === 'function'\n}\n\n/** Whether a response body is what its endpoint returns. */\ntype BodyCheck = (body: unknown) => boolean\n\nfunction isObject(value: unknown): boolean {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A body that is an object carrying `field`, with a value that passes `check`. */\nfunction has(field: string, check: (value: unknown) => boolean): BodyCheck {\n return (body) => isObject(body) && field in (body as object) && check((body as Record<string, unknown>)[field])\n}\n\n/**\n * The error for a response its endpoint never gives: a `2xx` with a body of\n * another shape, or a `304` nobody asked for. A plain `Error` without a status,\n * so the read path treats it as transient and serves the cache.\n */\nfunction unexpectedBody(url: string): Error {\n const err = new Error(`The studio answered with an unexpected response: ${url}`)\n err.name = 'UnexpectedResponseError'\n return err\n}\n\n// ── Cache-key + path helpers ──────────────────────────────────────────────────\n\n/**\n * Whether an error status says \"try again later\" rather than \"this is the\n * answer\": server errors, request timeout (408) and rate limiting (429).\n */\nfunction isTransientStatus(status: number): boolean {\n return status >= 500 || status === 408 || status === 429\n}\n\n/**\n * Errors whose response carried `Retry-After`: the studio, or the proxy in\n * front of it, asked to wait, so they are not tried again a moment later.\n * Kept here instead of on the error, which is public API.\n */\nconst askedToWait = new WeakSet<object>()\n\n/**\n * A `502` or `503`: worth one more try a moment later. A `504` already waited,\n * and an answer with `Retry-After` asked not to.\n */\nfunction isGatewayHiccup(err: unknown): boolean {\n return err instanceof HavenError && (err.status === 502 || err.status === 503) && !askedToWait.has(err)\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Whether a failed read is the studio's own definitive answer - this does not\n * exist, this key may not see it - rather than a sign that the studio could\n * not be reached. The only kind of failure that may cost a cached value.\n */\nfunction isDefinitive(err: unknown): err is HavenError {\n return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err)\n}\n\n/**\n * Whether an error response was written by the studio, and not by something\n * answering in its place. While the studio container is gone (a redeploy, a\n * crash) the proxy in front of it answers for it, and often with a `404`:\n * Traefik's `404 page not found`, an HTML error page, a gateway's own JSON.\n * Taking that for \"this record was deleted\" would drop the very entry that\n * should carry the site through the outage.\n *\n * The studio's errors are JSON objects that restate their status\n * (`{ \"statusCode\": 404, \"message\": \"...\" }`); nothing else is trusted to be\n * the studio speaking. `status` is accepted next to `statusCode`, the name\n * newer server frameworks give the same field.\n */\nfunction isStudioAnswer(err: HavenError): boolean {\n const body = err.body as { statusCode?: unknown, status?: unknown } | null | undefined\n if (typeof body !== 'object' || body === null) return false\n return body.statusCode === err.status || body.status === err.status\n}\n\n/**\n * Whether a failed stamp check says \"this studio has no stamp route\": its own\n * `404`, as an older server answers. Not the `404` of a proxy standing in for a\n * studio that is away - that one is an outage like any other.\n */\nfunction isMissingRoute(err: unknown): boolean {\n return err instanceof HavenError && err.status === 404 && isStudioAnswer(err)\n}\n\n/**\n * Whether a failed write may have been stored all the same. Only an answered\n * 4xx rules it out: the request was refused. A timeout, a dropped connection or\n * a 5xx can each follow a write the studio did carry out.\n */\nfunction writeMayHaveLanded(err: unknown): boolean {\n return !(err instanceof HavenError && err.status >= 400 && err.status < 500)\n}\n\nfunction datasetPath(nodeSlug: string, datasetSlug: string): string {\n return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`\n}\n\n/**\n * Maps a requested locale onto one the project is configured with, by the rule\n * the studio applies itself: the exact locale, else one in the same language\n * (`nl` or `nl-NL` for a configured `nl-BE`), else the project's fallback\n * locale. `undefined` means the project default, which is requested by sending\n * no locale at all.\n *\n * With several locales in one language and no exact match, the default locale\n * wins if it is among them, otherwise the first one listed.\n */\nfunction matchLocale(requested: string, locales: ContentLocale[]): string | undefined {\n const canonical = (code: string): string => code.trim().toLowerCase().replace(/_/g, '-')\n const known = locales.filter((locale) => typeof locale?.code === 'string' && locale.code !== '')\n const wanted = canonical(requested)\n\n const exact = known.find((locale) => canonical(locale.code) === wanted)\n if (exact) return exact.code\n\n const language = wanted.split('-')[0]\n const related = known.filter((locale) => canonical(locale.code).split('-')[0] === language)\n const close = related.find((locale) => locale.isDefault) ?? related[0]\n if (close) return close.code\n\n return known.find((locale) => locale.isFallback)?.code\n}\n\n/** `?locale=xx` query suffix, or empty for the default locale. */\nfunction localeQuery(locale?: string): string {\n return locale ? `?locale=${encodeURIComponent(locale)}` : ''\n}\n\n/** Locale cache-key suffix. `::<locale>` keeps each locale a distinct entry;\n * the default locale has no suffix. `::` never collides with a slug. */\nfunction localeKeySuffix(locale?: string): string {\n return locale ? `::${locale}` : ''\n}\n\nfunction recordsKey(nodeSlug: string, datasetSlug: string, locale?: string): string {\n return `records:${nodeSlug}/${datasetSlug}${localeKeySuffix(locale)}`\n}\n\nfunction recordKey(nodeSlug: string, datasetSlug: string, recordUid: string, locale?: string): string {\n return `record:${nodeSlug}/${datasetSlug}/${recordUid}${localeKeySuffix(locale)}`\n}\n","/**\n * The chart contract: what a chart block is (`ChartSpec`, as authored and\n * stored) and what a renderer draws (`ChartData`, the resolved categories and\n * series). Shared by the Nordhavn OS server, the client and every renderer, so a\n * chart means the same thing wherever it is read. Pure data: no dependencies.\n * The zod schemas for these shapes live in `@nordhavnhq/beacon/schema`.\n */\n\n/**\n * The palette a series colour may pick from. A renderer maps a key to a colour\n * of the theme it runs in; a spec never carries a raw hex.\n */\nexport const PALETTE_KEYS = ['ember', 'aurora', 'crimson', 'dusk', 'jade', 'cobalt', 'iris', 'nebula'] as const\nexport type PaletteKey = typeof PALETTE_KEYS[number]\n\nexport const CHART_TYPES = ['bar', 'bar-horizontal', 'line', 'area', 'pie', 'donut', 'share', 'heatmap'] as const\nexport type ChartType = typeof CHART_TYPES[number]\n\n/**\n * How a chart reads its data: `cartesian` plots each series over the\n * categories, `part` cuts one series into its categories (one whole), `matrix`\n * is a grid of the categories (columns) by the series (rows).\n */\nexport type ChartFamily = 'cartesian' | 'part' | 'matrix'\n\n/** What a chart type is and takes: every editor, parser and renderer reads it from here. */\nexport interface ChartTypeInfo {\n value: ChartType\n label: string\n /** One line on what the type is for (editor hint, agent docs). */\n purpose: string\n /** A lucide icon name (kebab-case); the host maps it to its icon set. */\n icon: string\n family: ChartFamily\n /** Exactly one series (the parts are the categories). */\n singleSeries: boolean\n /** Series may sit on a left or right value axis. */\n axes: boolean\n /** Series may stack. */\n stacked: boolean\n /** Each series wears its own colour (else one hue in tints). */\n seriesColors: boolean\n /** Value labels on the marks are possible. */\n valueLabels: boolean\n /** Drawn as HTML that sizes to its content, not into a fixed canvas box. */\n html: boolean\n /** Default box height in px. */\n height: number\n}\n\nexport const CHART_TYPE_INFO: Record<ChartType, ChartTypeInfo> = {\n 'bar': {\n value: 'bar', label: 'Bar', icon: 'chart-column', family: 'cartesian',\n purpose: 'Compare values across categories or periods.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: true, html: false, height: 300,\n },\n 'bar-horizontal': {\n value: 'bar-horizontal', label: 'Bar (horizontal)', icon: 'chart-bar', family: 'cartesian',\n purpose: 'Rank categories with long labels, largest on top when sorted by value.',\n singleSeries: false, axes: false, stacked: true, seriesColors: true, valueLabels: true, html: false, height: 300,\n },\n 'line': {\n value: 'line', label: 'Line', icon: 'chart-line', family: 'cartesian',\n purpose: 'A trend over time.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: false, html: false, height: 300,\n },\n 'area': {\n value: 'area', label: 'Area', icon: 'chart-area', family: 'cartesian',\n purpose: 'A trend over time with its volume.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: false, html: false, height: 300,\n },\n 'pie': {\n value: 'pie', label: 'Pie', icon: 'chart-pie', family: 'part',\n purpose: 'Parts of one whole, few slices.',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: false, height: 260,\n },\n 'donut': {\n value: 'donut', label: 'Donut', icon: 'circle-dashed', family: 'part',\n purpose: 'Parts of one whole around a centred total (status, category breakdown).',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: false, height: 260,\n },\n 'share': {\n value: 'share', label: 'Share bars', icon: 'align-left', family: 'part',\n purpose: 'Parts of one whole as ranked thin bars with figure and percentage; reads well with many parts.',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: true, height: 260,\n },\n 'heatmap': {\n value: 'heatmap', label: 'Heatmap', icon: 'grid-3x3', family: 'matrix',\n purpose: 'A grid of the categories (columns) by the series (rows), one hue from faint to full.',\n singleSeries: false, axes: false, stacked: false, seriesColors: false, valueLabels: true, html: false, height: 300,\n },\n}\n\nexport function chartTypeInfo(type: ChartType): ChartTypeInfo {\n return CHART_TYPE_INFO[type] ?? CHART_TYPE_INFO.bar\n}\n\n/** Pie, donut and share: one series cut into its categories. */\nexport function isPartChart(type: ChartType): boolean {\n return chartTypeInfo(type).family === 'part'\n}\n\n/** Bar in either direction. */\nexport function isBarChart(type: ChartType): boolean {\n return type === 'bar' || type === 'bar-horizontal'\n}\n\n/** Which Y axis a series scales against. Only for the types with `axes`. */\nexport const CHART_AXES = ['left', 'right'] as const\nexport type ChartAxis = typeof CHART_AXES[number]\n\n/** Periods a date category can be grouped into. */\nexport const DATE_BUCKET_VALUES = ['day', 'week', 'month', 'quarter', 'year'] as const\nexport type DateBucket = typeof DATE_BUCKET_VALUES[number]\n\n/** `auto` picks the period from the date range. */\nexport const BUCKET_MODES = ['auto', ...DATE_BUCKET_VALUES] as const\nexport type BucketMode = typeof BUCKET_MODES[number]\n\n/** How the records that fall in one category combine into one point. */\nexport const AGGREGATIONS = ['sum', 'avg', 'count', 'min', 'max', 'first', 'last'] as const\nexport type Aggregation = typeof AGGREGATIONS[number]\n\n/** Category order. `default` is chronological for dates, source order otherwise. */\nexport const CHART_SORTS = ['default', 'category-asc', 'category-desc', 'value-desc', 'value-asc'] as const\nexport type ChartSort = typeof CHART_SORTS[number]\n\nexport interface ChartSeriesSpec {\n /** Field slug whose numeric value is the Y value. */\n field: string\n label?: string\n /** Omitted: the next colour of the renderer's default rotation. */\n color?: PaletteKey\n axis: ChartAxis\n aggregate: Aggregation\n}\n\n/** A chart as authored and stored: where its data comes from and how it is shaped. */\nexport interface ChartSpec {\n title: string\n chartType: ChartType\n /** A dataset (`node.dataset`) or a saved query (`queries.<slug>`). */\n source: string\n /** Field slug for the X axis or the slice labels. */\n categoryField: string\n /**\n * Field slug to split the first series by: one series per distinct value of\n * this field (top 12 by record count, the rest as \"Other\"). The rows of a\n * heatmap, the stacks of a bar. Empty: the series are the value fields.\n */\n splitField: string\n series: ChartSeriesSpec[]\n /** Date categories only. */\n bucket: BucketMode\n sort: ChartSort\n /** Keep the top N categories, the rest becomes \"Other\". 0 is no limit. Non-date only. */\n limit: number\n /** Date buckets only: emit empty periods so a line stays continuous. */\n fillGaps: boolean\n stacked: boolean\n legend: boolean\n}\n\nexport interface ChartSeriesData {\n name: string\n /** One value per category; null is a gap (nothing measured there). */\n data: Array<number | null>\n /** A palette key or any CSS colour the host resolved. */\n color?: string\n axis?: ChartAxis\n}\n\n/** A chart as a renderer draws it: the data already resolved and consolidated. */\nexport interface ChartData {\n type: ChartType\n categories: string[]\n series: ChartSeriesData[]\n stacked?: boolean\n legend?: boolean\n}\n","/**\n * The ```chart fence: a chart written inline in markdown, as JSON in the\n * shape a renderer draws (`ChartData`) plus a title. One parser for every\n * reader: the Nordhavn OS server validates a save with it, the markdown renderer\n * draws what it returns, the PDF export rasterises it, a site can use it too.\n * Pure and dependency-free.\n *\n * A `{{ expr }}` signal may stand where a number goes (`\"data\": [{{ a.b }}, 4]`).\n * The host fills it in before parsing; whatever is still left reads as a gap\n * (null), so a document never fails to save or print on a signal.\n */\nimport { CHART_AXES, CHART_TYPES, PALETTE_KEYS, chartTypeInfo, type ChartData, type ChartSeriesData } from './chart'\n\n/** The fence language. */\nexport const CHART_FENCE_LANG = 'chart'\n\nexport const CHART_FENCE_LIMITS = {\n categories: 100,\n series: 12,\n label: 120,\n title: 200,\n minHeight: 120,\n maxHeight: 600,\n} as const\n\n/** A chart as a ```chart fence carries it. */\nexport interface ChartFence extends ChartData {\n title?: string\n /** Box height in px; the renderer's default when omitted. */\n height?: number\n /** Value labels on the marks (bar types and heatmap). */\n valueLabels?: boolean\n}\n\nexport type ChartFenceResult = { ok: true, chart: ChartFence } | { ok: false, error: string }\n\nconst SIGNAL_RE = /\\{\\{[\\s\\S]*?\\}\\}/g\n\n/** Box height of a fenced chart in px: its own `height`, else a default per type. */\nexport function chartFenceHeight(chart: Pick<ChartFence, 'type' | 'height'>): number {\n if (chart.height) return chart.height\n return chartTypeInfo(chart.type).height\n}\n\n/** True for the language of a ```chart fence (case-insensitive, options after it ignored). */\nexport function isChartFence(lang: string | null | undefined): boolean {\n return (lang ?? '').trim().split(/\\s+/)[0]?.toLowerCase() === CHART_FENCE_LANG\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\nfunction oneOf<T extends string>(list: readonly T[], v: unknown): v is T {\n return typeof v === 'string' && (list as readonly string[]).includes(v)\n}\n\nfunction label(v: unknown, what: string, max: number = CHART_FENCE_LIMITS.label): string {\n if (typeof v === 'number' && Number.isFinite(v)) return String(v)\n if (typeof v !== 'string') throw new Error(`${what} must be a string`)\n if (v.length > max) throw new Error(`${what} is longer than ${max} characters`)\n return v\n}\n\nfunction parseSeries(raw: unknown, i: number, size: number): ChartSeriesData {\n const at = `series[${i}]`\n if (!isRecord(raw)) throw new Error(`${at} must be an object with \"name\" and \"data\"`)\n if (!Array.isArray(raw.data)) throw new Error(`${at}.data must be an array of numbers`)\n if (raw.data.length !== size) throw new Error(`${at}.data has ${raw.data.length} values, \"categories\" has ${size}: one value per category`)\n const data = raw.data.map((v, j) => {\n if (v === null) return null\n if (typeof v === 'number' && Number.isFinite(v)) return v\n throw new Error(`${at}.data[${j}] must be a number or null, got ${JSON.stringify(v)}`)\n })\n const out: ChartSeriesData = { name: raw.name === undefined ? `Series ${i + 1}` : label(raw.name, `${at}.name`), data }\n if (raw.color !== undefined) {\n if (!oneOf(PALETTE_KEYS, raw.color)) throw new Error(`${at}.color must be one of ${PALETTE_KEYS.join(', ')}`)\n out.color = raw.color\n }\n if (raw.axis !== undefined) {\n if (!oneOf(CHART_AXES, raw.axis)) throw new Error(`${at}.axis must be ${CHART_AXES.join(' or ')}`)\n out.axis = raw.axis\n }\n return out\n}\n\nfunction parseShape(raw: unknown): ChartFence {\n if (!isRecord(raw)) throw new Error('The fence must hold one JSON object')\n if (!oneOf(CHART_TYPES, raw.type)) throw new Error(`\"type\" must be one of ${CHART_TYPES.join(', ')}`)\n if (!Array.isArray(raw.categories) || raw.categories.length === 0) throw new Error('\"categories\" must be a non-empty array of labels')\n if (raw.categories.length > CHART_FENCE_LIMITS.categories) throw new Error(`\"categories\" has ${raw.categories.length} entries, at most ${CHART_FENCE_LIMITS.categories}`)\n const categories = raw.categories.map((c, i) => label(c, `categories[${i}]`))\n if (!Array.isArray(raw.series) || raw.series.length === 0) throw new Error('\"series\" must be a non-empty array')\n if (raw.series.length > CHART_FENCE_LIMITS.series) throw new Error(`\"series\" has ${raw.series.length} entries, at most ${CHART_FENCE_LIMITS.series}`)\n if (chartTypeInfo(raw.type).singleSeries && raw.series.length !== 1) throw new Error(`A ${raw.type} takes exactly one series (the parts are the categories)`)\n const series = raw.series.map((s, i) => parseSeries(s, i, categories.length))\n\n const chart: ChartFence = { type: raw.type, categories, series }\n if (raw.title !== undefined) chart.title = label(raw.title, '\"title\"', CHART_FENCE_LIMITS.title)\n for (const key of ['stacked', 'legend', 'valueLabels'] as const) {\n if (raw[key] === undefined) continue\n if (typeof raw[key] !== 'boolean') throw new Error(`\"${key}\" must be true or false`)\n chart[key] = raw[key]\n }\n if (raw.height !== undefined) {\n const h = raw.height\n if (typeof h !== 'number' || h < CHART_FENCE_LIMITS.minHeight || h > CHART_FENCE_LIMITS.maxHeight) {\n throw new Error(`\"height\" must be a number from ${CHART_FENCE_LIMITS.minHeight} to ${CHART_FENCE_LIMITS.maxHeight}`)\n }\n chart.height = Math.round(h)\n }\n return chart\n}\n\n/** The chart in a ```chart fence body, or what is wrong with it (one line an author can act on). */\nexport function parseChartFence(source: string): ChartFenceResult {\n const text = source.replace(SIGNAL_RE, 'null').trim()\n if (!text) return { ok: false, error: 'Empty chart fence' }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n }\n catch (err) {\n return { ok: false, error: `Not valid JSON: ${err instanceof Error ? err.message : String(err)}` }\n }\n try {\n return { ok: true, chart: parseShape(raw) }\n }\n catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n }\n}\n","export { HavenClient, DatasetHandle, DEFAULT_BASE_URL, PREVIEW_PARAM, isPreviewRequest } from './client'\nexport type { HavenClientOptions, ReadOptions, PreviewInput, StudioFailure } from './client'\nexport { HavenError } from './errors'\nexport { ContentCache, MemoryCacheStore } from './cache'\nexport type { CacheOptions, CacheStore, CacheEntry } from './cache'\nexport type {\n ContentSchema,\n SchemaNode,\n SchemaDataset,\n SchemaField,\n FieldKind,\n FieldType,\n ContentRecord,\n ContentLocale,\n QueryResult,\n QueryShape,\n} from './types'\nexport {\n PALETTE_KEYS,\n CHART_TYPES,\n CHART_TYPE_INFO,\n chartTypeInfo,\n isPartChart,\n isBarChart,\n CHART_AXES,\n DATE_BUCKET_VALUES,\n BUCKET_MODES,\n AGGREGATIONS,\n CHART_SORTS,\n} from './chart'\nexport type {\n PaletteKey,\n ChartType,\n ChartFamily,\n ChartTypeInfo,\n ChartAxis,\n DateBucket,\n BucketMode,\n Aggregation,\n ChartSort,\n ChartSeriesSpec,\n ChartSpec,\n ChartSeriesData,\n ChartData,\n} from './chart'\nexport { CHART_FENCE_LANG, CHART_FENCE_LIMITS, chartFenceHeight, isChartFence, parseChartFence } from './chart-fence'\nexport type { ChartFence, ChartFenceResult } from './chart-fence'\nexport type {\n RoadmapPhaseState,\n RoadmapWorkState,\n RoadmapTone,\n RoadmapTip,\n RoadmapPhase,\n RoadmapLane,\n RoadmapMilestone,\n RoadmapWaiting,\n RoadmapTask,\n RoadmapRepeat,\n RoadmapHappening,\n RoadmapEvent,\n RoadmapData,\n ForecastSeries,\n} from './roadmap'\n\nimport { HavenClient, type HavenClientOptions } from './client'\n\n/** Convenience factory: `createClient({ apiKey, baseUrl })`. */\nexport function createClient(options: HavenClientOptions): HavenClient {\n return new HavenClient(options)\n}\n\n// Names of the package's former life as `@justmade/client`, so a site that\n// switches only changes its import. Removed in the next breaking release.\n/** @deprecated Use `HavenClient`. */\nexport { HavenClient as JustmadeClient } from './client'\n/** @deprecated Use `HavenClientOptions`. */\nexport type { HavenClientOptions as JustmadeClientOptions } from './client'\n/** @deprecated Use `HavenError`. */\nexport { HavenError as JustmadeError } from './errors'\n"]}
1
+ {"version":3,"sources":["../src/cache.ts","../src/errors.ts","../src/live-policy.ts","../src/live-sse.ts","../src/version.ts","../src/live.ts","../src/client.ts","../src/chart.ts","../src/chart-fence.ts","../src/index.ts"],"names":["version"],"mappings":";;;AAiGA,IAAM,OAAA,GAAU,CAAA;AA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AkC;AAChE,EAAA,MAAM,OAAO,MAAA,CAAO,OAAA,CAAQ,SAAA,EAAW,MAAM,EAAE,IAAA,EAAK;AACpD,EAAA,IAAI,CAAC,IAAA,EAAM,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,mBAAA,EAAoB;AAC1D,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACvB,SACO,GAAA,EAAK;AACV,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,gBAAA,EAAmB,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA,CAAA,EAAG;AAAA,EACnG;AACA,EAAA,IAAI;AACF,IAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,KAAA,EAAO,UAAA,CAAW,GAAG,CAAA,EAAE;AAAA,EAC5C,SACO,GAAA,EAAK;AACV,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAA,EAAE;AAAA,EAC9E;AACF;;;AC/DO,SAAS,aAAa,OAAA,EAA0C;AACrE,EAAA,OAAO,IAAI,YAAY,OAAO,CAAA;AAChC","file":"index.cjs","sourcesContent":["/**\n * Read caching for the content client. GET responses (schema, record lists,\n * single records, queries) are cached by request key and kept fresh by\n * conditional revalidation: each entry stores the studio's `ETag`, which the\n * client sends back as `If-None-Match`. A cheap project-wide stamp gates whether\n * a revalidation is even attempted, so a stable site serves straight from cache.\n *\n * Swap in a custom `CacheStore` to share a cache across client instances or to\n * back it with something persistent.\n */\n\nexport interface CacheEntry {\n value: unknown\n /**\n * The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`\n * to revalidate: a `304` means the stored value is still current.\n */\n etag?: string\n /**\n * The project stamp this entry was last confirmed current against. When it\n * equals the client's latest known stamp, the entry is served without any\n * network call at all.\n */\n validatedVersion?: string\n /** Epoch ms when the entry expires. `0` means it never expires. */\n expiresAt: number\n /**\n * Epoch ms before which a failed refetch is not retried: until then the entry\n * is served as-is. Set after a transient error, cleared by a fresh value or a\n * `304`.\n */\n retryAt?: number\n}\n\n/** Pluggable backing store. The default is an in-memory, insertion-ordered map. */\nexport interface CacheStore {\n get(key: string): CacheEntry | undefined\n set(key: string, entry: CacheEntry): void\n delete(key: string): void\n /** Iterate current keys (used for prefix invalidation). */\n keys(): Iterable<string>\n clear(): void\n}\n\nexport interface CacheOptions {\n /** Master switch. Default `true`. */\n enabled?: boolean\n /**\n * How long a cached entry survives, in ms. Default `604800000` (7 days).\n *\n * This is NOT how long until content refreshes - revalidation keeps entries\n * current within `revalidate` (seconds) whenever the studio is reachable. The\n * TTL only decides when an entry stops being served blindly and the next read\n * must refetch it. If that refetch fails transiently (studio down, 5xx,\n * network), the expired value is served anyway, so a studio outage degrades\n * to \"slightly stale\" rather than \"site errors\" however long it lasts.\n *\n * The one case where it bounds staleness directly is when revalidation is off\n * (`revalidate: false`) or the server has no `/version` endpoint: then content\n * can be up to `ttl` old while the studio is reachable. `0` = never expire.\n */\n ttl?: number\n /**\n * Minimum ms between two project-stamp checks. Default `60000` (1 minute) -\n * this is the freshness window for PUBLIC visitors (an edit is picked up on\n * the next check after it lands). A read with `{ cache: false }` skips the\n * wait.\n *\n * The check fires only on a read and is throttled, so a quiet site barely\n * checks at all; the interval only caps the busy case. Each check costs the\n * studio a small API-key lookup, so raise it (a few minutes) if you run many\n * frontends; lower it for a tighter public window. `false` disables checking\n * and leaves you with pure TTL expiry.\n */\n revalidate?: number | false\n /**\n * How long a read that already holds a cached value waits on the studio for a\n * fresher one, in ms. Default `1000`. Past it the read gets the cached value\n * and the refresh finishes in the background, so the next read has it.\n *\n * It keeps a slow or hanging studio from slowing your pages down: without it\n * every read after an edit waits for as long as the studio takes, up to\n * `timeout`. The price is that on a slow studio an edit shows one read later.\n *\n * `0` never waits (always serve the cached value, refresh in the background).\n * `false` waits for the studio; choose it where work cannot outlive the\n * request, as on serverless platforms that freeze the process once the\n * response is out. A read with nothing cached always waits.\n */\n waitForFresh?: number | false\n /** Soft cap on entries; oldest are evicted first. Default `500`. */\n maxEntries?: number\n /** Custom backing store. Defaults to an in-memory store. */\n store?: CacheStore\n}\n\n/** An `expiresAt` that is always in the past (`0` would mean \"never expires\"). */\nconst EXPIRED = 1\n\n/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */\nexport class MemoryCacheStore implements CacheStore {\n private map = new Map<string, CacheEntry>()\n\n constructor(private maxEntries = 500) {}\n\n get(key: string): CacheEntry | undefined {\n return this.map.get(key)\n }\n\n set(key: string, entry: CacheEntry): void {\n // Re-insert so recently written keys are considered newest.\n this.map.delete(key)\n this.map.set(key, entry)\n while (this.map.size > this.maxEntries) {\n const oldest = this.map.keys().next().value\n if (oldest === undefined) break\n this.map.delete(oldest)\n }\n }\n\n delete(key: string): void {\n this.map.delete(key)\n }\n\n keys(): Iterable<string> {\n return this.map.keys()\n }\n\n clear(): void {\n this.map.clear()\n }\n}\n\n/**\n * Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation\n * bookkeeping (etag + validated stamp), and prefix invalidation, so the client\n * only deals in cache keys.\n */\nexport class ContentCache {\n readonly enabled: boolean\n private ttl: number\n /** Pause after a failed refetch: the `revalidate` interval, or 1 minute without one. */\n private retryDelay: number\n private store: CacheStore\n\n constructor(opts: CacheOptions = {}) {\n this.enabled = opts.enabled ?? true\n this.ttl = opts.ttl ?? 604_800_000\n this.retryDelay = typeof opts.revalidate === 'number' && opts.revalidate > 0 ? opts.revalidate : 60_000\n this.store = opts.store ?? new MemoryCacheStore(opts.maxEntries ?? 500)\n }\n\n /**\n * The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the\n * whole entry (value + etag + validated stamp) so the client can decide\n * whether to serve it, revalidate it, or fall back to it on error.\n *\n * An expired entry is left in the store (the refetch overwrites it, or\n * `maxEntries` evicts it) so `stale` can still fall back to it.\n */\n peek(key: string, now: number): CacheEntry | undefined {\n const entry = this.stale(key)\n if (!entry) return undefined\n if (entry.expiresAt !== 0 && entry.expiresAt <= now) return undefined\n return entry\n }\n\n /**\n * The entry for `key` whether or not its TTL has run out: the last good value\n * to serve when a refetch fails transiently.\n */\n stale(key: string): CacheEntry | undefined {\n if (!this.enabled) return undefined\n return this.store.get(key)\n }\n\n /** Store a freshly fetched value with its validator and the stamp it is current against. */\n set(key: string, value: unknown, opts: { etag?: string, version?: string }, now: number): void {\n if (!this.enabled) return\n this.store.set(key, {\n value,\n etag: opts.etag,\n validatedVersion: opts.version,\n expiresAt: this.ttl === 0 ? 0 : now + this.ttl,\n })\n }\n\n /**\n * Record that an existing entry is still current as of `version` (after a\n * `304`), refreshing its TTL without touching the value. No-op if it is gone.\n */\n confirm(key: string, version: string | undefined, now: number): void {\n const entry = this.store.get(key)\n if (!entry) return\n entry.validatedVersion = version\n entry.expiresAt = this.ttl === 0 ? 0 : now + this.ttl\n delete entry.retryAt\n this.store.set(key, entry)\n }\n\n /**\n * Record that refetching `key` from `from` just failed transiently, so reads\n * serve it as-is for a while instead of each waiting on an unreachable studio.\n * Returns the entry to serve: `from`, or the newer one a concurrent read stored\n * in the meantime (left unpaused, since its own fetch succeeded).\n */\n backoff(key: string, from: CacheEntry, now: number): CacheEntry {\n const entry = this.store.get(key)\n if (!entry) return from\n // Compare fields, not identity: a custom store may hand back copies.\n if (entry.etag !== from.etag || entry.expiresAt !== from.expiresAt) return entry\n entry.retryAt = now + this.retryDelay\n this.store.set(key, entry)\n return entry\n }\n\n /**\n * Mark `key` as due for a refetch while keeping its value to fall back on:\n * the next read asks the studio again whatever the stamp says, and still\n * serves this value if the studio does not answer. For when the stored value\n * may be outdated but there is no telling - dropping it would throw away the\n * only thing left to show during an outage. No-op for a key that is not held.\n */\n expire(key: string): void {\n const entry = this.store.get(key)\n if (!entry) return\n entry.expiresAt = EXPIRED\n delete entry.retryAt\n this.store.set(key, entry)\n }\n\n /** `expire` for every key that starts with `prefix`. */\n expirePrefix(prefix: string): void {\n for (const key of [...this.store.keys()]) {\n if (key.startsWith(prefix)) this.expire(key)\n }\n }\n\n /** Drop one exact key. */\n delete(key: string): void {\n this.store.delete(key)\n }\n\n /** Drop every key that starts with `prefix`. */\n deletePrefix(prefix: string): void {\n for (const key of [...this.store.keys()]) {\n if (key.startsWith(prefix)) this.store.delete(key)\n }\n }\n\n clear(): void {\n this.store.clear()\n }\n}\n","/**\n * Error thrown for any non-2xx response from the content API. `status` carries\n * the HTTP status code so callers can branch (401 bad key, 403 out of scope,\n * 404 missing node/dataset/record, 422 query failed). `code` says more where\n * the studio sends one: why an upload was refused, for example\n * (`upload_too_large`).\n */\nexport class HavenError extends Error {\n readonly status: number\n /** The raw parsed response body, when the server returned one. */\n readonly body: unknown\n /**\n * The studio's code for this error (`data.code` in the body), when it sent\n * one, else `undefined`. Unlike the message it never changes wording, so it\n * is what a site branches on: the upload codes are `upload_type_not_allowed`,\n * `upload_content_invalid`, `upload_too_large` and the ones about the field.\n */\n readonly code: string | undefined\n\n constructor(message: string, status: number, body?: unknown) {\n super(message)\n this.name = 'HavenError'\n this.status = status\n this.body = body\n this.code = errorCode(body)\n // Restore prototype chain for `instanceof` when transpiled to ES5.\n Object.setPrototypeOf(this, HavenError.prototype)\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401\n }\n\n get isForbidden(): boolean {\n return this.status === 403\n }\n\n get isNotFound(): boolean {\n return this.status === 404\n }\n}\n\n/** `data.code` of an error body, when it is a non-empty string. */\nfunction errorCode(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined\n const data = (body as { data?: unknown }).data\n if (typeof data !== 'object' || data === null) return undefined\n const code = (data as { code?: unknown }).code\n return typeof code === 'string' && code !== '' ? code : undefined\n}\n\n/**\n * Whether an error body was written by the studio, and not by something\n * answering in its place (a proxy's `404 page not found`, a WAF's HTML page, a\n * gateway's own JSON). The studio's errors are JSON objects that restate their\n * status (`{ \"statusCode\": 404, \"message\": \"...\" }`); `status` is accepted next\n * to `statusCode`, the name newer server frameworks give the same field.\n */\nexport function isStudioBody(status: number, body: unknown): boolean {\n if (typeof body !== 'object' || body === null) return false\n const b = body as { statusCode?: unknown, status?: unknown }\n return b.statusCode === status || b.status === status\n}\n","/**\n * The decisions of the live connection, as plain functions: whether a client\n * goes live by default, and what to do after a connection attempt ended (how\n * long to wait before the next one, or to stop). `live.ts` does the I/O.\n *\n * No imports and only erasable TypeScript, so its test can load the source as\n * it is and walk every branch without a server or a clock.\n */\n\n/** Every number the live connection runs on. */\nexport const LIVE = {\n /**\n * No message (a version or a ping) for this long and the connection counts\n * as dead. The studio pings every 25 s, so this is two missed pings and then\n * some: a frozen process, a proxy that holds the stream without passing it on.\n */\n staleMs: 60_000,\n /**\n * A connection that stayed up this long, and heard from the studio, resets\n * the backoff. One that is accepted and then closed sooner counts as a\n * failure, so accept-then-close cannot loop.\n */\n stableMs: 60_000,\n /**\n * Even while the connection is healthy, it is checked against the stamp\n * itself this often (once per connection, in the background, never awaited\n * by a read): a safety net for a change the stream missed. It should never\n * miss one, but one missed would otherwise stay unseen until the stream ends.\n */\n safetyPollMs: 5 * 60_000,\n /**\n * How long the stream may stay behind a check that found the studio ahead\n * before it counts as having missed a change and is replaced. The studio\n * sends a change up to 5.25 s late on purpose (at most once per 5 s per\n * project), so a stream that is merely behind catches up well within this.\n */\n lagToleranceMs: 10_000,\n /** The longest that check may take; it runs on an unref'd socket, so it never holds a process. */\n safetyProbeTimeoutMs: 3_000,\n /** The longest the studio may take to answer the connection with its headers. */\n connectTimeoutMs: 10_000,\n /** After the studio ended a connection that lived its full term: wait 1 to 5 s. */\n cleanMinMs: 1_000,\n cleanMaxMs: 5_000,\n /** After a failure: at least 1 s, then a window that doubles per failure, up to 30 s. */\n backoffBaseMs: 1_000,\n backoffMaxMs: 30_000,\n /** `Retry-After` is honoured within these bounds. */\n retryAfterMinMs: 30_000,\n retryAfterMaxMs: 60 * 60_000,\n /** A `429` without `Retry-After` waits as long as the studio itself asks for. */\n rateLimitedMs: 5 * 60_000,\n /** The most added at random to a long wait, so the sites refused together do not return together. */\n longJitterMs: 60_000,\n} as const\n\n/** How a connection attempt ended. */\nexport type LiveOutcome =\n /** The studio ended the stream properly (its lifetime is up, or the key changed). */\n | { kind: 'closed' }\n /** A network error, a timeout, a dropped connection, a stream that is not the studio's. */\n | { kind: 'failed' }\n /** Nothing heard for `LIVE.staleMs`. */\n | { kind: 'silent' }\n /** Answered with something other than the stream. */\n | {\n kind: 'refused'\n status: number\n /** Whether the body is the studio's own JSON error (see `isStudioBody`). */\n studio: boolean\n /** The `Retry-After` header as sent, `null` without one. */\n retryAfter: string | null\n }\n\nexport type LivePlan =\n | { stop: true }\n | { stop: false, delay: number, attempts: number }\n\nexport interface LivePlanContext {\n /** Failures in a row so far. */\n attempts: number\n /** Whether the connection that just ended was stable (see `LIVE.stableMs`). */\n stable: boolean\n /** How long a server without the stream is left alone (`UNSUPPORTED_PAUSE_MS`). */\n pauseMs: number\n now: number\n random: () => number\n}\n\n/**\n * What to do after a connection attempt: when to try again, or to stop for good.\n *\n * - closed by the studio after a stable connection: a few seconds;\n * - a network error, a `5xx`, anything that is not the studio speaking (a\n * proxy's `404` page, a `200` that is no stream), an early close, silence:\n * exponential backoff with jitter, 1 s to 30 s;\n * - `429`, or a `503` with `Retry-After`: as asked, within 30 s and 1 hour,\n * plus jitter;\n * - the studio's own `401` or `403`: stop (reads report the key themselves);\n * - the studio's own `404` (a server without the stream), another of its\n * `4xx`, or a redirect: the long pause, as for a server without `/version`.\n */\nexport function planReconnect(outcome: LiveOutcome, ctx: LivePlanContext): LivePlan {\n const attempts = ctx.stable ? 0 : ctx.attempts\n if (outcome.kind === 'closed' && ctx.stable) {\n return { stop: false, delay: between(LIVE.cleanMinMs, LIVE.cleanMaxMs, ctx.random), attempts: 0 }\n }\n if (outcome.kind === 'refused') return planRefused(outcome, { ...ctx, attempts })\n return backoff(attempts, ctx.random)\n}\n\n/** `planReconnect` for an answer other than the stream. */\nfunction planRefused(outcome: Extract<LiveOutcome, { kind: 'refused' }>, ctx: LivePlanContext): LivePlan {\n const { status, studio } = outcome\n if (studio && (status === 401 || status === 403)) return { stop: true }\n const asked = parseRetryAfter(outcome.retryAfter, ctx.now)\n if (status === 429 || (status === 503 && asked !== undefined)) {\n const wait = clamp(asked ?? LIVE.rateLimitedMs, LIVE.retryAfterMinMs, LIVE.retryAfterMaxMs)\n return { stop: false, delay: wait + longJitter(wait, ctx.random), attempts: ctx.attempts }\n }\n const studioRefusal = studio && status >= 400 && status < 500 && status !== 408\n if (studioRefusal || (status >= 300 && status < 400)) {\n return { stop: false, delay: ctx.pauseMs + longJitter(ctx.pauseMs, ctx.random), attempts: ctx.attempts }\n }\n return backoff(ctx.attempts, ctx.random)\n}\n\n/** At least `backoffBaseMs`, plus full jitter over a window that doubles per failure, capped. */\nfunction backoff(attempts: number, random: () => number): LivePlan {\n const window = LIVE.backoffBaseMs * 2 ** Math.min(attempts, 16)\n const delay = Math.min(LIVE.backoffMaxMs, LIVE.backoffBaseMs + random() * window)\n return { stop: false, delay, attempts: attempts + 1 }\n}\n\nfunction longJitter(wait: number, random: () => number): number {\n return random() * Math.min(LIVE.longJitterMs, wait / 5)\n}\n\nfunction between(min: number, max: number, random: () => number): number {\n return min + random() * (max - min)\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value))\n}\n\n/**\n * `Retry-After` in ms from `now`: a number of seconds or an HTTP date.\n * `undefined` without one, or when it cannot be read.\n */\nexport function parseRetryAfter(value: string | null | undefined, now: number): number | undefined {\n const text = value?.trim()\n if (!text) return undefined\n if (/^-?\\d+$/.test(text)) return text.startsWith('-') ? undefined : Number(text) * 1000\n const at = Date.parse(text)\n return Number.isNaN(at) ? undefined : Math.max(0, at - now)\n}\n\n/**\n * Environment variables that say this process is short-lived or frozen between\n * requests, so a connection held open would mostly cost the studio a slot:\n *\n * - `VERCEL`, `NETLIFY`, `AWS_LAMBDA_FUNCTION_NAME` and `LAMBDA_TASK_ROOT`\n * (Lambda, also under Netlify's functions), `FUNCTIONS_WORKER_RUNTIME`\n * (Azure Functions), `FUNCTION_TARGET` (Google Cloud Functions),\n * `DENO_DEPLOYMENT_ID` (Deno Deploy);\n * - `K_SERVICE`: Google Cloud Run (and Cloud Functions on it). Its processes\n * run between requests only with \"CPU always allocated\", which is not the\n * default, and it scales out to many instances that would each hold one of\n * the key's 50 connections. A service set up to stay warm turns `live` on;\n * - `CI`: a build or a test job. It ends in minutes, and a framework building\n * in many workers would hold a connection per worker, from the same 50 the\n * site's own processes need.\n *\n * A variable counts when it is set to anything but empty, `0` or `false`.\n */\nexport const SHORT_LIVED_ENV = [\n 'VERCEL',\n 'NETLIFY',\n 'AWS_LAMBDA_FUNCTION_NAME',\n 'LAMBDA_TASK_ROOT',\n 'FUNCTIONS_WORKER_RUNTIME',\n 'FUNCTION_TARGET',\n 'DENO_DEPLOYMENT_ID',\n 'K_SERVICE',\n 'CI',\n] as const\n\n/** Whether one of `SHORT_LIVED_ENV` is set in `env`. */\nexport function isShortLived(env: Record<string, string | undefined>): boolean {\n return SHORT_LIVED_ENV.some((name) => {\n const value = env[name]?.trim().toLowerCase()\n return value !== undefined && value !== '' && value !== '0' && value !== 'false'\n })\n}\n\nexport interface LiveChoice {\n /** The `live` option as given. */\n option: boolean | undefined\n /** Whether this runtime can hold the connection: Node's `http`, not a browser. */\n runtime: boolean\n /** Whether the client checks the stamp at all (a cache, `revalidate` not off). */\n revalidating: boolean\n /** Whether a custom `fetch` was passed. */\n customFetch: boolean\n /** `cache.waitForFresh: false`: the host asked that nothing outlives a read. */\n waitsForStudio: boolean\n env: Record<string, string | undefined>\n}\n\n/**\n * Whether a client goes live. Never where it cannot (no Node `http`, a browser)\n * or where it would serve no purpose (no cache, `revalidate: false`). Else\n * `live: true` and `live: false` decide. By default it is on, except where the\n * process does not live on between requests (`SHORT_LIVED_ENV`, or\n * `waitForFresh: false`, which says as much), and with a custom `fetch`: the\n * stream goes over Node's `http` and not through that `fetch`, so it would skip\n * whatever the `fetch` adds (a proxy, a header, a test's fake studio).\n */\nexport function chooseLive(choice: LiveChoice): boolean {\n if (!choice.runtime || !choice.revalidating || choice.option === false) return false\n if (choice.option === true) return true\n return !choice.customFetch && !choice.waitsForStudio && !isShortLived(choice.env)\n}\n","/**\n * A small parser for server-sent events, enough for the live connection\n * (`GET /api/content/events`). Fed text as it arrives, in chunks that may end\n * anywhere (mid-line, between a `\\r` and its `\\n`), it hands back the complete\n * events. It follows the WHATWG rules that matter here: lines end in `\\n`,\n * `\\r\\n` or `\\r`; a line starting with `:` is a comment; `data` lines add up,\n * joined with `\\n`; a blank line ends the event; `id`, `retry` and unknown\n * fields are ignored. An event without `data` lines is dropped, as a browser\n * does.\n *\n * No imports and only erasable TypeScript, so its test can load the source as\n * it is.\n */\n\nexport interface SseEvent {\n /** The `event` field, `message` when the event named none. */\n event: string\n data: string\n}\n\n/** The most text the parser holds while waiting for the end of a line or an event. */\nconst DEFAULT_LIMIT = 64 * 1024\n\nexport class SseParser {\n private buffer = ''\n private data: string[] = []\n private dataSize = 0\n private event = ''\n private started = false\n /** The last chunk ended in `\\r`: a `\\n` that starts the next one belongs to it. */\n private afterCr = false\n private readonly limit: number\n\n constructor(limit: number = DEFAULT_LIMIT) {\n this.limit = limit\n }\n\n /**\n * The events completed by `chunk`, in order. `null` once more than the limit\n * is waiting for a line or an event to end: a stream like that is not the\n * studio's, and the caller drops the connection rather than the memory.\n */\n feed(chunk: string): SseEvent[] | null {\n const text = this.prepare(this.buffer + chunk)\n const out: SseEvent[] = []\n let pos = 0\n const breaks = { cr: text.indexOf('\\r'), lf: text.indexOf('\\n') }\n while (pos < text.length) {\n const end = nextBreak(text, pos, breaks)\n if (end === -1) break\n let next = end + 1\n if (text.charCodeAt(end) === 13) {\n // A `\\r` that ends the text may be the first half of a `\\r\\n` split\n // over two chunks: the line ends here, and a `\\n` up next is skipped.\n if (end + 1 === text.length) this.afterCr = true\n else if (text.charCodeAt(end + 1) === 10) next = end + 2\n }\n this.line(text.slice(pos, end), out)\n pos = next\n }\n this.buffer = text.slice(pos)\n if (this.buffer.length > this.limit || this.dataSize > this.limit) return null\n return out\n }\n\n /** Drops the `\\n` of a `\\r\\n` split over two chunks, and a byte order mark at the start. */\n private prepare(text: string): string {\n let out = text\n if (this.afterCr && out.length > 0) {\n this.afterCr = false\n if (out.charCodeAt(0) === 10) out = out.slice(1)\n }\n if (!this.started && out.length > 0) {\n this.started = true\n if (out.charCodeAt(0) === 0xFEFF) out = out.slice(1)\n }\n return out\n }\n\n private line(line: string, out: SseEvent[]): void {\n if (line === '') {\n if (this.data.length > 0) out.push({ event: this.event || 'message', data: this.data.join('\\n') })\n this.data = []\n this.dataSize = 0\n this.event = ''\n return\n }\n if (line.charCodeAt(0) === 58) return\n const colon = line.indexOf(':')\n const field = colon === -1 ? line : line.slice(0, colon)\n let value = colon === -1 ? '' : line.slice(colon + 1)\n if (value.charCodeAt(0) === 32) value = value.slice(1)\n if (field === 'event') this.event = value\n else if (field === 'data') {\n this.data.push(value)\n this.dataSize += value.length + 1\n }\n }\n}\n\n/**\n * Where the next line ends from `pos` on: the first `\\r` or `\\n`, `-1` when\n * there is none yet. `breaks` remembers the last ones found, so a long text is\n * searched once and not once per line.\n */\nfunction nextBreak(text: string, pos: number, breaks: { cr: number, lf: number }): number {\n if (breaks.cr !== -1 && breaks.cr < pos) breaks.cr = text.indexOf('\\r', pos)\n if (breaks.lf !== -1 && breaks.lf < pos) breaks.lf = text.indexOf('\\n', pos)\n const { cr, lf } = breaks\n return cr === -1 ? lf : lf === -1 ? cr : Math.min(cr, lf)\n}\n","/**\n * Project-stamp tracker: the cheap gate in front of conditional revalidation.\n *\n * The cache lives in YOUR process, so the studio cannot push an invalidation\n * into it. Instead it publishes a stamp per project at `GET /api/content/version`\n * that changes on every content edit. This tracker fetches that stamp at most\n * once per interval (one tiny request regardless of read volume) and exposes the\n * latest value it has seen.\n *\n * The client uses it as a gate: while the stamp is unchanged, cached entries are\n * served with no network at all; when it moves, entries revalidate individually\n * with `If-None-Match` (a `304` keeps the cached value, a `200` replaces it). If\n * the stamp check itself fails - studio down, network blip - the last known\n * stamp stands, so the cache keeps serving instead of hammering a dead endpoint.\n *\n * Where the client holds a live connection (`live.ts`), the stamps it hears are\n * fed in with `observe` and the probe is skipped while that connection is\n * healthy; the probe is the fallback for when it is not.\n */\n\nexport type VersionProbe = () => Promise<string>\n\n/** How long a server without the version route silences the check. */\nexport const UNSUPPORTED_PAUSE_MS = 15 * 60_000\n\nexport class VersionTracker {\n private lastChecked = 0\n private version: string | null = null\n private inFlight: Promise<void> | null = null\n /**\n * Epoch ms before which we do not ask again, after the server turned out\n * to have no version route. A pause and not a final verdict: an old server\n * costs one request per pause, and one that gains the route is picked up\n * without a restart.\n */\n private pausedUntil = 0\n\n constructor(\n private readonly probe: VersionProbe,\n /** Minimum ms between two probes. `0` disables checking entirely. */\n private readonly interval: number,\n /**\n * Whether a probe failure means \"this server has no version route\", as\n * opposed to \"could not be reached\". The caller decides, as only it can\n * tell the server's own `404` from the one a proxy answers with while\n * the server is away - and that one must not pause anything: the server\n * is back in seconds, and freshness would stay off for the whole pause.\n */\n private readonly isUnsupported: (err: unknown) => boolean = (err) => (err as { status?: number } | null)?.status === 404,\n ) {}\n\n /** The most recent stamp seen, or `null` before the first successful probe. */\n current(): string | null {\n return this.version\n }\n\n /**\n * A stamp heard from the live connection, current as of `at`. It counts as a\n * check made at that moment: the next probe is due one interval after it.\n * Never a request of its own, and never a reason for one.\n */\n observe(version: string, at: number): void {\n this.version = version\n this.lastChecked = Math.max(this.lastChecked, at)\n }\n\n /**\n * Makes the next `refresh` ask at once, whatever the interval says (still\n * not during the pause for a server without the route). For when the stamp\n * may have moved unseen: the live connection went silent.\n */\n due(): void {\n this.lastChecked = 0\n }\n\n /**\n * Refresh the stamp if we are due. Resolves once the answer is in, so the\n * read that triggered it sees an up-to-date stamp. A failed probe leaves the\n * last known stamp in place (serve-from-cache rather than thrash).\n *\n * A failed probe counts towards the interval like any other, also when no\n * stamp has ever come in. Otherwise a process that starts while the studio\n * is down (with a persisted cache to serve from) would probe on every read,\n * and against a hanging studio make each of them wait out the probe.\n */\n async refresh(now: number): Promise<void> {\n if (this.interval <= 0 || now < this.pausedUntil) return\n if (this.inFlight) return this.inFlight\n if (now - this.lastChecked < this.interval) return\n\n this.lastChecked = now\n this.inFlight = this.run(now)\n try {\n await this.inFlight\n }\n finally {\n this.inFlight = null\n }\n }\n\n private async run(now: number): Promise<void> {\n try {\n this.version = await this.probe()\n }\n catch (err) {\n // A server that predates the version route: ask again only after a\n // long pause. Any other failure is transient - keep the last stamp\n // so the cache keeps serving, and try again next interval.\n if (this.isUnsupported(err)) {\n this.pausedUntil = now + Math.max(this.interval, UNSUPPORTED_PAUSE_MS)\n }\n }\n }\n}\n","/**\n * The live connection: `GET /api/content/events`, a stream on which the studio\n * pushes the project's stamp the moment it changes, so a site sees an edit at\n * its next visitor instead of up to a minute later.\n *\n * An optimisation on top of the `/version` poll, never a replacement, and\n * built so that it cannot take a site down:\n *\n * - A stamp it hears only feeds the `VersionTracker` (`observe`), at the next\n * read. It never fetches anything itself: revalidation stays lazy, on the\n * read path and by its rules, so fifty sites do not all fetch the moment an\n * editor saves.\n * - While it is healthy, reads skip the poll. When it is not (still\n * connecting, dropped, refused, silent for a minute) they poll as before.\n * - It never keeps a process alive: Node's `http` with the socket unref'd,\n * every timer unref'd. A build or a script ends as it would without it.\n * - It never throws into a read, and leaves no unhandled rejection or `error`\n * event behind.\n * - One connection per server and key in a process, whatever the number of\n * clients (a dev server builds a new one on every reload): the hubs live in\n * a registry on `globalThis`, which outlasts a reloaded copy of this module.\n *\n * The decisions (when it is on, how long to wait after what) are in\n * `live-policy.ts`, the stream parser in `live-sse.ts`.\n */\nimport { isStudioBody } from './errors'\nimport { LIVE, chooseLive, planReconnect, type LiveOutcome } from './live-policy'\nimport { SseParser } from './live-sse'\nimport { UNSUPPORTED_PAUSE_MS, type VersionTracker } from './version'\n\n/** What the connection looks like to a read. */\ninterface LiveView {\n /** Open, and the studio told the stamp on it within `LIVE.staleMs`. */\n healthy: boolean\n /** The stamp heard on the open connection. */\n version: string | undefined\n /** Epoch ms of the last message: the moment `version` is known to be current. */\n at: number\n /** How many times the connection went silent: the stamp may have moved unseen. */\n silences: number\n}\n\n/**\n * A hub as a link sees it. Shared through `globalThis`, so also with a copy of\n * this module from another build (a reload, a second install): when its shape\n * changes, so does the number in `REGISTRY`.\n */\ninterface SharedHub {\n /** Joins a client; returns the hub's `silences`. */\n attach(token: object): number\n /** Leaves; the last one out stops the connection, at once or after `LINGER_MS`. */\n detach(token: object, linger: boolean): void\n view(now: number): LiveView\n /** Checks the open connection against the stamp itself, when that is due (`LIVE.safetyPollMs`). In the background. */\n safetyCheck(now: number): void\n}\n\nconst REGISTRY = Symbol.for('@nordhavnhq/beacon/live-hubs/2')\n\n/** How long a hub that lost its last client to the garbage collector waits for a new one. */\nconst LINGER_MS = 5 * 60_000\n/** The most of an error body read to tell the studio's own from a proxy's. */\nconst REFUSAL_BODY_LIMIT = 16 * 1024\n\ntype Timer = ReturnType<typeof setTimeout>\n/** What a Node timer adds to the handle; absent from the DOM's `number`. */\ntype NodeTimer = { unref?: () => void, refresh?: () => void }\n\n/*\n * The few parts of Node's `http` used here, declared locally and not imported\n * from `node:http`: beacon's source also typechecks without Node's types, in a\n * consumer with only the DOM library.\n */\ninterface NodeSocket {\n unref(): void\n setKeepAlive(enable: boolean, initialDelay: number): void\n}\ninterface NodeResponse {\n statusCode?: number\n headers: Record<string, string | string[] | undefined>\n setEncoding(encoding: 'utf8'): void\n on(event: 'data', listener: (chunk: string) => void): void\n on(event: 'end' | 'close', listener: () => void): void\n on(event: 'error', listener: (err: unknown) => void): void\n resume(): void\n destroy(): void\n}\ninterface NodeRequest {\n on(event: 'socket', listener: (socket: NodeSocket) => void): void\n on(event: 'error', listener: (err: unknown) => void): void\n end(): void\n destroy(): void\n}\ntype HttpModule = {\n request: (url: URL, options: { method: 'GET', headers: Record<string, string>, agent: false }, callback: (res: NodeResponse) => void) => NodeRequest\n}\ntype Globals = {\n process?: {\n versions?: { node?: unknown }\n env?: Record<string, string | undefined>\n getBuiltinModule?: (id: string) => unknown\n }\n window?: unknown\n document?: unknown\n navigator?: { userAgent?: unknown }\n}\n\nfunction hubs(): Map<string, SharedHub> {\n const scope = globalThis as unknown as Record<symbol, Map<string, SharedHub> | undefined>\n let map = scope[REGISTRY]\n if (!map) {\n map = new Map()\n scope[REGISTRY] = map\n }\n return map\n}\n\n/** A client that is collected without `close()` leaves its hub, after a grace period. */\nconst collected = typeof FinalizationRegistry === 'function'\n ? new FinalizationRegistry<{ hub: SharedHub, token: object }>(({ hub, token }) => {\n try {\n hub.detach(token, true)\n }\n catch {\n /* nothing to do */\n }\n })\n : undefined\n\n/** Whether this runtime can hold the connection: Node (or one that speaks its `http`), not a browser or a worker. */\nfunction liveRuntime(): boolean {\n const g = globalThis as Globals\n if (typeof g.window !== 'undefined' || typeof g.document !== 'undefined') return false\n if (g.navigator?.userAgent === 'Cloudflare-Workers') return false\n return typeof g.process?.versions?.node === 'string'\n}\n\n/** Whether a client with these settings goes live (see `chooseLive`). */\nexport function wantLive(settings: { option: boolean | undefined, revalidating: boolean, customFetch: boolean, waitsForStudio: boolean }): boolean {\n try {\n return chooseLive({ ...settings, runtime: liveRuntime(), env: (globalThis as Globals).process?.env ?? {} })\n }\n catch {\n return false\n }\n}\n\n/**\n * Loads Node's `http` or `https` only when a connection is made, and out of\n * sight of bundlers: the package must load where neither exists (an edge\n * runtime, a browser), and never gets here there.\n */\nasync function loadHttp(protocol: string): Promise<HttpModule> {\n const name = protocol === 'https:' ? 'node:https' : 'node:http'\n const proc = (globalThis as Globals).process\n const builtin = typeof proc?.getBuiltinModule === 'function' ? proc.getBuiltinModule(name) : undefined\n if (builtin) return builtin as HttpModule\n return (await import(/* webpackIgnore: true */ /* @vite-ignore */ name)) as HttpModule\n}\n\nfunction unrefTimer(run: () => void, ms: number): Timer {\n const timer = setTimeout(run, ms)\n ;(timer as unknown as NodeTimer).unref?.()\n return timer\n}\n\n/** A client's handle on the shared connection. Each `HavenClient` with `live` has one. */\nexport class LiveLink {\n private hub: SharedHub | undefined\n private readonly token = {}\n private silences = 0\n private closed = false\n private owner: object | undefined\n\n constructor(\n private readonly baseUrl: string,\n private readonly apiKey: string,\n private readonly headers: Record<string, string>,\n owner: object,\n ) {\n this.owner = owner\n }\n\n /**\n * The stamp gate in front of a read, in place of `tracker.refresh`. While\n * the connection is healthy the stamp it heard counts as a fresh check and\n * nothing is fetched; otherwise the poll runs, at once when the connection\n * went silent since the last read. Connects on the first call.\n */\n gate(tracker: VersionTracker, now: number): Promise<void> {\n try {\n const view = this.join()?.view(now)\n if (view?.healthy && view.version !== undefined) {\n tracker.observe(view.version, view.at)\n this.hub?.safetyCheck(now)\n return Promise.resolve()\n }\n if (view && view.silences !== this.silences) {\n this.silences = view.silences\n tracker.due()\n }\n }\n catch {\n /* the poll below is the answer */\n }\n return tracker.refresh(now)\n }\n\n /** Leaves the connection for good; the last client out closes it. */\n close(): void {\n if (this.closed) return\n this.closed = true\n const hub = this.hub\n this.hub = undefined\n this.owner = undefined\n if (!hub) return\n collected?.unregister(this.token)\n try {\n hub.detach(this.token, false)\n }\n catch {\n /* nothing to do */\n }\n }\n\n private join(): SharedHub | undefined {\n if (this.hub || this.closed) return this.hub\n const url = eventsUrl(this.baseUrl)\n if (!url) {\n this.closed = true\n return undefined\n }\n const registry = hubs()\n // Keyed on the credentials actually sent: `headers` may override the\n // key's Authorization, and a client of another project must never share\n // (and so trust) this project's stream.\n const headers = liveHeaders(this.apiKey, this.headers)\n const id = `${this.baseUrl}\\n${headers.authorization ?? ''}`\n let hub = registry.get(id)\n if (!hub) {\n hub = new LiveHub(id, url, headers)\n registry.set(id, hub)\n }\n this.silences = hub.attach(this.token)\n if (this.owner) collected?.register(this.owner, { hub, token: this.token }, this.token)\n this.owner = undefined\n this.hub = hub\n return hub\n }\n}\n\nfunction eventsUrl(baseUrl: string): URL | undefined {\n try {\n const url = new URL(`${baseUrl}/api/content/events`)\n return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined\n }\n catch {\n return undefined\n }\n}\n\n/**\n * The headers of the stream: the key, the client's extra headers (which may\n * override it, as on every request), and what makes it a stream. No\n * compression: a proxy that gzips the stream would hand the parser bytes.\n */\nfunction liveHeaders(apiKey: string, extra: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = { authorization: `Bearer ${apiKey}` }\n for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value\n headers.accept = 'text/event-stream'\n headers['cache-control'] = 'no-cache'\n headers['accept-encoding'] = 'identity'\n return headers\n}\n\ntype HubState = 'idle' | 'connecting' | 'open' | 'waiting' | 'stopped'\n\n/** One connection per server and key in this process, shared by the clients that use them. */\nclass LiveHub implements SharedHub {\n private state: HubState = 'idle'\n private current: LiveAttempt | undefined\n /** The stamp heard on the open connection, `undefined` until it is told. */\n private version: string | undefined\n private openedAt = 0\n private lastHeardAt = 0\n /** Failures in a row, for the backoff. */\n private attempts = 0\n private retryAt = 0\n private silences = 0\n private retryTimer: Timer | undefined\n private lingerTimer: Timer | undefined\n private readonly owners = new Set<object>()\n /** Version events on the open connection: tells a stream that moved from one that did not. */\n private tells = 0\n /** When the open connection was last checked against the stamp itself. */\n private checkedAt = 0\n private checking = false\n /** A check found the studio ahead of the stream, with `tells` as it was then. */\n private behind: { tells: number, since: number } | undefined\n\n constructor(\n private readonly id: string,\n private readonly url: URL,\n private readonly headers: Record<string, string>,\n ) {}\n\n attach(token: object): number {\n clearTimeout(this.lingerTimer)\n this.lingerTimer = undefined\n this.owners.add(token)\n return this.silences\n }\n\n detach(token: object, linger: boolean): void {\n if (!this.owners.delete(token) || this.owners.size > 0) return\n clearTimeout(this.lingerTimer)\n if (linger) this.lingerTimer = unrefTimer(() => this.owners.size === 0 && this.dispose(), LINGER_MS)\n else this.dispose()\n }\n\n /**\n * The state of the connection for a read at `now`, after the checks a read\n * makes: connect the first time; a connection silent for `LIVE.staleMs` is\n * dead (a frozen process misses events and runs no timers, so the watchdog\n * alone cannot be trusted); a reconnect whose time has come goes now.\n */\n view(now: number): LiveView {\n if (this.state === 'idle') this.connect()\n else if (this.state === 'open' && now - this.lastHeardAt > LIVE.staleMs) this.current?.end({ kind: 'silent' })\n else if (this.state === 'waiting' && now >= this.retryAt) this.connect()\n if (this.state === 'open' && this.behind) this.judgeBehind(now)\n return {\n healthy: this.state === 'open' && this.version !== undefined,\n version: this.version,\n at: this.lastHeardAt,\n silences: this.silences,\n }\n }\n\n /**\n * The safety net, at most once per `LIVE.safetyPollMs` per connection, set\n * off by a read: ask the stamp and compare it with the stream's. Never\n * awaited by a read, never reported, and over an unref'd socket, so it holds\n * up no read and no process. Only a clear answer counts: a failed check, a\n * check that outlived its connection, or one during which the stream told a\n * new stamp proves nothing. A studio ahead of the stream is noted, not acted\n * on: see `judgeBehind`.\n */\n safetyCheck(now: number): void {\n if (this.state !== 'open' || this.version === undefined || this.checking || this.behind) return\n if (now - this.checkedAt < LIVE.safetyPollMs) return\n this.checking = true\n this.checkedAt = now\n const attempt = this.current\n const tells = this.tells\n const heard = this.version\n const url = versionUrl(this.url)\n const headers = { ...this.headers, accept: 'application/json' }\n loadHttp(url.protocol).then(http => probeStamp(http, url, headers), () => undefined).then(\n (stamp) => {\n this.checking = false\n if (stamp === undefined || attempt !== this.current || tells !== this.tells) return\n if (stamp !== heard) this.behind = { tells, since: Date.now() }\n },\n () => {\n this.checking = false\n },\n )\n }\n\n /**\n * A check found the studio ahead of the stream. The studio sends late on\n * purpose (its 5 s throttle), so that alone is no fault: only a stream that\n * told nothing new for `LIVE.lagToleranceMs` since then missed a change. The\n * first read after that drops it, which makes that same read check the stamp\n * itself (and the hub reconnect).\n */\n private judgeBehind(now: number): void {\n const behind = this.behind!\n if (this.tells !== behind.tells) this.behind = undefined\n else if (now - behind.since >= LIVE.lagToleranceMs) {\n this.behind = undefined\n this.current?.end({ kind: 'silent' })\n }\n }\n\n private connect(): void {\n clearTimeout(this.retryTimer)\n this.state = 'connecting'\n const attempt = new LiveAttempt(this)\n this.current = attempt\n loadHttp(this.url.protocol).then(\n (http) => {\n if (this.current === attempt) attempt.start(http, this.url, this.headers)\n },\n () => {\n // No `http` here after all: nothing to connect with, ever.\n if (this.current === attempt) this.halt()\n },\n )\n }\n\n /** The attempt got its stream: the studio's answer is in. */\n opened(attempt: LiveAttempt): void {\n if (attempt !== this.current) return\n this.state = 'open'\n this.version = undefined\n this.openedAt = Date.now()\n this.lastHeardAt = this.openedAt\n this.checkedAt = this.openedAt\n this.behind = undefined\n }\n\n /** Something came in on the stream: a sign of life. */\n heard(attempt: LiveAttempt): void {\n if (attempt === this.current) this.lastHeardAt = Date.now()\n }\n\n /** A `version` event, its data as sent. */\n told(attempt: LiveAttempt, data: string): void {\n if (attempt !== this.current) return\n try {\n const version = (JSON.parse(data) as { version?: unknown } | null)?.version\n if (typeof version === 'string' && version !== '') {\n this.version = version\n this.tells++\n }\n }\n catch {\n /* not a stamp: ignored */\n }\n }\n\n /** The attempt is over: plan the next one. `outcome` is absent when the hub ended it itself. */\n ended(attempt: LiveAttempt, outcome: LiveOutcome | undefined): void {\n if (attempt !== this.current) return\n this.current = undefined\n const now = Date.now()\n const stable = this.state === 'open' && this.version !== undefined && now - this.openedAt >= LIVE.stableMs\n this.version = undefined\n if (!outcome || this.state === 'stopped') return\n if (outcome.kind === 'silent') this.silences++\n const plan = planReconnect(outcome, { attempts: this.attempts, stable, pauseMs: UNSUPPORTED_PAUSE_MS, now, random: Math.random })\n if (plan.stop) {\n this.halt()\n return\n }\n this.attempts = plan.attempts\n this.state = 'waiting'\n this.retryAt = now + plan.delay\n this.retryTimer = unrefTimer(() => {\n if (this.state === 'waiting') this.connect()\n }, plan.delay)\n }\n\n /** Stops for good: reads keep to the poll. */\n private halt(): void {\n this.state = 'stopped'\n clearTimeout(this.retryTimer)\n const attempt = this.current\n this.current = undefined\n this.version = undefined\n attempt?.end()\n }\n\n private dispose(): void {\n this.halt()\n const registry = hubs()\n if (registry.get(this.id) === this) registry.delete(this.id)\n }\n}\n\n/**\n * One connection attempt, from the request to its end. Settles exactly once,\n * however it ends (an error, a close, a timeout, the hub ending it), and\n * reports to the hub only before that. Every event a socket or a stream can\n * emit has a listener here, so none of them can surface as an uncaught error.\n */\nclass LiveAttempt {\n private done = false\n private req: NodeRequest | undefined\n private timers: Timer[] = []\n\n constructor(private readonly hub: LiveHub) {}\n\n start(http: HttpModule, url: URL, headers: Record<string, string>): void {\n if (this.done) return\n this.timers.push(unrefTimer(() => this.end({ kind: 'failed' }), LIVE.connectTimeoutMs))\n try {\n const req = http.request(url, { method: 'GET', headers, agent: false }, (res) => this.answered(res))\n this.req = req\n // A listener that throws would be an uncaught exception, which ends the\n // process: a runtime that speaks Node's `http` may lack either method.\n req.on('socket', (socket) => {\n try {\n socket.unref()\n }\n catch {\n // A socket that cannot be unref'd would keep a build alive: no stream.\n this.end({ kind: 'refused', status: 400, studio: true, retryAfter: null })\n return\n }\n try {\n socket.setKeepAlive(true, 30_000)\n }\n catch {\n /* the pings and the watchdog find a dead connection anyway */\n }\n })\n req.on('error', () => this.end({ kind: 'failed' }))\n req.end()\n }\n catch {\n // A header Node will not send, say: the long pause, not a loop.\n this.end({ kind: 'refused', status: 400, studio: true, retryAfter: null })\n }\n }\n\n /** Ends the attempt; the hub plans what comes next from `outcome`, unless it ended it itself. */\n end(outcome?: LiveOutcome): void {\n if (this.done) return\n this.done = true\n for (const timer of this.timers) clearTimeout(timer)\n try {\n this.req?.destroy()\n }\n catch {\n /* already gone */\n }\n this.hub.ended(this, outcome)\n }\n\n private answered(res: NodeResponse): void {\n res.on('error', () => this.end({ kind: 'failed' }))\n if (this.done) {\n res.resume()\n return\n }\n const type = String(res.headers['content-type'] ?? '')\n if (res.statusCode === 200 && type.includes('text/event-stream')) this.stream(res)\n else this.refused(res)\n }\n\n private stream(res: NodeResponse): void {\n for (const timer of this.timers) clearTimeout(timer)\n this.timers = []\n const watchdog = unrefTimer(() => this.end({ kind: 'silent' }), LIVE.staleMs)\n this.timers.push(watchdog)\n this.hub.opened(this)\n const parser = new SseParser()\n res.setEncoding('utf8')\n res.on('data', (chunk: string) => {\n if (this.done) return\n ;(watchdog as unknown as NodeTimer).refresh?.()\n this.hub.heard(this)\n const events = parser.feed(chunk)\n if (events === null) {\n this.end({ kind: 'failed' })\n return\n }\n for (const event of events) {\n if (event.event === 'version') this.hub.told(this, event.data)\n }\n })\n res.on('end', () => this.end({ kind: 'closed' }))\n res.on('close', () => this.end({ kind: 'failed' }))\n }\n\n /** Not the stream: read a little of the body, to tell the studio's own refusal from a proxy's. */\n private refused(res: NodeResponse): void {\n const status = res.statusCode ?? 0\n const header = res.headers['retry-after']\n const retryAfter = (Array.isArray(header) ? header[0] : header) ?? null\n let body = ''\n res.setEncoding('utf8')\n res.on('data', (chunk: string) => {\n body += chunk\n if (body.length > REFUSAL_BODY_LIMIT) res.destroy()\n })\n const settle = (): void => this.end({ kind: 'refused', status, retryAfter, studio: isStudioBody(status, parseJson(body)) })\n res.on('end', settle)\n res.on('close', settle)\n }\n}\n\n/** `/api/content/version` beside the stream's `/api/content/events`. */\nfunction versionUrl(events: URL): URL {\n const url = new URL(events.href)\n url.pathname = url.pathname.replace(/events$/, 'version')\n return url\n}\n\n/**\n * The safety check's request: the stamp from `GET /version`, `undefined` for\n * anything else (an error, a status other than 200, a body without a stamp,\n * no answer within `LIVE.safetyProbeTimeoutMs`). Settles exactly once, and\n * its socket and timer are unref'd: a script whose last read set it off ends\n * without waiting for it.\n */\nfunction probeStamp(http: HttpModule, url: URL, headers: Record<string, string>): Promise<string | undefined> {\n return new Promise((resolve) => {\n let req: NodeRequest | undefined\n let settled = false\n const finish = (stamp?: string): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n try {\n req?.destroy()\n }\n catch {\n /* already gone */\n }\n resolve(stamp)\n }\n const timer = unrefTimer(() => finish(), LIVE.safetyProbeTimeoutMs)\n try {\n req = http.request(url, { method: 'GET', headers, agent: false }, (res) => {\n res.on('error', () => finish())\n if (res.statusCode !== 200) {\n res.resume()\n finish()\n return\n }\n let body = ''\n res.setEncoding('utf8')\n res.on('data', (chunk: string) => {\n body += chunk\n if (body.length > REFUSAL_BODY_LIMIT) finish()\n })\n res.on('end', () => {\n const stamp = (parseJson(body) as { version?: unknown } | undefined)?.version\n finish(typeof stamp === 'string' && stamp !== '' ? stamp : undefined)\n })\n res.on('close', () => finish())\n })\n req.on('socket', (socket) => {\n try {\n socket.unref()\n }\n catch {\n /* a short request; the timer still ends it */\n }\n })\n req.on('error', () => finish())\n req.end()\n }\n catch {\n finish()\n }\n })\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n }\n catch {\n return undefined\n }\n}\n","import { ContentCache, type CacheEntry, type CacheOptions } from './cache'\nimport { HavenError, isStudioBody } from './errors'\nimport type { ContentLocale, ContentRecord, ContentSchema, QueryResult, SchemaNode, UploadedFile } from './types'\nimport { LiveLink, wantLive } from './live'\nimport { VersionTracker } from './version'\n\n/** Hosted Nordhavn OS platform. Used when no `baseUrl` is provided. */\nexport const DEFAULT_BASE_URL = 'https://beacon.nordhavn.ai'\n\n/** Default request timeout in ms (`timeout` option). */\nconst DEFAULT_TIMEOUT = 10_000\n/** The least time an upload gets by default: the studio takes up to 10 MB. */\nconst MIN_UPLOAD_TIMEOUT = 60_000\n/** Ceiling for the stamp check, which every concurrent read waits on. */\nconst VERSION_TIMEOUT = 3_000\n/** Default for `cache.waitForFresh`, in ms. */\nconst DEFAULT_WAIT_FOR_FRESH = 1_000\n/** The longest delay a timer holds; beyond it `setTimeout` fires after 1 ms. */\nconst MAX_TIMER = 2_147_483_647\n/** How many keys `storedBy` remembers before it starts over. */\nconst STORED_LIMIT = 5_000\n/** How long a failed read of the project's locales is not repeated. */\nconst LOCALES_RETRY_MS = 60_000\n/** Default for `gatewayRetry`, in ms. */\nconst DEFAULT_GATEWAY_RETRY = 200\n/** The longest `gatewayRetry` honoured; a larger value is cut back to this. */\nconst MAX_GATEWAY_RETRY = 60_000\n\n/** A studio failure the client absorbed, handed to `onError`. */\nexport interface StudioFailure {\n /**\n * What failed: the periodic `stamp-check`, or the `read` that refreshes one\n * cache entry (its cached value was served instead).\n */\n during: 'stamp-check' | 'read'\n /** Cache key of the entry that could not be refreshed. Only for `read`. */\n key?: string\n /** What went wrong: a `HavenError`, a `TimeoutError`, a network error. */\n error: unknown\n}\n\nexport interface HavenClientOptions {\n /**\n * Project API key, `slk_...`. Mint one in the project's settings under\n * \"API keys\". Its reach is the union of its per-node read/write scopes.\n */\n apiKey: string\n /**\n * Base URL of your Nordhavn OS server, without a trailing `/api/content`\n * (that path is appended automatically). Defaults to the hosted platform at\n * `https://beacon.nordhavn.ai`; override it for a self-hosted instance.\n */\n baseUrl?: string\n /**\n * Default locale for reads, e.g. `nl` or `fr-BE`. When set, records are\n * returned in that language, with untranslated fields falling back to the\n * project default. Override per call with `opts.locale`. Omit for the default\n * locale. Discover available locales with `client.locales()`.\n */\n locale?: string\n /** Read caching. Pass `false` to disable, or an options object to tune it. */\n cache?: boolean | CacheOptions\n /** Custom `fetch` implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch\n /**\n * Give up on a request after this many ms, body included. Default `10000`.\n * `0` disables it, as does `Infinity`.\n *\n * Without one, a studio that accepts the connection but never answers holds\n * every read until the runtime gives up (minutes, in Node). A timed-out read\n * counts as transient, like a `5xx`: the last good value is served. The\n * once-a-minute stamp check uses at most 3 seconds of it, as every read in\n * that moment waits on the check.\n *\n * It covers writes too. A write that times out may still have reached the\n * studio, so do not blindly send it again: you could store it twice.\n */\n timeout?: number\n /**\n * A read with nothing cached that gets a `502` or `503` tries once more after\n * this many ms, plus up to as many again at random (so the reads of one page\n * do not all come back at once). Default `200`. `false` turns it off.\n *\n * Often one bad moment, such as a proxy switching to a new studio container;\n * and with nothing cached the error is all the caller would get. Never for a\n * read with a value cached (that value is served), a `cache: false` read,\n * a write, or an answer carrying `Retry-After`.\n */\n gatewayRetry?: number | false\n /**\n * Called for every studio failure the client absorbs: a failed stamp check,\n * or a read answered from the cache because its refresh failed. These never\n * reach your code as an error, so this is the only place to notice that the\n * site is running on cached content. Errors that are thrown to the caller\n * (a read with nothing cached, a write) are not repeated here.\n *\n * At most one call per stamp check and one per cache entry per retry pause,\n * so it is safe to log or alert from. Without it the client logs one\n * `console.warn` per outage.\n */\n onError?: (failure: StudioFailure) => void\n /** Extra headers merged into every request. */\n headers?: Record<string, string>\n /**\n * Hold a live connection to the studio, which tells the moment content\n * changes, so an edit shows at the next read instead of up to `revalidate`\n * later. While it is up, reads skip the once-a-minute stamp check; when it\n * is down, they make it as before. It only ever replaces that check: it\n * fetches no content itself, keeps no process alive, and cannot fail a read.\n *\n * On by default in a long-lived Node process, for a client with a cache.\n * Off by default on serverless and in CI (`VERCEL`, `NETLIFY`, AWS Lambda,\n * Azure Functions, Google Cloud Functions and Cloud Run, Deno Deploy, `CI`),\n * with `cache.waitForFresh: false`, and with a custom `fetch` (the\n * connection goes over Node's `http`, not through it); `true` turns it on\n * there. Never in a browser or an edge runtime, nor without a cache or with\n * `revalidate: false`. One connection per server and key in a process, shared\n * by every client with those.\n */\n live?: boolean\n}\n\n/** Per-call read options. */\nexport interface ReadOptions {\n /** Set `false` to bypass the cache for this call and always hit the network. */\n cache?: boolean\n /**\n * Locale for this read, overriding the client-level `locale`. Pass an empty\n * string to force the project default even when a client locale is set;\n * `undefined` or `null` (a missing header, from `headers.get()`) leaves the\n * client locale in place. Untranslated fields fall back to the default\n * locale. Only record reads use it (`listRecords`, `getRecord`, a dataset's\n * `list` and `get`); `query()`, `schema()`, `nodes()` and `locales()` ignore it.\n */\n locale?: string | null | undefined\n}\n\n/** Per-call options for `uploadFile`. */\nexport interface UploadOptions {\n /**\n * The file name to send, extension included: the studio checks the\n * extension against the field's allowed types. Defaults to the name of a\n * `File`; required for a plain `Blob`.\n */\n filename?: string\n /**\n * Give up after this many ms, body included. Defaults to the client's\n * `timeout`, but at least 60 s (an upload may be 10 MB); `0` for none. A\n * client created with `timeout: 0` uploads without one too. A negative\n * number or `NaN` counts as not given.\n */\n timeout?: number\n}\n\ntype Method = 'GET' | 'POST' | 'PATCH'\n\n/**\n * Typed client for the Nordhavn OS content API: read and write a project's node\n * datasets from any website or app. Reads are cached (see the `cache` option);\n * writes invalidate the affected cache entries automatically.\n *\n * ```ts\n * const studio = new HavenClient({ apiKey: 'slk_...', baseUrl: 'https://studio.example.com' })\n * const posts = await studio.dataset<Post>('blog', 'posts').list()\n * ```\n */\nexport class HavenClient {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly fetchImpl: typeof fetch\n private readonly headers: Record<string, string>\n private readonly cache: ContentCache\n private readonly versionTracker: VersionTracker\n /** The client's share of the live connection, when it has one (`live` option). */\n private live: LiveLink | undefined\n /** Client-level default locale for reads (undefined = project default). */\n private readonly locale?: string\n /** Request timeout in ms, `0` for none. */\n private readonly timeout: number\n /** `cache.waitForFresh` in ms, `Infinity` to wait for the studio. */\n private readonly waitForFresh: number\n /** `gatewayRetry` in ms, `undefined` when it is off. */\n private readonly gatewayRetry: number | undefined\n /**\n * The refresh under way per cache key, so concurrent reads of one key share\n * one request, with the ticket it left on (see `state.ticket`).\n */\n private readonly inflight = new Map<string, { job: Promise<unknown>, ticket: number }>()\n /**\n * Per cache key, the ticket of the request whose answer the cache holds.\n * Emptied on every invalidation, capped by `STORED_LIMIT`. See `storable`.\n */\n private readonly storedBy = new Map<string, number>()\n private readonly onError?: (failure: StudioFailure) => void\n /**\n * Everything that changes while the client runs and is not a collection of\n * its own.\n */\n private readonly state = {\n /**\n * Numbers the requests in the order they leave. Answers come back in any\n * order, and the cache must never go back in time: a request takes a\n * ticket when it leaves, and `storable` compares it on the way back.\n */\n ticket: 0,\n /** The last ticket handed out when the cache was last invalidated. */\n invalidatedAt: 0,\n /** Set by an absorbed failure, cleared by the next answer: one warning per outage. */\n unreachable: false,\n /**\n * The project's locales as last read. Kept here and not only in the cache,\n * where the entry can be evicted: without the list a requested locale\n * cannot be mapped onto the key its content is cached under, and that\n * content would be out of reach for as long as the studio is away.\n */\n locales: undefined as ContentLocale[] | undefined,\n /** Epoch ms before which the locales are not asked for again, after that failed. */\n localesRetryAt: 0,\n }\n\n constructor(options: HavenClientOptions) {\n if (!options.apiKey) throw new Error('HavenClient: `apiKey` is required')\n\n this.apiKey = options.apiKey\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n const resolvedFetch = options.fetch ?? globalThis.fetch\n if (!resolvedFetch) {\n throw new Error('HavenClient: no `fetch` available; pass one via options.fetch')\n }\n this.fetchImpl = resolvedFetch.bind(globalThis)\n this.headers = options.headers ?? {}\n this.locale = options.locale || undefined\n this.timeout = normalizeTimeout(options.timeout)\n this.onError = options.onError\n\n const cacheOpt = options.cache\n const cacheOptions: CacheOptions\n = cacheOpt === false ? { enabled: false }\n : cacheOpt === true || cacheOpt === undefined ? {}\n : cacheOpt\n this.cache = new ContentCache(cacheOptions)\n this.waitForFresh = normalizeWait(cacheOptions.waitForFresh)\n this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry)\n\n const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false\n ? 0\n : cacheOptions.revalidate ?? 60_000\n // The stamp check is tiny, and every read arriving while it runs waits on it,\n // so it gets a tighter budget than a full read.\n const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT)\n this.versionTracker = new VersionTracker(\n async () => {\n try {\n const res = await this.request<{ version?: unknown }>('GET', '/version', undefined, probeTimeout)\n // Anything but a stamp (a maintenance page answering 200) is no\n // answer: the last known stamp stands.\n if (typeof res?.version !== 'string') throw unexpectedBody(`${this.baseUrl}/api/content/version`)\n this.state.unreachable = false\n return res.version\n }\n catch (err) {\n // A studio without the route is up and answering: nothing to report.\n if (isMissingRoute(err)) this.state.unreachable = false\n else this.report({ during: 'stamp-check', error: err })\n throw err\n }\n },\n revalidate,\n isMissingRoute,\n )\n const live = wantLive({\n option: options.live,\n revalidating: revalidate > 0,\n customFetch: options.fetch !== undefined,\n waitsForStudio: this.waitForFresh === Infinity,\n })\n this.live = live ? new LiveLink(this.baseUrl, this.apiKey, this.headers, this) : undefined\n }\n\n /**\n * Lets go of the live connection: the last client of a server and key to\n * close it closes the connection. The client keeps working, on the stamp\n * check alone. Not needed to let a process end (the connection never keeps\n * one alive); for a test, or code that builds clients and drops them.\n */\n close(): void {\n this.live?.close()\n this.live = undefined\n }\n\n // ── Introspection ─────────────────────────────────────────────────────────\n\n /** The full content shape this key can reach: nodes, datasets, field schemas. */\n async schema(opts?: ReadOptions): Promise<ContentSchema> {\n return this.cachedGet<ContentSchema>('schema', '/schema', opts, has('nodes', Array.isArray))\n }\n\n /** Shorthand for `schema()` then `.nodes`. */\n async nodes(opts?: ReadOptions): Promise<SchemaNode[]> {\n return (await this.schema(opts)).nodes\n }\n\n /**\n * The locales this project's content can be requested in (default first). Use\n * a locale `code` as the client `locale` option or a per-call `opts.locale`.\n */\n async locales(opts?: ReadOptions): Promise<ContentLocale[]> {\n const res = await this.cachedGet<{ locales: ContentLocale[] }>('locales', '/locales', opts, has('locales', Array.isArray))\n return res.locales\n }\n\n /**\n * Resolve the locale for a read: per-call override, else the client default.\n * Only a value overrides: `{ locale: undefined }` (or `null`) is what a site\n * passes when the visitor sent no language, and must leave the client locale standing.\n * `''` is the one way to ask for the project default.\n */\n private resolveLocale(opts?: ReadOptions): string | undefined {\n // `!= null`: from plain JavaScript a missing header arrives as `null`\n // (`headers.get()`), and means the same as `undefined`.\n const l = opts?.locale != null ? opts.locale : this.locale\n return l || undefined\n }\n\n /**\n * The locale a read is requested and cached under: the requested one mapped\n * onto a locale the project is configured with (see `matchLocale`).\n *\n * Sites pass on whatever language the visitor's browser asks for, and the\n * studio answers all of `nl`, `nl-NL` and `nl-BE` with the same content. Keyed\n * by the raw value, each spelling would be its own cache entry and its own\n * request - and a stream of made-up ones would push every real entry out of\n * the cache, the last good values for an outage among them. Mapped first,\n * the cache holds one entry per configured locale, whatever is asked for.\n *\n * Without the list of locales (caching off, an older studio without the\n * route, studio unreachable and never read) the requested value goes to the\n * studio as it is, and the studio resolves it.\n */\n private async readLocale(opts?: ReadOptions): Promise<string | undefined> {\n const requested = this.resolveLocale(opts)?.trim() || undefined\n if (requested === undefined || !this.cache.enabled) return requested\n\n // A `cache: false` read is never tried twice (`gatewayRetry`), and\n // neither is the lookup it may have to wait for.\n const bypass = opts?.cache === false\n const configured = await this.configuredLocales(!bypass)\n return configured ? matchLocale(requested, configured) : requested\n }\n\n /**\n * The project's locales, or `undefined` when they have never been read and\n * cannot be now. An empty list is an answer like any other: the project has\n * no locales, the studio serves the same content whatever language is asked\n * for, and `matchLocale` then maps every request onto the default.\n *\n * Once the list is known this does not wait for anything: the read maps from\n * the list as it stands, and the list is brought up to date on the side. A\n * read therefore spends its `waitForFresh` on its content alone, and keeps\n * finding that content under the same key while the studio is away. Only\n * the very first localized read waits here, as it has nothing to map from.\n *\n * The exception is `waitForFresh: false`. That setting promises that a read\n * waits for the studio and leaves nothing running when it returns - what a\n * host needs that freezes the process once the response is out. So there\n * the list is brought up to date first, like the content after it.\n */\n private async configuredLocales(retry: boolean): Promise<ContentLocale[] | undefined> {\n const state = this.state\n if (Date.now() >= state.localesRetryAt) {\n // Always through the cache, also for a `cache: false` read: this runs on every\n // localized read, and a new locale shows up when the stamp moves.\n const lookup = this.cachedGet<{ locales: ContentLocale[] }>(\n 'locales',\n '/locales',\n { cache: true },\n has('locales', Array.isArray),\n retry,\n ).then(\n (res) => {\n state.locales = res.locales\n },\n () => {\n // Leave the list as it is, and the studio alone for a while.\n state.localesRetryAt = Date.now() + LOCALES_RETRY_MS\n },\n )\n if (state.locales === undefined || this.waitForFresh === Infinity) await lookup\n }\n return state.locales\n }\n\n // ── Records ───────────────────────────────────────────────────────────────\n\n /** List every record in a dataset (references inflated). Requires read scope. */\n async listRecords<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n opts?: ReadOptions,\n ): Promise<ContentRecord<T>[]> {\n const locale = await this.readLocale(opts)\n const res = await this.cachedGet<{ records: ContentRecord<T>[] }>(\n recordsKey(nodeSlug, datasetSlug, locale),\n datasetPath(nodeSlug, datasetSlug) + localeQuery(locale),\n opts,\n has('records', Array.isArray),\n )\n return res.records\n }\n\n /** Read one record by uid. Requires read scope. Throws 404 if it does not exist. */\n async getRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n recordUid: string,\n opts?: ReadOptions,\n ): Promise<ContentRecord<T>> {\n const locale = await this.readLocale(opts)\n const res = await this.cachedGet<{ record: ContentRecord<T> }>(\n recordKey(nodeSlug, datasetSlug, recordUid, locale),\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}${localeQuery(locale)}`,\n opts,\n has('record', isObject),\n )\n return res.record\n }\n\n /** Create a record. Requires write scope. Invalidates cached reads of the dataset. */\n async createRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n data: Record<string, unknown>,\n ): Promise<ContentRecord<T>> {\n const res = await this.write<{ record: ContentRecord<T> }>(\n 'POST',\n datasetPath(nodeSlug, datasetSlug),\n { data },\n nodeSlug,\n datasetSlug,\n )\n return res.record\n }\n\n /**\n * Partially update a record. The patch is merged onto the stored data (omitted\n * top-level fields are preserved). Requires write scope. Invalidates cached\n * reads of the dataset and of this record.\n */\n async updateRecord<T = Record<string, unknown>>(\n nodeSlug: string,\n datasetSlug: string,\n recordUid: string,\n data: Record<string, unknown>,\n ): Promise<ContentRecord<T>> {\n const res = await this.write<{ record: ContentRecord<T> }>(\n 'PATCH',\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}`,\n { data },\n nodeSlug,\n datasetSlug,\n )\n return res.record\n }\n\n /**\n * Upload one file for a `file` field, for a form that sends an attachment.\n * Requires write scope on the dataset. Returns the file; hang it on a record\n * in a second call by writing `{ uid }` into that field:\n *\n * ```ts\n * const attachment = form.get('attachment')\n * if (attachment instanceof File && attachment.size > 0) {\n * const file = await studio.uploadFile('contact', 'requests', 'attachment', attachment)\n * await studio.createRecord('contact', 'requests', { name, attachment: { uid: file.uid } })\n * }\n * ```\n *\n * The field decides what it takes: its `mimes` and `max_size` rules, within\n * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The\n * studio reads the type from the content, so a renamed file is refused. Only\n * top-level fields. A file of the wrong type or size throws `HavenError` 400\n * with a message fit to show; other refusals (400, 403, 404) are setup\n * errors. More than 10 uploads a minute per key throws 429. From a Node\n * `Buffer`, send `new Blob([buffer])` with a `filename`.\n *\n * Server-side only: the key that uploads can write, and must never reach a\n * browser. Not retried, not cached, and it leaves cached reads alone: until a\n * record takes it up, the file belongs to no content. An upload that failed\n * may still have been stored; an unused one is removed after 24 hours.\n */\n async uploadFile(\n nodeSlug: string,\n datasetSlug: string,\n fieldSlug: string,\n file: Blob,\n opts?: UploadOptions,\n ): Promise<UploadedFile> {\n const filename = opts?.filename ?? (file as Partial<File>).name\n if (!filename) {\n throw new Error('HavenClient.uploadFile: the file has no name; pass `filename` (with its extension)')\n }\n const form = new FormData()\n form.set('file', file, filename)\n form.set('nodeSlug', nodeSlug)\n form.set('datasetSlug', datasetSlug)\n form.set('fieldSlug', fieldSlug)\n\n const url = `${this.baseUrl}/api/content/files`\n const timeout = uploadTimeout(this.timeout, opts?.timeout)\n return withTimeout(url, timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method: 'POST',\n // No Content-Type: fetch sets the multipart one, with its boundary.\n headers: { Authorization: `Bearer ${this.apiKey}`, ...withoutContentType(this.headers) },\n body: form,\n signal,\n })\n if (!res.ok) throw await this.toError(res)\n // A maintenance page, or an empty body, is no upload either.\n const value: unknown = await res.json().catch(() => undefined)\n if (!has('uid', (uid) => typeof uid === 'string' && uid !== '')(value)) throw unexpectedBody(url)\n return value as UploadedFile\n })\n }\n\n /**\n * Sends a write and settles the cached reads of its dataset with the outcome.\n *\n * Stored: they are dropped. Refused (an answered 4xx): they are still right\n * and stay. Anything else - a timeout, a dropped connection, a 5xx - leaves\n * open whether the studio carried the write out, so they are marked for a\n * recheck: the next read asks the studio again, and keeps the cached value to\n * fall back on if the studio is in fact down.\n */\n private async write<T>(method: Method, path: string, body: unknown, nodeSlug: string, datasetSlug: string): Promise<T> {\n let res: T\n try {\n res = await this.request<T>(method, path, body)\n }\n catch (err) {\n if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, 'recheck')\n throw err\n }\n this.invalidateDataset(nodeSlug, datasetSlug)\n return res\n }\n\n // -- Queries --\n\n /** Run a saved query (`queries.<slug>`) and return its result. Requires read scope. */\n async query<V = unknown>(querySlug: string, opts?: ReadOptions): Promise<QueryResult<V>> {\n return this.cachedGet<QueryResult<V>>(\n `query:${querySlug}`,\n `/queries/${encodeURIComponent(querySlug)}`,\n opts,\n // Recognised by `shape`, never by `value`: that may be anything, and a\n // query without a result can come back with no `value` at all.\n has('shape', (shape) => typeof shape === 'string'),\n )\n }\n\n // ── Fluent dataset handle ───────────────────────────────────────────────────\n\n /**\n * A fluent, type-parameterised handle to one dataset:\n * `client.dataset<Post>('blog', 'posts').list()`.\n */\n dataset<T = Record<string, unknown>>(nodeSlug: string, datasetSlug: string): DatasetHandle<T> {\n return new DatasetHandle<T>(this, nodeSlug, datasetSlug)\n }\n\n // ── Cache control ───────────────────────────────────────────────────────────\n\n /**\n * Clear cached reads. With no argument, clears everything. Pass a scope to\n * clear just part of it: a node slug, or `{ node, dataset }` for one dataset.\n * A scoped clear also drops every saved query result, as any of them may\n * aggregate the content that was cleared.\n */\n clearCache(scope?: string | { node: string, dataset?: string }): void {\n if (scope === undefined) {\n this.cache.clear()\n this.invalidated()\n return\n }\n const node = typeof scope === 'string' ? scope : scope.node\n const dataset = typeof scope === 'string' ? undefined : scope.dataset\n if (dataset) {\n this.invalidateDataset(node, dataset)\n return\n }\n this.dropPrefix(`records:${node}/`)\n this.dropPrefix(`record:${node}/`)\n this.dropPrefix('query:')\n }\n\n /**\n * Invalidate cached record reads for a dataset (every locale), plus all query\n * results (which may aggregate it). `drop` removes them; `recheck` keeps each\n * value as a fallback but makes the next read ask the studio again.\n */\n private invalidateDataset(nodeSlug: string, datasetSlug: string, how: 'drop' | 'recheck' = 'drop'): void {\n const one = how === 'drop' ? (key: string) => this.drop(key) : (key: string) => this.recheck(key)\n const all = how === 'drop' ? (prefix: string) => this.dropPrefix(prefix) : (prefix: string) => this.recheckPrefix(prefix)\n // Default-locale list key + every `::<locale>` variant of it.\n one(recordsKey(nodeSlug, datasetSlug))\n all(`${recordsKey(nodeSlug, datasetSlug)}::`)\n // All single-record keys under the dataset (every uid, every locale).\n all(`${recordKey(nodeSlug, datasetSlug, '')}`)\n all('query:')\n }\n\n /** Drop one key from the cache. */\n private drop(key: string): void {\n this.cache.delete(key)\n this.invalidated()\n }\n\n /** `drop` for every key that starts with `prefix`. */\n private dropPrefix(prefix: string): void {\n this.cache.deletePrefix(prefix)\n this.invalidated()\n }\n\n /** Like `drop`, but the value stays as a fallback (see `ContentCache.expire`). */\n private recheck(key: string): void {\n this.cache.expire(key)\n this.invalidated()\n }\n\n /** `recheck` for every key that starts with `prefix`. */\n private recheckPrefix(prefix: string): void {\n this.cache.expirePrefix(prefix)\n this.invalidated()\n }\n\n /**\n * Called by everything that invalidates cached reads. Every request that is\n * under way at this moment left before it, so its answer may show the\n * content as it was: none of them may store what they come back with\n * (`storable`), and no later read may join one of them (hence the cleared\n * `inflight`). They still answer the reads that were already waiting on them.\n *\n * Deliberately not narrowed to the keys that were invalidated. The price is\n * that an unrelated answer now and then is served without being stored, and\n * asked for once more; what it buys is one rule without exceptions.\n */\n private invalidated(): void {\n this.state.invalidatedAt = this.state.ticket\n this.storedBy.clear()\n this.inflight.clear()\n }\n\n /**\n * Whether the answer to the request that left on `ticket` may change what\n * the cache holds for `key`. The single gate in front of every cache write\n * that follows a request - cached read or bypass, a new value, a `304`, a\n * deletion or a retry pause alike. It keeps the cache from going back in time:\n *\n * - not when the cache was invalidated after the request left: the answer\n * may show the content from before (a write, `clearCache`);\n * - not when the cache already holds the answer to a request that left\n * later: that one is newer, whichever of the two came back first.\n */\n private storable(key: string, ticket: number): boolean {\n return ticket > this.state.invalidatedAt && ticket >= (this.storedBy.get(key) ?? 0)\n }\n\n /**\n * Settles the cache with the studio's own definitive \"no\" for `key` (deleted,\n * forbidden), in answer to the request that left on `ticket`: the entry goes.\n * The one place this happens, for a cached read and a bypass alike.\n *\n * The deletion is noted like any other answer. Without that, a request that\n * left earlier and comes back later would pass the gate and put the deleted\n * content straight back.\n */\n private gone(key: string, ticket: number): void {\n if (!this.storable(key, ticket)) return\n this.cache.delete(key)\n this.stored(key, ticket)\n }\n\n /**\n * Notes that the cache now reflects, for `key`, the answer to the request\n * that left on `ticket` - a value, a `304`, or the studio's own \"this does\n * not exist\", after which the cache holds nothing for it. A refresh of that\n * key that left earlier and is still under way is retired: a read arriving\n * now must not join it for an older answer than the cache already reflects.\n */\n private stored(key: string, ticket: number): void {\n // Unbounded growth is cut off the blunt, safe way: forget everything and\n // bar every request under way from storing, as an invalidation does.\n if (this.storedBy.size >= STORED_LIMIT) this.invalidated()\n this.storedBy.set(key, ticket)\n const running = this.inflight.get(key)\n if (running && running.ticket < ticket) this.inflight.delete(key)\n }\n\n // ── Transport ───────────────────────────────────────────────────────────────\n\n /**\n * The read path, with conditional revalidation.\n *\n * Steady state (project stamp unchanged since we last confirmed this entry):\n * served straight from cache, zero network. After a content change the stamp\n * moves, so the entry is revalidated once with `If-None-Match` - a `304` keeps\n * the cached value, a `200` replaces it - and then it is fast again.\n *\n * Five rules hold for every read, whatever the studio does. Each is enforced\n * in exactly one place, named here, so that it cannot hold for one kind of\n * read and not for another:\n *\n * 1. A failure that is not the studio's own definitive answer never costs a\n * cached value: it is served instead, and stays cached (`refresh`).\n * 2. Only what is recognisably this endpoint's answer is ever stored\n * (`conditionalGet`).\n * 3. The cache never goes back in time: an answer is not stored when the\n * cache was invalidated, or filled with a newer answer, after its request\n * left (`storable`, in front of every write to the cache).\n * 4. A read that already holds a value waits on the studio for `waitForFresh`\n * at most, stamp check and refresh together (here); the refresh then\n * finishes on the side.\n * 5. One request per key at a time (`refresh`).\n */\n private async cachedGet<T>(\n cacheKey: string,\n path: string,\n opts: ReadOptions | undefined,\n isExpected: BodyCheck,\n /** Whether a `502`/`503` with nothing cached may be tried again (`gatewayRetry`). */\n retry = true,\n ): Promise<T> {\n const useCache = opts?.cache !== false\n\n // An explicit bypass: always fetch fresh and never fall back, but still\n // refresh the cache so the reads after it benefit from the warm entry.\n if (!useCache) {\n // The stamp as it stands before asking, like the cached path below. Read\n // after the answer it can be newer than the content that came back (an\n // edit landed in between, and another read's stamp check saw it), and\n // that older content would then count as current until the next edit.\n const version = this.versionTracker.current() ?? undefined\n const ticket = ++this.state.ticket\n let res: Awaited<ReturnType<HavenClient['conditionalGet']>>\n try {\n res = await this.conditionalGet(path, undefined, isExpected)\n }\n catch (err) {\n // Never falls back - but the studio's own \"this does not exist\" is an\n // answer for the cache as well, here as on the cached path.\n if (isDefinitive(err)) this.gone(cacheKey, ticket)\n throw err\n }\n if (this.storable(cacheKey, ticket)) {\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n this.stored(cacheKey, ticket)\n }\n return res.value as T\n }\n\n // With something to serve, expired or not, the studio gets a budget.\n const started = Date.now()\n const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity\n\n // Cheap, throttled: at most one tiny stamp request per `revalidate` window,\n // and none while the live connection is healthy (its stamp counts as a check).\n // A check that outlasts the budget carries on; this read uses the stamp we had.\n await within(this.checkVersion(started), budget)\n const version = this.versionTracker.current() ?? undefined\n const entry = this.cache.peek(cacheKey, Date.now())\n\n if (entry) {\n // Serve from cache when we cannot see a newer stamp (tracking off, first\n // probe not in yet, or studio unreachable) or the stamp is unchanged since\n // this entry was last confirmed.\n if (version === undefined || entry.validatedVersion === version) {\n return entry.value as T\n }\n }\n\n // Revalidate (the stamp moved) or refetch (miss / TTL expired). An expired\n // entry still has its etag, so an unchanged value comes back as a `304`.\n const last = entry ?? this.cache.stale(cacheKey)\n // A refetch failed moments ago: serve the last good value until the pause\n // is over, rather than making every read wait on an unreachable studio.\n if (last?.retryAt !== undefined && Date.now() < last.retryAt) {\n return last.value as T\n }\n\n const refresh = this.refresh<T>(cacheKey, path, last, version, isExpected, retry)\n if (!last) return refresh\n const outcome = await within(refresh, budget - (Date.now() - started))\n return outcome.settled ? outcome.value : last.value as T\n }\n\n /** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */\n private checkVersion(now: number): Promise<void> {\n return this.live ? this.live.gate(this.versionTracker, now) : this.versionTracker.refresh(now)\n }\n\n /**\n * Fetches `cacheKey` from the studio and settles the cache with the answer.\n * One per key at a time: reads that arrive while it runs get the same promise,\n * so a slow studio sees one request for a key and not one per visitor.\n *\n * Resolves with the value to serve: the fresh one, or a cached one when the\n * studio failed transiently. Rejects on a definitive answer, or when there is\n * nothing cached to serve in its place.\n */\n private refresh<T>(\n cacheKey: string,\n path: string,\n last: CacheEntry | undefined,\n version: string | undefined,\n isExpected: BodyCheck,\n retry: boolean,\n ): Promise<T> {\n const running = this.inflight.get(cacheKey)\n if (running) return running.job as Promise<T>\n\n let ticket = ++this.state.ticket\n // Whether the slot for this key is still this refresh's own: once retired\n // it is empty, or belongs to the refresh that came after.\n const registered = (): boolean => this.inflight.get(cacheKey)?.job === job\n const register = (): void => {\n this.inflight.set(cacheKey, { job, ticket })\n }\n const job: Promise<T> = (async () => {\n try {\n let res: Awaited<ReturnType<HavenClient['conditionalGet']>>\n try {\n res = await this.conditionalGet(path, last?.etag, isExpected)\n }\n catch (err) {\n // A `502` or `503` is often one bad moment (a proxy switching to a\n // new studio container), and with nothing cached it is all the caller\n // would get. So once more, a moment later. A read is safe to repeat;\n // with a value to fall back on it is served instead, as below.\n const pause = this.gatewayRetry\n if (!retry || pause === undefined || last || this.cache.stale(cacheKey) || !isGatewayHiccup(err)) throw err\n await sleep(pause + Math.random() * pause)\n\n // Another request may have stored a value meanwhile: serve that.\n const meanwhile = this.cache.stale(cacheKey)\n if (meanwhile) return meanwhile.value as T\n // Or the slot went to a refresh that started during the pause, after\n // a newer answer retired this one's: that refresh left later, so its\n // answer is the one to have, and asking alongside it would break the\n // one request per key.\n const slot = this.inflight.get(cacheKey)\n // Returned as it is, not awaited: its outcome is that refresh's own,\n // already settled with the cache there, not a failure of this one.\n if (slot && !registered()) return slot.job as Promise<T>\n\n // The second try leaves now, after anything that left during the\n // pause, so it takes a ticket of its own: under the first one its\n // answer, newer than theirs, would count as older (`storable`). The\n // slot carries it, so an older answer does not retire it (`stored`);\n // emptied meanwhile (an invalidation), it is taken again, so that\n // reads arriving now join this request instead of sending their own.\n // And it reads the stamp as it stands now, before leaving: the\n // answer is at least as new as that.\n ticket = ++this.state.ticket\n if (slot) slot.ticket = ticket\n else register()\n version = this.versionTracker.current() ?? undefined\n res = await this.conditionalGet(path, undefined, isExpected)\n }\n // A `304` is only ever accepted in answer to an etag, so `last` is there.\n if (res.notModified && last) {\n if (this.storable(cacheKey, ticket)) {\n this.cache.confirm(cacheKey, version, Date.now())\n this.stored(cacheKey, ticket)\n }\n return last.value as T\n }\n if (this.storable(cacheKey, ticket)) {\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n this.stored(cacheKey, ticket)\n }\n return res.value as T\n }\n catch (err) {\n // Definitive answer from the studio itself (deleted/forbidden): drop the\n // entry and surface it.\n if (isDefinitive(err)) {\n this.gone(cacheKey, ticket)\n throw err\n }\n // Anything else is transient: studio down, 5xx, timeout, rate limit,\n // network, a body that is not what this endpoint returns, or a 4xx from\n // whatever stands in front of the studio while it is gone. Serve a\n // cached value, even an expired one, and keep it.\n //\n // What the cache holds *now*, not only what it held when this request\n // left: every read that joined gets this same outcome, and one of them\n // may hold a value that was stored in the meantime (by a `cache: false`\n // read, say) while the read that started the request had none. Failing that\n // one with an error it had the content for is exactly what rule 1 forbids.\n const held = this.cache.stale(cacheKey) ?? last\n if (!held) throw err\n this.report({ during: 'read', key: cacheKey, error: err })\n return (this.storable(cacheKey, ticket) ? this.cache.backoff(cacheKey, held, Date.now()) : held).value as T\n }\n finally {\n if (registered()) this.inflight.delete(cacheKey)\n }\n })()\n this.inflight.set(cacheKey, { job, ticket })\n return job\n }\n\n /**\n * Hands an absorbed failure to `onError`, or without one warns once per\n * outage. Never throws and never leaves a rejection behind: a broken hook\n * must not turn a served read into an error, and an `async` hook whose own\n * work fails (an alert that cannot be delivered, during the very outage it\n * reports) must not become the unhandled rejection that stops the process.\n */\n private report(failure: StudioFailure): void {\n const first = !this.state.unreachable\n this.state.unreachable = true\n try {\n if (this.onError) {\n const outcome: unknown = this.onError(failure)\n if (isThenable(outcome)) outcome.then(undefined, () => {})\n }\n else if (first) {\n const reason = failure.error instanceof Error ? failure.error.message : String(failure.error)\n const what = failure.during === 'read' ? `could not refresh \"${failure.key}\"` : 'stamp check failed'\n console.warn(`[@nordhavnhq/beacon] ${what} (${reason}); cached content keeps being served.`)\n }\n }\n catch {\n /* the hook's own problem */\n }\n }\n\n /**\n * A GET that understands conditional requests: sends `If-None-Match` when an\n * etag is supplied, and reports a `304` as `notModified` rather than a value.\n *\n * The one place that decides what counts as an answer, for every read:\n *\n * - A `2xx` whose body fails `isExpected` is rejected, not returned. A\n * maintenance page or a captive portal can answer `200` with JSON of its\n * own; storing that would replace the last good value with nothing, at the\n * very moment the studio is away.\n * - A `304` is only an answer to a request that sent an etag. Unasked for,\n * it says \"keep what you have\" to a caller that has nothing, and there is\n * no value to return or store.\n */\n private async conditionalGet(\n path: string,\n ifNoneMatch: string | undefined,\n isExpected: BodyCheck,\n ): Promise<{ notModified: boolean, value?: unknown, etag?: string }> {\n const url = `${this.baseUrl}/api/content${path}`\n return withTimeout(url, this.timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(ifNoneMatch ? { 'If-None-Match': ifNoneMatch } : {}),\n ...this.headers,\n },\n signal,\n })\n\n if (res.status === 304) {\n if (!ifNoneMatch) throw unexpectedBody(url)\n this.state.unreachable = false\n return { notModified: true, etag: res.headers.get('etag') ?? ifNoneMatch }\n }\n if (!res.ok) throw await this.toError(res)\n const etag = res.headers.get('etag') ?? undefined\n const value: unknown = res.status === 204 ? undefined : await res.json()\n if (!isExpected(value)) throw unexpectedBody(url)\n this.state.unreachable = false\n return { notModified: false, value, etag }\n })\n }\n\n private async request<T>(method: Method, path: string, body?: unknown, timeout = this.timeout): Promise<T> {\n const url = `${this.baseUrl}/api/content${path}`\n return withTimeout(url, timeout, async (signal) => {\n const res = await this.fetchImpl(url, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...this.headers,\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal,\n })\n\n if (!res.ok) throw await this.toError(res)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n })\n }\n\n /** Parse a non-2xx response into a `HavenError`, preferring its message. */\n private async toError(res: Response): Promise<HavenError> {\n let message = res.statusText || `Request failed with status ${res.status}`\n let parsed: unknown\n try {\n parsed = await res.json()\n const m = parsed as { message?: unknown, statusMessage?: unknown }\n if (typeof m?.message === 'string') message = m.message\n else if (typeof m?.statusMessage === 'string') message = m.statusMessage\n } catch {\n /* non-JSON error body; keep the status text */\n }\n const err = new HavenError(message, res.status, parsed)\n if (res.headers.has('retry-after')) askedToWait.add(err)\n return err\n }\n}\n\n/** Fluent, dataset-scoped view returned by `client.dataset()`. */\nexport class DatasetHandle<T = Record<string, unknown>> {\n constructor(\n private readonly client: HavenClient,\n private readonly nodeSlug: string,\n private readonly datasetSlug: string,\n ) {}\n\n list(opts?: ReadOptions): Promise<ContentRecord<T>[]> {\n return this.client.listRecords<T>(this.nodeSlug, this.datasetSlug, opts)\n }\n\n get(recordUid: string, opts?: ReadOptions): Promise<ContentRecord<T>> {\n return this.client.getRecord<T>(this.nodeSlug, this.datasetSlug, recordUid, opts)\n }\n\n create(data: Record<string, unknown>): Promise<ContentRecord<T>> {\n return this.client.createRecord<T>(this.nodeSlug, this.datasetSlug, data)\n }\n\n update(recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>> {\n return this.client.updateRecord<T>(this.nodeSlug, this.datasetSlug, recordUid, data)\n }\n\n /** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */\n uploadFile(fieldSlug: string, file: Blob, opts?: UploadOptions): Promise<UploadedFile> {\n return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts)\n }\n\n /** Clear cached reads for this dataset. */\n clearCache(): void {\n this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug })\n }\n}\n\n// ── Timeout ───────────────────────────────────────────────────────────────────\n\n/**\n * Runs `run` with an abort signal that fires after `ms`, and rejects with a\n * `TimeoutError` at that moment whether or not `run` listens to the signal: a\n * custom `fetch` may ignore it. The timer spans the whole of `run`, so a studio\n * that sends headers and then stalls the body is caught too.\n *\n * The error is a plain `Error`, not a `HavenError`: the read path treats\n * anything without an HTTP status as transient and serves the cache.\n */\nasync function withTimeout<T>(url: string, ms: number, run: (signal?: AbortSignal) => Promise<T>): Promise<T> {\n if (ms <= 0) return run(undefined)\n\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const expired = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const err = new Error(`The studio did not answer within ${ms}ms: ${url}`)\n err.name = 'TimeoutError'\n controller.abort(err)\n reject(err)\n }, ms)\n })\n\n try {\n return await Promise.race([run(controller.signal), expired])\n }\n finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * The `timeout` option as a usable number of ms, `0` for none. `Infinity`, or\n * more than a timer can hold, means \"no timeout\" - handed to `setTimeout` as\n * it is, it would fire after 1 ms and fail every request.\n */\nfunction normalizeTimeout(value: number | undefined): number {\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT\n return value > MAX_TIMER ? 0 : value\n}\n\n/**\n * An upload's timeout in ms, `0` for none. A valid per-call `timeout` wins;\n * otherwise (none, or a negative number or `NaN`, as from an unset\n * environment variable) the client's, but at least `MIN_UPLOAD_TIMEOUT`. A\n * client without a timeout (`0`) uploads without one too.\n */\nfunction uploadTimeout(clientTimeout: number, perCall: number | undefined): number {\n if (typeof perCall === 'number' && perCall >= 0) return normalizeTimeout(perCall)\n return clientTimeout === 0 ? 0 : Math.max(clientTimeout, MIN_UPLOAD_TIMEOUT)\n}\n\n/**\n * The client's extra headers without a `Content-Type`: one set for every\n * request would replace the multipart type and its boundary, and the studio\n * could not read the upload.\n */\nfunction withoutContentType(headers: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'content-type'))\n}\n\n/** `gatewayRetry` in ms, `undefined` when the second try is off. */\nfunction normalizeGatewayRetry(value: number | false | undefined): number | undefined {\n if (value === false) return undefined\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY\n return Math.min(value, MAX_GATEWAY_RETRY)\n}\n\n/** `cache.waitForFresh` in ms, `Infinity` when a read should wait for the studio. */\nfunction normalizeWait(value: number | false | undefined): number {\n if (value === false) return Infinity\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH\n // More than a timer can hold is no budget at all: `within` already waits\n // such a value out, so it is made to mean `false` everywhere, in one place.\n return value > MAX_TIMER ? Infinity : value\n}\n\ntype Settled<T> = { settled: true, value: T } | { settled: false }\n\n/**\n * Waits on `promise` for at most `ms`. Past that it reports \"not settled\" and\n * lets the promise run on; a later rejection is swallowed here, as whoever\n * started the work deals with its outcome. A rejection within `ms` is thrown.\n */\nasync function within<T>(promise: Promise<T>, ms: number): Promise<Settled<T>> {\n if (ms > MAX_TIMER) return { settled: true, value: await promise }\n if (ms <= 0) {\n promise.catch(() => {})\n return { settled: false }\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined\n const late = new Promise<Settled<T>>((resolve) => {\n timer = setTimeout(() => resolve({ settled: false }), ms)\n })\n try {\n return await Promise.race([promise.then((value): Settled<T> => ({ settled: true, value })), late])\n }\n finally {\n clearTimeout(timer)\n }\n}\n\n// ── Response shape ────────────────────────────────────────────────────────────\n\n/** Whether a value is a promise, or anything else that settles later. */\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null | undefined)?.then === 'function'\n}\n\n/** Whether a response body is what its endpoint returns. */\ntype BodyCheck = (body: unknown) => boolean\n\nfunction isObject(value: unknown): boolean {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A body that is an object carrying `field`, with a value that passes `check`. */\nfunction has(field: string, check: (value: unknown) => boolean): BodyCheck {\n return (body) => isObject(body) && field in (body as object) && check((body as Record<string, unknown>)[field])\n}\n\n/**\n * The error for a response its endpoint never gives: a `2xx` with a body of\n * another shape, or a `304` nobody asked for. A plain `Error` without a status,\n * so the read path treats it as transient and serves the cache.\n */\nfunction unexpectedBody(url: string): Error {\n const err = new Error(`The studio answered with an unexpected response: ${url}`)\n err.name = 'UnexpectedResponseError'\n return err\n}\n\n// ── Cache-key + path helpers ──────────────────────────────────────────────────\n\n/**\n * Whether an error status says \"try again later\" rather than \"this is the\n * answer\": server errors, request timeout (408) and rate limiting (429).\n */\nfunction isTransientStatus(status: number): boolean {\n return status >= 500 || status === 408 || status === 429\n}\n\n/**\n * Errors whose response carried `Retry-After`: the studio, or the proxy in\n * front of it, asked to wait, so they are not tried again a moment later.\n * Kept here instead of on the error, which is public API.\n */\nconst askedToWait = new WeakSet<object>()\n\n/**\n * A `502` or `503`: worth one more try a moment later. A `504` already waited,\n * and an answer with `Retry-After` asked not to.\n */\nfunction isGatewayHiccup(err: unknown): boolean {\n return err instanceof HavenError && (err.status === 502 || err.status === 503) && !askedToWait.has(err)\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Whether a failed read is the studio's own definitive answer - this does not\n * exist, this key may not see it - rather than a sign that the studio could\n * not be reached. The only kind of failure that may cost a cached value.\n */\nfunction isDefinitive(err: unknown): err is HavenError {\n return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err)\n}\n\n/**\n * Whether an error response was written by the studio, and not by something\n * answering in its place. While the studio container is gone (a redeploy, a\n * crash) the proxy in front of it answers for it, and often with a `404`:\n * Traefik's `404 page not found`, an HTML error page, a gateway's own JSON.\n * Taking that for \"this record was deleted\" would drop the very entry that\n * should carry the site through the outage.\n *\n * The studio's errors are JSON objects that restate their status\n * (`{ \"statusCode\": 404, \"message\": \"...\" }`); nothing else is trusted to be\n * the studio speaking. `status` is accepted next to `statusCode`, the name\n * newer server frameworks give the same field.\n */\nfunction isStudioAnswer(err: HavenError): boolean {\n return isStudioBody(err.status, err.body)\n}\n\n/**\n * Whether a failed stamp check says \"this studio has no stamp route\": its own\n * `404`, as an older server answers. Not the `404` of a proxy standing in for a\n * studio that is away - that one is an outage like any other.\n */\nfunction isMissingRoute(err: unknown): boolean {\n return err instanceof HavenError && err.status === 404 && isStudioAnswer(err)\n}\n\n/**\n * Whether a failed write may have been stored all the same. Only an answered\n * 4xx rules it out: the request was refused. A timeout, a dropped connection or\n * a 5xx can each follow a write the studio did carry out.\n */\nfunction writeMayHaveLanded(err: unknown): boolean {\n return !(err instanceof HavenError && err.status >= 400 && err.status < 500)\n}\n\nfunction datasetPath(nodeSlug: string, datasetSlug: string): string {\n return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`\n}\n\n/**\n * Maps a requested locale onto one the project is configured with, by the rule\n * the studio applies itself: the exact locale, else one in the same language\n * (`nl` or `nl-NL` for a configured `nl-BE`), else the project's fallback\n * locale. `undefined` means the project default, which is requested by sending\n * no locale at all.\n *\n * With several locales in one language and no exact match, the default locale\n * wins if it is among them, otherwise the first one listed.\n */\nfunction matchLocale(requested: string, locales: ContentLocale[]): string | undefined {\n const canonical = (code: string): string => code.trim().toLowerCase().replace(/_/g, '-')\n const known = locales.filter((locale) => typeof locale?.code === 'string' && locale.code !== '')\n const wanted = canonical(requested)\n\n const exact = known.find((locale) => canonical(locale.code) === wanted)\n if (exact) return exact.code\n\n const language = wanted.split('-')[0]\n const related = known.filter((locale) => canonical(locale.code).split('-')[0] === language)\n const close = related.find((locale) => locale.isDefault) ?? related[0]\n if (close) return close.code\n\n return known.find((locale) => locale.isFallback)?.code\n}\n\n/** `?locale=xx` query suffix, or empty for the default locale. */\nfunction localeQuery(locale?: string): string {\n return locale ? `?locale=${encodeURIComponent(locale)}` : ''\n}\n\n/** Locale cache-key suffix. `::<locale>` keeps each locale a distinct entry;\n * the default locale has no suffix. `::` never collides with a slug. */\nfunction localeKeySuffix(locale?: string): string {\n return locale ? `::${locale}` : ''\n}\n\nfunction recordsKey(nodeSlug: string, datasetSlug: string, locale?: string): string {\n return `records:${nodeSlug}/${datasetSlug}${localeKeySuffix(locale)}`\n}\n\nfunction recordKey(nodeSlug: string, datasetSlug: string, recordUid: string, locale?: string): string {\n return `record:${nodeSlug}/${datasetSlug}/${recordUid}${localeKeySuffix(locale)}`\n}\n","/**\n * The chart contract: what a chart block is (`ChartSpec`, as authored and\n * stored) and what a renderer draws (`ChartData`, the resolved categories and\n * series). Shared by the Nordhavn OS server, the client and every renderer, so a\n * chart means the same thing wherever it is read. Pure data: no dependencies.\n * The zod schemas for these shapes live in `@nordhavnhq/beacon/schema`.\n */\n\n/**\n * The palette a series colour may pick from. A renderer maps a key to a colour\n * of the theme it runs in; a spec never carries a raw hex.\n */\nexport const PALETTE_KEYS = ['ember', 'aurora', 'crimson', 'dusk', 'jade', 'cobalt', 'iris', 'nebula'] as const\nexport type PaletteKey = typeof PALETTE_KEYS[number]\n\nexport const CHART_TYPES = ['bar', 'bar-horizontal', 'line', 'area', 'pie', 'donut', 'share', 'heatmap'] as const\nexport type ChartType = typeof CHART_TYPES[number]\n\n/**\n * How a chart reads its data: `cartesian` plots each series over the\n * categories, `part` cuts one series into its categories (one whole), `matrix`\n * is a grid of the categories (columns) by the series (rows).\n */\nexport type ChartFamily = 'cartesian' | 'part' | 'matrix'\n\n/** What a chart type is and takes: every editor, parser and renderer reads it from here. */\nexport interface ChartTypeInfo {\n value: ChartType\n label: string\n /** One line on what the type is for (editor hint, agent docs). */\n purpose: string\n /** A lucide icon name (kebab-case); the host maps it to its icon set. */\n icon: string\n family: ChartFamily\n /** Exactly one series (the parts are the categories). */\n singleSeries: boolean\n /** Series may sit on a left or right value axis. */\n axes: boolean\n /** Series may stack. */\n stacked: boolean\n /** Each series wears its own colour (else one hue in tints). */\n seriesColors: boolean\n /** Value labels on the marks are possible. */\n valueLabels: boolean\n /** Drawn as HTML that sizes to its content, not into a fixed canvas box. */\n html: boolean\n /** Default box height in px. */\n height: number\n}\n\nexport const CHART_TYPE_INFO: Record<ChartType, ChartTypeInfo> = {\n 'bar': {\n value: 'bar', label: 'Bar', icon: 'chart-column', family: 'cartesian',\n purpose: 'Compare values across categories or periods.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: true, html: false, height: 300,\n },\n 'bar-horizontal': {\n value: 'bar-horizontal', label: 'Bar (horizontal)', icon: 'chart-bar', family: 'cartesian',\n purpose: 'Rank categories with long labels, largest on top when sorted by value.',\n singleSeries: false, axes: false, stacked: true, seriesColors: true, valueLabels: true, html: false, height: 300,\n },\n 'line': {\n value: 'line', label: 'Line', icon: 'chart-line', family: 'cartesian',\n purpose: 'A trend over time.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: false, html: false, height: 300,\n },\n 'area': {\n value: 'area', label: 'Area', icon: 'chart-area', family: 'cartesian',\n purpose: 'A trend over time with its volume.',\n singleSeries: false, axes: true, stacked: true, seriesColors: true, valueLabels: false, html: false, height: 300,\n },\n 'pie': {\n value: 'pie', label: 'Pie', icon: 'chart-pie', family: 'part',\n purpose: 'Parts of one whole, few slices.',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: false, height: 260,\n },\n 'donut': {\n value: 'donut', label: 'Donut', icon: 'circle-dashed', family: 'part',\n purpose: 'Parts of one whole around a centred total (status, category breakdown).',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: false, height: 260,\n },\n 'share': {\n value: 'share', label: 'Share bars', icon: 'align-left', family: 'part',\n purpose: 'Parts of one whole as ranked thin bars with figure and percentage; reads well with many parts.',\n singleSeries: true, axes: false, stacked: false, seriesColors: false, valueLabels: false, html: true, height: 260,\n },\n 'heatmap': {\n value: 'heatmap', label: 'Heatmap', icon: 'grid-3x3', family: 'matrix',\n purpose: 'A grid of the categories (columns) by the series (rows), one hue from faint to full.',\n singleSeries: false, axes: false, stacked: false, seriesColors: false, valueLabels: true, html: false, height: 300,\n },\n}\n\nexport function chartTypeInfo(type: ChartType): ChartTypeInfo {\n return CHART_TYPE_INFO[type] ?? CHART_TYPE_INFO.bar\n}\n\n/** Pie, donut and share: one series cut into its categories. */\nexport function isPartChart(type: ChartType): boolean {\n return chartTypeInfo(type).family === 'part'\n}\n\n/** Bar in either direction. */\nexport function isBarChart(type: ChartType): boolean {\n return type === 'bar' || type === 'bar-horizontal'\n}\n\n/** Which Y axis a series scales against. Only for the types with `axes`. */\nexport const CHART_AXES = ['left', 'right'] as const\nexport type ChartAxis = typeof CHART_AXES[number]\n\n/** Periods a date category can be grouped into. */\nexport const DATE_BUCKET_VALUES = ['day', 'week', 'month', 'quarter', 'year'] as const\nexport type DateBucket = typeof DATE_BUCKET_VALUES[number]\n\n/** `auto` picks the period from the date range. */\nexport const BUCKET_MODES = ['auto', ...DATE_BUCKET_VALUES] as const\nexport type BucketMode = typeof BUCKET_MODES[number]\n\n/** How the records that fall in one category combine into one point. */\nexport const AGGREGATIONS = ['sum', 'avg', 'count', 'min', 'max', 'first', 'last'] as const\nexport type Aggregation = typeof AGGREGATIONS[number]\n\n/** Category order. `default` is chronological for dates, source order otherwise. */\nexport const CHART_SORTS = ['default', 'category-asc', 'category-desc', 'value-desc', 'value-asc'] as const\nexport type ChartSort = typeof CHART_SORTS[number]\n\nexport interface ChartSeriesSpec {\n /** Field slug whose numeric value is the Y value. */\n field: string\n label?: string\n /** Omitted: the next colour of the renderer's default rotation. */\n color?: PaletteKey\n axis: ChartAxis\n aggregate: Aggregation\n}\n\n/** A chart as authored and stored: where its data comes from and how it is shaped. */\nexport interface ChartSpec {\n title: string\n chartType: ChartType\n /** A dataset (`node.dataset`) or a saved query (`queries.<slug>`). */\n source: string\n /** Field slug for the X axis or the slice labels. */\n categoryField: string\n /**\n * Field slug to split the first series by: one series per distinct value of\n * this field (top 12 by record count, the rest as \"Other\"). The rows of a\n * heatmap, the stacks of a bar. Empty: the series are the value fields.\n */\n splitField: string\n series: ChartSeriesSpec[]\n /** Date categories only. */\n bucket: BucketMode\n sort: ChartSort\n /** Keep the top N categories, the rest becomes \"Other\". 0 is no limit. Non-date only. */\n limit: number\n /** Date buckets only: emit empty periods so a line stays continuous. */\n fillGaps: boolean\n stacked: boolean\n legend: boolean\n}\n\nexport interface ChartSeriesData {\n name: string\n /** One value per category; null is a gap (nothing measured there). */\n data: Array<number | null>\n /** A palette key or any CSS colour the host resolved. */\n color?: string\n axis?: ChartAxis\n}\n\n/** A chart as a renderer draws it: the data already resolved and consolidated. */\nexport interface ChartData {\n type: ChartType\n categories: string[]\n series: ChartSeriesData[]\n stacked?: boolean\n legend?: boolean\n}\n","/**\n * The ```chart fence: a chart written inline in markdown, as JSON in the\n * shape a renderer draws (`ChartData`) plus a title. One parser for every\n * reader: the Nordhavn OS server validates a save with it, the markdown renderer\n * draws what it returns, the PDF export rasterises it, a site can use it too.\n * Pure and dependency-free.\n *\n * A `{{ expr }}` signal may stand where a number goes (`\"data\": [{{ a.b }}, 4]`).\n * The host fills it in before parsing; whatever is still left reads as a gap\n * (null), so a document never fails to save or print on a signal.\n */\nimport { CHART_AXES, CHART_TYPES, PALETTE_KEYS, chartTypeInfo, type ChartData, type ChartSeriesData } from './chart'\n\n/** The fence language. */\nexport const CHART_FENCE_LANG = 'chart'\n\nexport const CHART_FENCE_LIMITS = {\n categories: 100,\n series: 12,\n label: 120,\n title: 200,\n minHeight: 120,\n maxHeight: 600,\n} as const\n\n/** A chart as a ```chart fence carries it. */\nexport interface ChartFence extends ChartData {\n title?: string\n /** Box height in px; the renderer's default when omitted. */\n height?: number\n /** Value labels on the marks (bar types and heatmap). */\n valueLabels?: boolean\n}\n\nexport type ChartFenceResult = { ok: true, chart: ChartFence } | { ok: false, error: string }\n\nconst SIGNAL_RE = /\\{\\{[\\s\\S]*?\\}\\}/g\n\n/** Box height of a fenced chart in px: its own `height`, else a default per type. */\nexport function chartFenceHeight(chart: Pick<ChartFence, 'type' | 'height'>): number {\n if (chart.height) return chart.height\n return chartTypeInfo(chart.type).height\n}\n\n/** True for the language of a ```chart fence (case-insensitive, options after it ignored). */\nexport function isChartFence(lang: string | null | undefined): boolean {\n return (lang ?? '').trim().split(/\\s+/)[0]?.toLowerCase() === CHART_FENCE_LANG\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\nfunction oneOf<T extends string>(list: readonly T[], v: unknown): v is T {\n return typeof v === 'string' && (list as readonly string[]).includes(v)\n}\n\nfunction label(v: unknown, what: string, max: number = CHART_FENCE_LIMITS.label): string {\n if (typeof v === 'number' && Number.isFinite(v)) return String(v)\n if (typeof v !== 'string') throw new Error(`${what} must be a string`)\n if (v.length > max) throw new Error(`${what} is longer than ${max} characters`)\n return v\n}\n\nfunction parseSeries(raw: unknown, i: number, size: number): ChartSeriesData {\n const at = `series[${i}]`\n if (!isRecord(raw)) throw new Error(`${at} must be an object with \"name\" and \"data\"`)\n if (!Array.isArray(raw.data)) throw new Error(`${at}.data must be an array of numbers`)\n if (raw.data.length !== size) throw new Error(`${at}.data has ${raw.data.length} values, \"categories\" has ${size}: one value per category`)\n const data = raw.data.map((v, j) => {\n if (v === null) return null\n if (typeof v === 'number' && Number.isFinite(v)) return v\n throw new Error(`${at}.data[${j}] must be a number or null, got ${JSON.stringify(v)}`)\n })\n const out: ChartSeriesData = { name: raw.name === undefined ? `Series ${i + 1}` : label(raw.name, `${at}.name`), data }\n if (raw.color !== undefined) {\n if (!oneOf(PALETTE_KEYS, raw.color)) throw new Error(`${at}.color must be one of ${PALETTE_KEYS.join(', ')}`)\n out.color = raw.color\n }\n if (raw.axis !== undefined) {\n if (!oneOf(CHART_AXES, raw.axis)) throw new Error(`${at}.axis must be ${CHART_AXES.join(' or ')}`)\n out.axis = raw.axis\n }\n return out\n}\n\nfunction parseShape(raw: unknown): ChartFence {\n if (!isRecord(raw)) throw new Error('The fence must hold one JSON object')\n if (!oneOf(CHART_TYPES, raw.type)) throw new Error(`\"type\" must be one of ${CHART_TYPES.join(', ')}`)\n if (!Array.isArray(raw.categories) || raw.categories.length === 0) throw new Error('\"categories\" must be a non-empty array of labels')\n if (raw.categories.length > CHART_FENCE_LIMITS.categories) throw new Error(`\"categories\" has ${raw.categories.length} entries, at most ${CHART_FENCE_LIMITS.categories}`)\n const categories = raw.categories.map((c, i) => label(c, `categories[${i}]`))\n if (!Array.isArray(raw.series) || raw.series.length === 0) throw new Error('\"series\" must be a non-empty array')\n if (raw.series.length > CHART_FENCE_LIMITS.series) throw new Error(`\"series\" has ${raw.series.length} entries, at most ${CHART_FENCE_LIMITS.series}`)\n if (chartTypeInfo(raw.type).singleSeries && raw.series.length !== 1) throw new Error(`A ${raw.type} takes exactly one series (the parts are the categories)`)\n const series = raw.series.map((s, i) => parseSeries(s, i, categories.length))\n\n const chart: ChartFence = { type: raw.type, categories, series }\n if (raw.title !== undefined) chart.title = label(raw.title, '\"title\"', CHART_FENCE_LIMITS.title)\n for (const key of ['stacked', 'legend', 'valueLabels'] as const) {\n if (raw[key] === undefined) continue\n if (typeof raw[key] !== 'boolean') throw new Error(`\"${key}\" must be true or false`)\n chart[key] = raw[key]\n }\n if (raw.height !== undefined) {\n const h = raw.height\n if (typeof h !== 'number' || h < CHART_FENCE_LIMITS.minHeight || h > CHART_FENCE_LIMITS.maxHeight) {\n throw new Error(`\"height\" must be a number from ${CHART_FENCE_LIMITS.minHeight} to ${CHART_FENCE_LIMITS.maxHeight}`)\n }\n chart.height = Math.round(h)\n }\n return chart\n}\n\n/** The chart in a ```chart fence body, or what is wrong with it (one line an author can act on). */\nexport function parseChartFence(source: string): ChartFenceResult {\n const text = source.replace(SIGNAL_RE, 'null').trim()\n if (!text) return { ok: false, error: 'Empty chart fence' }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n }\n catch (err) {\n return { ok: false, error: `Not valid JSON: ${err instanceof Error ? err.message : String(err)}` }\n }\n try {\n return { ok: true, chart: parseShape(raw) }\n }\n catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n }\n}\n","export { HavenClient, DatasetHandle, DEFAULT_BASE_URL } from './client'\nexport type { HavenClientOptions, ReadOptions, UploadOptions, StudioFailure } from './client'\nexport { HavenError } from './errors'\nexport { ContentCache, MemoryCacheStore } from './cache'\nexport type { CacheOptions, CacheStore, CacheEntry } from './cache'\nexport type {\n ContentSchema,\n SchemaNode,\n SchemaDataset,\n SchemaField,\n FieldKind,\n FieldType,\n ContentRecord,\n ContentLocale,\n QueryResult,\n QueryShape,\n UploadedFile,\n} from './types'\nexport {\n PALETTE_KEYS,\n CHART_TYPES,\n CHART_TYPE_INFO,\n chartTypeInfo,\n isPartChart,\n isBarChart,\n CHART_AXES,\n DATE_BUCKET_VALUES,\n BUCKET_MODES,\n AGGREGATIONS,\n CHART_SORTS,\n} from './chart'\nexport type {\n PaletteKey,\n ChartType,\n ChartFamily,\n ChartTypeInfo,\n ChartAxis,\n DateBucket,\n BucketMode,\n Aggregation,\n ChartSort,\n ChartSeriesSpec,\n ChartSpec,\n ChartSeriesData,\n ChartData,\n} from './chart'\nexport { CHART_FENCE_LANG, CHART_FENCE_LIMITS, chartFenceHeight, isChartFence, parseChartFence } from './chart-fence'\nexport type { ChartFence, ChartFenceResult } from './chart-fence'\nexport type {\n RoadmapPhaseState,\n RoadmapWorkState,\n RoadmapTone,\n RoadmapTip,\n RoadmapPhase,\n RoadmapLane,\n RoadmapMilestone,\n RoadmapWaiting,\n RoadmapTask,\n RoadmapRepeat,\n RoadmapHappening,\n RoadmapEvent,\n RoadmapData,\n ForecastSeries,\n} from './roadmap'\n\nimport { HavenClient, type HavenClientOptions } from './client'\n\n/** Convenience factory: `createClient({ apiKey, baseUrl })`. */\nexport function createClient(options: HavenClientOptions): HavenClient {\n return new HavenClient(options)\n}\n"]}