@nordhavnhq/beacon 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -3
- package/dist/{cache-q8uLEGYg.d.cts → cache-1gURpP7O.d.cts} +2 -2
- package/dist/{cache-q8uLEGYg.d.ts → cache-1gURpP7O.d.ts} +2 -2
- package/dist/index.cjs +762 -57
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +103 -56
- package/dist/index.d.ts +103 -56
- package/dist/index.js +763 -54
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -137,6 +137,7 @@ var HavenError = class _HavenError extends Error {
|
|
|
137
137
|
this.name = "HavenError";
|
|
138
138
|
this.status = status;
|
|
139
139
|
this.body = body;
|
|
140
|
+
this.code = errorCode(body);
|
|
140
141
|
Object.setPrototypeOf(this, _HavenError.prototype);
|
|
141
142
|
}
|
|
142
143
|
get isUnauthorized() {
|
|
@@ -149,6 +150,208 @@ var HavenError = class _HavenError extends Error {
|
|
|
149
150
|
return this.status === 404;
|
|
150
151
|
}
|
|
151
152
|
};
|
|
153
|
+
function errorCode(body) {
|
|
154
|
+
if (typeof body !== "object" || body === null) return void 0;
|
|
155
|
+
const data = body.data;
|
|
156
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
157
|
+
const code = data.code;
|
|
158
|
+
return typeof code === "string" && code !== "" ? code : void 0;
|
|
159
|
+
}
|
|
160
|
+
function isStudioBody(status, body) {
|
|
161
|
+
if (typeof body !== "object" || body === null) return false;
|
|
162
|
+
const b = body;
|
|
163
|
+
return b.statusCode === status || b.status === status;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/live-policy.ts
|
|
167
|
+
var LIVE = {
|
|
168
|
+
/**
|
|
169
|
+
* No message (a version or a ping) for this long and the connection counts
|
|
170
|
+
* as dead. The studio pings every 25 s, so this is two missed pings and then
|
|
171
|
+
* some: a frozen process, a proxy that holds the stream without passing it on.
|
|
172
|
+
*/
|
|
173
|
+
staleMs: 6e4,
|
|
174
|
+
/**
|
|
175
|
+
* A connection that stayed up this long, and heard from the studio, resets
|
|
176
|
+
* the backoff. One that is accepted and then closed sooner counts as a
|
|
177
|
+
* failure, so accept-then-close cannot loop.
|
|
178
|
+
*/
|
|
179
|
+
stableMs: 6e4,
|
|
180
|
+
/**
|
|
181
|
+
* Even while the connection is healthy, it is checked against the stamp
|
|
182
|
+
* itself this often (once per connection, in the background, never awaited
|
|
183
|
+
* by a read): a safety net for a change the stream missed. It should never
|
|
184
|
+
* miss one, but one missed would otherwise stay unseen until the stream ends.
|
|
185
|
+
*/
|
|
186
|
+
safetyPollMs: 5 * 6e4,
|
|
187
|
+
/**
|
|
188
|
+
* How long the stream may stay behind a check that found the studio ahead
|
|
189
|
+
* before it counts as having missed a change and is replaced. The studio
|
|
190
|
+
* sends a change up to 5.25 s late on purpose (at most once per 5 s per
|
|
191
|
+
* project), so a stream that is merely behind catches up well within this.
|
|
192
|
+
*/
|
|
193
|
+
lagToleranceMs: 1e4,
|
|
194
|
+
/** The longest that check may take; it runs on an unref'd socket, so it never holds a process. */
|
|
195
|
+
safetyProbeTimeoutMs: 3e3,
|
|
196
|
+
/** The longest the studio may take to answer the connection with its headers. */
|
|
197
|
+
connectTimeoutMs: 1e4,
|
|
198
|
+
/** After the studio ended a connection that lived its full term: wait 1 to 5 s. */
|
|
199
|
+
cleanMinMs: 1e3,
|
|
200
|
+
cleanMaxMs: 5e3,
|
|
201
|
+
/** After a failure: at least 1 s, then a window that doubles per failure, up to 30 s. */
|
|
202
|
+
backoffBaseMs: 1e3,
|
|
203
|
+
backoffMaxMs: 3e4,
|
|
204
|
+
/** `Retry-After` is honoured within these bounds. */
|
|
205
|
+
retryAfterMinMs: 3e4,
|
|
206
|
+
retryAfterMaxMs: 60 * 6e4,
|
|
207
|
+
/** A `429` without `Retry-After` waits as long as the studio itself asks for. */
|
|
208
|
+
rateLimitedMs: 5 * 6e4,
|
|
209
|
+
/** The most added at random to a long wait, so the sites refused together do not return together. */
|
|
210
|
+
longJitterMs: 6e4
|
|
211
|
+
};
|
|
212
|
+
function planReconnect(outcome, ctx) {
|
|
213
|
+
const attempts = ctx.stable ? 0 : ctx.attempts;
|
|
214
|
+
if (outcome.kind === "closed" && ctx.stable) {
|
|
215
|
+
return { stop: false, delay: between(LIVE.cleanMinMs, LIVE.cleanMaxMs, ctx.random), attempts: 0 };
|
|
216
|
+
}
|
|
217
|
+
if (outcome.kind === "refused") return planRefused(outcome, { ...ctx, attempts });
|
|
218
|
+
return backoff(attempts, ctx.random);
|
|
219
|
+
}
|
|
220
|
+
function planRefused(outcome, ctx) {
|
|
221
|
+
const { status, studio } = outcome;
|
|
222
|
+
if (studio && (status === 401 || status === 403)) return { stop: true };
|
|
223
|
+
const asked = parseRetryAfter(outcome.retryAfter, ctx.now);
|
|
224
|
+
if (status === 429 || status === 503 && asked !== void 0) {
|
|
225
|
+
const wait = clamp(asked ?? LIVE.rateLimitedMs, LIVE.retryAfterMinMs, LIVE.retryAfterMaxMs);
|
|
226
|
+
return { stop: false, delay: wait + longJitter(wait, ctx.random), attempts: ctx.attempts };
|
|
227
|
+
}
|
|
228
|
+
const studioRefusal = studio && status >= 400 && status < 500 && status !== 408;
|
|
229
|
+
if (studioRefusal || status >= 300 && status < 400) {
|
|
230
|
+
return { stop: false, delay: ctx.pauseMs + longJitter(ctx.pauseMs, ctx.random), attempts: ctx.attempts };
|
|
231
|
+
}
|
|
232
|
+
return backoff(ctx.attempts, ctx.random);
|
|
233
|
+
}
|
|
234
|
+
function backoff(attempts, random) {
|
|
235
|
+
const window = LIVE.backoffBaseMs * 2 ** Math.min(attempts, 16);
|
|
236
|
+
const delay = Math.min(LIVE.backoffMaxMs, LIVE.backoffBaseMs + random() * window);
|
|
237
|
+
return { stop: false, delay, attempts: attempts + 1 };
|
|
238
|
+
}
|
|
239
|
+
function longJitter(wait, random) {
|
|
240
|
+
return random() * Math.min(LIVE.longJitterMs, wait / 5);
|
|
241
|
+
}
|
|
242
|
+
function between(min, max, random) {
|
|
243
|
+
return min + random() * (max - min);
|
|
244
|
+
}
|
|
245
|
+
function clamp(value, min, max) {
|
|
246
|
+
return Math.min(max, Math.max(min, value));
|
|
247
|
+
}
|
|
248
|
+
function parseRetryAfter(value, now) {
|
|
249
|
+
const text = value?.trim();
|
|
250
|
+
if (!text) return void 0;
|
|
251
|
+
if (/^-?\d+$/.test(text)) return text.startsWith("-") ? void 0 : Number(text) * 1e3;
|
|
252
|
+
const at = Date.parse(text);
|
|
253
|
+
return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
|
|
254
|
+
}
|
|
255
|
+
var SHORT_LIVED_ENV = [
|
|
256
|
+
"VERCEL",
|
|
257
|
+
"NETLIFY",
|
|
258
|
+
"AWS_LAMBDA_FUNCTION_NAME",
|
|
259
|
+
"LAMBDA_TASK_ROOT",
|
|
260
|
+
"FUNCTIONS_WORKER_RUNTIME",
|
|
261
|
+
"FUNCTION_TARGET",
|
|
262
|
+
"DENO_DEPLOYMENT_ID",
|
|
263
|
+
"K_SERVICE",
|
|
264
|
+
"CI"
|
|
265
|
+
];
|
|
266
|
+
function isShortLived(env) {
|
|
267
|
+
return SHORT_LIVED_ENV.some((name) => {
|
|
268
|
+
const value = env[name]?.trim().toLowerCase();
|
|
269
|
+
return value !== void 0 && value !== "" && value !== "0" && value !== "false";
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
function chooseLive(choice) {
|
|
273
|
+
if (!choice.runtime || !choice.revalidating || choice.option === false) return false;
|
|
274
|
+
if (choice.option === true) return true;
|
|
275
|
+
return !choice.customFetch && !choice.waitsForStudio && !isShortLived(choice.env);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/live-sse.ts
|
|
279
|
+
var DEFAULT_LIMIT = 64 * 1024;
|
|
280
|
+
var SseParser = class {
|
|
281
|
+
constructor(limit = DEFAULT_LIMIT) {
|
|
282
|
+
this.buffer = "";
|
|
283
|
+
this.data = [];
|
|
284
|
+
this.dataSize = 0;
|
|
285
|
+
this.event = "";
|
|
286
|
+
this.started = false;
|
|
287
|
+
/** The last chunk ended in `\r`: a `\n` that starts the next one belongs to it. */
|
|
288
|
+
this.afterCr = false;
|
|
289
|
+
this.limit = limit;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* The events completed by `chunk`, in order. `null` once more than the limit
|
|
293
|
+
* is waiting for a line or an event to end: a stream like that is not the
|
|
294
|
+
* studio's, and the caller drops the connection rather than the memory.
|
|
295
|
+
*/
|
|
296
|
+
feed(chunk) {
|
|
297
|
+
const text = this.prepare(this.buffer + chunk);
|
|
298
|
+
const out = [];
|
|
299
|
+
let pos = 0;
|
|
300
|
+
const breaks = { cr: text.indexOf("\r"), lf: text.indexOf("\n") };
|
|
301
|
+
while (pos < text.length) {
|
|
302
|
+
const end = nextBreak(text, pos, breaks);
|
|
303
|
+
if (end === -1) break;
|
|
304
|
+
let next = end + 1;
|
|
305
|
+
if (text.charCodeAt(end) === 13) {
|
|
306
|
+
if (end + 1 === text.length) this.afterCr = true;
|
|
307
|
+
else if (text.charCodeAt(end + 1) === 10) next = end + 2;
|
|
308
|
+
}
|
|
309
|
+
this.line(text.slice(pos, end), out);
|
|
310
|
+
pos = next;
|
|
311
|
+
}
|
|
312
|
+
this.buffer = text.slice(pos);
|
|
313
|
+
if (this.buffer.length > this.limit || this.dataSize > this.limit) return null;
|
|
314
|
+
return out;
|
|
315
|
+
}
|
|
316
|
+
/** Drops the `\n` of a `\r\n` split over two chunks, and a byte order mark at the start. */
|
|
317
|
+
prepare(text) {
|
|
318
|
+
let out = text;
|
|
319
|
+
if (this.afterCr && out.length > 0) {
|
|
320
|
+
this.afterCr = false;
|
|
321
|
+
if (out.charCodeAt(0) === 10) out = out.slice(1);
|
|
322
|
+
}
|
|
323
|
+
if (!this.started && out.length > 0) {
|
|
324
|
+
this.started = true;
|
|
325
|
+
if (out.charCodeAt(0) === 65279) out = out.slice(1);
|
|
326
|
+
}
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
line(line, out) {
|
|
330
|
+
if (line === "") {
|
|
331
|
+
if (this.data.length > 0) out.push({ event: this.event || "message", data: this.data.join("\n") });
|
|
332
|
+
this.data = [];
|
|
333
|
+
this.dataSize = 0;
|
|
334
|
+
this.event = "";
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (line.charCodeAt(0) === 58) return;
|
|
338
|
+
const colon = line.indexOf(":");
|
|
339
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
340
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
341
|
+
if (value.charCodeAt(0) === 32) value = value.slice(1);
|
|
342
|
+
if (field === "event") this.event = value;
|
|
343
|
+
else if (field === "data") {
|
|
344
|
+
this.data.push(value);
|
|
345
|
+
this.dataSize += value.length + 1;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
function nextBreak(text, pos, breaks) {
|
|
350
|
+
if (breaks.cr !== -1 && breaks.cr < pos) breaks.cr = text.indexOf("\r", pos);
|
|
351
|
+
if (breaks.lf !== -1 && breaks.lf < pos) breaks.lf = text.indexOf("\n", pos);
|
|
352
|
+
const { cr, lf } = breaks;
|
|
353
|
+
return cr === -1 ? lf : lf === -1 ? cr : Math.min(cr, lf);
|
|
354
|
+
}
|
|
152
355
|
|
|
153
356
|
// src/version.ts
|
|
154
357
|
var UNSUPPORTED_PAUSE_MS = 15 * 6e4;
|
|
@@ -172,6 +375,23 @@ var VersionTracker = class {
|
|
|
172
375
|
current() {
|
|
173
376
|
return this.version;
|
|
174
377
|
}
|
|
378
|
+
/**
|
|
379
|
+
* A stamp heard from the live connection, current as of `at`. It counts as a
|
|
380
|
+
* check made at that moment: the next probe is due one interval after it.
|
|
381
|
+
* Never a request of its own, and never a reason for one.
|
|
382
|
+
*/
|
|
383
|
+
observe(version, at) {
|
|
384
|
+
this.version = version;
|
|
385
|
+
this.lastChecked = Math.max(this.lastChecked, at);
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Makes the next `refresh` ask at once, whatever the interval says (still
|
|
389
|
+
* not during the pause for a server without the route). For when the stamp
|
|
390
|
+
* may have moved unseen: the live connection went silent.
|
|
391
|
+
*/
|
|
392
|
+
due() {
|
|
393
|
+
this.lastChecked = 0;
|
|
394
|
+
}
|
|
175
395
|
/**
|
|
176
396
|
* Refresh the stamp if we are due. Resolves once the answer is in, so the
|
|
177
397
|
* read that triggered it sees an up-to-date stamp. A failed probe leaves the
|
|
@@ -205,10 +425,465 @@ var VersionTracker = class {
|
|
|
205
425
|
}
|
|
206
426
|
};
|
|
207
427
|
|
|
428
|
+
// src/live.ts
|
|
429
|
+
var REGISTRY = /* @__PURE__ */ Symbol.for("@nordhavnhq/beacon/live-hubs/2");
|
|
430
|
+
var LINGER_MS = 5 * 6e4;
|
|
431
|
+
var REFUSAL_BODY_LIMIT = 16 * 1024;
|
|
432
|
+
function hubs() {
|
|
433
|
+
const scope = globalThis;
|
|
434
|
+
let map = scope[REGISTRY];
|
|
435
|
+
if (!map) {
|
|
436
|
+
map = /* @__PURE__ */ new Map();
|
|
437
|
+
scope[REGISTRY] = map;
|
|
438
|
+
}
|
|
439
|
+
return map;
|
|
440
|
+
}
|
|
441
|
+
var collected = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(({ hub, token }) => {
|
|
442
|
+
try {
|
|
443
|
+
hub.detach(token, true);
|
|
444
|
+
} catch {
|
|
445
|
+
}
|
|
446
|
+
}) : void 0;
|
|
447
|
+
function liveRuntime() {
|
|
448
|
+
const g = globalThis;
|
|
449
|
+
if (typeof g.window !== "undefined" || typeof g.document !== "undefined") return false;
|
|
450
|
+
if (g.navigator?.userAgent === "Cloudflare-Workers") return false;
|
|
451
|
+
return typeof g.process?.versions?.node === "string";
|
|
452
|
+
}
|
|
453
|
+
function wantLive(settings) {
|
|
454
|
+
try {
|
|
455
|
+
return chooseLive({ ...settings, runtime: liveRuntime(), env: globalThis.process?.env ?? {} });
|
|
456
|
+
} catch {
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
async function loadHttp(protocol) {
|
|
461
|
+
const name = protocol === "https:" ? "node:https" : "node:http";
|
|
462
|
+
const proc = globalThis.process;
|
|
463
|
+
const builtin = typeof proc?.getBuiltinModule === "function" ? proc.getBuiltinModule(name) : void 0;
|
|
464
|
+
if (builtin) return builtin;
|
|
465
|
+
return await import(
|
|
466
|
+
/* webpackIgnore: true */
|
|
467
|
+
/* @vite-ignore */
|
|
468
|
+
name
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
function unrefTimer(run, ms) {
|
|
472
|
+
const timer = setTimeout(run, ms);
|
|
473
|
+
timer.unref?.();
|
|
474
|
+
return timer;
|
|
475
|
+
}
|
|
476
|
+
var LiveLink = class {
|
|
477
|
+
constructor(baseUrl, apiKey, headers, owner) {
|
|
478
|
+
this.baseUrl = baseUrl;
|
|
479
|
+
this.apiKey = apiKey;
|
|
480
|
+
this.headers = headers;
|
|
481
|
+
this.token = {};
|
|
482
|
+
this.silences = 0;
|
|
483
|
+
this.closed = false;
|
|
484
|
+
this.owner = owner;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* The stamp gate in front of a read, in place of `tracker.refresh`. While
|
|
488
|
+
* the connection is healthy the stamp it heard counts as a fresh check and
|
|
489
|
+
* nothing is fetched; otherwise the poll runs, at once when the connection
|
|
490
|
+
* went silent since the last read. Connects on the first call.
|
|
491
|
+
*/
|
|
492
|
+
gate(tracker, now) {
|
|
493
|
+
try {
|
|
494
|
+
const view = this.join()?.view(now);
|
|
495
|
+
if (view?.healthy && view.version !== void 0) {
|
|
496
|
+
tracker.observe(view.version, view.at);
|
|
497
|
+
this.hub?.safetyCheck(now);
|
|
498
|
+
return Promise.resolve();
|
|
499
|
+
}
|
|
500
|
+
if (view && view.silences !== this.silences) {
|
|
501
|
+
this.silences = view.silences;
|
|
502
|
+
tracker.due();
|
|
503
|
+
}
|
|
504
|
+
} catch {
|
|
505
|
+
}
|
|
506
|
+
return tracker.refresh(now);
|
|
507
|
+
}
|
|
508
|
+
/** Leaves the connection for good; the last client out closes it. */
|
|
509
|
+
close() {
|
|
510
|
+
if (this.closed) return;
|
|
511
|
+
this.closed = true;
|
|
512
|
+
const hub = this.hub;
|
|
513
|
+
this.hub = void 0;
|
|
514
|
+
this.owner = void 0;
|
|
515
|
+
if (!hub) return;
|
|
516
|
+
collected?.unregister(this.token);
|
|
517
|
+
try {
|
|
518
|
+
hub.detach(this.token, false);
|
|
519
|
+
} catch {
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
join() {
|
|
523
|
+
if (this.hub || this.closed) return this.hub;
|
|
524
|
+
const url = eventsUrl(this.baseUrl);
|
|
525
|
+
if (!url) {
|
|
526
|
+
this.closed = true;
|
|
527
|
+
return void 0;
|
|
528
|
+
}
|
|
529
|
+
const registry = hubs();
|
|
530
|
+
const headers = liveHeaders(this.apiKey, this.headers);
|
|
531
|
+
const id = `${this.baseUrl}
|
|
532
|
+
${headers.authorization ?? ""}`;
|
|
533
|
+
let hub = registry.get(id);
|
|
534
|
+
if (!hub) {
|
|
535
|
+
hub = new LiveHub(id, url, headers);
|
|
536
|
+
registry.set(id, hub);
|
|
537
|
+
}
|
|
538
|
+
this.silences = hub.attach(this.token);
|
|
539
|
+
if (this.owner) collected?.register(this.owner, { hub, token: this.token }, this.token);
|
|
540
|
+
this.owner = void 0;
|
|
541
|
+
this.hub = hub;
|
|
542
|
+
return hub;
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
function eventsUrl(baseUrl) {
|
|
546
|
+
try {
|
|
547
|
+
const url = new URL(`${baseUrl}/api/content/events`);
|
|
548
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url : void 0;
|
|
549
|
+
} catch {
|
|
550
|
+
return void 0;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function liveHeaders(apiKey, extra) {
|
|
554
|
+
const headers = { authorization: `Bearer ${apiKey}` };
|
|
555
|
+
for (const [name, value] of Object.entries(extra)) headers[name.toLowerCase()] = value;
|
|
556
|
+
headers.accept = "text/event-stream";
|
|
557
|
+
headers["cache-control"] = "no-cache";
|
|
558
|
+
headers["accept-encoding"] = "identity";
|
|
559
|
+
return headers;
|
|
560
|
+
}
|
|
561
|
+
var LiveHub = class {
|
|
562
|
+
constructor(id, url, headers) {
|
|
563
|
+
this.id = id;
|
|
564
|
+
this.url = url;
|
|
565
|
+
this.headers = headers;
|
|
566
|
+
this.state = "idle";
|
|
567
|
+
this.openedAt = 0;
|
|
568
|
+
this.lastHeardAt = 0;
|
|
569
|
+
/** Failures in a row, for the backoff. */
|
|
570
|
+
this.attempts = 0;
|
|
571
|
+
this.retryAt = 0;
|
|
572
|
+
this.silences = 0;
|
|
573
|
+
this.owners = /* @__PURE__ */ new Set();
|
|
574
|
+
/** Version events on the open connection: tells a stream that moved from one that did not. */
|
|
575
|
+
this.tells = 0;
|
|
576
|
+
/** When the open connection was last checked against the stamp itself. */
|
|
577
|
+
this.checkedAt = 0;
|
|
578
|
+
this.checking = false;
|
|
579
|
+
}
|
|
580
|
+
attach(token) {
|
|
581
|
+
clearTimeout(this.lingerTimer);
|
|
582
|
+
this.lingerTimer = void 0;
|
|
583
|
+
this.owners.add(token);
|
|
584
|
+
return this.silences;
|
|
585
|
+
}
|
|
586
|
+
detach(token, linger) {
|
|
587
|
+
if (!this.owners.delete(token) || this.owners.size > 0) return;
|
|
588
|
+
clearTimeout(this.lingerTimer);
|
|
589
|
+
if (linger) this.lingerTimer = unrefTimer(() => this.owners.size === 0 && this.dispose(), LINGER_MS);
|
|
590
|
+
else this.dispose();
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* The state of the connection for a read at `now`, after the checks a read
|
|
594
|
+
* makes: connect the first time; a connection silent for `LIVE.staleMs` is
|
|
595
|
+
* dead (a frozen process misses events and runs no timers, so the watchdog
|
|
596
|
+
* alone cannot be trusted); a reconnect whose time has come goes now.
|
|
597
|
+
*/
|
|
598
|
+
view(now) {
|
|
599
|
+
if (this.state === "idle") this.connect();
|
|
600
|
+
else if (this.state === "open" && now - this.lastHeardAt > LIVE.staleMs) this.current?.end({ kind: "silent" });
|
|
601
|
+
else if (this.state === "waiting" && now >= this.retryAt) this.connect();
|
|
602
|
+
if (this.state === "open" && this.behind) this.judgeBehind(now);
|
|
603
|
+
return {
|
|
604
|
+
healthy: this.state === "open" && this.version !== void 0,
|
|
605
|
+
version: this.version,
|
|
606
|
+
at: this.lastHeardAt,
|
|
607
|
+
silences: this.silences
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* The safety net, at most once per `LIVE.safetyPollMs` per connection, set
|
|
612
|
+
* off by a read: ask the stamp and compare it with the stream's. Never
|
|
613
|
+
* awaited by a read, never reported, and over an unref'd socket, so it holds
|
|
614
|
+
* up no read and no process. Only a clear answer counts: a failed check, a
|
|
615
|
+
* check that outlived its connection, or one during which the stream told a
|
|
616
|
+
* new stamp proves nothing. A studio ahead of the stream is noted, not acted
|
|
617
|
+
* on: see `judgeBehind`.
|
|
618
|
+
*/
|
|
619
|
+
safetyCheck(now) {
|
|
620
|
+
if (this.state !== "open" || this.version === void 0 || this.checking || this.behind) return;
|
|
621
|
+
if (now - this.checkedAt < LIVE.safetyPollMs) return;
|
|
622
|
+
this.checking = true;
|
|
623
|
+
this.checkedAt = now;
|
|
624
|
+
const attempt = this.current;
|
|
625
|
+
const tells = this.tells;
|
|
626
|
+
const heard = this.version;
|
|
627
|
+
const url = versionUrl(this.url);
|
|
628
|
+
const headers = { ...this.headers, accept: "application/json" };
|
|
629
|
+
loadHttp(url.protocol).then((http) => probeStamp(http, url, headers), () => void 0).then(
|
|
630
|
+
(stamp) => {
|
|
631
|
+
this.checking = false;
|
|
632
|
+
if (stamp === void 0 || attempt !== this.current || tells !== this.tells) return;
|
|
633
|
+
if (stamp !== heard) this.behind = { tells, since: Date.now() };
|
|
634
|
+
},
|
|
635
|
+
() => {
|
|
636
|
+
this.checking = false;
|
|
637
|
+
}
|
|
638
|
+
);
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* A check found the studio ahead of the stream. The studio sends late on
|
|
642
|
+
* purpose (its 5 s throttle), so that alone is no fault: only a stream that
|
|
643
|
+
* told nothing new for `LIVE.lagToleranceMs` since then missed a change. The
|
|
644
|
+
* first read after that drops it, which makes that same read check the stamp
|
|
645
|
+
* itself (and the hub reconnect).
|
|
646
|
+
*/
|
|
647
|
+
judgeBehind(now) {
|
|
648
|
+
const behind = this.behind;
|
|
649
|
+
if (this.tells !== behind.tells) this.behind = void 0;
|
|
650
|
+
else if (now - behind.since >= LIVE.lagToleranceMs) {
|
|
651
|
+
this.behind = void 0;
|
|
652
|
+
this.current?.end({ kind: "silent" });
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
connect() {
|
|
656
|
+
clearTimeout(this.retryTimer);
|
|
657
|
+
this.state = "connecting";
|
|
658
|
+
const attempt = new LiveAttempt(this);
|
|
659
|
+
this.current = attempt;
|
|
660
|
+
loadHttp(this.url.protocol).then(
|
|
661
|
+
(http) => {
|
|
662
|
+
if (this.current === attempt) attempt.start(http, this.url, this.headers);
|
|
663
|
+
},
|
|
664
|
+
() => {
|
|
665
|
+
if (this.current === attempt) this.halt();
|
|
666
|
+
}
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
/** The attempt got its stream: the studio's answer is in. */
|
|
670
|
+
opened(attempt) {
|
|
671
|
+
if (attempt !== this.current) return;
|
|
672
|
+
this.state = "open";
|
|
673
|
+
this.version = void 0;
|
|
674
|
+
this.openedAt = Date.now();
|
|
675
|
+
this.lastHeardAt = this.openedAt;
|
|
676
|
+
this.checkedAt = this.openedAt;
|
|
677
|
+
this.behind = void 0;
|
|
678
|
+
}
|
|
679
|
+
/** Something came in on the stream: a sign of life. */
|
|
680
|
+
heard(attempt) {
|
|
681
|
+
if (attempt === this.current) this.lastHeardAt = Date.now();
|
|
682
|
+
}
|
|
683
|
+
/** A `version` event, its data as sent. */
|
|
684
|
+
told(attempt, data) {
|
|
685
|
+
if (attempt !== this.current) return;
|
|
686
|
+
try {
|
|
687
|
+
const version = JSON.parse(data)?.version;
|
|
688
|
+
if (typeof version === "string" && version !== "") {
|
|
689
|
+
this.version = version;
|
|
690
|
+
this.tells++;
|
|
691
|
+
}
|
|
692
|
+
} catch {
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
/** The attempt is over: plan the next one. `outcome` is absent when the hub ended it itself. */
|
|
696
|
+
ended(attempt, outcome) {
|
|
697
|
+
if (attempt !== this.current) return;
|
|
698
|
+
this.current = void 0;
|
|
699
|
+
const now = Date.now();
|
|
700
|
+
const stable = this.state === "open" && this.version !== void 0 && now - this.openedAt >= LIVE.stableMs;
|
|
701
|
+
this.version = void 0;
|
|
702
|
+
if (!outcome || this.state === "stopped") return;
|
|
703
|
+
if (outcome.kind === "silent") this.silences++;
|
|
704
|
+
const plan = planReconnect(outcome, { attempts: this.attempts, stable, pauseMs: UNSUPPORTED_PAUSE_MS, now, random: Math.random });
|
|
705
|
+
if (plan.stop) {
|
|
706
|
+
this.halt();
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
this.attempts = plan.attempts;
|
|
710
|
+
this.state = "waiting";
|
|
711
|
+
this.retryAt = now + plan.delay;
|
|
712
|
+
this.retryTimer = unrefTimer(() => {
|
|
713
|
+
if (this.state === "waiting") this.connect();
|
|
714
|
+
}, plan.delay);
|
|
715
|
+
}
|
|
716
|
+
/** Stops for good: reads keep to the poll. */
|
|
717
|
+
halt() {
|
|
718
|
+
this.state = "stopped";
|
|
719
|
+
clearTimeout(this.retryTimer);
|
|
720
|
+
const attempt = this.current;
|
|
721
|
+
this.current = void 0;
|
|
722
|
+
this.version = void 0;
|
|
723
|
+
attempt?.end();
|
|
724
|
+
}
|
|
725
|
+
dispose() {
|
|
726
|
+
this.halt();
|
|
727
|
+
const registry = hubs();
|
|
728
|
+
if (registry.get(this.id) === this) registry.delete(this.id);
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
var LiveAttempt = class {
|
|
732
|
+
constructor(hub) {
|
|
733
|
+
this.hub = hub;
|
|
734
|
+
this.done = false;
|
|
735
|
+
this.timers = [];
|
|
736
|
+
}
|
|
737
|
+
start(http, url, headers) {
|
|
738
|
+
if (this.done) return;
|
|
739
|
+
this.timers.push(unrefTimer(() => this.end({ kind: "failed" }), LIVE.connectTimeoutMs));
|
|
740
|
+
try {
|
|
741
|
+
const req = http.request(url, { method: "GET", headers, agent: false }, (res) => this.answered(res));
|
|
742
|
+
this.req = req;
|
|
743
|
+
req.on("socket", (socket) => {
|
|
744
|
+
try {
|
|
745
|
+
socket.unref();
|
|
746
|
+
} catch {
|
|
747
|
+
this.end({ kind: "refused", status: 400, studio: true, retryAfter: null });
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
try {
|
|
751
|
+
socket.setKeepAlive(true, 3e4);
|
|
752
|
+
} catch {
|
|
753
|
+
}
|
|
754
|
+
});
|
|
755
|
+
req.on("error", () => this.end({ kind: "failed" }));
|
|
756
|
+
req.end();
|
|
757
|
+
} catch {
|
|
758
|
+
this.end({ kind: "refused", status: 400, studio: true, retryAfter: null });
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
/** Ends the attempt; the hub plans what comes next from `outcome`, unless it ended it itself. */
|
|
762
|
+
end(outcome) {
|
|
763
|
+
if (this.done) return;
|
|
764
|
+
this.done = true;
|
|
765
|
+
for (const timer of this.timers) clearTimeout(timer);
|
|
766
|
+
try {
|
|
767
|
+
this.req?.destroy();
|
|
768
|
+
} catch {
|
|
769
|
+
}
|
|
770
|
+
this.hub.ended(this, outcome);
|
|
771
|
+
}
|
|
772
|
+
answered(res) {
|
|
773
|
+
res.on("error", () => this.end({ kind: "failed" }));
|
|
774
|
+
if (this.done) {
|
|
775
|
+
res.resume();
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
const type = String(res.headers["content-type"] ?? "");
|
|
779
|
+
if (res.statusCode === 200 && type.includes("text/event-stream")) this.stream(res);
|
|
780
|
+
else this.refused(res);
|
|
781
|
+
}
|
|
782
|
+
stream(res) {
|
|
783
|
+
for (const timer of this.timers) clearTimeout(timer);
|
|
784
|
+
this.timers = [];
|
|
785
|
+
const watchdog = unrefTimer(() => this.end({ kind: "silent" }), LIVE.staleMs);
|
|
786
|
+
this.timers.push(watchdog);
|
|
787
|
+
this.hub.opened(this);
|
|
788
|
+
const parser = new SseParser();
|
|
789
|
+
res.setEncoding("utf8");
|
|
790
|
+
res.on("data", (chunk) => {
|
|
791
|
+
if (this.done) return;
|
|
792
|
+
watchdog.refresh?.();
|
|
793
|
+
this.hub.heard(this);
|
|
794
|
+
const events = parser.feed(chunk);
|
|
795
|
+
if (events === null) {
|
|
796
|
+
this.end({ kind: "failed" });
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
for (const event of events) {
|
|
800
|
+
if (event.event === "version") this.hub.told(this, event.data);
|
|
801
|
+
}
|
|
802
|
+
});
|
|
803
|
+
res.on("end", () => this.end({ kind: "closed" }));
|
|
804
|
+
res.on("close", () => this.end({ kind: "failed" }));
|
|
805
|
+
}
|
|
806
|
+
/** Not the stream: read a little of the body, to tell the studio's own refusal from a proxy's. */
|
|
807
|
+
refused(res) {
|
|
808
|
+
const status = res.statusCode ?? 0;
|
|
809
|
+
const header = res.headers["retry-after"];
|
|
810
|
+
const retryAfter = (Array.isArray(header) ? header[0] : header) ?? null;
|
|
811
|
+
let body = "";
|
|
812
|
+
res.setEncoding("utf8");
|
|
813
|
+
res.on("data", (chunk) => {
|
|
814
|
+
body += chunk;
|
|
815
|
+
if (body.length > REFUSAL_BODY_LIMIT) res.destroy();
|
|
816
|
+
});
|
|
817
|
+
const settle = () => this.end({ kind: "refused", status, retryAfter, studio: isStudioBody(status, parseJson(body)) });
|
|
818
|
+
res.on("end", settle);
|
|
819
|
+
res.on("close", settle);
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
function versionUrl(events) {
|
|
823
|
+
const url = new URL(events.href);
|
|
824
|
+
url.pathname = url.pathname.replace(/events$/, "version");
|
|
825
|
+
return url;
|
|
826
|
+
}
|
|
827
|
+
function probeStamp(http, url, headers) {
|
|
828
|
+
return new Promise((resolve) => {
|
|
829
|
+
let req;
|
|
830
|
+
let settled = false;
|
|
831
|
+
const finish = (stamp) => {
|
|
832
|
+
if (settled) return;
|
|
833
|
+
settled = true;
|
|
834
|
+
clearTimeout(timer);
|
|
835
|
+
try {
|
|
836
|
+
req?.destroy();
|
|
837
|
+
} catch {
|
|
838
|
+
}
|
|
839
|
+
resolve(stamp);
|
|
840
|
+
};
|
|
841
|
+
const timer = unrefTimer(() => finish(), LIVE.safetyProbeTimeoutMs);
|
|
842
|
+
try {
|
|
843
|
+
req = http.request(url, { method: "GET", headers, agent: false }, (res) => {
|
|
844
|
+
res.on("error", () => finish());
|
|
845
|
+
if (res.statusCode !== 200) {
|
|
846
|
+
res.resume();
|
|
847
|
+
finish();
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
let body = "";
|
|
851
|
+
res.setEncoding("utf8");
|
|
852
|
+
res.on("data", (chunk) => {
|
|
853
|
+
body += chunk;
|
|
854
|
+
if (body.length > REFUSAL_BODY_LIMIT) finish();
|
|
855
|
+
});
|
|
856
|
+
res.on("end", () => {
|
|
857
|
+
const stamp = parseJson(body)?.version;
|
|
858
|
+
finish(typeof stamp === "string" && stamp !== "" ? stamp : void 0);
|
|
859
|
+
});
|
|
860
|
+
res.on("close", () => finish());
|
|
861
|
+
});
|
|
862
|
+
req.on("socket", (socket) => {
|
|
863
|
+
try {
|
|
864
|
+
socket.unref();
|
|
865
|
+
} catch {
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
req.on("error", () => finish());
|
|
869
|
+
req.end();
|
|
870
|
+
} catch {
|
|
871
|
+
finish();
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
function parseJson(text) {
|
|
876
|
+
try {
|
|
877
|
+
return JSON.parse(text);
|
|
878
|
+
} catch {
|
|
879
|
+
return void 0;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
208
883
|
// src/client.ts
|
|
209
|
-
var PREVIEW_PARAM = "sl-preview";
|
|
210
884
|
var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
|
|
211
885
|
var DEFAULT_TIMEOUT = 1e4;
|
|
886
|
+
var MIN_UPLOAD_TIMEOUT = 6e4;
|
|
212
887
|
var VERSION_TIMEOUT = 3e3;
|
|
213
888
|
var DEFAULT_WAIT_FOR_FRESH = 1e3;
|
|
214
889
|
var MAX_TIMER = 2147483647;
|
|
@@ -230,8 +905,7 @@ var HavenClient = class {
|
|
|
230
905
|
this.storedBy = /* @__PURE__ */ new Map();
|
|
231
906
|
/**
|
|
232
907
|
* Everything that changes while the client runs and is not a collection of
|
|
233
|
-
* its own.
|
|
234
|
-
* fields through its prototype - changes the same values and never a copy.
|
|
908
|
+
* its own.
|
|
235
909
|
*/
|
|
236
910
|
this.state = {
|
|
237
911
|
/**
|
|
@@ -264,7 +938,6 @@ var HavenClient = class {
|
|
|
264
938
|
this.fetchImpl = resolvedFetch.bind(globalThis);
|
|
265
939
|
this.headers = options.headers ?? {};
|
|
266
940
|
this.locale = options.locale || void 0;
|
|
267
|
-
this.readDefault = options.preview !== true;
|
|
268
941
|
this.timeout = normalizeTimeout(options.timeout);
|
|
269
942
|
this.onError = options.onError;
|
|
270
943
|
const cacheOpt = options.cache;
|
|
@@ -290,39 +963,23 @@ var HavenClient = class {
|
|
|
290
963
|
revalidate,
|
|
291
964
|
isMissingRoute
|
|
292
965
|
);
|
|
966
|
+
const live = wantLive({
|
|
967
|
+
option: options.live,
|
|
968
|
+
revalidating: revalidate > 0,
|
|
969
|
+
customFetch: options.fetch !== void 0,
|
|
970
|
+
waitsForStudio: this.waitForFresh === Infinity
|
|
971
|
+
});
|
|
972
|
+
this.live = live ? new LiveLink(this.baseUrl, this.apiKey, this.headers, this) : void 0;
|
|
293
973
|
}
|
|
294
|
-
// ── Preview scoping ─────────────────────────────────────────────────────────
|
|
295
974
|
/**
|
|
296
|
-
*
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
* Accepts whatever your framework hands you: a `Request`, a URL string or
|
|
302
|
-
* `URL`, `URLSearchParams`, or a plain searchParams object.
|
|
303
|
-
*
|
|
304
|
-
* ```ts
|
|
305
|
-
* // Next.js app router
|
|
306
|
-
* export default async function Page({ searchParams }) {
|
|
307
|
-
* const posts = await studio.forRequest(await searchParams).dataset('blog', 'posts').list()
|
|
308
|
-
* }
|
|
309
|
-
* ```
|
|
310
|
-
*
|
|
311
|
-
* Note this only bypasses the SDK's own cache. If the page itself sits behind
|
|
312
|
-
* a CDN or framework data cache, that layer needs the same treatment (e.g.
|
|
313
|
-
* `cache: 'no-store'` when the preview marker is present) or the editor keeps
|
|
314
|
-
* seeing a stale page no matter what this client returns.
|
|
975
|
+
* Lets go of the live connection: the last client of a server and key to
|
|
976
|
+
* close it closes the connection. The client keeps working, on the stamp
|
|
977
|
+
* check alone. Not needed to let a process end (the connection never keeps
|
|
978
|
+
* one alive); for a test, or code that builds clients and drops them.
|
|
315
979
|
*/
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
const view = Object.create(this);
|
|
320
|
-
view.readDefault = false;
|
|
321
|
-
return view;
|
|
322
|
-
}
|
|
323
|
-
/** Whether this client bypasses the cache (i.e. came from a preview request). */
|
|
324
|
-
get isPreview() {
|
|
325
|
-
return !this.readDefault;
|
|
980
|
+
close() {
|
|
981
|
+
this.live?.close();
|
|
982
|
+
this.live = void 0;
|
|
326
983
|
}
|
|
327
984
|
// ── Introspection ─────────────────────────────────────────────────────────
|
|
328
985
|
/** The full content shape this key can reach: nodes, datasets, field schemas. */
|
|
@@ -369,7 +1026,7 @@ var HavenClient = class {
|
|
|
369
1026
|
async readLocale(opts) {
|
|
370
1027
|
const requested = this.resolveLocale(opts)?.trim() || void 0;
|
|
371
1028
|
if (requested === void 0 || !this.cache.enabled) return requested;
|
|
372
|
-
const bypass =
|
|
1029
|
+
const bypass = opts?.cache === false;
|
|
373
1030
|
const configured = await this.configuredLocales(!bypass);
|
|
374
1031
|
return configured ? matchLocale(requested, configured) : requested;
|
|
375
1032
|
}
|
|
@@ -460,6 +1117,58 @@ var HavenClient = class {
|
|
|
460
1117
|
);
|
|
461
1118
|
return res.record;
|
|
462
1119
|
}
|
|
1120
|
+
/**
|
|
1121
|
+
* Upload one file for a `file` field, for a form that sends an attachment.
|
|
1122
|
+
* Requires write scope on the dataset. Returns the file; hang it on a record
|
|
1123
|
+
* in a second call by writing `{ uid }` into that field:
|
|
1124
|
+
*
|
|
1125
|
+
* ```ts
|
|
1126
|
+
* const attachment = form.get('attachment')
|
|
1127
|
+
* if (attachment instanceof File && attachment.size > 0) {
|
|
1128
|
+
* const file = await studio.uploadFile('contact', 'requests', 'attachment', attachment)
|
|
1129
|
+
* await studio.createRecord('contact', 'requests', { name, attachment: { uid: file.uid } })
|
|
1130
|
+
* }
|
|
1131
|
+
* ```
|
|
1132
|
+
*
|
|
1133
|
+
* The field decides what it takes: its `mimes` and `max_size` rules, within
|
|
1134
|
+
* what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
|
|
1135
|
+
* studio reads the type from the content, so a renamed file is refused. Only
|
|
1136
|
+
* top-level fields. A file of the wrong type or size throws `HavenError` 400
|
|
1137
|
+
* with a message fit to show; other refusals (400, 403, 404) are setup
|
|
1138
|
+
* errors. More than 10 uploads a minute per key throws 429. From a Node
|
|
1139
|
+
* `Buffer`, send `new Blob([buffer])` with a `filename`.
|
|
1140
|
+
*
|
|
1141
|
+
* Server-side only: the key that uploads can write, and must never reach a
|
|
1142
|
+
* browser. Not retried, not cached, and it leaves cached reads alone: until a
|
|
1143
|
+
* record takes it up, the file belongs to no content. An upload that failed
|
|
1144
|
+
* may still have been stored; an unused one is removed after 24 hours.
|
|
1145
|
+
*/
|
|
1146
|
+
async uploadFile(nodeSlug, datasetSlug, fieldSlug, file, opts) {
|
|
1147
|
+
const filename = opts?.filename ?? file.name;
|
|
1148
|
+
if (!filename) {
|
|
1149
|
+
throw new Error("HavenClient.uploadFile: the file has no name; pass `filename` (with its extension)");
|
|
1150
|
+
}
|
|
1151
|
+
const form = new FormData();
|
|
1152
|
+
form.set("file", file, filename);
|
|
1153
|
+
form.set("nodeSlug", nodeSlug);
|
|
1154
|
+
form.set("datasetSlug", datasetSlug);
|
|
1155
|
+
form.set("fieldSlug", fieldSlug);
|
|
1156
|
+
const url = `${this.baseUrl}/api/content/files`;
|
|
1157
|
+
const timeout = uploadTimeout(this.timeout, opts?.timeout);
|
|
1158
|
+
return withTimeout(url, timeout, async (signal) => {
|
|
1159
|
+
const res = await this.fetchImpl(url, {
|
|
1160
|
+
method: "POST",
|
|
1161
|
+
// No Content-Type: fetch sets the multipart one, with its boundary.
|
|
1162
|
+
headers: { Authorization: `Bearer ${this.apiKey}`, ...withoutContentType(this.headers) },
|
|
1163
|
+
body: form,
|
|
1164
|
+
signal
|
|
1165
|
+
});
|
|
1166
|
+
if (!res.ok) throw await this.toError(res);
|
|
1167
|
+
const value = await res.json().catch(() => void 0);
|
|
1168
|
+
if (!has("uid", (uid) => typeof uid === "string" && uid !== "")(value)) throw unexpectedBody(url);
|
|
1169
|
+
return value;
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
463
1172
|
/**
|
|
464
1173
|
* Sends a write and settles the cached reads of its dataset with the outcome.
|
|
465
1174
|
*
|
|
@@ -639,7 +1348,7 @@ var HavenClient = class {
|
|
|
639
1348
|
* 5. One request per key at a time (`refresh`).
|
|
640
1349
|
*/
|
|
641
1350
|
async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
|
|
642
|
-
const useCache = opts?.cache
|
|
1351
|
+
const useCache = opts?.cache !== false;
|
|
643
1352
|
if (!useCache) {
|
|
644
1353
|
const version2 = this.versionTracker.current() ?? void 0;
|
|
645
1354
|
const ticket = ++this.state.ticket;
|
|
@@ -658,7 +1367,7 @@ var HavenClient = class {
|
|
|
658
1367
|
}
|
|
659
1368
|
const started = Date.now();
|
|
660
1369
|
const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity;
|
|
661
|
-
await within(this.
|
|
1370
|
+
await within(this.checkVersion(started), budget);
|
|
662
1371
|
const version = this.versionTracker.current() ?? void 0;
|
|
663
1372
|
const entry = this.cache.peek(cacheKey, Date.now());
|
|
664
1373
|
if (entry) {
|
|
@@ -675,6 +1384,10 @@ var HavenClient = class {
|
|
|
675
1384
|
const outcome = await within(refresh, budget - (Date.now() - started));
|
|
676
1385
|
return outcome.settled ? outcome.value : last.value;
|
|
677
1386
|
}
|
|
1387
|
+
/** The stamp gate of a read: the live connection's stamp while it is healthy, else the poll. */
|
|
1388
|
+
checkVersion(now) {
|
|
1389
|
+
return this.live ? this.live.gate(this.versionTracker, now) : this.versionTracker.refresh(now);
|
|
1390
|
+
}
|
|
678
1391
|
/**
|
|
679
1392
|
* Fetches `cacheKey` from the studio and settles the cache with the answer.
|
|
680
1393
|
* One per key at a time: reads that arrive while it runs get the same promise,
|
|
@@ -853,24 +1566,15 @@ var DatasetHandle = class {
|
|
|
853
1566
|
update(recordUid, data) {
|
|
854
1567
|
return this.client.updateRecord(this.nodeSlug, this.datasetSlug, recordUid, data);
|
|
855
1568
|
}
|
|
1569
|
+
/** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */
|
|
1570
|
+
uploadFile(fieldSlug, file, opts) {
|
|
1571
|
+
return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts);
|
|
1572
|
+
}
|
|
856
1573
|
/** Clear cached reads for this dataset. */
|
|
857
1574
|
clearCache() {
|
|
858
1575
|
this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug });
|
|
859
1576
|
}
|
|
860
1577
|
};
|
|
861
|
-
function isPreviewRequest(input) {
|
|
862
|
-
if (!input) return false;
|
|
863
|
-
if (typeof input === "string") {
|
|
864
|
-
const query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
|
|
865
|
-
return new URLSearchParams(query).has(PREVIEW_PARAM);
|
|
866
|
-
}
|
|
867
|
-
if (input instanceof URLSearchParams) return input.has(PREVIEW_PARAM);
|
|
868
|
-
if (input instanceof URL) return input.searchParams.has(PREVIEW_PARAM);
|
|
869
|
-
if (typeof input.url === "string") {
|
|
870
|
-
return isPreviewRequest(input.url);
|
|
871
|
-
}
|
|
872
|
-
return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM);
|
|
873
|
-
}
|
|
874
1578
|
async function withTimeout(url, ms, run) {
|
|
875
1579
|
if (ms <= 0) return run(void 0);
|
|
876
1580
|
const controller = new AbortController();
|
|
@@ -893,6 +1597,13 @@ function normalizeTimeout(value) {
|
|
|
893
1597
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
|
|
894
1598
|
return value > MAX_TIMER ? 0 : value;
|
|
895
1599
|
}
|
|
1600
|
+
function uploadTimeout(clientTimeout, perCall) {
|
|
1601
|
+
if (typeof perCall === "number" && perCall >= 0) return normalizeTimeout(perCall);
|
|
1602
|
+
return clientTimeout === 0 ? 0 : Math.max(clientTimeout, MIN_UPLOAD_TIMEOUT);
|
|
1603
|
+
}
|
|
1604
|
+
function withoutContentType(headers) {
|
|
1605
|
+
return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-type"));
|
|
1606
|
+
}
|
|
896
1607
|
function normalizeGatewayRetry(value) {
|
|
897
1608
|
if (value === false) return void 0;
|
|
898
1609
|
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;
|
|
@@ -948,9 +1659,7 @@ function isDefinitive(err) {
|
|
|
948
1659
|
return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err);
|
|
949
1660
|
}
|
|
950
1661
|
function isStudioAnswer(err) {
|
|
951
|
-
|
|
952
|
-
if (typeof body !== "object" || body === null) return false;
|
|
953
|
-
return body.statusCode === err.status || body.status === err.status;
|
|
1662
|
+
return isStudioBody(err.status, err.body);
|
|
954
1663
|
}
|
|
955
1664
|
function isMissingRoute(err) {
|
|
956
1665
|
return err instanceof HavenError && err.status === 404 && isStudioAnswer(err);
|
|
@@ -1084,6 +1793,6 @@ function createClient(options) {
|
|
|
1084
1793
|
return new HavenClient(options);
|
|
1085
1794
|
}
|
|
1086
1795
|
|
|
1087
|
-
export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError,
|
|
1796
|
+
export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, ContentCache, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, MemoryCacheStore, chartFenceHeight, createClient, isChartFence, parseChartFence };
|
|
1088
1797
|
//# sourceMappingURL=index.js.map
|
|
1089
1798
|
//# sourceMappingURL=index.js.map
|