@nordhavnhq/beacon 0.4.0 → 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/dist/index.d.cts CHANGED
@@ -1,121 +1,8 @@
1
+ import { b as CacheOptions } from './cache-q8uLEGYg.cjs';
2
+ export { a as CacheEntry, C as CacheStore, c as ContentCache, M as MemoryCacheStore } from './cache-q8uLEGYg.cjs';
1
3
  import { C as ChartData } from './chart-CxtDbYAs.cjs';
2
4
  export { A as AGGREGATIONS, a as Aggregation, B as BUCKET_MODES, b as BucketMode, c as CHART_AXES, d as CHART_SORTS, e as CHART_TYPES, f as CHART_TYPE_INFO, g as ChartAxis, h as ChartFamily, i as ChartSeriesData, j as ChartSeriesSpec, k as ChartSort, l as ChartSpec, m as ChartType, n as ChartTypeInfo, D as DATE_BUCKET_VALUES, o as DateBucket, P as PALETTE_KEYS, p as PaletteKey, q as chartTypeInfo, r as isBarChart, s as isPartChart } from './chart-CxtDbYAs.cjs';
3
5
 
4
- /**
5
- * Read caching for the content client. GET responses (schema, record lists,
6
- * single records, queries) are cached by request key and kept fresh by
7
- * conditional revalidation: each entry stores the studio's `ETag`, which the
8
- * client sends back as `If-None-Match`. A cheap project-wide stamp gates whether
9
- * a revalidation is even attempted, so a stable site serves straight from cache.
10
- *
11
- * Swap in a custom `CacheStore` to share a cache across client instances or to
12
- * back it with something persistent.
13
- */
14
- interface CacheEntry {
15
- value: unknown;
16
- /**
17
- * The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`
18
- * to revalidate: a `304` means the stored value is still current.
19
- */
20
- etag?: string;
21
- /**
22
- * The project stamp this entry was last confirmed current against. When it
23
- * equals the client's latest known stamp, the entry is served without any
24
- * network call at all.
25
- */
26
- validatedVersion?: string;
27
- /** Epoch ms when the entry expires. `0` means it never expires. */
28
- expiresAt: number;
29
- }
30
- /** Pluggable backing store. The default is an in-memory, insertion-ordered map. */
31
- interface CacheStore {
32
- get(key: string): CacheEntry | undefined;
33
- set(key: string, entry: CacheEntry): void;
34
- delete(key: string): void;
35
- /** Iterate current keys (used for prefix invalidation). */
36
- keys(): Iterable<string>;
37
- clear(): void;
38
- }
39
- interface CacheOptions {
40
- /** Master switch. Default `true`. */
41
- enabled?: boolean;
42
- /**
43
- * How long a cached entry survives, in ms. Default `604800000` (7 days).
44
- *
45
- * This is NOT how long until content refreshes - revalidation keeps entries
46
- * current within `revalidate` (seconds) whenever the studio is reachable. The
47
- * TTL is really the outage window: how long the site keeps serving the
48
- * last-known content while the studio is unreachable, before an entry is
49
- * dropped and a read must hit the network again. A generous default so a
50
- * studio outage degrades to "slightly stale" rather than "site errors".
51
- *
52
- * The one case where it bounds staleness directly is when revalidation is off
53
- * (`revalidate: false`) or the server has no `/version` endpoint: then content
54
- * can be up to `ttl` old. `0` = never expire.
55
- */
56
- ttl?: number;
57
- /**
58
- * Minimum ms between two project-stamp checks. Default `60000` (1 minute) -
59
- * this is the freshness window for PUBLIC visitors (an edit is picked up on
60
- * the next check after it lands); an editor viewing a surface preview bypasses
61
- * the cache entirely and always sees changes instantly.
62
- *
63
- * The check fires only on a read and is throttled, so a quiet site barely
64
- * checks at all; the interval only caps the busy case. Each check costs the
65
- * studio a small API-key lookup, so raise it (a few minutes) if you run many
66
- * frontends; lower it for a tighter public window. `false` disables checking
67
- * and leaves you with pure TTL expiry.
68
- */
69
- revalidate?: number | false;
70
- /** Soft cap on entries; oldest are evicted first. Default `500`. */
71
- maxEntries?: number;
72
- /** Custom backing store. Defaults to an in-memory store. */
73
- store?: CacheStore;
74
- }
75
- /** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */
76
- declare class MemoryCacheStore implements CacheStore {
77
- private maxEntries;
78
- private map;
79
- constructor(maxEntries?: number);
80
- get(key: string): CacheEntry | undefined;
81
- set(key: string, entry: CacheEntry): void;
82
- delete(key: string): void;
83
- keys(): Iterable<string>;
84
- clear(): void;
85
- }
86
- /**
87
- * Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation
88
- * bookkeeping (etag + validated stamp), and prefix invalidation, so the client
89
- * only deals in cache keys.
90
- */
91
- declare class ContentCache {
92
- readonly enabled: boolean;
93
- private ttl;
94
- private store;
95
- constructor(opts?: CacheOptions);
96
- /**
97
- * The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the
98
- * whole entry (value + etag + validated stamp) so the client can decide
99
- * whether to serve it, revalidate it, or fall back to it on error.
100
- */
101
- peek(key: string, now: number): CacheEntry | undefined;
102
- /** Store a freshly fetched value with its validator and the stamp it is current against. */
103
- set(key: string, value: unknown, opts: {
104
- etag?: string;
105
- version?: string;
106
- }, now: number): void;
107
- /**
108
- * Record that an existing entry is still current as of `version` (after a
109
- * `304`), refreshing its TTL without touching the value. No-op if it is gone.
110
- */
111
- confirm(key: string, version: string | undefined, now: number): void;
112
- /** Drop one exact key. */
113
- delete(key: string): void;
114
- /** Drop every key that starts with `prefix`. */
115
- deletePrefix(prefix: string): void;
116
- clear(): void;
117
- }
118
-
119
6
  /**
120
7
  * Wire types for the Nordhavn OS content API. These mirror the server DTOs
121
8
  * (`server/utils/content/*`, `server/api/content/*`) one-to-one. Slugs are used
@@ -206,6 +93,18 @@ interface QueryResult<V = unknown> {
206
93
  declare const PREVIEW_PARAM = "sl-preview";
207
94
  /** Hosted Nordhavn OS platform. Used when no `baseUrl` is provided. */
