@nordhavnhq/beacon 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +3 -329
- 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 +621 -107
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +240 -130
- package/dist/index.d.ts +240 -130
- package/dist/index.js +621 -107
- package/dist/index.js.map +1 -1
- package/package.json +42 -19
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nordhavn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,335 +1,9 @@
|
|
|
1
1
|
# @nordhavnhq/beacon
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
node datasets from any website or app: headless-CMS style, and beyond.
|
|
3
|
+
Internal package of Nordhavn OS. Published only so our own sites can install it.
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
write access to specific nodes and datasets. This package wraps that surface in
|
|
9
|
-
a fully typed client with built-in read caching.
|
|
10
|
-
|
|
11
|
-
- Zero dependencies, works in Node 18+ and the browser (the API sends permissive CORS).
|
|
12
|
-
- Dual ESM / CommonJS build, full TypeScript types.
|
|
13
|
-
- Read caching with TTL, automatic invalidation on writes, and a `clearCache()` method.
|
|
14
|
-
|
|
15
|
-
## Install
|
|
16
|
-
|
|
17
|
-
Published on npmjs:
|
|
18
|
-
|
|
19
|
-
```bash
|
|
20
|
-
npm install @nordhavnhq/beacon
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
## Quick start
|
|
24
|
-
|
|
25
|
-
```ts
|
|
26
|
-
import { createClient } from '@nordhavnhq/beacon'
|
|
27
|
-
|
|
28
|
-
const studio = createClient({
|
|
29
|
-
apiKey: process.env.HAVEN_API_KEY!, // slk_...
|
|
30
|
-
// baseUrl defaults to https://beacon.nordhavn.ai;
|
|
31
|
-
// set it only for a self-hosted server:
|
|
32
|
-
// baseUrl: 'https://studio.example.com',
|
|
33
|
-
})
|
|
34
|
-
|
|
35
|
-
// Discover what this key can reach.
|
|
36
|
-
const { nodes } = await studio.schema()
|
|
37
|
-
|
|
38
|
-
// List records from a dataset.
|
|
39
|
-
const posts = await studio.listRecords('blog', 'posts')
|
|
40
|
-
|
|
41
|
-
// Or use the fluent, typed handle.
|
|
42
|
-
interface Post { title: string, slug: string, body: string, published: boolean }
|
|
43
|
-
const blog = studio.dataset<Post>('blog', 'posts')
|
|
44
|
-
|
|
45
|
-
const all = await blog.list()
|
|
46
|
-
const one = await blog.get('rec_abc123')
|
|
47
|
-
const created = await blog.create({ title: 'Hello', slug: 'hello', body: '...', published: true })
|
|
48
|
-
const updated = await blog.update('rec_abc123', { published: false })
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
Each record is `{ uid, data, createdAt, updatedAt }`, where `data` is keyed by
|
|
52
|
-
field slug with references (files, referenced records) already inflated.
|
|
53
|
-
|
|
54
|
-
## Authentication & scopes
|
|
55
|
-
|
|
56
|
-
Pass the project API key as `apiKey`. A key's reach is the union of its per-node
|
|
57
|
-
scopes (read and/or write, optionally narrowed to specific datasets). Calls
|
|
58
|
-
outside the key's scope throw a `HavenError` with `status` 403; an
|
|
59
|
-
unknown node/dataset/record throws 404.
|
|
60
|
-
|
|
61
|
-
```ts
|
|
62
|
-
import { HavenError } from '@nordhavnhq/beacon'
|
|
63
|
-
|
|
64
|
-
try {
|
|
65
|
-
await studio.getRecord('blog', 'posts', 'nope')
|
|
66
|
-
} catch (err) {
|
|
67
|
-
if (err instanceof HavenError && err.isNotFound) {
|
|
68
|
-
// handle missing record
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
## Introspection
|
|
74
|
-
|
|
75
|
-
`schema()` returns every node the key can reach, the datasets within, each
|
|
76
|
-
dataset's field schema, and `canRead` / `canWrite` flags so a site can adapt to
|
|
77
|
-
its access without hardcoding slugs.
|
|
78
|
-
|
|
79
|
-
```ts
|
|
80
|
-
for (const node of await studio.nodes()) {
|
|
81
|
-
for (const ds of node.datasets) {
|
|
82
|
-
console.log(node.slug, ds.slug, ds.canWrite ? '(writable)' : '(read-only)')
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
```
|
|
86
|
-
|
|
87
|
-
## Localisation
|
|
88
|
-
|
|
89
|
-
If the project has multiple languages, request one on reads. Untranslated fields
|
|
90
|
-
fall back to the project's default (source) language automatically, so a
|
|
91
|
-
partly-translated site never shows blanks.
|
|
92
|
-
|
|
93
|
-
```ts
|
|
94
|
-
// List the languages the project offers (default first).
|
|
95
|
-
const locales = await studio.locales()
|
|
96
|
-
// [{ code: 'nl-BE', label: 'Dutch (Belgium)', isDefault: true, isFallback: false },
|
|
97
|
-
// { code: 'en-US', label: 'English (US)', isDefault: false, isFallback: true }]
|
|
98
|
-
|
|
99
|
-
// A client-wide default locale for every read:
|
|
100
|
-
const en = createClient({ apiKey: 'slk_...', locale: 'en-US' })
|
|
101
|
-
const posts = await en.dataset('blog', 'posts').list()
|
|
102
|
-
|
|
103
|
-
// ...or per call, overriding the client locale:
|
|
104
|
-
const fr = await studio.listRecords('blog', 'posts', { locale: 'fr-BE' })
|
|
105
|
-
const one = await studio.getRecord('blog', 'posts', 'R12AB34C', { locale: 'nl-BE' })
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
Each locale is cached separately, so switching languages never serves the wrong
|
|
109
|
-
one. Pass `locale: ''` on a call to force the project default even when a
|
|
110
|
-
client-level `locale` is set.
|
|
111
|
-
|
|
112
|
-
### How a requested locale resolves
|
|
113
|
-
|
|
114
|
-
You can pass the visitor's **detected** locale verbatim (e.g. from
|
|
115
|
-
`Accept-Language`); the studio resolves it server-side, so you never have to map
|
|
116
|
-
it to a configured code yourself:
|
|
117
|
-
|
|
118
|
-
1. **Exact match** first (`nl-BE` -> `nl-BE`).
|
|
119
|
-
2. **Base-language match**: `nl` and `nl-NL` resolve to a configured `nl-BE`;
|
|
120
|
-
`en`, `en-GB`, `en-AU` resolve to `en-US`. So the project only needs one
|
|
121
|
-
regional variant per language.
|
|
122
|
-
3. **No match** (a language the project doesn't offer, e.g. a German visitor):
|
|
123
|
-
the project's **fallback** locale is served if one is set (the entry with
|
|
124
|
-
`isFallback: true`), otherwise the default. This lets a Dutch-authored site
|
|
125
|
-
(default `nl-BE`) show English to unknown languages while Dutch visitors still
|
|
126
|
-
get the source.
|
|
127
|
-
4. **No locale sent** (you omit it): the default/source language.
|
|
128
|
-
|
|
129
|
-
Within the chosen language, any field that isn't translated yet falls back to
|
|
130
|
-
the default language for that field, never a blank.
|
|
131
|
-
|
|
132
|
-
```ts
|
|
133
|
-
// Framework example: forward whatever the visitor asked for.
|
|
134
|
-
const accept = request.headers.get('accept-language')?.split(',')[0] // e.g. 'de-DE'
|
|
135
|
-
const posts = await studio.listRecords('blog', 'posts', { locale: accept })
|
|
136
|
-
// German isn't offered -> the project's fallback (say en-US) comes back.
|
|
137
|
-
```
|
|
138
|
-
|
|
139
|
-
## Saved queries
|
|
140
|
-
|
|
141
|
-
Run a server-defined query (`queries.<slug>`) and get its result. The `shape`
|
|
142
|
-
tells you whether `value` is a `collection`, a `single` record, or a scalar
|
|
143
|
-
`value`.
|
|
144
|
-
|
|
145
|
-
```ts
|
|
146
|
-
const result = await studio.query('featured-posts')
|
|
147
|
-
if (result.shape === 'collection') {
|
|
148
|
-
// result.value is an array of records
|
|
149
|
-
}
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
## Caching
|
|
153
|
-
|
|
154
|
-
Reads (`schema`, `listRecords`, `getRecord`, `query`) are cached in memory and
|
|
155
|
-
kept fresh by **conditional revalidation** - the site stays in sync with the
|
|
156
|
-
studio without you doing anything, and without a "publish" step.
|
|
157
|
-
|
|
158
|
-
How it stays fresh, cheaply:
|
|
159
|
-
|
|
160
|
-
- The studio publishes a tiny per-project **stamp** (`GET /api/content/version`)
|
|
161
|
-
that changes on every content edit. The client checks it at most once every
|
|
162
|
-
minute (one small request, no matter how many reads).
|
|
163
|
-
- While the stamp is unchanged, reads are served straight from cache - zero
|
|
164
|
-
network.
|
|
165
|
-
- When the stamp moves, the affected read is **revalidated** with its `ETag`
|
|
166
|
-
(`If-None-Match`): the studio answers `304 Not Modified` (keep the cached
|
|
167
|
-
value, no transfer) or `200` with the new content. So a change to one dataset
|
|
168
|
-
only refetches that dataset; everything else stays cached on a `304`.
|
|
169
|
-
|
|
170
|
-
What this buys you:
|
|
171
|
-
|
|
172
|
-
- **Edits go live on their own, within about a minute** for public visitors
|
|
173
|
-
(instantly in a surface preview) - a safe promise to a client is "live within
|
|
174
|
-
10 minutes". No button, no
|
|
175
|
-
webhook, no cache to clear.
|
|
176
|
-
- **Resilient:** if the studio is unreachable, the last good value keeps being
|
|
177
|
-
served (a definitive `404`/`403`, e.g. a deleted record, is surfaced as an
|
|
178
|
-
error rather than masked).
|
|
179
|
-
- The **TTL (7 days default)** is the outage window, not the refresh interval:
|
|
180
|
-
how long the site keeps serving the last-known content while the studio is
|
|
181
|
-
unreachable. An entry that keeps revalidating stays alive, so in practice an
|
|
182
|
-
entry only expires ~`ttl` after the studio goes down.
|
|
183
|
-
|
|
184
|
-
Every knob is overridable:
|
|
185
|
-
|
|
186
|
-
```ts
|
|
187
|
-
const studio = createClient({
|
|
188
|
-
apiKey, baseUrl,
|
|
189
|
-
// defaults: ttl 7d (outage window), revalidate 60s (stamp check), maxEntries 500
|
|
190
|
-
cache: { ttl: 604_800_000, revalidate: 60_000, maxEntries: 1000 },
|
|
191
|
-
})
|
|
192
|
-
|
|
193
|
-
// Survive an outage of any length - serve last-known until the studio returns:
|
|
194
|
-
createClient({ apiKey, baseUrl, cache: { ttl: 0 } })
|
|
195
|
-
|
|
196
|
-
// Pure TTL, never check the stamp (content can be up to `ttl` stale):
|
|
197
|
-
createClient({ apiKey, baseUrl, cache: { revalidate: false } })
|
|
198
|
-
|
|
199
|
-
// Disable caching entirely (every read hits the studio live):
|
|
200
|
-
createClient({ apiKey, baseUrl, cache: false })
|
|
201
|
-
|
|
202
|
-
// Bypass the cache for a single call (the fresh value still refreshes it):
|
|
203
|
-
await studio.listRecords('blog', 'posts', { cache: false })
|
|
204
|
-
```
|
|
205
|
-
|
|
206
|
-
> Caching is safe to leave on everywhere, including local/dev frontends: because
|
|
207
|
-
> every read revalidates against the stamp, a cached dev site is still always in
|
|
208
|
-
> sync. There is no "dev bypasses, production caches" split to manage.
|
|
209
|
-
|
|
210
|
-
### Preview requests
|
|
211
|
-
|
|
212
|
-
When the studio loads your site inside a surface preview it appends
|
|
213
|
-
`?sl-preview=…` to the URL. Pass the request through `forRequest()` and those
|
|
214
|
-
loads skip the cache completely, so an editor always sees their change
|
|
215
|
-
immediately:
|
|
216
|
-
|
|
217
|
-
```ts
|
|
218
|
-
// Next.js app router
|
|
219
|
-
export default async function Page({ searchParams }) {
|
|
220
|
-
const studioForThisRequest = studio.forRequest(await searchParams)
|
|
221
|
-
const posts = await studioForThisRequest.dataset('blog', 'posts').list()
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// Anything with a Request object
|
|
225
|
-
const posts = await studio.forRequest(request).dataset('blog', 'posts').list()
|
|
226
|
-
```
|
|
227
|
-
|
|
228
|
-
`forRequest()` accepts a `Request`, a URL string or `URL`, `URLSearchParams`, or
|
|
229
|
-
a plain searchParams object, and returns this same client unchanged when the
|
|
230
|
-
marker is absent - so it is safe to call on every request. Preview reads share
|
|
231
|
-
the normal cache and refresh it, they do not maintain a second copy.
|
|
232
|
-
|
|
233
|
-
One caveat: this only bypasses **this client's** cache. If your page also sits
|
|
234
|
-
behind a CDN or a framework data cache, that layer needs the same treatment or
|
|
235
|
-
the editor still sees a stale page. In Next.js:
|
|
236
|
-
|
|
237
|
-
```ts
|
|
238
|
-
import { isPreviewRequest } from '@nordhavnhq/beacon'
|
|
239
|
-
|
|
240
|
-
export const dynamic = 'force-dynamic' // or, per fetch: cache: 'no-store'
|
|
241
|
-
```
|
|
242
|
-
|
|
243
|
-
### Clearing the cache
|
|
244
|
-
|
|
245
|
-
```ts
|
|
246
|
-
studio.clearCache() // everything
|
|
247
|
-
studio.clearCache('blog') // one node
|
|
248
|
-
studio.clearCache({ node: 'blog', dataset: 'posts' }) // one dataset
|
|
249
|
-
studio.dataset('blog', 'posts').clearCache() // same, fluent
|
|
250
|
-
```
|
|
251
|
-
|
|
252
|
-
Bring your own store (share a cache across instances, or persist it) by
|
|
253
|
-
implementing `CacheStore` and passing it as `cache.store`.
|
|
254
|
-
|
|
255
|
-
## API
|
|
256
|
-
|
|
257
|
-
| Method | Description |
|
|
258
|
-
| --- | --- |
|
|
259
|
-
| `schema(opts?)` | Full reachable content shape (`{ nodes }`). |
|
|
260
|
-
| `nodes(opts?)` | Shortcut for `schema().nodes`. |
|
|
261
|
-
| `listRecords<T>(node, dataset, opts?)` | All records in a dataset. |
|
|
262
|
-
| `getRecord<T>(node, dataset, uid, opts?)` | One record by uid. |
|
|
263
|
-
| `createRecord<T>(node, dataset, data)` | Create a record (needs write scope). |
|
|
264
|
-
| `updateRecord<T>(node, dataset, uid, data)` | Merge-patch a record (needs write scope). |
|
|
265
|
-
| `query<V>(slug, opts?)` | Run a saved query. |
|
|
266
|
-
| `dataset<T>(node, dataset)` | Fluent handle: `.list() .get() .create() .update() .clearCache()`. |
|
|
267
|
-
| `clearCache(scope?)` | Clear all, one node, or one dataset. |
|
|
268
|
-
| `forRequest(req)` | Cache-bypassing view of this client for studio preview requests. |
|
|
269
|
-
| `isPreview` | Whether this client came from a preview request. |
|
|
270
|
-
|
|
271
|
-
`opts` is `{ cache?: boolean }`. All read methods accept a row type parameter
|
|
272
|
-
`<T>` for `record.data`.
|
|
273
|
-
|
|
274
|
-
## Chart contract
|
|
275
|
-
|
|
276
|
-
The shape of a chart block is part of the contract, so a site can render the
|
|
277
|
-
same charts the studio shows. Types and constants come from the main entry,
|
|
278
|
-
with no runtime dependencies:
|
|
279
|
-
|
|
280
|
-
```ts
|
|
281
|
-
import type { ChartSpec, ChartData } from '@nordhavnhq/beacon'
|
|
282
|
-
import { CHART_TYPES, PALETTE_KEYS, AGGREGATIONS } from '@nordhavnhq/beacon'
|
|
283
|
-
```
|
|
284
|
-
|
|
285
|
-
- `ChartSpec`: what a chart block stores (type, source, category field, series,
|
|
286
|
-
date bucket, sort, limit, gap filling, stacking, legend).
|
|
287
|
-
- `ChartData`: the consolidated result a renderer draws (categories plus one
|
|
288
|
-
value list per series).
|
|
289
|
-
- `PALETTE_KEYS`: the eight colour keys a series can use. A spec never holds a
|
|
290
|
-
raw colour; the renderer maps each key to a colour of its own theme.
|
|
291
|
-
|
|
292
|
-
To validate or fill in defaults, use the zod schema from a separate entry
|
|
293
|
-
(`zod` ^4 is an optional peer dependency, only needed for this entry):
|
|
294
|
-
|
|
295
|
-
```ts
|
|
296
|
-
import { chartSpecSchema, DEFAULT_CHART_SPEC } from '@nordhavnhq/beacon/schema'
|
|
297
|
-
|
|
298
|
-
const spec = chartSpecSchema.parse(block.props)
|
|
299
|
-
```
|
|
300
|
-
|
|
301
|
-
Two more shapes, plain types with no schema, for the roadmap and the
|
|
302
|
-
forecast chart of `@nordhavnhq/ui`:
|
|
303
|
-
|
|
304
|
-
- `RoadmapData`: a plan on a timeline (lanes with phases, milestones, what
|
|
305
|
-
waits on the viewer, tasks, repeats, happenings, events), with the tooltip
|
|
306
|
-
content (`RoadmapTip`) written by the host. All dates are ISO days.
|
|
307
|
-
- `ForecastSeries`: measured values per step, a forecast band
|
|
308
|
-
(`{ x, low, mid, high }`) and a target.
|
|
309
|
-
|
|
310
|
-
## Node < 18
|
|
311
|
-
|
|
312
|
-
Global `fetch` is required. On older runtimes, pass one:
|
|
313
|
-
|
|
314
|
-
```ts
|
|
315
|
-
import fetch from 'node-fetch'
|
|
316
|
-
createClient({ apiKey, baseUrl, fetch: fetch as unknown as typeof globalThis.fetch })
|
|
317
|
-
```
|
|
318
|
-
|
|
319
|
-
## Coming from `@justmade/client`
|
|
320
|
-
|
|
321
|
-
This package used to be published as `@justmade/client`. Those versions stay on
|
|
322
|
-
npm and keep working. To switch, install `@nordhavnhq/beacon` and change the import:
|
|
323
|
-
|
|
324
|
-
```ts
|
|
325
|
-
import { createClient, HavenError } from '@nordhavnhq/beacon'
|
|
326
|
-
```
|
|
327
|
-
|
|
328
|
-
`JustmadeClient`, `JustmadeClientOptions` and `JustmadeError` are still exported
|
|
329
|
-
as deprecated aliases of `HavenClient`, `HavenClientOptions` and `HavenError`,
|
|
330
|
-
and go in the next breaking release. One difference: an error's `name` is now
|
|
331
|
-
`'HavenError'`, so code that compares `err.name` must use the new name (or
|
|
332
|
-
`instanceof`).
|
|
5
|
+
Not meant for outside use: no support, no stability guarantees, and it needs an
|
|
6
|
+
API key for a Nordhavn OS server.
|
|
333
7
|
|
|
334
8
|
## License
|
|
335
9
|
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read caching for the content client. GET responses (schema, record lists,
|
|
3
|
+
* single records, queries) are cached by request key and kept fresh by
|
|
4
|
+
* conditional revalidation: each entry stores the studio's `ETag`, which the
|
|
5
|
+
* client sends back as `If-None-Match`. A cheap project-wide stamp gates whether
|
|
6
|
+
* a revalidation is even attempted, so a stable site serves straight from cache.
|
|
7
|
+
*
|
|
8
|
+
* Swap in a custom `CacheStore` to share a cache across client instances or to
|
|
9
|
+
* back it with something persistent.
|
|
10
|
+
*/
|
|
11
|
+
interface CacheEntry {
|
|
12
|
+
value: unknown;
|
|
13
|
+
/**
|
|
14
|
+
* The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`
|
|
15
|
+
* to revalidate: a `304` means the stored value is still current.
|
|
16
|
+
*/
|
|
17
|
+
etag?: string;
|
|
18
|
+
/**
|
|
19
|
+
* The project stamp this entry was last confirmed current against. When it
|
|
20
|
+
* equals the client's latest known stamp, the entry is served without any
|
|
21
|
+
* network call at all.
|
|
22
|
+
*/
|
|
23
|
+
validatedVersion?: string;
|
|
24
|
+
/** Epoch ms when the entry expires. `0` means it never expires. */
|
|
25
|
+
expiresAt: number;
|
|
26
|
+
/**
|
|
27
|
+
* Epoch ms before which a failed refetch is not retried: until then the entry
|
|
28
|
+
* is served as-is. Set after a transient error, cleared by a fresh value or a
|
|
29
|
+
* `304`.
|
|
30
|
+
*/
|
|
31
|
+
retryAt?: number;
|
|
32
|
+
}
|
|
33
|
+
/** Pluggable backing store. The default is an in-memory, insertion-ordered map. */
|
|
34
|
+
interface CacheStore {
|
|
35
|
+
get(key: string): CacheEntry | undefined;
|
|
36
|
+
set(key: string, entry: CacheEntry): void;
|
|
37
|
+
delete(key: string): void;
|
|
38
|
+
/** Iterate current keys (used for prefix invalidation). */
|
|
39
|
+
keys(): Iterable<string>;
|
|
40
|
+
clear(): void;
|
|
41
|
+
}
|
|
42
|
+
interface CacheOptions {
|
|
43
|
+
/** Master switch. Default `true`. */
|
|
44
|
+
enabled?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* How long a cached entry survives, in ms. Default `604800000` (7 days).
|
|
47
|
+
*
|
|
48
|
+
* This is NOT how long until content refreshes - revalidation keeps entries
|
|
49
|
+
* current within `revalidate` (seconds) whenever the studio is reachable. The
|
|
50
|
+
* TTL only decides when an entry stops being served blindly and the next read
|
|
51
|
+
* must refetch it. If that refetch fails transiently (studio down, 5xx,
|
|
52
|
+
* network), the expired value is served anyway, so a studio outage degrades
|
|
53
|
+
* to "slightly stale" rather than "site errors" however long it lasts.
|
|
54
|
+
*
|
|
55
|
+
* The one case where it bounds staleness directly is when revalidation is off
|
|
56
|
+
* (`revalidate: false`) or the server has no `/version` endpoint: then content
|
|
57
|
+
* can be up to `ttl` old while the studio is reachable. `0` = never expire.
|
|
58
|
+
*/
|
|
59
|
+
ttl?: number;
|
|
60
|
+
/**
|
|
61
|
+
* Minimum ms between two project-stamp checks. Default `60000` (1 minute) -
|
|
62
|
+
* this is the freshness window for PUBLIC visitors (an edit is picked up on
|
|
63
|
+
* the next check after it lands); an editor viewing a surface preview bypasses
|
|
64
|
+
* the cache entirely and always sees changes instantly.
|
|
65
|
+
*
|
|
66
|
+
* The check fires only on a read and is throttled, so a quiet site barely
|
|
67
|
+
* checks at all; the interval only caps the busy case. Each check costs the
|
|
68
|
+
* studio a small API-key lookup, so raise it (a few minutes) if you run many
|
|
69
|
+
* frontends; lower it for a tighter public window. `false` disables checking
|
|
70
|
+
* and leaves you with pure TTL expiry.
|
|
71
|
+
*/
|
|
72
|
+
revalidate?: number | false;
|
|
73
|
+
/**
|
|
74
|
+
* How long a read that already holds a cached value waits on the studio for a
|
|
75
|
+
* fresher one, in ms. Default `1000`. Past it the read gets the cached value
|
|
76
|
+
* and the refresh finishes in the background, so the next read has it.
|
|
77
|
+
*
|
|
78
|
+
* It keeps a slow or hanging studio from slowing your pages down: without it
|
|
79
|
+
* every read after an edit waits for as long as the studio takes, up to
|
|
80
|
+
* `timeout`. The price is that on a slow studio an edit shows one read later.
|
|
81
|
+
*
|
|
82
|
+
* `0` never waits (always serve the cached value, refresh in the background).
|
|
83
|
+
* `false` waits for the studio; choose it where work cannot outlive the
|
|
84
|
+
* request, as on serverless platforms that freeze the process once the
|
|
85
|
+
* response is out. A read with nothing cached always waits.
|
|
86
|
+
*/
|
|
87
|
+
waitForFresh?: number | false;
|
|
88
|
+
/** Soft cap on entries; oldest are evicted first. Default `500`. */
|
|
89
|
+
maxEntries?: number;
|
|
90
|
+
/** Custom backing store. Defaults to an in-memory store. */
|
|
91
|
+
store?: CacheStore;
|
|
92
|
+
}
|
|
93
|
+
/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */
|
|
94
|
+
declare class MemoryCacheStore implements CacheStore {
|
|
95
|
+
private maxEntries;
|
|
96
|
+
private map;
|
|
97
|
+
constructor(maxEntries?: number);
|
|
98
|
+
get(key: string): CacheEntry | undefined;
|
|
99
|
+
set(key: string, entry: CacheEntry): void;
|
|
100
|
+
delete(key: string): void;
|
|
101
|
+
keys(): Iterable<string>;
|
|
102
|
+
clear(): void;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation
|
|
106
|
+
* bookkeeping (etag + validated stamp), and prefix invalidation, so the client
|
|
107
|
+
* only deals in cache keys.
|
|
108
|
+
*/
|
|
109
|
+
declare class ContentCache {
|
|
110
|
+
readonly enabled: boolean;
|
|
111
|
+
private ttl;
|
|
112
|
+
/** Pause after a failed refetch: the `revalidate` interval, or 1 minute without one. */
|
|
113
|
+
private retryDelay;
|
|
114
|
+
private store;
|
|
115
|
+
constructor(opts?: CacheOptions);
|
|
116
|
+
/**
|
|
117
|
+
* The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the
|
|
118
|
+
* whole entry (value + etag + validated stamp) so the client can decide
|
|
119
|
+
* whether to serve it, revalidate it, or fall back to it on error.
|
|
120
|
+
*
|
|
121
|
+
* An expired entry is left in the store (the refetch overwrites it, or
|
|
122
|
+
* `maxEntries` evicts it) so `stale` can still fall back to it.
|
|
123
|
+
*/
|
|
124
|
+
peek(key: string, now: number): CacheEntry | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* The entry for `key` whether or not its TTL has run out: the last good value
|
|
127
|
+
* to serve when a refetch fails transiently.
|
|
128
|
+
*/
|
|
129
|
+
stale(key: string): CacheEntry | undefined;
|
|
130
|
+
/** Store a freshly fetched value with its validator and the stamp it is current against. */
|
|
131
|
+
set(key: string, value: unknown, opts: {
|
|
132
|
+
etag?: string;
|
|
133
|
+
version?: string;
|
|
134
|
+
}, now: number): void;
|
|
135
|
+
/**
|
|
136
|
+
* Record that an existing entry is still current as of `version` (after a
|
|
137
|
+
* `304`), refreshing its TTL without touching the value. No-op if it is gone.
|
|
138
|
+
*/
|
|
139
|
+
confirm(key: string, version: string | undefined, now: number): void;
|
|
140
|
+
/**
|
|
141
|
+
* Record that refetching `key` from `from` just failed transiently, so reads
|
|
142
|
+
* serve it as-is for a while instead of each waiting on an unreachable studio.
|
|
143
|
+
* Returns the entry to serve: `from`, or the newer one a concurrent read stored
|
|
144
|
+
* in the meantime (left unpaused, since its own fetch succeeded).
|
|
145
|
+
*/
|
|
146
|
+
backoff(key: string, from: CacheEntry, now: number): CacheEntry;
|
|
147
|
+
/**
|
|
148
|
+
* Mark `key` as due for a refetch while keeping its value to fall back on:
|
|
149
|
+
* the next read asks the studio again whatever the stamp says, and still
|
|
150
|
+
* serves this value if the studio does not answer. For when the stored value
|
|
151
|
+
* may be outdated but there is no telling - dropping it would throw away the
|
|
152
|
+
* only thing left to show during an outage. No-op for a key that is not held.
|
|
153
|
+
*/
|
|
154
|
+
expire(key: string): void;
|
|
155
|
+
/** `expire` for every key that starts with `prefix`. */
|
|
156
|
+
expirePrefix(prefix: string): void;
|
|
157
|
+
/** Drop one exact key. */
|
|
158
|
+
delete(key: string): void;
|
|
159
|
+
/** Drop every key that starts with `prefix`. */
|
|
160
|
+
deletePrefix(prefix: string): void;
|
|
161
|
+
clear(): void;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { MemoryCacheStore as M, ContentCache as c };
|
|
165
|
+
export type { CacheStore as C, CacheEntry as a, CacheOptions as b };
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read caching for the content client. GET responses (schema, record lists,
|
|
3
|
+
* single records, queries) are cached by request key and kept fresh by
|
|
4
|
+
* conditional revalidation: each entry stores the studio's `ETag`, which the
|
|
5
|
+
* client sends back as `If-None-Match`. A cheap project-wide stamp gates whether
|
|
6
|
+
* a revalidation is even attempted, so a stable site serves straight from cache.
|
|
7
|
+
*
|
|
8
|
+
* Swap in a custom `CacheStore` to share a cache across client instances or to
|
|
9
|
+
* back it with something persistent.
|
|
10
|
+
*/
|
|
11
|
+
interface CacheEntry {
|
|
12
|
+
value: unknown;
|
|
13
|
+
/**
|
|
14
|
+
* The studio's validator (`ETag`) for this value. Sent back as `If-None-Match`
|
|
15
|
+
* to revalidate: a `304` means the stored value is still current.
|
|
16
|
+
*/
|
|
17
|
+
etag?: string;
|
|
18
|
+
/**
|
|
19
|
+
* The project stamp this entry was last confirmed current against. When it
|
|
20
|
+
* equals the client's latest known stamp, the entry is served without any
|
|
21
|
+
* network call at all.
|
|
22
|
+
*/
|
|
23
|
+
validatedVersion?: string;
|
|
24
|
+
/** Epoch ms when the entry expires. `0` means it never expires. */
|
|
25
|
+
expiresAt: number;
|
|
26
|
+
/**
|
|
27
|
+
* Epoch ms before which a failed refetch is not retried: until then the entry
|
|
28
|
+
* is served as-is. Set after a transient error, cleared by a fresh value or a
|
|
29
|
+
* `304`.
|
|
30
|
+
*/
|
|
31
|
+
retryAt?: number;
|
|
32
|
+
}
|
|
33
|
+
/** Pluggable backing store. The default is an in-memory, insertion-ordered map. */
|
|
34
|
+
interface CacheStore {
|
|
35
|
+
get(key: string): CacheEntry | undefined;
|
|
36
|
+
set(key: string, entry: CacheEntry): void;
|
|
37
|
+
delete(key: string): void;
|
|
38
|
+
/** Iterate current keys (used for prefix invalidation). */
|
|
39
|
+
keys(): Iterable<string>;
|
|
40
|
+
clear(): void;
|
|
41
|
+
}
|
|
42
|
+
interface CacheOptions {
|
|
43
|
+
/** Master switch. Default `true`. */
|
|
44
|
+
enabled?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* How long a cached entry survives, in ms. Default `604800000` (7 days).
|
|
47
|
+
*
|
|
48
|
+
* This is NOT how long until content refreshes - revalidation keeps entries
|
|
49
|
+
* current within `revalidate` (seconds) whenever the studio is reachable. The
|
|
50
|
+
* TTL only decides when an entry stops being served blindly and the next read
|
|
51
|
+
* must refetch it. If that refetch fails transiently (studio down, 5xx,
|
|
52
|
+
* network), the expired value is served anyway, so a studio outage degrades
|
|
53
|
+
* to "slightly stale" rather than "site errors" however long it lasts.
|
|
54
|
+
*
|
|
55
|
+
* The one case where it bounds staleness directly is when revalidation is off
|
|
56
|
+
* (`revalidate: false`) or the server has no `/version` endpoint: then content
|
|
57
|
+
* can be up to `ttl` old while the studio is reachable. `0` = never expire.
|
|
58
|
+
*/
|
|
59
|
+
ttl?: number;
|
|
60
|
+
/**
|
|
61
|
+
* Minimum ms between two project-stamp checks. Default `60000` (1 minute) -
|
|
62
|
+
* this is the freshness window for PUBLIC visitors (an edit is picked up on
|
|
63
|
+
* the next check after it lands); an editor viewing a surface preview bypasses
|
|
64
|
+
* the cache entirely and always sees changes instantly.
|
|
65
|
+
*
|
|
66
|
+
* The check fires only on a read and is throttled, so a quiet site barely
|
|
67
|
+
* checks at all; the interval only caps the busy case. Each check costs the
|
|
68
|
+
* studio a small API-key lookup, so raise it (a few minutes) if you run many
|
|
69
|
+
* frontends; lower it for a tighter public window. `false` disables checking
|
|
70
|
+
* and leaves you with pure TTL expiry.
|
|
71
|
+
*/
|
|
72
|
+
revalidate?: number | false;
|
|
73
|
+
/**
|
|
74
|
+
* How long a read that already holds a cached value waits on the studio for a
|
|
75
|
+
* fresher one, in ms. Default `1000`. Past it the read gets the cached value
|
|
76
|
+
* and the refresh finishes in the background, so the next read has it.
|
|
77
|
+
*
|
|
78
|
+
* It keeps a slow or hanging studio from slowing your pages down: without it
|
|
79
|
+
* every read after an edit waits for as long as the studio takes, up to
|
|
80
|
+
* `timeout`. The price is that on a slow studio an edit shows one read later.
|
|
81
|
+
*
|
|
82
|
+
* `0` never waits (always serve the cached value, refresh in the background).
|
|
83
|
+
* `false` waits for the studio; choose it where work cannot outlive the
|
|
84
|
+
* request, as on serverless platforms that freeze the process once the
|
|
85
|
+
* response is out. A read with nothing cached always waits.
|
|
86
|
+
*/
|
|
87
|
+
waitForFresh?: number | false;
|
|
88
|
+
/** Soft cap on entries; oldest are evicted first. Default `500`. */
|
|
89
|
+
maxEntries?: number;
|
|
90
|
+
/** Custom backing store. Defaults to an in-memory store. */
|
|
91
|
+
store?: CacheStore;
|
|
92
|
+
}
|
|
93
|
+
/** In-memory store with insertion-order (FIFO) eviction once `maxEntries` is hit. */
|
|
94
|
+
declare class MemoryCacheStore implements CacheStore {
|
|
95
|
+
private maxEntries;
|
|
96
|
+
private map;
|
|
97
|
+
constructor(maxEntries?: number);
|
|
98
|
+
get(key: string): CacheEntry | undefined;
|
|
99
|
+
set(key: string, entry: CacheEntry): void;
|
|
100
|
+
delete(key: string): void;
|
|
101
|
+
keys(): Iterable<string>;
|
|
102
|
+
clear(): void;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Thin cache facade the client talks to. Owns TTL logic, conditional-revalidation
|
|
106
|
+
* bookkeeping (etag + validated stamp), and prefix invalidation, so the client
|
|
107
|
+
* only deals in cache keys.
|
|
108
|
+
*/
|
|
109
|
+
declare class ContentCache {
|
|
110
|
+
readonly enabled: boolean;
|
|
111
|
+
private ttl;
|
|
112
|
+
/** Pause after a failed refetch: the `revalidate` interval, or 1 minute without one. */
|
|
113
|
+
private retryDelay;
|
|
114
|
+
private store;
|
|
115
|
+
constructor(opts?: CacheOptions);
|
|
116
|
+
/**
|
|
117
|
+
* The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the
|
|
118
|
+
* whole entry (value + etag + validated stamp) so the client can decide
|
|
119
|
+
* whether to serve it, revalidate it, or fall back to it on error.
|
|
120
|
+
*
|
|
121
|
+
* An expired entry is left in the store (the refetch overwrites it, or
|
|
122
|
+
* `maxEntries` evicts it) so `stale` can still fall back to it.
|
|
123
|
+
*/
|
|
124
|
+
peek(key: string, now: number): CacheEntry | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* The entry for `key` whether or not its TTL has run out: the last good value
|
|
127
|
+
* to serve when a refetch fails transiently.
|
|
128
|
+
*/
|
|
129
|
+
stale(key: string): CacheEntry | undefined;
|
|
130
|
+
/** Store a freshly fetched value with its validator and the stamp it is current against. */
|
|
131
|
+
set(key: string, value: unknown, opts: {
|
|
132
|
+
etag?: string;
|
|
133
|
+
version?: string;
|
|
134
|
+
}, now: number): void;
|
|
135
|
+
/**
|
|
136
|
+
* Record that an existing entry is still current as of `version` (after a
|
|
137
|
+
* `304`), refreshing its TTL without touching the value. No-op if it is gone.
|
|
138
|
+
*/
|
|
139
|
+
confirm(key: string, version: string | undefined, now: number): void;
|
|
140
|
+
/**
|
|
141
|
+
* Record that refetching `key` from `from` just failed transiently, so reads
|
|
142
|
+
* serve it as-is for a while instead of each waiting on an unreachable studio.
|
|
143
|
+
* Returns the entry to serve: `from`, or the newer one a concurrent read stored
|
|
144
|
+
* in the meantime (left unpaused, since its own fetch succeeded).
|
|
145
|
+
*/
|
|
146
|
+
backoff(key: string, from: CacheEntry, now: number): CacheEntry;
|
|
147
|
+
/**
|
|
148
|
+
* Mark `key` as due for a refetch while keeping its value to fall back on:
|
|
149
|
+
* the next read asks the studio again whatever the stamp says, and still
|
|
150
|
+
* serves this value if the studio does not answer. For when the stored value
|
|
151
|
+
* may be outdated but there is no telling - dropping it would throw away the
|
|
152
|
+
* only thing left to show during an outage. No-op for a key that is not held.
|
|
153
|
+
*/
|
|
154
|
+
expire(key: string): void;
|
|
155
|
+
/** `expire` for every key that starts with `prefix`. */
|
|
156
|
+
expirePrefix(prefix: string): void;
|
|
157
|
+
/** Drop one exact key. */
|
|
158
|
+
delete(key: string): void;
|
|
159
|
+
/** Drop every key that starts with `prefix`. */
|
|
160
|
+
deletePrefix(prefix: string): void;
|
|
161
|
+
clear(): void;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { MemoryCacheStore as M, ContentCache as c };
|
|
165
|
+
export type { CacheStore as C, CacheEntry as a, CacheOptions as b };
|