@nordhavnhq/beacon 0.4.1 → 0.6.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.cjs CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/cache.ts
4
+ var EXPIRED = 1;
4
5
  var MemoryCacheStore = class {
5
6
  constructor(maxEntries = 500) {
6
7
  this.maxEntries = maxEntries;
@@ -32,23 +33,31 @@ var ContentCache = class {
32
33
  constructor(opts = {}) {
33
34
  this.enabled = opts.enabled ?? true;
34
35
  this.ttl = opts.ttl ?? 6048e5;
36
+ this.retryDelay = typeof opts.revalidate === "number" && opts.revalidate > 0 ? opts.revalidate : 6e4;
35
37
  this.store = opts.store ?? new MemoryCacheStore(opts.maxEntries ?? 500);
36
38
  }
37
39
  /**
38
40
  * The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the
39
41
  * whole entry (value + etag + validated stamp) so the client can decide
40
42
  * whether to serve it, revalidate it, or fall back to it on error.
43
+ *
44
+ * An expired entry is left in the store (the refetch overwrites it, or
45
+ * `maxEntries` evicts it) so `stale` can still fall back to it.
41
46
  */
42
47
  peek(key, now) {
43
- if (!this.enabled) return void 0;
44
- const entry = this.store.get(key);
48
+ const entry = this.stale(key);
45
49
  if (!entry) return void 0;
46
- if (entry.expiresAt !== 0 && entry.expiresAt <= now) {
47
- this.store.delete(key);
48
- return void 0;
49
- }
50
+ if (entry.expiresAt !== 0 && entry.expiresAt <= now) return void 0;
50
51
  return entry;
51
52
  }
53
+ /**
54
+ * The entry for `key` whether or not its TTL has run out: the last good value
55
+ * to serve when a refetch fails transiently.
56
+ */
57
+ stale(key) {
58
+ if (!this.enabled) return void 0;
59
+ return this.store.get(key);
60
+ }
52
61
  /** Store a freshly fetched value with its validator and the stamp it is current against. */
53
62
  set(key, value, opts, now) {
54
63
  if (!this.enabled) return;
@@ -68,7 +77,42 @@ var ContentCache = class {
68
77
  if (!entry) return;
69
78
  entry.validatedVersion = version;
70
79
  entry.expiresAt = this.ttl === 0 ? 0 : now + this.ttl;
80
+ delete entry.retryAt;
81
+ this.store.set(key, entry);
82
+ }
83
+ /**
84
+ * Record that refetching `key` from `from` just failed transiently, so reads
85
+ * serve it as-is for a while instead of each waiting on an unreachable studio.
86
+ * Returns the entry to serve: `from`, or the newer one a concurrent read stored
87
+ * in the meantime (left unpaused, since its own fetch succeeded).
88
+ */
89
+ backoff(key, from, now) {
90
+ const entry = this.store.get(key);
91
+ if (!entry) return from;
92
+ if (entry.etag !== from.etag || entry.expiresAt !== from.expiresAt) return entry;
93
+ entry.retryAt = now + this.retryDelay;
71
94
  this.store.set(key, entry);
95
+ return entry;
96
+ }
97
+ /**
98
+ * Mark `key` as due for a refetch while keeping its value to fall back on:
99
+ * the next read asks the studio again whatever the stamp says, and still
100
+ * serves this value if the studio does not answer. For when the stored value
101
+ * may be outdated but there is no telling - dropping it would throw away the
102
+ * only thing left to show during an outage. No-op for a key that is not held.
103
+ */
104
+ expire(key) {
105
+ const entry = this.store.get(key);
106
+ if (!entry) return;
107
+ entry.expiresAt = EXPIRED;
108
+ delete entry.retryAt;
109
+ this.store.set(key, entry);
110
+ }
111
+ /** `expire` for every key that starts with `prefix`. */
112
+ expirePrefix(prefix) {
113
+ for (const key of [...this.store.keys()]) {
114
+ if (key.startsWith(prefix)) this.expire(key);
115
+ }
72
116
  }
73
117
  /** Drop one exact key. */
74
118
  delete(key) {
@@ -106,15 +150,22 @@ var HavenError = class _HavenError extends Error {
106
150
  };
107
151
 
108
152
  // src/version.ts
153
+ var UNSUPPORTED_PAUSE_MS = 15 * 6e4;
109
154
  var VersionTracker = class {
110
- constructor(probe, interval) {
155
+ constructor(probe, interval, isUnsupported = (err) => err?.status === 404) {
111
156
  this.probe = probe;
112
157
  this.interval = interval;
158
+ this.isUnsupported = isUnsupported;
113
159
  this.lastChecked = 0;
114
160
  this.version = null;
115
161
  this.inFlight = null;
116
- /** Set when the server has no version route, so we stop asking. */
117
- this.unsupported = false;
162
+ /**
163
+ * Epoch ms before which we do not ask again, after the server turned out
164
+ * to have no version route. A pause and not a final verdict: an old server
165
+ * costs one request per pause, and one that gains the route is picked up
166
+ * without a restart.
167
+ */
168
+ this.pausedUntil = 0;
118
169
  }
119
170
  /** The most recent stamp seen, or `null` before the first successful probe. */
120
171
  current() {
@@ -124,24 +175,31 @@ var VersionTracker = class {
124
175
  * Refresh the stamp if we are due. Resolves once the answer is in, so the
125
176
  * read that triggered it sees an up-to-date stamp. A failed probe leaves the
126
177
  * last known stamp in place (serve-from-cache rather than thrash).
178
+ *
179
+ * A failed probe counts towards the interval like any other, also when no
180
+ * stamp has ever come in. Otherwise a process that starts while the studio
181
+ * is down (with a persisted cache to serve from) would probe on every read,
182
+ * and against a hanging studio make each of them wait out the probe.
127
183
  */
128
184
  async refresh(now) {
129
- if (this.interval <= 0 || this.unsupported) return;
185
+ if (this.interval <= 0 || now < this.pausedUntil) return;
130
186
  if (this.inFlight) return this.inFlight;
131
- if (this.version !== null && now - this.lastChecked < this.interval) return;
187
+ if (now - this.lastChecked < this.interval) return;
132
188
  this.lastChecked = now;
133
- this.inFlight = this.run();
189
+ this.inFlight = this.run(now);
134
190
  try {
135
191
  await this.inFlight;
136
192
  } finally {
137
193
  this.inFlight = null;
138
194
  }
139
195
  }
140
- async run() {
196
+ async run(now) {
141
197
  try {
142
198
  this.version = await this.probe();
143
199
  } catch (err) {
144
- if (err?.status === 404) this.unsupported = true;
200
+ if (this.isUnsupported(err)) {
201
+ this.pausedUntil = now + Math.max(this.interval, UNSUPPORTED_PAUSE_MS);
202
+ }
145
203
  }
146
204
  }
147
205
  };
@@ -149,26 +207,88 @@ var VersionTracker = class {
149
207
  // src/client.ts
150
208
  var PREVIEW_PARAM = "sl-preview";
151
209
  var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
152
- var HavenClient = class _HavenClient {
210
+ var DEFAULT_TIMEOUT = 1e4;
211
+ var MIN_UPLOAD_TIMEOUT = 6e4;
212
+ var VERSION_TIMEOUT = 3e3;
213
+ var DEFAULT_WAIT_FOR_FRESH = 1e3;
214
+ var MAX_TIMER = 2147483647;
215
+ var STORED_LIMIT = 5e3;
216
+ var LOCALES_RETRY_MS = 6e4;
217
+ var DEFAULT_GATEWAY_RETRY = 200;
218
+ var MAX_GATEWAY_RETRY = 6e4;
219
+ var HavenClient = class {
153
220
  constructor(options) {
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
+ this.inflight = /* @__PURE__ */ new Map();
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
+ this.storedBy = /* @__PURE__ */ new Map();
231
+ /**
232
+ * Everything that changes while the client runs and is not a collection of
233
+ * its own. One object, so that a preview view - which shares this client's
234
+ * fields through its prototype - changes the same values and never a copy.
235
+ */
236
+ this.state = {
237
+ /**
238
+ * Numbers the requests in the order they leave. Answers come back in any
239
+ * order, and the cache must never go back in time: a request takes a
240
+ * ticket when it leaves, and `storable` compares it on the way back.
241
+ */
242
+ ticket: 0,
243
+ /** The last ticket handed out when the cache was last invalidated. */
244
+ invalidatedAt: 0,
245
+ /** Set by an absorbed failure, cleared by the next answer: one warning per outage. */
246
+ unreachable: false,
247
+ /**
248
+ * The project's locales as last read. Kept here and not only in the cache,
249
+ * where the entry can be evicted: without the list a requested locale
250
+ * cannot be mapped onto the key its content is cached under, and that
251
+ * content would be out of reach for as long as the studio is away.
252
+ */
253
+ locales: void 0,
254
+ /** Epoch ms before which the locales are not asked for again, after that failed. */
255
+ localesRetryAt: 0
256
+ };
154
257
  if (!options.apiKey) throw new Error("HavenClient: `apiKey` is required");
155
258
  this.apiKey = options.apiKey;
156
259
  this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
157
260
  const resolvedFetch = options.fetch ?? globalThis.fetch;
158
261
  if (!resolvedFetch) {
159
- throw new Error("HavenClient: no `fetch` available; pass one via options.fetch (Node < 18)");
262
+ throw new Error("HavenClient: no `fetch` available; pass one via options.fetch");
160
263
  }
161
264
  this.fetchImpl = resolvedFetch.bind(globalThis);
162
265
  this.headers = options.headers ?? {};
163
266
  this.locale = options.locale || void 0;
164
267
  this.readDefault = options.preview !== true;
268
+ this.timeout = normalizeTimeout(options.timeout);
269
+ this.onError = options.onError;
165
270
  const cacheOpt = options.cache;
166
271
  const cacheOptions = cacheOpt === false ? { enabled: false } : cacheOpt === true || cacheOpt === void 0 ? {} : cacheOpt;
167
272
  this.cache = new ContentCache(cacheOptions);
273
+ this.waitForFresh = normalizeWait(cacheOptions.waitForFresh);
274
+ this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry);
168
275
  const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false ? 0 : cacheOptions.revalidate ?? 6e4;
276
+ const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT);
169
277
  this.versionTracker = new VersionTracker(
170
- async () => (await this.request("GET", "/version")).version,
171
- revalidate
278
+ async () => {
279
+ try {
280
+ const res = await this.request("GET", "/version", void 0, probeTimeout);
281
+ if (typeof res?.version !== "string") throw unexpectedBody(`${this.baseUrl}/api/content/version`);
282
+ this.state.unreachable = false;
283
+ return res.version;
284
+ } catch (err) {
285
+ if (isMissingRoute(err)) this.state.unreachable = false;
286
+ else this.report({ during: "stamp-check", error: err });
287
+ throw err;
288
+ }
289
+ },
290
+ revalidate,
291
+ isMissingRoute
172
292
  );
173
293
  }
174
294
  // ── Preview scoping ─────────────────────────────────────────────────────────
@@ -196,17 +316,9 @@ var HavenClient = class _HavenClient {
196
316
  forRequest(input) {
197
317
  if (!this.readDefault) return this;
198
318
  if (!isPreviewRequest(input)) return this;
199
- const clone = new _HavenClient({
200
- apiKey: this.apiKey,
201
- baseUrl: this.baseUrl,
202
- fetch: this.fetchImpl,
203
- headers: this.headers,
204
- locale: this.locale,
205
- preview: true
206
- });
207
- clone.cache = this.cache;
208
- clone.versionTracker = this.versionTracker;
209
- return clone;
319
+ const view = Object.create(this);
320
+ view.readDefault = false;
321
+ return view;
210
322
  }
211
323
  /** Whether this client bypasses the cache (i.e. came from a preview request). */
212
324
  get isPreview() {
@@ -215,7 +327,7 @@ var HavenClient = class _HavenClient {
215
327
  // ── Introspection ─────────────────────────────────────────────────────────
216
328
  /** The full content shape this key can reach: nodes, datasets, field schemas. */
217
329
  async schema(opts) {
218
- return this.cachedGet("schema", "/schema", opts);
330
+ return this.cachedGet("schema", "/schema", opts, has("nodes", Array.isArray));
219
331
  }
220
332
  /** Shorthand for `schema()` then `.nodes`. */
221
333
  async nodes(opts) {
@@ -226,43 +338,111 @@ var HavenClient = class _HavenClient {
226
338
  * a locale `code` as the client `locale` option or a per-call `opts.locale`.
227
339
  */
228
340
  async locales(opts) {
229
- const res = await this.cachedGet("locales", "/locales", opts);
341
+ const res = await this.cachedGet("locales", "/locales", opts, has("locales", Array.isArray));
230
342
  return res.locales;
231
343
  }
232
- /** Resolve the locale for a read: per-call override, else the client default. */
344
+ /**
345
+ * Resolve the locale for a read: per-call override, else the client default.
346
+ * Only a value overrides: `{ locale: undefined }` (or `null`) is what a site
347
+ * passes when the visitor sent no language, and must leave the client locale standing.
348
+ * `''` is the one way to ask for the project default.
349
+ */
233
350
  resolveLocale(opts) {
234
- const l = opts && "locale" in opts ? opts.locale : this.locale;
351
+ const l = opts?.locale != null ? opts.locale : this.locale;
235
352
  return l || void 0;
236
353
  }
354
+ /**
355
+ * The locale a read is requested and cached under: the requested one mapped
356
+ * onto a locale the project is configured with (see `matchLocale`).
357
+ *
358
+ * Sites pass on whatever language the visitor's browser asks for, and the
359
+ * studio answers all of `nl`, `nl-NL` and `nl-BE` with the same content. Keyed
360
+ * by the raw value, each spelling would be its own cache entry and its own
361
+ * request - and a stream of made-up ones would push every real entry out of
362
+ * the cache, the last good values for an outage among them. Mapped first,
363
+ * the cache holds one entry per configured locale, whatever is asked for.
364
+ *
365
+ * Without the list of locales (caching off, an older studio without the
366
+ * route, studio unreachable and never read) the requested value goes to the
367
+ * studio as it is, and the studio resolves it.
368
+ */
369
+ async readLocale(opts) {
370
+ const requested = this.resolveLocale(opts)?.trim() || void 0;
371
+ if (requested === void 0 || !this.cache.enabled) return requested;
372
+ const bypass = !(opts?.cache ?? this.readDefault);
373
+ const configured = await this.configuredLocales(!bypass);
374
+ return configured ? matchLocale(requested, configured) : requested;
375
+ }
376
+ /**
377
+ * The project's locales, or `undefined` when they have never been read and
378
+ * cannot be now. An empty list is an answer like any other: the project has
379
+ * no locales, the studio serves the same content whatever language is asked
380
+ * for, and `matchLocale` then maps every request onto the default.
381
+ *
382
+ * Once the list is known this does not wait for anything: the read maps from
383
+ * the list as it stands, and the list is brought up to date on the side. A
384
+ * read therefore spends its `waitForFresh` on its content alone, and keeps
385
+ * finding that content under the same key while the studio is away. Only
386
+ * the very first localized read waits here, as it has nothing to map from.
387
+ *
388
+ * The exception is `waitForFresh: false`. That setting promises that a read
389
+ * waits for the studio and leaves nothing running when it returns - what a
390
+ * host needs that freezes the process once the response is out. So there
391
+ * the list is brought up to date first, like the content after it.
392
+ */
393
+ async configuredLocales(retry) {
394
+ const state = this.state;
395
+ if (Date.now() >= state.localesRetryAt) {
396
+ const lookup = this.cachedGet(
397
+ "locales",
398
+ "/locales",
399
+ { cache: true },
400
+ has("locales", Array.isArray),
401
+ retry
402
+ ).then(
403
+ (res) => {
404
+ state.locales = res.locales;
405
+ },
406
+ () => {
407
+ state.localesRetryAt = Date.now() + LOCALES_RETRY_MS;
408
+ }
409
+ );
410
+ if (state.locales === void 0 || this.waitForFresh === Infinity) await lookup;
411
+ }
412
+ return state.locales;
413
+ }
237
414
  // ── Records ───────────────────────────────────────────────────────────────
238
415
  /** List every record in a dataset (references inflated). Requires read scope. */
239
416
  async listRecords(nodeSlug, datasetSlug, opts) {
240
- const locale = this.resolveLocale(opts);
417
+ const locale = await this.readLocale(opts);
241
418
  const res = await this.cachedGet(
242
419
  recordsKey(nodeSlug, datasetSlug, locale),
243
420
  datasetPath(nodeSlug, datasetSlug) + localeQuery(locale),
244
- opts
421
+ opts,
422
+ has("records", Array.isArray)
245
423
  );
246
424
  return res.records;
247
425
  }
248
426
  /** Read one record by uid. Requires read scope. Throws 404 if it does not exist. */
249
427
  async getRecord(nodeSlug, datasetSlug, recordUid, opts) {
250
- const locale = this.resolveLocale(opts);
428
+ const locale = await this.readLocale(opts);
251
429
  const res = await this.cachedGet(
252
430
  recordKey(nodeSlug, datasetSlug, recordUid, locale),
253
431
  `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}${localeQuery(locale)}`,
254
- opts
432
+ opts,
433
+ has("record", isObject)
255
434
  );
256
435
  return res.record;
257
436
  }
258
437
  /** Create a record. Requires write scope. Invalidates cached reads of the dataset. */
259
438
  async createRecord(nodeSlug, datasetSlug, data) {
260
- const res = await this.request(
439
+ const res = await this.write(
261
440
  "POST",
262
441
  datasetPath(nodeSlug, datasetSlug),
263
- { data }
442
+ { data },
443
+ nodeSlug,
444
+ datasetSlug
264
445
  );
265
- this.invalidateDataset(nodeSlug, datasetSlug);
266
446
  return res.record;
267
447
  }
268
448
  /**
@@ -271,22 +451,97 @@ var HavenClient = class _HavenClient {
271
451
  * reads of the dataset and of this record.
272
452
  */
273
453
  async updateRecord(nodeSlug, datasetSlug, recordUid, data) {
274
- const res = await this.request(
454
+ const res = await this.write(
275
455
  "PATCH",
276
456
  `${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}`,
277
- { data }
457
+ { data },
458
+ nodeSlug,
459
+ datasetSlug
278
460
  );
279
- this.invalidateDataset(nodeSlug, datasetSlug);
280
- this.cache.delete(recordKey(nodeSlug, datasetSlug, recordUid));
281
461
  return res.record;
282
462
  }
463
+ /**
464
+ * Upload one file for a `file` field, for a form that sends an attachment.
465
+ * Requires write scope on the dataset. Returns the file; hang it on a record
466
+ * in a second call by writing `{ uid }` into that field:
467
+ *
468
+ * ```ts
469
+ * const attachment = form.get('attachment')
470
+ * if (attachment instanceof File && attachment.size > 0) {
471
+ * const file = await studio.uploadFile('contact', 'requests', 'attachment', attachment)
472
+ * await studio.createRecord('contact', 'requests', { name, attachment: { uid: file.uid } })
473
+ * }
474
+ * ```
475
+ *
476
+ * The field decides what it takes: its `mimes` and `max_size` rules, within
477
+ * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
478
+ * studio reads the type from the content, so a renamed file is refused. Only
479
+ * top-level fields. A file of the wrong type or size throws `HavenError` 400
480
+ * with a message fit to show; other refusals (400, 403, 404) are setup
481
+ * errors. More than 10 uploads a minute per key throws 429. From a Node
482
+ * `Buffer`, send `new Blob([buffer])` with a `filename`.
483
+ *
484
+ * Server-side only: the key that uploads can write, and must never reach a
485
+ * browser. Not retried, not cached, and it leaves cached reads alone: until a
486
+ * record takes it up, the file belongs to no content. An upload that failed
487
+ * may still have been stored; an unused one is removed after 24 hours.
488
+ */
489
+ async uploadFile(nodeSlug, datasetSlug, fieldSlug, file, opts) {
490
+ const filename = opts?.filename ?? file.name;
491
+ if (!filename) {
492
+ throw new Error("HavenClient.uploadFile: the file has no name; pass `filename` (with its extension)");
493
+ }
494
+ const form = new FormData();
495
+ form.set("file", file, filename);
496
+ form.set("nodeSlug", nodeSlug);
497
+ form.set("datasetSlug", datasetSlug);
498
+ form.set("fieldSlug", fieldSlug);
499
+ const url = `${this.baseUrl}/api/content/files`;
500
+ const timeout = uploadTimeout(this.timeout, opts?.timeout);
501
+ return withTimeout(url, timeout, async (signal) => {
502
+ const res = await this.fetchImpl(url, {
503
+ method: "POST",
504
+ // No Content-Type: fetch sets the multipart one, with its boundary.
505
+ headers: { Authorization: `Bearer ${this.apiKey}`, ...withoutContentType(this.headers) },
506
+ body: form,
507
+ signal
508
+ });
509
+ if (!res.ok) throw await this.toError(res);
510
+ const value = await res.json().catch(() => void 0);
511
+ if (!has("uid", (uid) => typeof uid === "string" && uid !== "")(value)) throw unexpectedBody(url);
512
+ return value;
513
+ });
514
+ }
515
+ /**
516
+ * Sends a write and settles the cached reads of its dataset with the outcome.
517
+ *
518
+ * Stored: they are dropped. Refused (an answered 4xx): they are still right
519
+ * and stay. Anything else - a timeout, a dropped connection, a 5xx - leaves
520
+ * open whether the studio carried the write out, so they are marked for a
521
+ * recheck: the next read asks the studio again, and keeps the cached value to
522
+ * fall back on if the studio is in fact down.
523
+ */
524
+ async write(method, path, body, nodeSlug, datasetSlug) {
525
+ let res;
526
+ try {
527
+ res = await this.request(method, path, body);
528
+ } catch (err) {
529
+ if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, "recheck");
530
+ throw err;
531
+ }
532
+ this.invalidateDataset(nodeSlug, datasetSlug);
533
+ return res;
534
+ }
283
535
  // -- Queries --
284
536
  /** Run a saved query (`queries.<slug>`) and return its result. Requires read scope. */
285
537
  async query(querySlug, opts) {
286
538
  return this.cachedGet(
287
539
  `query:${querySlug}`,
288
540
  `/queries/${encodeURIComponent(querySlug)}`,
289
- opts
541
+ opts,
542
+ // Recognised by `shape`, never by `value`: that may be anything, and a
543
+ // query without a result can come back with no `value` at all.
544
+ has("shape", (shape) => typeof shape === "string")
290
545
  );
291
546
  }
292
547
  // ── Fluent dataset handle ───────────────────────────────────────────────────
@@ -301,31 +556,114 @@ var HavenClient = class _HavenClient {
301
556
  /**
302
557
  * Clear cached reads. With no argument, clears everything. Pass a scope to
303
558
  * clear just part of it: a node slug, or `{ node, dataset }` for one dataset.
559
+ * A scoped clear also drops every saved query result, as any of them may
560
+ * aggregate the content that was cleared.
304
561
  */
305
562
  clearCache(scope) {
306
563
  if (scope === void 0) {
307
564
  this.cache.clear();
565
+ this.invalidated();
308
566
  return;
309
567
  }
310
- if (typeof scope === "string") {
311
- this.cache.deletePrefix(`records:${scope}/`);
312
- this.cache.deletePrefix(`record:${scope}/`);
568
+ const node = typeof scope === "string" ? scope : scope.node;
569
+ const dataset = typeof scope === "string" ? void 0 : scope.dataset;
570
+ if (dataset) {
571
+ this.invalidateDataset(node, dataset);
313
572
  return;
314
573
  }
315
- if (scope.dataset) {
316
- this.invalidateDataset(scope.node, scope.dataset);
317
- } else {
318
- this.cache.deletePrefix(`records:${scope.node}/`);
319
- this.cache.deletePrefix(`record:${scope.node}/`);
320
- }
574
+ this.dropPrefix(`records:${node}/`);
575
+ this.dropPrefix(`record:${node}/`);
576
+ this.dropPrefix("query:");
577
+ }
578
+ /**
579
+ * Invalidate cached record reads for a dataset (every locale), plus all query
580
+ * results (which may aggregate it). `drop` removes them; `recheck` keeps each
581
+ * value as a fallback but makes the next read ask the studio again.
582
+ */
583
+ invalidateDataset(nodeSlug, datasetSlug, how = "drop") {
584
+ const one = how === "drop" ? (key) => this.drop(key) : (key) => this.recheck(key);
585
+ const all = how === "drop" ? (prefix) => this.dropPrefix(prefix) : (prefix) => this.recheckPrefix(prefix);
586
+ one(recordsKey(nodeSlug, datasetSlug));
587
+ all(`${recordsKey(nodeSlug, datasetSlug)}::`);
588
+ all(`${recordKey(nodeSlug, datasetSlug, "")}`);
589
+ all("query:");
590
+ }
591
+ /** Drop one key from the cache. */
592
+ drop(key) {
593
+ this.cache.delete(key);
594
+ this.invalidated();
595
+ }
596
+ /** `drop` for every key that starts with `prefix`. */
597
+ dropPrefix(prefix) {
598
+ this.cache.deletePrefix(prefix);
599
+ this.invalidated();
321
600
  }
322
- /** Drop cached record reads for a dataset (every locale), plus all query
323
- * results (which may aggregate it). */
324
- invalidateDataset(nodeSlug, datasetSlug) {
325
- this.cache.delete(recordsKey(nodeSlug, datasetSlug));
326
- this.cache.deletePrefix(`${recordsKey(nodeSlug, datasetSlug)}::`);
327
- this.cache.deletePrefix(`${recordKey(nodeSlug, datasetSlug, "")}`);
328
- this.cache.deletePrefix("query:");
601
+ /** Like `drop`, but the value stays as a fallback (see `ContentCache.expire`). */
602
+ recheck(key) {
603
+ this.cache.expire(key);
604
+ this.invalidated();
605
+ }
606
+ /** `recheck` for every key that starts with `prefix`. */
607
+ recheckPrefix(prefix) {
608
+ this.cache.expirePrefix(prefix);
609
+ this.invalidated();
610
+ }
611
+ /**
612
+ * Called by everything that invalidates cached reads. Every request that is
613
+ * under way at this moment left before it, so its answer may show the
614
+ * content as it was: none of them may store what they come back with
615
+ * (`storable`), and no later read may join one of them (hence the cleared
616
+ * `inflight`). They still answer the reads that were already waiting on them.
617
+ *
618
+ * Deliberately not narrowed to the keys that were invalidated. The price is
619
+ * that an unrelated answer now and then is served without being stored, and
620
+ * asked for once more; what it buys is one rule without exceptions.
621
+ */
622
+ invalidated() {
623
+ this.state.invalidatedAt = this.state.ticket;
624
+ this.storedBy.clear();
625
+ this.inflight.clear();
626
+ }
627
+ /**
628
+ * Whether the answer to the request that left on `ticket` may change what
629
+ * the cache holds for `key`. The single gate in front of every cache write
630
+ * that follows a request - cached read or bypass, a new value, a `304`, a
631
+ * deletion or a retry pause alike. It keeps the cache from going back in time:
632
+ *
633
+ * - not when the cache was invalidated after the request left: the answer
634
+ * may show the content from before (a write, `clearCache`);
635
+ * - not when the cache already holds the answer to a request that left
636
+ * later: that one is newer, whichever of the two came back first.
637
+ */
638
+ storable(key, ticket) {
639
+ return ticket > this.state.invalidatedAt && ticket >= (this.storedBy.get(key) ?? 0);
640
+ }
641
+ /**
642
+ * Settles the cache with the studio's own definitive "no" for `key` (deleted,
643
+ * forbidden), in answer to the request that left on `ticket`: the entry goes.
644
+ * The one place this happens, for a cached read and a bypass alike.
645
+ *
646
+ * The deletion is noted like any other answer. Without that, a request that
647
+ * left earlier and comes back later would pass the gate and put the deleted
648
+ * content straight back.
649
+ */
650
+ gone(key, ticket) {
651
+ if (!this.storable(key, ticket)) return;
652
+ this.cache.delete(key);
653
+ this.stored(key, ticket);
654
+ }
655
+ /**
656
+ * Notes that the cache now reflects, for `key`, the answer to the request
657
+ * that left on `ticket` - a value, a `304`, or the studio's own "this does
658
+ * not exist", after which the cache holds nothing for it. A refresh of that
659
+ * key that left earlier and is still under way is retired: a read arriving
660
+ * now must not join it for an older answer than the cache already reflects.
661
+ */
662
+ stored(key, ticket) {
663
+ if (this.storedBy.size >= STORED_LIMIT) this.invalidated();
664
+ this.storedBy.set(key, ticket);
665
+ const running = this.inflight.get(key);
666
+ if (running && running.ticket < ticket) this.inflight.delete(key);
329
667
  }
330
668
  // ── Transport ───────────────────────────────────────────────────────────────
331
669
  /**
@@ -334,76 +672,204 @@ var HavenClient = class _HavenClient {
334
672
  * Steady state (project stamp unchanged since we last confirmed this entry):
335
673
  * served straight from cache, zero network. After a content change the stamp
336
674
  * moves, so the entry is revalidated once with `If-None-Match` - a `304` keeps
337
- * the cached value, a `200` replaces it - and then it is fast again. If the
338
- * studio is unreachable, the last good value is served rather than failing
339
- * (unless it is a definitive 4xx like a deleted record).
675
+ * the cached value, a `200` replaces it - and then it is fast again.
676
+ *
677
+ * Five rules hold for every read, whatever the studio does. Each is enforced
678
+ * in exactly one place, named here, so that it cannot hold for one kind of
679
+ * read and not for another:
680
+ *
681
+ * 1. A failure that is not the studio's own definitive answer never costs a
682
+ * cached value: it is served instead, and stays cached (`refresh`).
683
+ * 2. Only what is recognisably this endpoint's answer is ever stored
684
+ * (`conditionalGet`).
685
+ * 3. The cache never goes back in time: an answer is not stored when the
686
+ * cache was invalidated, or filled with a newer answer, after its request
687
+ * left (`storable`, in front of every write to the cache).
688
+ * 4. A read that already holds a value waits on the studio for `waitForFresh`
689
+ * at most, stamp check and refresh together (here); the refresh then
690
+ * finishes on the side.
691
+ * 5. One request per key at a time (`refresh`).
340
692
  */
341
- async cachedGet(cacheKey, path, opts) {
693
+ async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
342
694
  const useCache = opts?.cache ?? this.readDefault;
343
695
  if (!useCache) {
344
- const res2 = await this.conditionalGet(path);
345
- this.cache.set(cacheKey, res2.value, { etag: res2.etag, version: this.versionTracker.current() ?? void 0 }, Date.now());
346
- return res2.value;
696
+ const version2 = this.versionTracker.current() ?? void 0;
697
+ const ticket = ++this.state.ticket;
698
+ let res;
699
+ try {
700
+ res = await this.conditionalGet(path, void 0, isExpected);
701
+ } catch (err) {
702
+ if (isDefinitive(err)) this.gone(cacheKey, ticket);
703
+ throw err;
704
+ }
705
+ if (this.storable(cacheKey, ticket)) {
706
+ this.cache.set(cacheKey, res.value, { etag: res.etag, version: version2 }, Date.now());
707
+ this.stored(cacheKey, ticket);
708
+ }
709
+ return res.value;
347
710
  }
348
- await this.versionTracker.refresh(Date.now());
711
+ const started = Date.now();
712
+ const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity;
713
+ await within(this.versionTracker.refresh(started), budget);
349
714
  const version = this.versionTracker.current() ?? void 0;
350
715
  const entry = this.cache.peek(cacheKey, Date.now());
351
716
  if (entry) {
352
717
  if (version === void 0 || entry.validatedVersion === version) {
353
718
  return entry.value;
354
719
  }
720
+ }
721
+ const last = entry ?? this.cache.stale(cacheKey);
722
+ if (last?.retryAt !== void 0 && Date.now() < last.retryAt) {
723
+ return last.value;
724
+ }
725
+ const refresh = this.refresh(cacheKey, path, last, version, isExpected, retry);
726
+ if (!last) return refresh;
727
+ const outcome = await within(refresh, budget - (Date.now() - started));
728
+ return outcome.settled ? outcome.value : last.value;
729
+ }
730
+ /**
731
+ * Fetches `cacheKey` from the studio and settles the cache with the answer.
732
+ * One per key at a time: reads that arrive while it runs get the same promise,
733
+ * so a slow studio sees one request for a key and not one per visitor.
734
+ *
735
+ * Resolves with the value to serve: the fresh one, or a cached one when the
736
+ * studio failed transiently. Rejects on a definitive answer, or when there is
737
+ * nothing cached to serve in its place.
738
+ */
739
+ refresh(cacheKey, path, last, version, isExpected, retry) {
740
+ const running = this.inflight.get(cacheKey);
741
+ if (running) return running.job;
742
+ let ticket = ++this.state.ticket;
743
+ const registered = () => this.inflight.get(cacheKey)?.job === job;
744
+ const register = () => {
745
+ this.inflight.set(cacheKey, { job, ticket });
746
+ };
747
+ const job = (async () => {
355
748
  try {
356
- const res2 = await this.conditionalGet(path, entry.etag);
357
- if (res2.notModified) {
358
- this.cache.confirm(cacheKey, version, Date.now());
359
- return entry.value;
749
+ let res;
750
+ try {
751
+ res = await this.conditionalGet(path, last?.etag, isExpected);
752
+ } catch (err) {
753
+ const pause = this.gatewayRetry;
754
+ if (!retry || pause === void 0 || last || this.cache.stale(cacheKey) || !isGatewayHiccup(err)) throw err;
755
+ await sleep(pause + Math.random() * pause);
756
+ const meanwhile = this.cache.stale(cacheKey);
757
+ if (meanwhile) return meanwhile.value;
758
+ const slot = this.inflight.get(cacheKey);
759
+ if (slot && !registered()) return slot.job;
760
+ ticket = ++this.state.ticket;
761
+ if (slot) slot.ticket = ticket;
762
+ else register();
763
+ version = this.versionTracker.current() ?? void 0;
764
+ res = await this.conditionalGet(path, void 0, isExpected);
765
+ }
766
+ if (res.notModified && last) {
767
+ if (this.storable(cacheKey, ticket)) {
768
+ this.cache.confirm(cacheKey, version, Date.now());
769
+ this.stored(cacheKey, ticket);
770
+ }
771
+ return last.value;
360
772
  }
361
- this.cache.set(cacheKey, res2.value, { etag: res2.etag, version }, Date.now());
362
- return res2.value;
773
+ if (this.storable(cacheKey, ticket)) {
774
+ this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now());
775
+ this.stored(cacheKey, ticket);
776
+ }
777
+ return res.value;
363
778
  } catch (err) {
364
- if (err instanceof HavenError && err.status < 500) {
365
- this.cache.delete(cacheKey);
779
+ if (isDefinitive(err)) {
780
+ this.gone(cacheKey, ticket);
366
781
  throw err;
367
782
  }
368
- return entry.value;
783
+ const held = this.cache.stale(cacheKey) ?? last;
784
+ if (!held) throw err;
785
+ this.report({ during: "read", key: cacheKey, error: err });
786
+ return (this.storable(cacheKey, ticket) ? this.cache.backoff(cacheKey, held, Date.now()) : held).value;
787
+ } finally {
788
+ if (registered()) this.inflight.delete(cacheKey);
369
789
  }
790
+ })();
791
+ this.inflight.set(cacheKey, { job, ticket });
792
+ return job;
793
+ }
794
+ /**
795
+ * Hands an absorbed failure to `onError`, or without one warns once per
796
+ * outage. Never throws and never leaves a rejection behind: a broken hook
797
+ * must not turn a served read into an error, and an `async` hook whose own
798
+ * work fails (an alert that cannot be delivered, during the very outage it
799
+ * reports) must not become the unhandled rejection that stops the process.
800
+ */
801
+ report(failure) {
802
+ const first = !this.state.unreachable;
803
+ this.state.unreachable = true;
804
+ try {
805
+ if (this.onError) {
806
+ const outcome = this.onError(failure);
807
+ if (isThenable(outcome)) outcome.then(void 0, () => {
808
+ });
809
+ } else if (first) {
810
+ const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
811
+ const what = failure.during === "read" ? `could not refresh "${failure.key}"` : "stamp check failed";
812
+ console.warn(`[@nordhavnhq/beacon] ${what} (${reason}); cached content keeps being served.`);
813
+ }
814
+ } catch {
370
815
  }
371
- const res = await this.conditionalGet(path);
372
- this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now());
373
- return res.value;
374
816
  }
375
817
  /**
376
818
  * A GET that understands conditional requests: sends `If-None-Match` when an
377
819
  * etag is supplied, and reports a `304` as `notModified` rather than a value.
820
+ *
821
+ * The one place that decides what counts as an answer, for every read:
822
+ *
823
+ * - A `2xx` whose body fails `isExpected` is rejected, not returned. A
824
+ * maintenance page or a captive portal can answer `200` with JSON of its
825
+ * own; storing that would replace the last good value with nothing, at the
826
+ * very moment the studio is away.
827
+ * - A `304` is only an answer to a request that sent an etag. Unasked for,
828
+ * it says "keep what you have" to a caller that has nothing, and there is
829
+ * no value to return or store.
378
830
  */
379
- async conditionalGet(path, ifNoneMatch) {
380
- const res = await this.fetchImpl(`${this.baseUrl}/api/content${path}`, {
381
- method: "GET",
382
- headers: {
383
- Authorization: `Bearer ${this.apiKey}`,
384
- ...ifNoneMatch ? { "If-None-Match": ifNoneMatch } : {},
385
- ...this.headers
831
+ async conditionalGet(path, ifNoneMatch, isExpected) {
832
+ const url = `${this.baseUrl}/api/content${path}`;
833
+ return withTimeout(url, this.timeout, async (signal) => {
834
+ const res = await this.fetchImpl(url, {
835
+ method: "GET",
836
+ headers: {
837
+ Authorization: `Bearer ${this.apiKey}`,
838
+ ...ifNoneMatch ? { "If-None-Match": ifNoneMatch } : {},
839
+ ...this.headers
840
+ },
841
+ signal
842
+ });
843
+ if (res.status === 304) {
844
+ if (!ifNoneMatch) throw unexpectedBody(url);
845
+ this.state.unreachable = false;
846
+ return { notModified: true, etag: res.headers.get("etag") ?? ifNoneMatch };
386
847
  }
848
+ if (!res.ok) throw await this.toError(res);
849
+ const etag = res.headers.get("etag") ?? void 0;
850
+ const value = res.status === 204 ? void 0 : await res.json();
851
+ if (!isExpected(value)) throw unexpectedBody(url);
852
+ this.state.unreachable = false;
853
+ return { notModified: false, value, etag };
387
854
  });
388
- if (res.status === 304) return { notModified: true, etag: res.headers.get("etag") ?? ifNoneMatch ?? void 0 };
389
- if (!res.ok) throw await this.toError(res);
390
- const etag = res.headers.get("etag") ?? void 0;
391
- if (res.status === 204) return { notModified: false, value: void 0, etag };
392
- return { notModified: false, value: await res.json(), etag };
393
- }
394
- async request(method, path, body) {
395
- const res = await this.fetchImpl(`${this.baseUrl}/api/content${path}`, {
396
- method,
397
- headers: {
398
- Authorization: `Bearer ${this.apiKey}`,
399
- ...body !== void 0 ? { "Content-Type": "application/json" } : {},
400
- ...this.headers
401
- },
402
- body: body !== void 0 ? JSON.stringify(body) : void 0
855
+ }
856
+ async request(method, path, body, timeout = this.timeout) {
857
+ const url = `${this.baseUrl}/api/content${path}`;
858
+ return withTimeout(url, timeout, async (signal) => {
859
+ const res = await this.fetchImpl(url, {
860
+ method,
861
+ headers: {
862
+ Authorization: `Bearer ${this.apiKey}`,
863
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {},
864
+ ...this.headers
865
+ },
866
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
867
+ signal
868
+ });
869
+ if (!res.ok) throw await this.toError(res);
870
+ if (res.status === 204) return void 0;
871
+ return await res.json();
403
872
  });
404
- if (!res.ok) throw await this.toError(res);
405
- if (res.status === 204) return void 0;
406
- return res.json();
407
873
  }
408
874
  /** Parse a non-2xx response into a `HavenError`, preferring its message. */
409
875
  async toError(res) {
@@ -416,7 +882,9 @@ var HavenClient = class _HavenClient {
416
882
  else if (typeof m?.statusMessage === "string") message = m.statusMessage;
417
883
  } catch {
418
884
  }
419
- return new HavenError(message, res.status, parsed);
885
+ const err = new HavenError(message, res.status, parsed);
886
+ if (res.headers.has("retry-after")) askedToWait.add(err);
887
+ return err;
420
888
  }
421
889
  };
422
890
  var DatasetHandle = class {
@@ -437,6 +905,10 @@ var DatasetHandle = class {
437
905
  update(recordUid, data) {
438
906
  return this.client.updateRecord(this.nodeSlug, this.datasetSlug, recordUid, data);
439
907
  }
908
+ /** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */
909
+ uploadFile(fieldSlug, file, opts) {
910
+ return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts);
911
+ }
440
912
  /** Clear cached reads for this dataset. */
441
913
  clearCache() {
442
914
  this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug });
@@ -455,9 +927,115 @@ function isPreviewRequest(input) {
455
927
  }
456
928
  return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM);
457
929
  }
930
+ async function withTimeout(url, ms, run) {
931
+ if (ms <= 0) return run(void 0);
932
+ const controller = new AbortController();
933
+ let timer;
934
+ const expired = new Promise((_, reject) => {
935
+ timer = setTimeout(() => {
936
+ const err = new Error(`The studio did not answer within ${ms}ms: ${url}`);
937
+ err.name = "TimeoutError";
938
+ controller.abort(err);
939
+ reject(err);
940
+ }, ms);
941
+ });
942
+ try {
943
+ return await Promise.race([run(controller.signal), expired]);
944
+ } finally {
945
+ clearTimeout(timer);
946
+ }
947
+ }
948
+ function normalizeTimeout(value) {
949
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
950
+ return value > MAX_TIMER ? 0 : value;
951
+ }
952
+ function uploadTimeout(clientTimeout, perCall) {
953
+ if (typeof perCall === "number" && perCall >= 0) return normalizeTimeout(perCall);
954
+ return clientTimeout === 0 ? 0 : Math.max(clientTimeout, MIN_UPLOAD_TIMEOUT);
955
+ }
956
+ function withoutContentType(headers) {
957
+ return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-type"));
958
+ }
959
+ function normalizeGatewayRetry(value) {
960
+ if (value === false) return void 0;
961
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;
962
+ return Math.min(value, MAX_GATEWAY_RETRY);
963
+ }
964
+ function normalizeWait(value) {
965
+ if (value === false) return Infinity;
966
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH;
967
+ return value > MAX_TIMER ? Infinity : value;
968
+ }
969
+ async function within(promise, ms) {
970
+ if (ms > MAX_TIMER) return { settled: true, value: await promise };
971
+ if (ms <= 0) {
972
+ promise.catch(() => {
973
+ });
974
+ return { settled: false };
975
+ }
976
+ let timer;
977
+ const late = new Promise((resolve) => {
978
+ timer = setTimeout(() => resolve({ settled: false }), ms);
979
+ });
980
+ try {
981
+ return await Promise.race([promise.then((value) => ({ settled: true, value })), late]);
982
+ } finally {
983
+ clearTimeout(timer);
984
+ }
985
+ }
986
+ function isThenable(value) {
987
+ return typeof value?.then === "function";
988
+ }
989
+ function isObject(value) {
990
+ return typeof value === "object" && value !== null && !Array.isArray(value);
991
+ }
992
+ function has(field, check) {
993
+ return (body) => isObject(body) && field in body && check(body[field]);
994
+ }
995
+ function unexpectedBody(url) {
996
+ const err = new Error(`The studio answered with an unexpected response: ${url}`);
997
+ err.name = "UnexpectedResponseError";
998
+ return err;
999
+ }
1000
+ function isTransientStatus(status) {
1001
+ return status >= 500 || status === 408 || status === 429;
1002
+ }
1003
+ var askedToWait = /* @__PURE__ */ new WeakSet();
1004
+ function isGatewayHiccup(err) {
1005
+ return err instanceof HavenError && (err.status === 502 || err.status === 503) && !askedToWait.has(err);
1006
+ }
1007
+ function sleep(ms) {
1008
+ return new Promise((resolve) => setTimeout(resolve, ms));
1009
+ }
1010
+ function isDefinitive(err) {
1011
+ return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err);
1012
+ }
1013
+ function isStudioAnswer(err) {
1014
+ const body = err.body;
1015
+ if (typeof body !== "object" || body === null) return false;
1016
+ return body.statusCode === err.status || body.status === err.status;
1017
+ }
1018
+ function isMissingRoute(err) {
1019
+ return err instanceof HavenError && err.status === 404 && isStudioAnswer(err);
1020
+ }
1021
+ function writeMayHaveLanded(err) {
1022
+ return !(err instanceof HavenError && err.status >= 400 && err.status < 500);
1023
+ }
458
1024
  function datasetPath(nodeSlug, datasetSlug) {
459
1025
  return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`;
460
1026
  }
1027
+ function matchLocale(requested, locales) {
1028
+ const canonical = (code) => code.trim().toLowerCase().replace(/_/g, "-");
1029
+ const known = locales.filter((locale) => typeof locale?.code === "string" && locale.code !== "");
1030
+ const wanted = canonical(requested);
1031
+ const exact = known.find((locale) => canonical(locale.code) === wanted);
1032
+ if (exact) return exact.code;
1033
+ const language = wanted.split("-")[0];
1034
+ const related = known.filter((locale) => canonical(locale.code).split("-")[0] === language);
1035
+ const close = related.find((locale) => locale.isDefault) ?? related[0];
1036
+ if (close) return close.code;
1037
+ return known.find((locale) => locale.isFallback)?.code;
1038
+ }
461
1039
  function localeQuery(locale) {
462
1040
  return locale ? `?locale=${encodeURIComponent(locale)}` : "";
463
1041
  }