208
95
  declare const DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
96
+ /** A studio failure the client absorbed, handed to `onError`. */
97
+ interface StudioFailure {
98
+ /**
99
+ * What failed: the periodic `stamp-check`, or the `read` that refreshes one
100
+ * cache entry (its cached value was served instead).
101
+ */
102
+ during: 'stamp-check' | 'read';
103
+ /** Cache key of the entry that could not be refreshed. Only for `read`. */
104
+ key?: string;
105
+ /** What went wrong: a `HavenError`, a `TimeoutError`, a network error. */
106
+ error: unknown;
107
+ }
209
108
  interface HavenClientOptions {
210
109
  /**
211
110
  * Project API key, `slk_...`. Mint one in the project's settings under
@@ -229,6 +128,43 @@ interface HavenClientOptions {
229
128
  cache?: boolean | CacheOptions;
230
129
  /** Custom `fetch` implementation. Defaults to the global `fetch`. */
231
130
  fetch?: typeof fetch;
131
+ /**
132
+ * Give up on a request after this many ms, body included. Default `10000`.
133
+ * `0` disables it, as does `Infinity`.
134
+ *
135
+ * Without one, a studio that accepts the connection but never answers holds
136
+ * every read until the runtime gives up (minutes, in Node). A timed-out read
137
+ * counts as transient, like a `5xx`: the last good value is served. The
138
+ * once-a-minute stamp check uses at most 3 seconds of it, as every read in
139
+ * that moment waits on the check.
140
+ *
141
+ * It covers writes too. A write that times out may still have reached the
142
+ * studio, so do not blindly send it again: you could store it twice.
143
+ */
144
+ timeout?: number;
145
+ /**
146
+ * A read with nothing cached that gets a `502` or `503` tries once more after
147
+ * this many ms, plus up to as many again at random (so the reads of one page
148
+ * do not all come back at once). Default `200`. `false` turns it off.
149
+ *
150
+ * Often one bad moment, such as a proxy switching to a new studio container;
151
+ * and with nothing cached the error is all the caller would get. Never for a
152
+ * read with a value cached (that value is served), a preview or
153
+ * `cache: false` read, a write, or an answer carrying `Retry-After`.
154
+ */
155
+ gatewayRetry?: number | false;
156
+ /**
157
+ * Called for every studio failure the client absorbs: a failed stamp check,
158
+ * or a read answered from the cache because its refresh failed. These never
159
+ * reach your code as an error, so this is the only place to notice that the
160
+ * site is running on cached content. Errors that are thrown to the caller
161
+ * (a read with nothing cached, a write) are not repeated here.
162
+ *
163
+ * At most one call per stamp check and one per cache entry per retry pause,
164
+ * so it is safe to log or alert from. Without it the client logs one
165
+ * `console.warn` per outage.
166
+ */
167
+ onError?: (failure: StudioFailure) => void;
232
168
  /** Extra headers merged into every request. */
233
169
  headers?: Record<string, string>;
234
170
  /**
@@ -244,10 +180,13 @@ interface ReadOptions {
244
180
  cache?: boolean;
245
181
  /**
246
182
  * Locale for this read, overriding the client-level `locale`. Pass an empty
247
- * string to force the project default even when a client locale is set.
248
- * Untranslated fields fall back to the default locale.
183
+ * string to force the project default even when a client locale is set;
184
+ * `undefined` or `null` (a missing header, from `headers.get()`) leaves the
185
+ * client locale in place. Untranslated fields fall back to the default
186
+ * locale. Only record reads use it (`listRecords`, `getRecord`, a dataset's
187
+ * `list` and `get`); `query()`, `schema()`, `nodes()` and `locales()` ignore it.
249
188
  */
250
- locale?: string;
189
+ locale?: string | null | undefined;
251
190
  }
