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