@nordhavnhq/beacon 0.6.0 → 0.8.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.js CHANGED
@@ -1,6 +1,180 @@
1
+ import { builtinFileDeps, attachShared, ATTACH } from './chunk-FLRBCD6H.js';
1
2
  import { chartTypeInfo, CHART_TYPES, PALETTE_KEYS, CHART_AXES } from './chunk-UNIWH5QN.js';
2
3
  export { AGGREGATIONS, BUCKET_MODES, CHART_AXES, CHART_SORTS, CHART_TYPES, CHART_TYPE_INFO, DATE_BUCKET_VALUES, PALETTE_KEYS, chartTypeInfo, isBarChart, isPartChart } from './chunk-UNIWH5QN.js';
3
4
 
5
+ // src/runtime.ts
6
+ var BODY_LIMIT = 16 * 1024;
7
+ function environment() {
8
+ try {
9
+ return globalThis.process?.env ?? {};
10
+ } catch {
11
+ return {};
12
+ }
13
+ }
14
+ function readEnv(name) {
15
+ try {
16
+ const value = environment()[name];
17
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
18
+ } catch {
19
+ return void 0;
20
+ }
21
+ }
22
+ function nodeRuntime() {
23
+ const g = globalThis;
24
+ if (typeof g.window !== "undefined" || typeof g.document !== "undefined") return false;
25
+ if (g.navigator?.userAgent === "Cloudflare-Workers") return false;
26
+ return typeof g.process?.versions?.node === "string";
27
+ }
28
+ function nodeBuiltin(id) {
29
+ try {
30
+ const proc = globalThis.process;
31
+ return typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule(id) : void 0;
32
+ } catch {
33
+ return void 0;
34
+ }
35
+ }
36
+ async function loadHttp(protocol) {
37
+ const name = protocol === "https:" ? "node:https" : "node:http";
38
+ const builtin = nodeBuiltin(name);
39
+ if (builtin) return builtin;
40
+ return await import(
41
+ /* webpackIgnore: true */
42
+ /* @vite-ignore */
43
+ name
44
+ );
45
+ }
46
+ function unrefTimer(run, ms) {
47
+ const timer = setTimeout(run, ms);
48
+ timer.unref?.();
49
+ return timer;
50
+ }
51
+ function sentHeaders(apiKey, extra) {
52
+ const headers = { authorization: `Bearer ${apiKey}` };
53
+ for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value;
54
+ return headers;
55
+ }
56
+ function identityOf(baseUrl, headers) {
57
+ return `${baseUrl}
58
+ ${headers.authorization ?? ""}`;
59
+ }
60
+ function getJson(http, url, headers, timeoutMs) {
61
+ return new Promise((resolve) => {
62
+ let req;
63
+ let settled = false;
64
+ const finish = (body) => {
65
+ if (settled) return;
66
+ settled = true;
67
+ clearTimeout(timer);
68
+ try {
69
+ req?.destroy();
70
+ } catch {
71
+ }
72
+ resolve(body);
73
+ };
74
+ const timer = unrefTimer(() => finish(), timeoutMs);
75
+ try {
76
+ req = http.request(url, { method: "GET", headers, agent: false }, (res) => {
77
+ res.on("error", () => finish());
78
+ if (res.statusCode !== 200) {
79
+ res.resume();
80
+ finish();
81
+ return;
82
+ }
83
+ let body = "";
84
+ res.setEncoding("utf8");
85
+ res.on("data", (chunk) => {
86
+ body += chunk;
87
+ if (body.length > BODY_LIMIT) finish();
88
+ });
89
+ res.on("end", () => finish(parseJson(body)));
90
+ res.on("close", () => finish());
91
+ });
92
+ req.on("socket", (socket) => {
93
+ try {
94
+ socket.unref();
95
+ } catch {
96
+ }
97
+ });
98
+ req.on("error", () => finish());
99
+ req.end();
100
+ } catch {
101
+ finish();
102
+ }
103
+ });
104
+ }
105
+ function parseJson(text) {
106
+ try {
107
+ return JSON.parse(text);
108
+ } catch {
109
+ return void 0;
110
+ }
111
+ }
112
+ var WRITTEN = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/written/1");
113
+ function firstTime(key) {
114
+ const scope = globalThis;
115
+ let seen = scope[WRITTEN];
116
+ if (!seen) {
117
+ seen = /* @__PURE__ */ new Set();
118
+ scope[WRITTEN] = seen;
119
+ }
120
+ if (seen.has(key)) return false;
121
+ seen.add(key);
122
+ return true;
123
+ }
124
+ function loggerOf(option) {
125
+ if (option === false) return void 0;
126
+ return option ?? console;
127
+ }
128
+ function logLine(log, level, message, ...rest) {
129
+ try {
130
+ const write = log?.[level];
131
+ if (typeof write === "function") write.call(log, `[@nordhavnhq/beacon] ${message}`, ...rest);
132
+ } catch {
133
+ }
134
+ }
135
+
136
+ // src/announce.ts
137
+ var PROJECT_TIMEOUT_MS = 3e3;
138
+ var NAME_LIMIT = 200;
139
+ function isDevelopment(env) {
140
+ if (env.NODE_ENV?.trim().toLowerCase() !== "development") return false;
141
+ const ci = env.CI?.trim().toLowerCase();
142
+ return ci === void 0 || ci === "" || ci === "0" || ci === "false";
143
+ }
144
+ function wantAnnounce(settings) {
145
+ try {
146
+ return typeof settings.log?.info === "function" && !settings.customFetch && nodeRuntime() && isDevelopment(environment());
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+ function announceProject(baseUrl, headers, log) {
152
+ try {
153
+ if (!firstTime(`project
154
+ ${identityOf(baseUrl, headers)}`)) return;
155
+ const url = new URL(`${baseUrl}/api/content/project`);
156
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
157
+ loadHttp(url.protocol).then((http) => getJson(http, url, { ...headers, accept: "application/json" }, PROJECT_TIMEOUT_MS)).then((body) => {
158
+ const line = projectLine(body);
159
+ if (line) logLine(log, "info", line);
160
+ }, () => {
161
+ });
162
+ } catch {
163
+ }
164
+ }
165
+ function projectLine(body) {
166
+ const answer = body;
167
+ const project = printable(answer?.project?.name);
168
+ if (!project) return void 0;
169
+ const key = printable(answer?.key?.name);
170
+ return key ? `connected to "${project}" (key "${key}")` : `connected to "${project}"`;
171
+ }
172
+ function printable(value) {
173
+ if (typeof value !== "string") return void 0;
174
+ const text = value.replace(/[\u0000-\u001F\u007F]+/g, " ").trim().slice(0, NAME_LIMIT);
175
+ return text === "" ? void 0 : text;
176
+ }
177
+
4
178
  // src/cache.ts
5
179
  var EXPIRED = 1;
6
180
  var MemoryCacheStore = class {
@@ -131,13 +305,14 @@ var ContentCache = class {
131
305
  };
132
306
 
133
307
  // src/errors.ts
134
- var HavenError = class _HavenError extends Error {
308
+ var NordhavnError = class _NordhavnError extends Error {
135
309
  constructor(message, status, body) {
136
310
  super(message);
137
- this.name = "HavenError";
311
+ this.name = "NordhavnError";
138
312
  this.status = status;
139
313
  this.body = body;
140
- Object.setPrototypeOf(this, _HavenError.prototype);
314
+ this.code = errorCode(body);
315
+ Object.setPrototypeOf(this, _NordhavnError.prototype);
141
316
  }
142
317
  get isUnauthorized() {
143
318
  return this.status === 401;
@@ -149,6 +324,209 @@ var HavenError = class _HavenError extends Error {
149
324
  return this.status === 404;
150
325
  }
151
326
  };
327
+ function errorCode(body) {
328
+ if (typeof body !== "object" || body === null) return void 0;
329
+ const data = body.data;
330
+ if (typeof data !== "object" || data === null) return void 0;
331
+ const code = data.code;
332
+ return typeof code === "string" && code !== "" ? code : void 0;
333
+ }
334
+ function isStudioBody(status, body) {
335
+ if (typeof body !== "object" || body === null) return false;
336
+ const b = body;
337
+ return b.statusCode === status || b.status === status;
338
+ }
339
+
340
+ // src/live-policy.ts
341
+ var LIVE = {
342
+ /**
343
+ * No message (a version or a ping) for this long and the connection counts
344
+ * as dead. The studio pings every 25 s, so this is two missed pings and then
345
+ * some: a frozen process, a proxy that holds the stream without passing it on.
346
+ */
347
+ staleMs: 6e4,
348
+ /**
349
+ * A connection that stayed up this long, and heard from the studio, resets
350
+ * the backoff. One that is accepted and then closed sooner counts as a
351
+ * failure, so accept-then-close cannot loop.
352
+ */
353
+ stableMs: 6e4,
354
+ /**
355
+ * Even while the connection is healthy, it is checked against the stamp
356
+ * itself this often (once per connection, in the background, never awaited
357
+ * by a read): a safety net for a change the stream missed. It should never
358
+ * miss one, but one missed would otherwise stay unseen until the stream ends.
359
+ */
360
+ safetyPollMs: 5 * 6e4,
361
+ /**
362
+ * How long the stream may stay behind a check that found the studio ahead
363
+ * before it counts as having missed a change and is replaced. The studio
364
+ * sends a change up to 5.25 s late on purpose (at most once per 5 s per
365
+ * project), so a stream that is merely behind catches up well within this.
366
+ */
367
+ lagToleranceMs: 1e4,
368
+ /** The longest that check may take; it runs on an unref'd socket, so it never holds a process. */
369
+ safetyProbeTimeoutMs: 3e3,
370
+ /** The longest the studio may take to answer the connection with its headers. */
371
+ connectTimeoutMs: 1e4,
372
+ /** After the studio ended a connection that lived its full term: wait 1 to 5 s. */
373
+ cleanMinMs: 1e3,
374
+ cleanMaxMs: 5e3,
375
+ /** After a failure: at least 1 s, then a window that doubles per failure, up to 30 s. */
376
+ backoffBaseMs: 1e3,
377
+ backoffMaxMs: 3e4,
378
+ /** `Retry-After` is honoured within these bounds. */
379
+ retryAfterMinMs: 3e4,
380
+ retryAfterMaxMs: 60 * 6e4,
381
+ /** A `429` without `Retry-After` waits as long as the studio itself asks for. */
382
+ rateLimitedMs: 5 * 6e4,
383
+ /** The most added at random to a long wait, so the sites refused together do not return together. */
384
+ longJitterMs: 6e4
385
+ };
386
+ function planReconnect(outcome, ctx) {
387
+ const attempts = ctx.stable ? 0 : ctx.attempts;
388
+ if (outcome.kind === "closed" && ctx.stable) {
389
+ return { delay: between(LIVE.cleanMinMs, LIVE.cleanMaxMs, ctx.random), attempts: 0 };
390
+ }
391
+ if (outcome.kind === "refused") return planRefused(outcome, { ...ctx, attempts });
392
+ return backoff(attempts, ctx.random);
393
+ }
394
+ function planRefused(outcome, ctx) {
395
+ const { status, studio } = outcome;
396
+ const asked = parseRetryAfter(outcome.retryAfter, ctx.now);
397
+ if (status === 429 || status === 503 && asked !== void 0) {
398
+ const wait = clamp(asked ?? LIVE.rateLimitedMs, LIVE.retryAfterMinMs, LIVE.retryAfterMaxMs);
399
+ return { delay: wait + longJitter(wait, ctx.random), attempts: ctx.attempts };
400
+ }
401
+ const studioRefusal = studio && status >= 400 && status < 500 && status !== 408;
402
+ if (studioRefusal || status >= 300 && status < 400) {
403
+ return { delay: ctx.pauseMs + longJitter(ctx.pauseMs, ctx.random), attempts: ctx.attempts };
404
+ }
405
+ return backoff(ctx.attempts, ctx.random);
406
+ }
407
+ function backoff(attempts, random) {
408
+ const window = LIVE.backoffBaseMs * 2 ** Math.min(attempts, 16);
409
+ const delay = Math.min(LIVE.backoffMaxMs, LIVE.backoffBaseMs + random() * window);
410
+ return { delay, attempts: attempts + 1 };
411
+ }
412
+ function longJitter(wait, random) {
413
+ return random() * Math.min(LIVE.longJitterMs, wait / 5);
414
+ }
415
+ function between(min, max, random) {
416
+ return min + random() * (max - min);
417
+ }
418
+ function clamp(value, min, max) {
419
+ return Math.min(max, Math.max(min, value));
420
+ }
421
+ var IMF_FIXDATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/;
422
+ function parseRetryAfter(value, now) {
423
+ const text = value?.trim();
424
+ if (!text) return void 0;
425
+ if (/^\d+$/.test(text)) return Number(text) * 1e3;
426
+ if (!IMF_FIXDATE.test(text)) return void 0;
427
+ const at = Date.parse(text);
428
+ return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
429
+ }
430
+ var SHORT_LIVED_ENV = [
431
+ "VERCEL",
432
+ "NETLIFY",
433
+ "AWS_LAMBDA_FUNCTION_NAME",
434
+ "LAMBDA_TASK_ROOT",
435
+ "FUNCTIONS_WORKER_RUNTIME",
436
+ "FUNCTION_TARGET",
437
+ "DENO_DEPLOYMENT_ID",
438
+ "K_SERVICE",
439
+ "CI"
440
+ ];
441
+ function isShortLived(env) {
442
+ return SHORT_LIVED_ENV.some((name) => {
443
+ const value = env[name]?.trim().toLowerCase();
444
+ return value !== void 0 && value !== "" && value !== "0" && value !== "false";
445
+ });
446
+ }
447
+ function chooseLive(choice) {
448
+ if (!choice.runtime || !choice.revalidating || choice.option === false) return false;
449
+ if (choice.option === true) return true;
450
+ return !choice.customFetch && !choice.waitsForStudio && !isShortLived(choice.env);
451
+ }
452
+
453
+ // src/live-sse.ts
454
+ var DEFAULT_LIMIT = 64 * 1024;
455
+ var SseParser = class {
456
+ constructor(limit = DEFAULT_LIMIT) {
457
+ this.buffer = "";
458
+ this.data = [];
459
+ this.dataSize = 0;
460
+ this.event = "";
461
+ this.started = false;
462
+ /** The last chunk ended in `\r`: a `\n` that starts the next one belongs to it. */
463
+ this.afterCr = false;
464
+ this.limit = limit;
465
+ }
466
+ /**
467
+ * The events completed by `chunk`, in order. `null` once more than the limit
468
+ * is waiting for a line or an event to end: a stream like that is not the
469
+ * studio's, and the caller drops the connection rather than the memory.
470
+ */
471
+ feed(chunk) {
472
+ const text = this.prepare(this.buffer + chunk);
473
+ const out = [];
474
+ let pos = 0;
475
+ const breaks = { cr: text.indexOf("\r"), lf: text.indexOf("\n") };
476
+ while (pos < text.length) {
477
+ const end = nextBreak(text, pos, breaks);
478
+ if (end === -1) break;
479
+ let next = end + 1;
480
+ if (text.charCodeAt(end) === 13) {
481
+ if (end + 1 === text.length) this.afterCr = true;
482
+ else if (text.charCodeAt(end + 1) === 10) next = end + 2;
483
+ }
484
+ this.line(text.slice(pos, end), out);
485
+ pos = next;
486
+ }
487
+ this.buffer = text.slice(pos);
488
+ if (this.buffer.length > this.limit || this.dataSize > this.limit) return null;
489
+ return out;
490
+ }
491
+ /** Drops the `\n` of a `\r\n` split over two chunks, and a byte order mark at the start. */
492
+ prepare(text) {
493
+ let out = text;
494
+ if (this.afterCr && out.length > 0) {
495
+ this.afterCr = false;
496
+ if (out.charCodeAt(0) === 10) out = out.slice(1);
497
+ }
498
+ if (!this.started && out.length > 0) {
499
+ this.started = true;
500
+ if (out.charCodeAt(0) === 65279) out = out.slice(1);
501
+ }
502
+ return out;
503
+ }
504
+ line(line, out) {
505
+ if (line === "") {
506
+ if (this.data.length > 0) out.push({ event: this.event || "message", data: this.data.join("\n") });
507
+ this.data = [];
508
+ this.dataSize = 0;
509
+ this.event = "";
510
+ return;
511
+ }
512
+ if (line.charCodeAt(0) === 58) return;
513
+ const colon = line.indexOf(":");
514
+ const field = colon === -1 ? line : line.slice(0, colon);
515
+ let value = colon === -1 ? "" : line.slice(colon + 1);
516
+ if (value.charCodeAt(0) === 32) value = value.slice(1);
517
+ if (field === "event") this.event = value;
518
+ else if (field === "data") {
519
+ this.data.push(value);
520
+ this.dataSize += value.length + 1;
521
+ }
522
+ }
523
+ };
524
+ function nextBreak(text, pos, breaks) {
525
+ if (breaks.cr !== -1 && breaks.cr < pos) breaks.cr = text.indexOf("\r", pos);
526
+ if (breaks.lf !== -1 && breaks.lf < pos) breaks.lf = text.indexOf("\n", pos);
527
+ const { cr, lf } = breaks;
528
+ return cr === -1 ? lf : lf === -1 ? cr : Math.min(cr, lf);
529
+ }
152
530
 
153
531
  // src/version.ts
154
532
  var UNSUPPORTED_PAUSE_MS = 15 * 6e4;
@@ -172,6 +550,23 @@ var VersionTracker = class {
172
550
  current() {
173
551
  return this.version;
174
552
  }
553
+ /**
554
+ * A stamp heard from the live connection, current as of `at`. It counts as a
555
+ * check made at that moment: the next probe is due one interval after it.
556
+ * Never a request of its own, and never a reason for one.
557
+ */
558
+ observe(version, at) {
559
+ this.version = version;
560
+ this.lastChecked = Math.max(this.lastChecked, at);
561
+ }
562
+ /**
563
+ * Makes the next `refresh` ask at once, whatever the interval says (still
564
+ * not during the pause for a server without the route). For when the stamp
565
+ * may have moved unseen: the live connection went silent.
566
+ */
567
+ due() {
568
+ this.lastChecked = 0;
569
+ }
175
570
  /**
176
571
  * Refresh the stamp if we are due. Resolves once the answer is in, so the
177
572
  * read that triggered it sees an up-to-date stamp. A failed probe leaves the
@@ -205,10 +600,486 @@ var VersionTracker = class {
205
600
  }
206
601
  };
207
602
 
208
- // src/client.ts
209
- var PREVIEW_PARAM = "sl-preview";
603
+ // src/live.ts
604
+ var REGISTRY = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/live-hubs/2");
605
+ var LINGER_MS = 5 * 6e4;
606
+ var REFUSAL_BODY_LIMIT = 16 * 1024;
607
+ function hubs() {
608
+ const scope = globalThis;
609
+ let map = scope[REGISTRY];
610
+ if (!map) {
611
+ map = /* @__PURE__ */ new Map();
612
+ scope[REGISTRY] = map;
613
+ }
614
+ return map;
615
+ }
616
+ var collected = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(({ hub, token }) => {
617
+ try {
618
+ hub.detach(token, true);
619
+ } catch {
620
+ }
621
+ }) : void 0;
622
+ function wantLive(settings) {
623
+ try {
624
+ return chooseLive({ ...settings, runtime: nodeRuntime(), env: environment() });
625
+ } catch {
626
+ return false;
627
+ }
628
+ }
629
+ var LiveLink = class {
630
+ constructor(baseUrl, apiKey, headers, owner) {
631
+ this.baseUrl = baseUrl;
632
+ this.apiKey = apiKey;
633
+ this.headers = headers;
634
+ this.token = {};
635
+ this.silences = 0;
636
+ this.closed = false;
637
+ this.owner = owner;
638
+ }
639
+ /**
640
+ * The stamp gate in front of a read, in place of `tracker.refresh`. While
641
+ * the connection is healthy the stamp it heard counts as a fresh check and
642
+ * nothing is fetched; otherwise the poll runs, at once when the connection
643
+ * went silent since the last read. Connects on the first call.
644
+ */
645
+ gate(tracker, now) {
646
+ try {
647
+ const view = this.join()?.view(now);
648
+ if (view?.healthy && view.version !== void 0) {
649
+ tracker.observe(view.version, view.at);
650
+ this.hub?.safetyCheck(now);
651
+ return Promise.resolve();
652
+ }
653
+ if (view && view.silences !== this.silences) {
654
+ this.silences = view.silences;
655
+ tracker.due();
656
+ }
657
+ } catch {
658
+ }
659
+ return tracker.refresh(now);
660
+ }
661
+ /** Leaves the connection for good; the last client out closes it. */
662
+ close() {
663
+ if (this.closed) return;
664
+ this.closed = true;
665
+ const hub = this.hub;
666
+ this.hub = void 0;
667
+ this.owner = void 0;
668
+ if (!hub) return;
669
+ collected?.unregister(this.token);
670
+ try {
671
+ hub.detach(this.token, false);
672
+ } catch {
673
+ }
674
+ }
675
+ join() {
676
+ if (this.hub || this.closed) return this.hub;
677
+ const url = eventsUrl(this.baseUrl);
678
+ if (!url) {
679
+ this.closed = true;
680
+ return void 0;
681
+ }
682
+ const registry = hubs();
683
+ const headers = liveHeaders(this.apiKey, this.headers);
684
+ const id = identityOf(this.baseUrl, headers);
685
+ let hub = registry.get(id);
686
+ if (!hub) {
687
+ hub = new LiveHub(id, url, headers);
688
+ registry.set(id, hub);
689
+ }
690
+ this.silences = hub.attach(this.token);
691
+ if (this.owner) collected?.register(this.owner, { hub, token: this.token }, this.token);
692
+ this.owner = void 0;
693
+ this.hub = hub;
694
+ return hub;
695
+ }
696
+ };
697
+ function eventsUrl(baseUrl) {
698
+ try {
699
+ const url = new URL(`${baseUrl}/api/content/events`);
700
+ return url.protocol === "http:" || url.protocol === "https:" ? url : void 0;
701
+ } catch {
702
+ return void 0;
703
+ }
704
+ }
705
+ function liveHeaders(apiKey, extra) {
706
+ const headers = sentHeaders(apiKey, extra);
707
+ headers.accept = "text/event-stream";
708
+ headers["cache-control"] = "no-cache";
709
+ headers["accept-encoding"] = "identity";
710
+ return headers;
711
+ }
712
+ var LiveHub = class {
713
+ constructor(id, url, headers) {
714
+ this.id = id;
715
+ this.url = url;
716
+ this.headers = headers;
717
+ this.state = "idle";
718
+ this.openedAt = 0;
719
+ this.lastHeardAt = 0;
720
+ /** Failures in a row, for the backoff. */
721
+ this.attempts = 0;
722
+ this.retryAt = 0;
723
+ this.silences = 0;
724
+ this.owners = /* @__PURE__ */ new Set();
725
+ /** Version events on the open connection: tells a stream that moved from one that did not. */
726
+ this.tells = 0;
727
+ /** When the open connection was last checked against the stamp itself. */
728
+ this.checkedAt = 0;
729
+ this.checking = false;
730
+ }
731
+ attach(token) {
732
+ clearTimeout(this.lingerTimer);
733
+ this.lingerTimer = void 0;
734
+ this.owners.add(token);
735
+ return this.silences;
736
+ }
737
+ detach(token, linger) {
738
+ if (!this.owners.delete(token) || this.owners.size > 0) return;
739
+ clearTimeout(this.lingerTimer);
740
+ if (linger) this.lingerTimer = unrefTimer(() => this.owners.size === 0 && this.dispose(), LINGER_MS);
741
+ else this.dispose();
742
+ }
743
+ /**
744
+ * The state of the connection for a read at `now`, after the checks a read
745
+ * makes: connect the first time; a connection silent for `LIVE.staleMs` is
746
+ * dead (a frozen process misses events and runs no timers, so the watchdog
747
+ * alone cannot be trusted); a reconnect whose time has come goes now.
748
+ */
749
+ view(now) {
750
+ if (this.state === "idle") this.connect();
751
+ else if (this.state === "open" && now - this.lastHeardAt > LIVE.staleMs) this.current?.end({ kind: "silent" });
752
+ else if (this.state === "waiting" && now >= this.retryAt) this.connect();
753
+ if (this.state === "open" && this.behind) this.judgeBehind(now);
754
+ return {
755
+ healthy: this.state === "open" && this.version !== void 0,
756
+ version: this.version,
757
+ at: this.lastHeardAt,
758
+ silences: this.silences
759
+ };
760
+ }
761
+ /**
762
+ * The safety net, at most once per `LIVE.safetyPollMs` per connection, set
763
+ * off by a read: ask the stamp and compare it with the stream's. Never
764
+ * awaited by a read, never reported, and over an unref'd socket, so it holds
765
+ * up no read and no process. Only a clear answer counts: a failed check, a
766
+ * check that outlived its connection, or one during which the stream told a
767
+ * new stamp proves nothing. A studio ahead of the stream is noted, not acted
768
+ * on: see `judgeBehind`.
769
+ */
770
+ safetyCheck(now) {
771
+ if (this.state !== "open" || this.version === void 0 || this.checking || this.behind) return;
772
+ if (now - this.checkedAt < LIVE.safetyPollMs) return;
773
+ this.checking = true;
774
+ this.checkedAt = now;
775
+ const attempt = this.current;
776
+ const tells = this.tells;
777
+ const heard = this.version;
778
+ const url = versionUrl(this.url);
779
+ const headers = { ...this.headers, accept: "application/json" };
780
+ loadHttp(url.protocol).then((http) => probeStamp(http, url, headers), () => void 0).then(
781
+ (stamp) => {
782
+ this.checking = false;
783
+ if (stamp === void 0 || attempt !== this.current || tells !== this.tells) return;
784
+ if (stamp !== heard) this.behind = { tells, since: Date.now() };
785
+ },
786
+ () => {
787
+ this.checking = false;
788
+ }
789
+ );
790
+ }
791
+ /**
792
+ * A check found the studio ahead of the stream. The studio sends late on
793
+ * purpose (its 5 s throttle), so that alone is no fault: only a stream that
794
+ * told nothing new for `LIVE.lagToleranceMs` since then missed a change. The
795
+ * first read after that drops it, which makes that same read check the stamp
796
+ * itself (and the hub reconnect).
797
+ */
798
+ judgeBehind(now) {
799
+ const behind = this.behind;
800
+ if (this.tells !== behind.tells) this.behind = void 0;
801
+ else if (now - behind.since >= LIVE.lagToleranceMs) {
802
+ this.behind = void 0;
803
+ this.current?.end({ kind: "silent" });
804
+ }
805
+ }
806
+ connect() {
807
+ clearTimeout(this.retryTimer);
808
+ this.state = "connecting";
809
+ const attempt = new LiveAttempt(this);
810
+ this.current = attempt;
811
+ loadHttp(this.url.protocol).then(
812
+ (http) => {
813
+ if (this.current === attempt) attempt.start(http, this.url, this.headers);
814
+ },
815
+ () => {
816
+ if (this.current === attempt) this.halt();
817
+ }
818
+ );
819
+ }
820
+ /** The attempt got its stream: the studio's answer is in. */
821
+ opened(attempt) {
822
+ if (attempt !== this.current) return;
823
+ this.state = "open";
824
+ this.version = void 0;
825
+ this.openedAt = Date.now();
826
+ this.lastHeardAt = this.openedAt;
827
+ this.checkedAt = this.openedAt;
828
+ this.behind = void 0;
829
+ }
830
+ /** Something came in on the stream: a sign of life. */
831
+ heard(attempt) {
832
+ if (attempt === this.current) this.lastHeardAt = Date.now();
833
+ }
834
+ /** A `version` event, its data as sent. */
835
+ told(attempt, data) {
836
+ if (attempt !== this.current) return;
837
+ try {
838
+ const version = JSON.parse(data)?.version;
839
+ if (typeof version === "string" && version !== "") {
840
+ this.version = version;
841
+ this.tells++;
842
+ }
843
+ } catch {
844
+ }
845
+ }
846
+ /** The attempt is over: plan the next one. `outcome` is absent when the hub ended it itself. */
847
+ ended(attempt, outcome) {
848
+ if (attempt !== this.current) return;
849
+ this.current = void 0;
850
+ const now = Date.now();
851
+ const stable = this.state === "open" && this.version !== void 0 && now - this.openedAt >= LIVE.stableMs;
852
+ this.version = void 0;
853
+ if (!outcome || this.state === "stopped") return;
854
+ if (outcome.kind === "silent") this.silences++;
855
+ const plan = planReconnect(outcome, { attempts: this.attempts, stable, pauseMs: UNSUPPORTED_PAUSE_MS, now, random: Math.random });
856
+ this.attempts = plan.attempts;
857
+ this.state = "waiting";
858
+ this.retryAt = now + plan.delay;
859
+ this.retryTimer = unrefTimer(() => {
860
+ if (this.state === "waiting") this.connect();
861
+ }, plan.delay);
862
+ }
863
+ /** Stops for good (no `http` here, or the last client left): reads keep to the poll. */
864
+ halt() {
865
+ this.state = "stopped";
866
+ clearTimeout(this.retryTimer);
867
+ const attempt = this.current;
868
+ this.current = void 0;
869
+ this.version = void 0;
870
+ attempt?.end();
871
+ }
872
+ dispose() {
873
+ this.halt();
874
+ const registry = hubs();
875
+ if (registry.get(this.id) === this) registry.delete(this.id);
876
+ }
877
+ };
878
+ var LiveAttempt = class {
879
+ constructor(hub) {
880
+ this.hub = hub;
881
+ this.done = false;
882
+ this.timers = [];
883
+ }
884
+ start(http, url, headers) {
885
+ if (this.done) return;
886
+ this.timers.push(unrefTimer(() => this.end({ kind: "failed" }), LIVE.connectTimeoutMs));
887
+ try {
888
+ const req = http.request(url, { method: "GET", headers, agent: false }, (res) => this.answered(res));
889
+ this.req = req;
890
+ req.on("socket", (socket) => {
891
+ try {
892
+ socket.unref();
893
+ } catch {
894
+ this.end({ kind: "refused", status: 400, studio: true, retryAfter: null });
895
+ return;
896
+ }
897
+ try {
898
+ socket.setKeepAlive(true, 3e4);
899
+ } catch {
900
+ }
901
+ });
902
+ req.on("error", () => this.end({ kind: "failed" }));
903
+ req.end();
904
+ } catch {
905
+ this.end({ kind: "refused", status: 400, studio: true, retryAfter: null });
906
+ }
907
+ }
908
+ /** Ends the attempt; the hub plans what comes next from `outcome`, unless it ended it itself. */
909
+ end(outcome) {
910
+ if (this.done) return;
911
+ this.done = true;
912
+ for (const timer of this.timers) clearTimeout(timer);
913
+ try {
914
+ this.req?.destroy();
915
+ } catch {
916
+ }
917
+ this.hub.ended(this, outcome);
918
+ }
919
+ answered(res) {
920
+ res.on("error", () => this.end({ kind: "failed" }));
921
+ if (this.done) {
922
+ res.resume();
923
+ return;
924
+ }
925
+ const type = String(res.headers["content-type"] ?? "");
926
+ if (res.statusCode === 200 && type.includes("text/event-stream")) this.stream(res);
927
+ else this.refused(res);
928
+ }
929
+ stream(res) {
930
+ for (const timer of this.timers) clearTimeout(timer);
931
+ this.timers = [];
932
+ const watchdog = unrefTimer(() => this.end({ kind: "silent" }), LIVE.staleMs);
933
+ this.timers.push(watchdog);
934
+ this.hub.opened(this);
935
+ const parser = new SseParser();
936
+ res.setEncoding("utf8");
937
+ res.on("data", (chunk) => {
938
+ if (this.done) return;
939
+ watchdog.refresh?.();
940
+ this.hub.heard(this);
941
+ const events = parser.feed(chunk);
942
+ if (events === null) {
943
+ this.end({ kind: "failed" });
944
+ return;
945
+ }
946
+ for (const event of events) {
947
+ if (event.event === "version") this.hub.told(this, event.data);
948
+ }
949
+ });
950
+ res.on("end", () => this.end({ kind: "closed" }));
951
+ res.on("close", () => this.end({ kind: "failed" }));
952
+ }
953
+ /** Not the stream: read a little of the body, to tell the studio's own refusal from a proxy's. */
954
+ refused(res) {
955
+ const status = res.statusCode ?? 0;
956
+ const header = res.headers["retry-after"];
957
+ const retryAfter = (Array.isArray(header) ? header[0] : header) ?? null;
958
+ let body = "";
959
+ res.setEncoding("utf8");
960
+ res.on("data", (chunk) => {
961
+ body += chunk;
962
+ if (body.length > REFUSAL_BODY_LIMIT) res.destroy();
963
+ });
964
+ const settle = () => this.end({ kind: "refused", status, retryAfter, studio: isStudioBody(status, parseJson(body)) });
965
+ res.on("end", settle);
966
+ res.on("close", settle);
967
+ }
968
+ };
969
+ function versionUrl(events) {
970
+ const url = new URL(events.href);
971
+ url.pathname = url.pathname.replace(/events$/, "version");
972
+ return url;
973
+ }
974
+ async function probeStamp(http, url, headers) {
975
+ const stamp = (await getJson(http, url, headers, LIVE.safetyProbeTimeoutMs))?.version;
976
+ return typeof stamp === "string" && stamp !== "" ? stamp : void 0;
977
+ }
978
+
979
+ // src/options.ts
210
980
  var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
981
+ var API_KEY_ENV = "NORDHAVN_API_KEY";
982
+ var BASE_URL_ENV = "NORDHAVN_BASE_URL";
983
+ function connectionOf(options) {
984
+ const apiKey = "apiKey" in options ? options.apiKey?.trim() : readEnv(API_KEY_ENV);
985
+ if (!apiKey) throw new Error(missingKey(options));
986
+ const baseUrl = "baseUrl" in options ? options.baseUrl === void 0 ? DEFAULT_BASE_URL : options.baseUrl.trim() : readEnv(BASE_URL_ENV) ?? DEFAULT_BASE_URL;
987
+ if (!baseUrl) {
988
+ throw new Error("NordhavnClient: `baseUrl` is empty (leave it out for NORDHAVN_BASE_URL or the hosted platform)");
989
+ }
990
+ return { apiKey, baseUrl: baseUrl.replace(/\/+$/, "") };
991
+ }
992
+ function missingKey(options) {
993
+ if (!("apiKey" in options)) return `NordhavnClient: \`apiKey\` is required: pass it, or set ${API_KEY_ENV}`;
994
+ if (options.apiKey === void 0) {
995
+ return `NordhavnClient: \`apiKey\` is required (it was passed as \`undefined\`; leave it out altogether to read ${API_KEY_ENV})`;
996
+ }
997
+ return "NordhavnClient: `apiKey` is empty (an empty string does not fall back to the environment)";
998
+ }
999
+ function cacheStore(options, identity, log) {
1000
+ if (options.enabled === false) return options.store;
1001
+ const dir = options.dir || void 0;
1002
+ if (dir !== void 0 && options.store !== void 0) {
1003
+ throw new Error("NordhavnClient: pass `cache.dir` or `cache.store`, not both");
1004
+ }
1005
+ const warn = log && typeof log.warn === "function" ? (...args) => log.warn(...args) : void 0;
1006
+ const scope = { identity, adoptLegacy: dir === void 0, warn };
1007
+ let attached;
1008
+ if (dir !== void 0) {
1009
+ const deps = builtinFileDeps(nodeBuiltin);
1010
+ if (!deps) {
1011
+ if (firstTime("no-file-cache")) {
1012
+ logLine(log, "warn", "`cache.dir` needs Node 22.3 or later (`process.getBuiltinModule`): caching in memory. `FileCacheStore` from `@nordhavnhq/beacon/file-store` works on any Node.");
1013
+ }
1014
+ return void 0;
1015
+ }
1016
+ attached = attachShared({ dir, maxEntries: options.maxEntries }, deps, scope);
1017
+ } else {
1018
+ const attach = options.store?.[ATTACH];
1019
+ if (typeof attach !== "function") return options.store;
1020
+ attached = attach.call(options.store, scope);
1021
+ }
1022
+ if (!attached) {
1023
+ logLine(log, "warn", "this FileCacheStore (a subclass, used as given) already holds the cache of another key, so this client caches in memory. Give each key its own store.");
1024
+ return new MemoryCacheStore(options.maxEntries ?? 500);
1025
+ }
1026
+ if (attached.first) tellDisk(attached, dir === void 0, log);
1027
+ return attached.store;
1028
+ }
1029
+ function tellDisk(attached, fromStore, log) {
1030
+ const { folder, loaded, legacy, copied } = attached;
1031
+ if (copied > 0 && firstTime(`copied
1032
+ ${folder}`)) {
1033
+ logLine(log, "info", `file cache ${folder}: ${count(copied, "entry", "entries")} copied from the cache beacon 0.7 kept in ${attached.dir}, which is left as it is`);
1034
+ } else if (copied === 0 && legacy > 0 && loaded === 0 && firstTime(`legacy
1035
+ ${folder}`)) {
1036
+ const why = fromStore ? "only the first start after 0.7 copies them" : "`cache.dir` keeps its entries per key";
1037
+ logLine(log, "info", `file cache ${attached.dir}: ${count(legacy, "entry", "entries")} left by beacon 0.7 ${legacy === 1 ? "is" : "are"} not used for this key (${why}); this cache starts empty in ${folder}`);
1038
+ }
1039
+ if (!firstTime(`disk
1040
+ ${folder}`)) return;
1041
+ if (loaded > 0) logLine(log, "info", `file cache ${folder}: ${count(loaded, "entry", "entries")} on disk`);
1042
+ else logLine(log, "warn", `file cache ${folder}: nothing on disk yet, so until the studio has answered once, a read fails while it is unreachable. Expected on a first start; on every start, the directory does not survive a restart (put it on a persistent volume).`);
1043
+ }
1044
+ function count(n, one, many) {
1045
+ return `${n} ${n === 1 ? one : many}`;
1046
+ }
1047
+
1048
+ // src/rate-gate.ts
1049
+ var GATES = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/rate-gates/2");
1050
+ var GATE_MAX_MS = 6e4;
1051
+ function monotonicNow() {
1052
+ const perf = globalThis.performance;
1053
+ return typeof perf?.now === "function" ? perf.now() : Date.now();
1054
+ }
1055
+ function gates() {
1056
+ const scope = globalThis;
1057
+ let map = scope[GATES];
1058
+ if (!map) {
1059
+ map = /* @__PURE__ */ new Map();
1060
+ scope[GATES] = map;
1061
+ }
1062
+ return map;
1063
+ }
1064
+ function gateRemaining(identity, now = monotonicNow()) {
1065
+ const map = gates();
1066
+ const opensAt = map.get(identity) ?? 0;
1067
+ if (opensAt > now) return opensAt - now;
1068
+ map.delete(identity);
1069
+ return 0;
1070
+ }
1071
+ function shutGate(identity, ms, now = monotonicNow()) {
1072
+ const map = gates();
1073
+ const opensAt = now + Math.min(Math.max(0, ms), GATE_MAX_MS);
1074
+ if (opensAt > (map.get(identity) ?? 0)) map.set(identity, opensAt);
1075
+ }
1076
+ function spreadOf(ms, random = Math.random) {
1077
+ return random() * Math.max(1e3, ms / 5);
1078
+ }
1079
+
1080
+ // src/client.ts
211
1081
  var DEFAULT_TIMEOUT = 1e4;
1082
+ var MIN_WRITE_TIMEOUT = 3e4;
212
1083
  var MIN_UPLOAD_TIMEOUT = 6e4;
213
1084
  var VERSION_TIMEOUT = 3e3;
214
1085
  var DEFAULT_WAIT_FOR_FRESH = 1e3;
@@ -217,8 +1088,10 @@ var STORED_LIMIT = 5e3;
217
1088
  var LOCALES_RETRY_MS = 6e4;
218
1089
  var DEFAULT_GATEWAY_RETRY = 200;
219
1090
  var MAX_GATEWAY_RETRY = 6e4;
220
- var HavenClient = class {
221
- constructor(options) {
1091
+ var DEFAULT_RATE_LIMIT_WAIT = 1e4;
1092
+ var MAX_RATE_LIMIT_RETRIES = 2;
1093
+ var NordhavnClient = class {
1094
+ constructor(options = {}) {
222
1095
  /**
223
1096
  * The refresh under way per cache key, so concurrent reads of one key share
224
1097
  * one request, with the ticket it left on (see `state.ticket`).
@@ -231,8 +1104,7 @@ var HavenClient = class {
231
1104
  this.storedBy = /* @__PURE__ */ new Map();
232
1105
  /**
233
1106
  * 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.
1107
+ * its own.
236
1108
  */
237
1109
  this.state = {
238
1110
  /**
@@ -253,26 +1125,32 @@ var HavenClient = class {
253
1125
  */
254
1126
  locales: void 0,
255
1127
  /** Epoch ms before which the locales are not asked for again, after that failed. */
256
- localesRetryAt: 0
1128
+ localesRetryAt: 0,
1129
+ /** Whether the first read still has to say which project this is (`announceProject`). */
1130
+ announce: false
257
1131
  };
258
- if (!options.apiKey) throw new Error("HavenClient: `apiKey` is required");
259
- this.apiKey = options.apiKey;
260
- this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
1132
+ const { apiKey, baseUrl } = connectionOf(options);
1133
+ this.apiKey = apiKey;
1134
+ this.baseUrl = baseUrl;
261
1135
  const resolvedFetch = options.fetch ?? globalThis.fetch;
262
1136
  if (!resolvedFetch) {
263
- throw new Error("HavenClient: no `fetch` available; pass one via options.fetch");
1137
+ throw new Error("NordhavnClient: no `fetch` available; pass one via options.fetch");
264
1138
  }
265
1139
  this.fetchImpl = resolvedFetch.bind(globalThis);
266
1140
  this.headers = options.headers ?? {};
267
1141
  this.locale = options.locale || void 0;
268
- this.readDefault = options.preview !== true;
269
1142
  this.timeout = normalizeTimeout(options.timeout);
1143
+ this.writeTimeout = normalizeWriteTimeout(this.timeout, options.writeTimeout);
270
1144
  this.onError = options.onError;
1145
+ this.log = loggerOf(options.logger);
1146
+ this.identity = identityOf(this.baseUrl, sentHeaders(this.apiKey, this.headers));
271
1147
  const cacheOpt = options.cache;
272
1148
  const cacheOptions = cacheOpt === false ? { enabled: false } : cacheOpt === true || cacheOpt === void 0 ? {} : cacheOpt;
273
- this.cache = new ContentCache(cacheOptions);
1149
+ this.cache = new ContentCache({ ...cacheOptions, store: cacheStore(cacheOptions, this.identity, this.log) });
274
1150
  this.waitForFresh = normalizeWait(cacheOptions.waitForFresh);
275
1151
  this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry);
1152
+ this.rateLimitWait = normalizeRateLimitWait(options.rateLimitWait);
1153
+ this.state.announce = wantAnnounce({ log: this.log, customFetch: options.fetch !== void 0 });
276
1154
  const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false ? 0 : cacheOptions.revalidate ?? 6e4;
277
1155
  const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT);
278
1156
  this.versionTracker = new VersionTracker(
@@ -291,39 +1169,23 @@ var HavenClient = class {
291
1169
  revalidate,
292
1170
  isMissingRoute
293
1171
  );
1172
+ const live = wantLive({
1173
+ option: options.live,
1174
+ revalidating: revalidate > 0,
1175
+ customFetch: options.fetch !== void 0,
1176
+ waitsForStudio: this.waitForFresh === Infinity
1177
+ });
1178
+ this.live = live ? new LiveLink(this.baseUrl, this.apiKey, this.headers, this) : void 0;
294
1179
  }
295
- // ── Preview scoping ─────────────────────────────────────────────────────────
296
1180
  /**
297
- * A per-request view of this client that skips the cache when the request
298
- * comes from a Nordhavn OS surface preview, and behaves exactly like this
299
- * client otherwise. Reads still refresh the shared cache, so an editor
300
- * refreshing the preview also warms what real visitors get.
301
- *
302
- * Accepts whatever your framework hands you: a `Request`, a URL string or
303
- * `URL`, `URLSearchParams`, or a plain searchParams object.
304
- *
305
- * ```ts
306
- * // Next.js app router
307
- * export default async function Page({ searchParams }) {
308
- * const posts = await studio.forRequest(await searchParams).dataset('blog', 'posts').list()
309
- * }
310
- * ```
311
- *
312
- * Note this only bypasses the SDK's own cache. If the page itself sits behind
313
- * a CDN or framework data cache, that layer needs the same treatment (e.g.
314
- * `cache: 'no-store'` when the preview marker is present) or the editor keeps
315
- * seeing a stale page no matter what this client returns.
1181
+ * Lets go of the live connection: the last client of a server and key to
1182
+ * close it closes the connection. The client keeps working, on the stamp
1183
+ * check alone. Not needed to let a process end (the connection never keeps
1184
+ * one alive); for a test, or code that builds clients and drops them.
316
1185
  */
317
- forRequest(input) {
318
- if (!this.readDefault) return this;
319
- if (!isPreviewRequest(input)) return this;
320
- const view = Object.create(this);
321
- view.readDefault = false;
322
- return view;
323
- }
324
- /** Whether this client bypasses the cache (i.e. came from a preview request). */
325
- get isPreview() {
326
- return !this.readDefault;
1186
+ close() {
1187
+ this.live?.close();
1188
+ this.live = void 0;
327
1189
  }
328
1190
  // ── Introspection ─────────────────────────────────────────────────────────
329
1191
  /** The full content shape this key can reach: nodes, datasets, field schemas. */
@@ -370,7 +1232,7 @@ var HavenClient = class {
370
1232
  async readLocale(opts) {
371
1233
  const requested = this.resolveLocale(opts)?.trim() || void 0;
372
1234
  if (requested === void 0 || !this.cache.enabled) return requested;
373
- const bypass = !(opts?.cache ?? this.readDefault);
1235
+ const bypass = opts?.cache === false;
374
1236
  const configured = await this.configuredLocales(!bypass);
375
1237
  return configured ? matchLocale(requested, configured) : requested;
376
1238
  }
@@ -477,7 +1339,7 @@ var HavenClient = class {
477
1339
  * The field decides what it takes: its `mimes` and `max_size` rules, within
478
1340
  * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
479
1341
  * studio reads the type from the content, so a renamed file is refused. Only
480
- * top-level fields. A file of the wrong type or size throws `HavenError` 400
1342
+ * top-level fields. A file of the wrong type or size throws `NordhavnError` 400
481
1343
  * with a message fit to show; other refusals (400, 403, 404) are setup
482
1344
  * errors. More than 10 uploads a minute per key throws 429. From a Node
483
1345
  * `Buffer`, send `new Blob([buffer])` with a `filename`.
@@ -490,7 +1352,7 @@ var HavenClient = class {
490
1352
  async uploadFile(nodeSlug, datasetSlug, fieldSlug, file, opts) {
491
1353
  const filename = opts?.filename ?? file.name;
492
1354
  if (!filename) {
493
- throw new Error("HavenClient.uploadFile: the file has no name; pass `filename` (with its extension)");
1355
+ throw new Error("NordhavnClient.uploadFile: the file has no name; pass `filename` (with its extension)");
494
1356
  }
495
1357
  const form = new FormData();
496
1358
  form.set("file", file, filename);
@@ -498,7 +1360,7 @@ var HavenClient = class {
498
1360
  form.set("datasetSlug", datasetSlug);
499
1361
  form.set("fieldSlug", fieldSlug);
500
1362
  const url = `${this.baseUrl}/api/content/files`;
501
- const timeout = uploadTimeout(this.timeout, opts?.timeout);
1363
+ const timeout = uploadTimeout(this.writeTimeout, opts?.timeout);
502
1364
  return withTimeout(url, timeout, async (signal) => {
503
1365
  const res = await this.fetchImpl(url, {
504
1366
  method: "POST",
@@ -525,7 +1387,7 @@ var HavenClient = class {
525
1387
  async write(method, path, body, nodeSlug, datasetSlug) {
526
1388
  let res;
527
1389
  try {
528
- res = await this.request(method, path, body);
1390
+ res = await this.request(method, path, body, this.writeTimeout);
529
1391
  } catch (err) {
530
1392
  if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, "recheck");
531
1393
  throw err;
@@ -692,13 +1554,22 @@ var HavenClient = class {
692
1554
  * 5. One request per key at a time (`refresh`).
693
1555
  */
694
1556
  async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
695
- const useCache = opts?.cache ?? this.readDefault;
1557
+ const useCache = opts?.cache !== false;
1558
+ this.announceOnce();
696
1559
  if (!useCache) {
697
- const version2 = this.versionTracker.current() ?? void 0;
698
- const ticket = ++this.state.ticket;
1560
+ let version2 = this.versionTracker.current() ?? void 0;
1561
+ let ticket = ++this.state.ticket;
699
1562
  let res;
700
1563
  try {
701
- res = await this.conditionalGet(path, void 0, isExpected);
1564
+ const got = await this.askRetrying(path, void 0, isExpected, false, {
1565
+ allowed: () => true,
1566
+ resume: () => {
1567
+ ticket = ++this.state.ticket;
1568
+ version2 = this.versionTracker.current() ?? void 0;
1569
+ return void 0;
1570
+ }
1571
+ });
1572
+ res = got.answer;
702
1573
  } catch (err) {
703
1574
  if (isDefinitive(err)) this.gone(cacheKey, ticket);
704
1575
  throw err;
@@ -711,7 +1582,7 @@ var HavenClient = class {
711
1582
  }
712
1583
  const started = Date.now();
713
1584
  const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity;
714
- await within(this.versionTracker.refresh(started), budget);
1585
+ await within(this.checkVersion(started), budget);
715
1586
  const version = this.versionTracker.current() ?? void 0;
716
1587
  const entry = this.cache.peek(cacheKey, Date.now());
717
1588
  if (entry) {
@@ -728,6 +1599,16 @@ var HavenClient = class {
728
1599
  const outcome = await within(refresh, budget - (Date.now() - started));
729
1600
  return outcome.settled ? outcome.value : last.value;
730
1601
  }
1602
+ /** On the first read, in development: which project this key reads (`announceProject`). */
1603
+ announceOnce() {
1604
+ if (!this.state.announce) return;
1605
+ this.state.announce = false;
1606
+ announceProject(this.baseUrl, sentHeaders(this.apiKey, this.headers), this.log);
1607
+ }
1608
+ /** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */
1609
+ checkVersion(now) {
1610
+ return this.live ? this.live.gate(this.versionTracker, now) : this.versionTracker.refresh(now);
1611
+ }
731
1612
  /**
732
1613
  * Fetches `cacheKey` from the studio and settles the cache with the answer.
733
1614
  * One per key at a time: reads that arrive while it runs get the same promise,
@@ -747,23 +1628,22 @@ var HavenClient = class {
747
1628
  };
748
1629
  const job = (async () => {
749
1630
  try {
750
- let res;
751
- try {
752
- res = await this.conditionalGet(path, last?.etag, isExpected);
753
- } catch (err) {
754
- const pause = this.gatewayRetry;
755
- if (!retry || pause === void 0 || last || this.cache.stale(cacheKey) || !isGatewayHiccup(err)) throw err;
756
- await sleep(pause + Math.random() * pause);
757
- const meanwhile = this.cache.stale(cacheKey);
758
- if (meanwhile) return meanwhile.value;
759
- const slot = this.inflight.get(cacheKey);
760
- if (slot && !registered()) return slot.job;
761
- ticket = ++this.state.ticket;
762
- if (slot) slot.ticket = ticket;
763
- else register();
764
- version = this.versionTracker.current() ?? void 0;
765
- res = await this.conditionalGet(path, void 0, isExpected);
766
- }
1631
+ const got = await this.askRetrying(path, last?.etag, isExpected, retry, {
1632
+ allowed: () => !last && !this.cache.stale(cacheKey),
1633
+ resume: () => {
1634
+ const meanwhile = this.cache.stale(cacheKey);
1635
+ if (meanwhile) return { value: meanwhile.value };
1636
+ const slot = this.inflight.get(cacheKey);
1637
+ if (slot && !registered()) return { value: slot.job };
1638
+ ticket = ++this.state.ticket;
1639
+ if (slot) slot.ticket = ticket;
1640
+ else register();
1641
+ version = this.versionTracker.current() ?? void 0;
1642
+ return void 0;
1643
+ }
1644
+ });
1645
+ if ("value" in got) return got.value;
1646
+ const res = got.answer;
767
1647
  if (res.notModified && last) {
768
1648
  if (this.storable(cacheKey, ticket)) {
769
1649
  this.cache.confirm(cacheKey, version, Date.now());
@@ -792,6 +1672,102 @@ var HavenClient = class {
792
1672
  this.inflight.set(cacheKey, { job, ticket });
793
1673
  return job;
794
1674
  }
1675
+ /**
1676
+ * Sends a read's request, and sends it again where the failure says that
1677
+ * may help (`retryPause`) and `hooks.allowed()` says the read has nothing to
1678
+ * serve instead; such a read is also held back while its key is rate
1679
+ * limited (`holdBack`). Every other failure is thrown as it is.
1680
+ *
1681
+ * The one retry loop of the read path, for the cached read (`refresh`) and
1682
+ * the bypass alike, so the waits are the same for both. What differs sits in
1683
+ * the hooks: `resume` runs after each wait, just before the next try, and
1684
+ * either ends the read without one (`{ value }`: what another request stored
1685
+ * meanwhile, a newer refresh to join) or takes the ticket and stamp the
1686
+ * next try leaves with and returns `undefined`.
1687
+ *
1688
+ * A next try only ever happens with nothing cached, so it never has an etag
1689
+ * to send: `etag` is the first try's.
1690
+ */
1691
+ async askRetrying(path, etag, isExpected, gateway, hooks) {
1692
+ const read = { started: Date.now(), gateway, rateLimited: 0, heldUntil: 0, spread: false };
1693
+ let ifNoneMatch = etag;
1694
+ for (; ; ) {
1695
+ if (await this.holdBack(read, hooks.allowed())) {
1696
+ const early = hooks.resume();
1697
+ if (early) return early;
1698
+ ifNoneMatch = void 0;
1699
+ continue;
1700
+ }
1701
+ try {
1702
+ return { answer: await this.conditionalGet(path, ifNoneMatch, isExpected) };
1703
+ } catch (err) {
1704
+ const asked = rateLimitPause(err);
1705
+ if (asked !== void 0 && err instanceof NordhavnError && isStudioAnswer(err)) shutGate(this.identity, asked);
1706
+ const pause = hooks.allowed() ? this.retryPause(err, read) : void 0;
1707
+ if (pause === void 0) throw err;
1708
+ ifNoneMatch = void 0;
1709
+ if (pause === "hold") continue;
1710
+ await sleep(pause);
1711
+ const early = hooks.resume();
1712
+ if (early) return early;
1713
+ }
1714
+ }
1715
+ }
1716
+ /**
1717
+ * Whether, and how, a failed read with nothing cached is sent again;
1718
+ * counts what it allows in `read`.
1719
+ *
1720
+ * - A `502` or `503` is often one bad moment (a proxy switching to a new
1721
+ * studio container): once, `gatewayRetry` later plus up to as much at
1722
+ * random. Not when it carried `Retry-After`: that one asked to wait.
1723
+ * - A `429` with `Retry-After`: `'hold'`, so `holdBack` waits as asked, at
1724
+ * most `MAX_RATE_LIMIT_RETRIES` times, and only when that wait ends
1725
+ * within `rateLimitWait` of the read's start. Without `Retry-After`
1726
+ * nothing says when it would help: thrown.
1727
+ */
1728
+ retryPause(err, read) {
1729
+ if (read.gateway && this.gatewayRetry !== void 0 && isGatewayHiccup(err)) {
1730
+ read.gateway = false;
1731
+ return this.gatewayRetry + Math.random() * this.gatewayRetry;
1732
+ }
1733
+ const asked = rateLimitPause(err);
1734
+ if (asked === void 0 || this.rateLimitWait === void 0 || read.rateLimited >= MAX_RATE_LIMIT_RETRIES) return void 0;
1735
+ const now = Date.now();
1736
+ if (now + asked - read.started > this.rateLimitWait) return void 0;
1737
+ read.rateLimited++;
1738
+ read.heldUntil = now + asked;
1739
+ read.spread = true;
1740
+ return "hold";
1741
+ }
1742
+ /**
1743
+ * Keeps a read from going out while its key is rate limited: until its own
1744
+ * `429` said, or the studio's own `429` to any read of this server and key
1745
+ * in the process (`gateRemaining`, at most a minute). Resolves `true` after
1746
+ * waiting, `false` to go now.
1747
+ *
1748
+ * A read with nothing cached (`uncached`) waits for the gate, plus a random
1749
+ * spread (`spreadOf`, also after a `Retry-After: 0`), when that wait ends
1750
+ * within `rateLimitWait` of the read's start. Otherwise (a read with a value
1751
+ * cached, a wait that does not fit, `rateLimitWait: false`) the request is
1752
+ * not sent: the studio already said this key must wait, so it would be
1753
+ * refused, and count against the key's limit as well. It fails as that
1754
+ * refusal would (`heldBackError`), so a cached value is served in its place
1755
+ * and a read with nothing cached throws, without a request.
1756
+ */
1757
+ async holdBack(read, uncached) {
1758
+ const now = Date.now();
1759
+ const gateLeft = gateRemaining(this.identity);
1760
+ const gate = gateLeft > 0 ? now + gateLeft : 0;
1761
+ const until = uncached ? Math.max(gate, read.heldUntil) : gate;
1762
+ if (until <= now && !read.spread) return false;
1763
+ if (!uncached || this.rateLimitWait === void 0 || until - read.started > this.rateLimitWait) {
1764
+ throw heldBackError(until - now);
1765
+ }
1766
+ read.spread = false;
1767
+ const wait = Math.max(0, until - now);
1768
+ await sleep(wait + spreadOf(wait));
1769
+ return true;
1770
+ }
795
1771
  /**
796
1772
  * Hands an absorbed failure to `onError`, or without one warns once per
797
1773
  * outage. Never throws and never leaves a rejection behind: a broken hook
@@ -810,7 +1786,7 @@ var HavenClient = class {
810
1786
  } else if (first) {
811
1787
  const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
812
1788
  const what = failure.during === "read" ? `could not refresh "${failure.key}"` : "stamp check failed";
813
- console.warn(`[@nordhavnhq/beacon] ${what} (${reason}); cached content keeps being served.`);
1789
+ logLine(this.log, "warn", `${what} (${reason}); cached content keeps being served.`);
814
1790
  }
815
1791
  } catch {
816
1792
  }
@@ -872,7 +1848,7 @@ var HavenClient = class {
872
1848
  return await res.json();
873
1849
  });
874
1850
  }
875
- /** Parse a non-2xx response into a `HavenError`, preferring its message. */
1851
+ /** Parse a non-2xx response into a `NordhavnError`, preferring its message. */
876
1852
  async toError(res) {
877
1853
  let message = res.statusText || `Request failed with status ${res.status}`;
878
1854
  let parsed;
@@ -883,8 +1859,8 @@ var HavenClient = class {
883
1859
  else if (typeof m?.statusMessage === "string") message = m.statusMessage;
884
1860
  } catch {
885
1861
  }
886
- const err = new HavenError(message, res.status, parsed);
887
- if (res.headers.has("retry-after")) askedToWait.add(err);
1862
+ const err = new NordhavnError(message, res.status, parsed);
1863
+ if (res.headers.has("retry-after")) askedToWait.set(err, parseRetryAfter(res.headers.get("retry-after"), Date.now()));
888
1864
  return err;
889
1865
  }
890
1866
  };
@@ -906,7 +1882,7 @@ var DatasetHandle = class {
906
1882
  update(recordUid, data) {
907
1883
  return this.client.updateRecord(this.nodeSlug, this.datasetSlug, recordUid, data);
908
1884
  }
909
- /** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */
1885
+ /** Upload a file for one of this dataset's file fields; see `NordhavnClient.uploadFile`. */
910
1886
  uploadFile(fieldSlug, file, opts) {
911
1887
  return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts);
912
1888
  }
@@ -915,19 +1891,6 @@ var DatasetHandle = class {
915
1891
  this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug });
916
1892
  }
917
1893
  };
918
- function isPreviewRequest(input) {
919
- if (!input) return false;
920
- if (typeof input === "string") {
921
- const query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
922
- return new URLSearchParams(query).has(PREVIEW_PARAM);
923
- }
924
- if (input instanceof URLSearchParams) return input.has(PREVIEW_PARAM);
925
- if (input instanceof URL) return input.searchParams.has(PREVIEW_PARAM);
926
- if (typeof input.url === "string") {
927
- return isPreviewRequest(input.url);
928
- }
929
- return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM);
930
- }
931
1894
  async function withTimeout(url, ms, run) {
932
1895
  if (ms <= 0) return run(void 0);
933
1896
  const controller = new AbortController();
@@ -950,9 +1913,13 @@ function normalizeTimeout(value) {
950
1913
  if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
951
1914
  return value > MAX_TIMER ? 0 : value;
952
1915
  }
953
- function uploadTimeout(clientTimeout, perCall) {
1916
+ function normalizeWriteTimeout(timeout, value) {
1917
+ if (typeof value === "number" && !Number.isNaN(value) && value >= 0) return normalizeTimeout(value);
1918
+ return timeout === 0 ? 0 : Math.max(timeout, MIN_WRITE_TIMEOUT);
1919
+ }
1920
+ function uploadTimeout(writeTimeout, perCall) {
954
1921
  if (typeof perCall === "number" && perCall >= 0) return normalizeTimeout(perCall);
955
- return clientTimeout === 0 ? 0 : Math.max(clientTimeout, MIN_UPLOAD_TIMEOUT);
1922
+ return writeTimeout === 0 ? 0 : Math.max(writeTimeout, MIN_UPLOAD_TIMEOUT);
956
1923
  }
957
1924
  function withoutContentType(headers) {
958
1925
  return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-type"));
@@ -962,6 +1929,11 @@ function normalizeGatewayRetry(value) {
962
1929
  if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;
963
1930
  return Math.min(value, MAX_GATEWAY_RETRY);
964
1931
  }
1932
+ function normalizeRateLimitWait(value) {
1933
+ if (value === false) return void 0;
1934
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_RATE_LIMIT_WAIT;
1935
+ return Math.min(value, MAX_TIMER);
1936
+ }
965
1937
  function normalizeWait(value) {
966
1938
  if (value === false) return Infinity;
967
1939
  if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH;
@@ -1001,26 +1973,34 @@ function unexpectedBody(url) {
1001
1973
  function isTransientStatus(status) {
1002
1974
  return status >= 500 || status === 408 || status === 429;
1003
1975
  }
1004
- var askedToWait = /* @__PURE__ */ new WeakSet();
1976
+ var askedToWait = /* @__PURE__ */ new WeakMap();
1977
+ function heldBackError(waitMs) {
1978
+ const seconds = Math.max(1, Math.ceil(waitMs / 1e3));
1979
+ const message = `Too many requests: this key is rate limited for ${seconds} s more, so the request was not sent`;
1980
+ const err = new NordhavnError(message, 429, { statusCode: 429, statusMessage: "Too Many Requests", message });
1981
+ askedToWait.set(err, Math.max(0, waitMs));
1982
+ return err;
1983
+ }
1984
+ function rateLimitPause(err) {
1985
+ return err instanceof NordhavnError && err.status === 429 ? askedToWait.get(err) : void 0;
1986
+ }
1005
1987
  function isGatewayHiccup(err) {
1006
- return err instanceof HavenError && (err.status === 502 || err.status === 503) && !askedToWait.has(err);
1988
+ return err instanceof NordhavnError && (err.status === 502 || err.status === 503) && !askedToWait.has(err);
1007
1989
  }
1008
1990
  function sleep(ms) {
1009
1991
  return new Promise((resolve) => setTimeout(resolve, ms));
1010
1992
  }
1011
1993
  function isDefinitive(err) {
1012
- return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err);
1994
+ return err instanceof NordhavnError && !isTransientStatus(err.status) && isStudioAnswer(err);
1013
1995
  }
1014
1996
  function isStudioAnswer(err) {
1015
- const body = err.body;
1016
- if (typeof body !== "object" || body === null) return false;
1017
- return body.statusCode === err.status || body.status === err.status;
1997
+ return isStudioBody(err.status, err.body);
1018
1998
  }
1019
1999
  function isMissingRoute(err) {
1020
- return err instanceof HavenError && err.status === 404 && isStudioAnswer(err);
2000
+ return err instanceof NordhavnError && err.status === 404 && isStudioAnswer(err);
1021
2001
  }
1022
2002
  function writeMayHaveLanded(err) {
1023
- return !(err instanceof HavenError && err.status >= 400 && err.status < 500);
2003
+ return !(err instanceof NordhavnError && err.status >= 400 && err.status < 500);
1024
2004
  }
1025
2005
  function datasetPath(nodeSlug, datasetSlug) {
1026
2006
  return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`;
@@ -1145,9 +2125,11 @@ function parseChartFence(source) {
1145
2125
 
1146
2126
  // src/index.ts
1147
2127
  function createClient(options) {
1148
- return new HavenClient(options);
2128
+ return new NordhavnClient(options);
1149
2129
  }
2130
+ var HavenClient = NordhavnClient;
2131
+ var HavenError = NordhavnError;
1150
2132
 
1151
- export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, HavenClient as JustmadeClient, HavenError as JustmadeError, MemoryCacheStore, PREVIEW_PARAM, chartFenceHeight, createClient, isChartFence, isPreviewRequest, parseChartFence };
2133
+ export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, MemoryCacheStore, NordhavnClient, NordhavnError, chartFenceHeight, createClient, isChartFence, parseChartFence };
1152
2134
  //# sourceMappingURL=index.js.map
1153
2135
  //# sourceMappingURL=index.js.map