252
191
  /**
253
192
  * Typed client for the Nordhavn OS content API: read and write a project's node
@@ -264,13 +203,38 @@ declare class HavenClient {
264
203
  private readonly baseUrl;
265
204
  private readonly fetchImpl;
266
205
  private readonly headers;
267
- /** Not readonly: `forRequest` hands its clone the SAME cache instance. */
268
- private cache;
269
- private versionTracker;
270
- /** `false` on a preview-scoped clone, so reads bypass the cache by default. */
206
+ private readonly cache;
207
+ private readonly versionTracker;
208
+ /**
209
+ * `false` on a preview view (see `forRequest`), so reads bypass the cache by
210
+ * default. The one field such a view has of its own; all the rest is shared.
211
+ */
271
212
  private readDefault;
272
213
  /** Client-level default locale for reads (undefined = project default). */
273
214
  private readonly locale?;
215
+ /** Request timeout in ms, `0` for none. */
216
+ private readonly timeout;
217
+ /** `cache.waitForFresh` in ms, `Infinity` to wait for the studio. */
218
+ private readonly waitForFresh;
219
+ /** `gatewayRetry` in ms, `undefined` when it is off. */
220
+ private readonly gatewayRetry;
221
+ /**
222
+ * The refresh under way per cache key, so concurrent reads of one key share
223
+ * one request, with the ticket it left on (see `state.ticket`).
224
+ */
225
+ private readonly inflight;
226
+ /**
227
+ * Per cache key, the ticket of the request whose answer the cache holds.
228
+ * Emptied on every invalidation, capped by `STORED_LIMIT`. See `storable`.
229
+ */
230
+ private readonly storedBy;
231
+ private readonly onError?;
232
+ /**
233
+ * Everything that changes while the client runs and is not a collection of
234
+ * its own. One object, so that a preview view - which shares this client's
235
+ * fields through its prototype - changes the same values and never a copy.
236
+ */
237
+ private readonly state;
274
238
  constructor(options: HavenClientOptions);
275
239
  /**
276
240
  * A per-request view of this client that skips the cache when the request
@@ -305,8 +269,47 @@ declare class HavenClient {
305
269
  * a locale `code` as the client `locale` option or a per-call `opts.locale`.
306
270
  */
