@nordhavnhq/beacon 0.4.1 → 0.5.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.
- package/LICENSE +21 -0
- package/dist/cache-q8uLEGYg.d.cts +165 -0
- package/dist/cache-q8uLEGYg.d.ts +165 -0
- package/dist/file-store.cjs +148 -0
- package/dist/file-store.cjs.map +1 -0
- package/dist/file-store.d.cts +47 -0
- package/dist/file-store.d.ts +47 -0
- package/dist/file-store.js +146 -0
- package/dist/file-store.js.map +1 -0
- package/dist/index.cjs +621 -107
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +240 -130
- package/dist/index.d.ts +240 -130
- package/dist/index.js +621 -107
- package/dist/index.js.map +1 -1
- package/package.json +41 -9
package/dist/index.cjs.map
CHANGED
|
@@ -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":["res"],"mappings":";;;AA4EO,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,IAA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AA,EAAO,kBAAA,CAAmB,SAAS,CAAA,CAAE,CAAA;AAAA,IACrH;AACA,IAAA,KAAA,CAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AAAA,EAC7B;AACA,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,gBAAgB,MAAA,EAAkC;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;;;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\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 is really the outage window: how long the site keeps serving the\n * last-known content while the studio is unreachable, before an entry is\n * dropped and a read must hit the network again. A generous default so a\n * studio outage degrades to \"slightly stale\" rather than \"site errors\".\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. `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 /** 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/** 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 private store: CacheStore\n\n constructor(opts: CacheOptions = {}) {\n this.enabled = opts.enabled ?? true\n this.ttl = opts.ttl ?? 604_800_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 peek(key: string, now: number): CacheEntry | undefined {\n if (!this.enabled) return undefined\n const entry = this.store.get(key)\n if (!entry) return undefined\n if (entry.expiresAt !== 0 && entry.expiresAt <= now) {\n this.store.delete(key)\n return undefined\n }\n return entry\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 this.store.set(key, entry)\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\nexport class VersionTracker {\n private lastChecked = 0\n private version: string | null = null\n private inFlight: Promise<void> | null = null\n /** Set when the server has no version route, so we stop asking. */\n private unsupported = false\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\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 async refresh(now: number): Promise<void> {\n if (this.interval <= 0 || this.unsupported) return\n if (this.inFlight) return this.inFlight\n if (this.version !== null && now - this.lastChecked < this.interval) return\n\n this.lastChecked = now\n this.inFlight = this.run()\n try {\n await this.inFlight\n }\n finally {\n this.inFlight = null\n }\n }\n\n private async run(): Promise<void> {\n try {\n this.version = await this.probe()\n }\n catch (err) {\n // A server that predates the version route will never answer; stop\n // asking. Any other failure is transient - keep the last stamp so the\n // cache keeps serving, and try again next interval.\n if ((err as { status?: number })?.status === 404) this.unsupported = true\n }\n }\n}\n","import { ContentCache, 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\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 /** 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 * Untranslated fields fall back to the default locale.\n */\n locale?: string\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 /** Not readonly: `forRequest` hands its clone the SAME cache instance. */\n private cache: ContentCache\n private versionTracker: VersionTracker\n /** `false` on a preview-scoped clone, so reads bypass the cache by default. */\n private readDefault: boolean\n /** Client-level default locale for reads (undefined = project default). */\n private readonly locale?: string\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 (Node < 18)')\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\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\n const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false\n ? 0\n : cacheOptions.revalidate ?? 60_000\n this.versionTracker = new VersionTracker(\n async () => (await this.request<{ version: string }>('GET', '/version')).version,\n revalidate,\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 const clone = new HavenClient({\n apiKey: this.apiKey,\n baseUrl: this.baseUrl,\n fetch: this.fetchImpl,\n headers: this.headers,\n locale: this.locale,\n preview: true,\n })\n // Share the cache and the version tracker: the preview must refresh what the\n // public site reads, not maintain a second universe of its own.\n clone.cache = this.cache\n clone.versionTracker = this.versionTracker\n return clone\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)\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)\n return res.locales\n }\n\n /** Resolve the locale for a read: per-call override, else the client default. */\n private resolveLocale(opts?: ReadOptions): string | undefined {\n const l = opts && 'locale' in opts ? opts.locale : this.locale\n return l || undefined\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 = this.resolveLocale(opts)\n const res = await this.cachedGet<{ records: ContentRecord<T>[] }>(\n recordsKey(nodeSlug, datasetSlug, locale),\n datasetPath(nodeSlug, datasetSlug) + localeQuery(locale),\n opts,\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 = this.resolveLocale(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 )\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.request<{ record: ContentRecord<T> }>(\n 'POST',\n datasetPath(nodeSlug, datasetSlug),\n { data },\n )\n this.invalidateDataset(nodeSlug, datasetSlug)\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.request<{ record: ContentRecord<T> }>(\n 'PATCH',\n `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}`,\n { data },\n )\n this.invalidateDataset(nodeSlug, datasetSlug)\n this.cache.delete(recordKey(nodeSlug, datasetSlug, recordUid))\n return res.record\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 )\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 */\n clearCache(scope?: string | { node: string, dataset?: string }): void {\n if (scope === undefined) {\n this.cache.clear()\n return\n }\n if (typeof scope === 'string') {\n this.cache.deletePrefix(`records:${scope}/`)\n this.cache.deletePrefix(`record:${scope}/`)\n return\n }\n if (scope.dataset) {\n this.invalidateDataset(scope.node, scope.dataset)\n } else {\n this.cache.deletePrefix(`records:${scope.node}/`)\n this.cache.deletePrefix(`record:${scope.node}/`)\n }\n }\n\n /** Drop cached record reads for a dataset (every locale), plus all query\n * results (which may aggregate it). */\n private invalidateDataset(nodeSlug: string, datasetSlug: string): void {\n // Default-locale list key + every `::<locale>` variant of it.\n this.cache.delete(recordsKey(nodeSlug, datasetSlug))\n this.cache.deletePrefix(`${recordsKey(nodeSlug, datasetSlug)}::`)\n // All single-record keys under the dataset (every uid, every locale).\n this.cache.deletePrefix(`${recordKey(nodeSlug, datasetSlug, '')}`)\n this.cache.deletePrefix('query:')\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. If the\n * studio is unreachable, the last good value is served rather than failing\n * (unless it is a definitive 4xx like a deleted record).\n */\n private async cachedGet<T>(cacheKey: string, path: string, opts?: ReadOptions): Promise<T> {\n const useCache = opts?.cache ?? this.readDefault\n\n // Preview / explicit bypass: always fetch fresh, but still refresh the shared\n // cache so real visitors benefit from the warm entry.\n if (!useCache) {\n const res = await this.conditionalGet(path)\n this.cache.set(cacheKey, res.value, { etag: res.etag, version: this.versionTracker.current() ?? undefined }, Date.now())\n return res.value as T\n }\n\n // Cheap, throttled: at most one tiny stamp request per `revalidate` window.\n await this.versionTracker.refresh(Date.now())\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 // The stamp moved: revalidate just this entry against the studio.\n try {\n const res = await this.conditionalGet(path, entry.etag)\n if (res.notModified) {\n this.cache.confirm(cacheKey, version, Date.now())\n return entry.value as T\n }\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n return res.value as T\n }\n catch (err) {\n // Definitive answer (deleted/forbidden): drop the entry and surface it.\n // Transient (studio down, 5xx, network): serve the last good value.\n if (err instanceof HavenError && err.status < 500) {\n this.cache.delete(cacheKey)\n throw err\n }\n return entry.value as T\n }\n }\n\n // Cache miss: fetch fresh. Nothing to fall back to, so errors propagate.\n const res = await this.conditionalGet(path)\n this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now())\n return res.value as T\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 private async conditionalGet(\n path: string,\n ifNoneMatch?: string,\n ): Promise<{ notModified: boolean, value?: unknown, etag?: string }> {\n const res = await this.fetchImpl(`${this.baseUrl}/api/content${path}`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n ...(ifNoneMatch ? { 'If-None-Match': ifNoneMatch } : {}),\n ...this.headers,\n },\n })\n\n if (res.status === 304) return { notModified: true, etag: res.headers.get('etag') ?? ifNoneMatch ?? undefined }\n if (!res.ok) throw await this.toError(res)\n const etag = res.headers.get('etag') ?? undefined\n if (res.status === 204) return { notModified: false, value: undefined, etag }\n return { notModified: false, value: await res.json(), etag }\n }\n\n private async request<T>(method: Method, path: string, body?: unknown): Promise<T> {\n const res = await this.fetchImpl(`${this.baseUrl}/api/content${path}`, {\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 })\n\n if (!res.ok) throw await this.toError(res)\n if (res.status === 204) return undefined as T\n return res.json() as Promise<T>\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 return new HavenError(message, res.status, parsed)\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// ── Cache-key + path helpers ──────────────────────────────────────────────────\n\nfunction datasetPath(nodeSlug: string, datasetSlug: string): string {\n return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`\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 } 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/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,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MAAA,MAAM,IAAI,MAAM,CAAA,+BAAA,EAAkC,kBAAA,CAAmB,SAAS,CAAA,IAAA,EAAO,kBAAA,CAAmB,SAAS,CAAA,CAAE,CAAA;AAAA,IACrH;AACA,IAAA,KAAA,CAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AAAA,EAC7B;AACA,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,gBAAgB,MAAA,EAAkC;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;;;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"]}
|