307
271
  locales(opts?: ReadOptions): Promise<ContentLocale[]>;
308
- /** Resolve the locale for a read: per-call override, else the client default. */
272
+ /**
273
+ * Resolve the locale for a read: per-call override, else the client default.
274
+ * Only a value overrides: `{ locale: undefined }` (or `null`) is what a site
275
+ * passes when the visitor sent no language, and must leave the client locale standing.
276
+ * `''` is the one way to ask for the project default.
277
+ */
309
278
  private resolveLocale;
279
+ /**
280
+ * The locale a read is requested and cached under: the requested one mapped
281
+ * onto a locale the project is configured with (see `matchLocale`).
282
+ *
283
+ * Sites pass on whatever language the visitor's browser asks for, and the
284
+ * studio answers all of `nl`, `nl-NL` and `nl-BE` with the same content. Keyed
285
+ * by the raw value, each spelling would be its own cache entry and its own
286
+ * request - and a stream of made-up ones would push every real entry out of
287
+ * the cache, the last good values for an outage among them. Mapped first,
288
+ * the cache holds one entry per configured locale, whatever is asked for.
289
+ *
290
+ * Without the list of locales (caching off, an older studio without the
291
+ * route, studio unreachable and never read) the requested value goes to the
292
+ * studio as it is, and the studio resolves it.
293
+ */
294
+ private readLocale;
295
+ /**
296
+ * The project's locales, or `undefined` when they have never been read and
297
+ * cannot be now. An empty list is an answer like any other: the project has
298
+ * no locales, the studio serves the same content whatever language is asked
299
+ * for, and `matchLocale` then maps every request onto the default.
300
+ *
301
+ * Once the list is known this does not wait for anything: the read maps from
302
+ * the list as it stands, and the list is brought up to date on the side. A
303
+ * read therefore spends its `waitForFresh` on its content alone, and keeps
304
+ * finding that content under the same key while the studio is away. Only
305
+ * the very first localized read waits here, as it has nothing to map from.
306
+ *
307
+ * The exception is `waitForFresh: false`. That setting promises that a read
308
+ * waits for the studio and leaves nothing running when it returns - what a
309
+ * host needs that freezes the process once the response is out. So there
310
+ * the list is brought up to date first, like the content after it.
311
+ */
312
+ private configuredLocales;
310
313
  /** List every record in a dataset (references inflated). Requires read scope. */
311
314
  listRecords<T = Record<string, unknown>>(nodeSlug: string, datasetSlug: string, opts?: ReadOptions): Promise<ContentRecord<T>[]>;
312
315
  /** Read one record by uid. Requires read scope. Throws 404 if it does not exist. */
@@ -319,6 +322,16 @@ declare class HavenClient {
319
322
  * reads of the dataset and of this record.
320
323
  */
321
324
  updateRecord<T = Record<string, unknown>>(nodeSlug: string, datasetSlug: string, recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>>;
325
+ /**
326
+ * Sends a write and settles the cached reads of its dataset with the outcome.
327
+ *
328
+ * Stored: they are dropped. Refused (an answered 4xx): they are still right
329
+ * and stay. Anything else - a timeout, a dropped connection, a 5xx - leaves
330
+ * open whether the studio carried the write out, so they are marked for a
331
+ * recheck: the next read asks the studio again, and keeps the cached value to
332
+ * fall back on if the studio is in fact down.
333
+ */
334
+ private write;
322
335
  /** Run a saved query (`queries.<slug>`) and return its result. Requires read scope. */
323
336
  query<V = unknown>(querySlug: string, opts?: ReadOptions): Promise<QueryResult<V>>;
324
337
  /**
@@ -329,28 +342,125 @@ declare class HavenClient {
329
342
  /**
330
343
  * Clear cached reads. With no argument, clears everything. Pass a scope to
331
344
  * clear just part of it: a node slug, or `{ node, dataset }` for one dataset.
345
+ * A scoped clear also drops every saved query result, as any of them may
346
+ * aggregate the content that was cleared.
332
347
  */
333
348
  clearCache(scope?: string | {
334
349
  node: string;
335
350
  dataset?: string;
336
351
  }): void;
337
- /** Drop cached record reads for a dataset (every locale), plus all query
338
- * results (which may aggregate it). */
352
+ /**
353
+ * Invalidate cached record reads for a dataset (every locale), plus all query
354
+ * results (which may aggregate it). `drop` removes them; `recheck` keeps each
355
+ * value as a fallback but makes the next read ask the studio again.
356
+ */
339
357
  private invalidateDataset;
358
+ /** Drop one key from the cache. */
359
+ private drop;
360
+ /** `drop` for every key that starts with `prefix`. */
361
+ private dropPrefix;
362
+ /** Like `drop`, but the value stays as a fallback (see `ContentCache.expire`). */
363
+ private recheck;
364
+ /** `recheck` for every key that starts with `prefix`. */
365
+ private recheckPrefix;
366
+ /**
367
+ * Called by everything that invalidates cached reads. Every request that is
368
+ * under way at this moment left before it, so its answer may show the
369
+ * content as it was: none of them may store what they come back with
370
+ * (`storable`), and no later read may join one of them (hence the cleared
371
+ * `inflight`). They still answer the reads that were already waiting on them.
372
+ *
373
+ * Deliberately not narrowed to the keys that were invalidated. The price is
374
+ * that an unrelated answer now and then is served without being stored, and
375
+ * asked for once more; what it buys is one rule without exceptions.
376
+ */
377
+ private invalidated;
378
+ /**
379
+ * Whether the answer to the request that left on `ticket` may change what
380
+ * the cache holds for `key`. The single gate in front of every cache write
381
+ * that follows a request - cached read or bypass, a new value, a `304`, a
382
+ * deletion or a retry pause alike. It keeps the cache from going back in time:
383
+ *
384
+ * - not when the cache was invalidated after the request left: the answer
385
+ * may show the content from before (a write, `clearCache`);
386
+ * - not when the cache already holds the answer to a request that left
387
+ * later: that one is newer, whichever of the two came back first.
388
+ */
389
+ private storable;
390
+ /**
391
+ * Settles the cache with the studio's own definitive "no" for `key` (deleted,
392
+ * forbidden), in answer to the request that left on `ticket`: the entry goes.
393
+ * The one place this happens, for a cached read and a bypass alike.
394
+ *
395
+ * The deletion is noted like any other answer. Without that, a request that
396
+ * left earlier and comes back later would pass the gate and put the deleted
397
+ * content straight back.
398
+ */
399
+ private gone;
400
+ /**
401
+ * Notes that the cache now reflects, for `key`, the answer to the request
402
+ * that left on `ticket` - a value, a `304`, or the studio's own "this does
403
+ * not exist", after which the cache holds nothing for it. A refresh of that
404
+ * key that left earlier and is still under way is retired: a read arriving
405
+ * now must not join it for an older answer than the cache already reflects.
406
+ */
407
+ private stored;
340
408
  /**
341
409
  * The read path, with conditional revalidation.
342
410
  *
343
411
  * Steady state (project stamp unchanged since we last confirmed this entry):
344
412
  * served straight from cache, zero network. After a content change the stamp
345
413
  * moves, so the entry is revalidated once with `If-None-Match` - a `304` keeps
346
- * the cached value, a `200` replaces it - and then it is fast again. If the
347
- * studio is unreachable, the last good value is served rather than failing
348
- * (unless it is a definitive 4xx like a deleted record).
414
+ * the cached value, a `200` replaces it - and then it is fast again.
415
+ *
416
+ * Five rules hold for every read, whatever the studio does. Each is enforced
417
+ * in exactly one place, named here, so that it cannot hold for one kind of
418
+ * read and not for another:
419
+ *
420
+ * 1. A failure that is not the studio's own definitive answer never costs a
421
+ * cached value: it is served instead, and stays cached (`refresh`).
422
+ * 2. Only what is recognisably this endpoint's answer is ever stored
423
+ * (`conditionalGet`).
424
+ * 3. The cache never goes back in time: an answer is not stored when the
425
+ * cache was invalidated, or filled with a newer answer, after its request
426
+ * left (`storable`, in front of every write to the cache).
427
+ * 4. A read that already holds a value waits on the studio for `waitForFresh`
428
+ * at most, stamp check and refresh together (here); the refresh then
429
+ * finishes on the side.
430
+ * 5. One request per key at a time (`refresh`).
349
431
  */
350
432
  private cachedGet;
433
+ /**
434
+ * Fetches `cacheKey` from the studio and settles the cache with the answer.
435
+ * One per key at a time: reads that arrive while it runs get the same promise,
436
+ * so a slow studio sees one request for a key and not one per visitor.
437
+ *
438
+ * Resolves with the value to serve: the fresh one, or a cached one when the
439
+ * studio failed transiently. Rejects on a definitive answer, or when there is
440
+ * nothing cached to serve in its place.
441
+ */
442
+ private refresh;
443
+ /**
444
+ * Hands an absorbed failure to `onError`, or without one warns once per
445
+ * outage. Never throws and never leaves a rejection behind: a broken hook
446
+ * must not turn a served read into an error, and an `async` hook whose own
447
+ * work fails (an alert that cannot be delivered, during the very outage it
448
+ * reports) must not become the unhandled rejection that stops the process.
449
+ */
450
+ private report;
351
451
  /**
352
452
  * A GET that understands conditional requests: sends `If-None-Match` when an
353
453
  * etag is supplied, and reports a `304` as `notModified` rather than a value.
454
+ *
455
+ * The one place that decides what counts as an answer, for every read:
456
+ *
457
+ * - A `2xx` whose body fails `isExpected` is rejected, not returned. A
458
+ * maintenance page or a captive portal can answer `200` with JSON of its
459
+ * own; storing that would replace the last good value with nothing, at the
460
+ * very moment the studio is away.
461
+ * - A `304` is only an answer to a request that sent an etag. Unasked for,
462
+ * it says "keep what you have" to a caller that has nothing, and there is
463
+ * no value to return or store.
354
464
  */
355
465
  private conditionalGet;
356
466
  private request;
@@ -597,5 +707,5 @@ interface ForecastSeries {
597
707
  /** Convenience factory: `createClient({ apiKey, baseUrl })`. */
598
708
  declare function createClient(options: HavenClientOptions): HavenClient;
599
709
 
600
- export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ChartData, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, HavenClient as JustmadeClient, HavenError as JustmadeError, MemoryCacheStore, PREVIEW_PARAM, chartFenceHeight, createClient, isChartFence, isPreviewRequest, parseChartFence };
601
- export type { CacheEntry, CacheOptions, CacheStore, ChartFence, ChartFenceResult, ContentLocale, ContentRecord, ContentSchema, FieldKind, FieldType, ForecastSeries, HavenClientOptions, HavenClientOptions as JustmadeClientOptions, PreviewInput, QueryResult, QueryShape, ReadOptions, RoadmapData, RoadmapEvent, RoadmapHappening, RoadmapLane, RoadmapMilestone, RoadmapPhase, RoadmapPhaseState, RoadmapRepeat, RoadmapTask, RoadmapTip, RoadmapTone, RoadmapWaiting, RoadmapWorkState, SchemaDataset, SchemaField, SchemaNode };
710
+ export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, CacheOptions, ChartData, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, HavenClient as JustmadeClient, HavenError as JustmadeError, PREVIEW_PARAM, chartFenceHeight, createClient, isChartFence, isPreviewRequest, parseChartFence };
711
+ export type { ChartFence, ChartFenceResult, ContentLocale, ContentRecord, ContentSchema, FieldKind, FieldType, ForecastSeries, HavenClientOptions, HavenClientOptions as JustmadeClientOptions, PreviewInput, QueryResult, QueryShape, ReadOptions, RoadmapData, RoadmapEvent, RoadmapHappening, RoadmapLane, RoadmapMilestone, RoadmapPhase, RoadmapPhaseState, RoadmapRepeat, RoadmapTask, RoadmapTip, RoadmapTone, RoadmapWaiting, RoadmapWorkState, SchemaDataset, SchemaField, SchemaNode, StudioFailure };