@mapled/next 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -0
- package/dist/live.d.ts +12 -0
- package/dist/live.js +32 -0
- package/dist/server.d.ts +16 -0
- package/dist/server.js +69 -0
- package/dist/watch.d.ts +23 -0
- package/dist/watch.js +96 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# @mapled/next
|
|
2
2
|
|
|
3
|
-
Read published [Mapled](https://mapled.io) content in a Next.js site — a delivery client with ISR cache tags,
|
|
3
|
+
Read published [Mapled](https://mapled.io) content in a Next.js site — a delivery client with ISR cache tags, a revalidation webhook handler so publishes show up instantly, and live updates for the tabs that are already open.
|
|
4
4
|
|
|
5
5
|
Mapled is a hosted headless CMS built for sites created with AI. Your agent (or you) models collections and fills in content; this package is how the site reads what's published.
|
|
6
6
|
|
|
7
7
|
- [Install](#install)
|
|
8
8
|
- [Integrate by hand](#integrate-by-hand) — the whole integration step by step, no AI agent needed
|
|
9
|
-
- Reference: [Read published content](#read-published-content) • [Rich text](#rich-text) • [Images](#images) • [Refresh on publish](#refresh-on-publish) • [Preview drafts](#preview-drafts) • [Forms](#forms) • [Live data](#live-data) • [Without Next.js: the HTTP API](#without-nextjs-the-http-api) • [API](#api)
|
|
9
|
+
- Reference: [Read published content](#read-published-content) • [Rich text](#rich-text) • [Images](#images) • [Refresh on publish](#refresh-on-publish) • [Live updates](#live-updates) • [Preview drafts](#preview-drafts) • [Forms](#forms) • [Live data](#live-data) • [Without Next.js: the HTTP API](#without-nextjs-the-http-api) • [API](#api)
|
|
10
10
|
|
|
11
11
|
## Install
|
|
12
12
|
|
|
@@ -153,6 +153,8 @@ export const POST = createRevalidateHandler({
|
|
|
153
153
|
|
|
154
154
|
Deploy, then in Mapled → **Integrations** → **Your site** save `https://your-site.com/api/mapled/revalidate` as the **Revalidation webhook**, copy the **Signing secret** into `MAPLED_WEBHOOK_SECRET` (hosting env and `.env.local`), redeploy, and press **Send test ping**: the delivery shows up under **Recent deliveries** as Delivered. The URL has to be public — Mapled refuses addresses that resolve to a private network.
|
|
155
155
|
|
|
156
|
+
Optional: pages that are already open can follow a publish too, without a reload — a route and one component, see [Live updates](#live-updates).
|
|
157
|
+
|
|
156
158
|
### 7. Preview drafts
|
|
157
159
|
|
|
158
160
|
```ts
|
|
@@ -315,6 +317,64 @@ Then in Mapled (**Integrations** → **Your site**) set the revalidation webhook
|
|
|
315
317
|
|
|
316
318
|
Each ping is tried up to three times (after 2 and 6 seconds, 5 seconds to answer); **Recent deliveries** keeps them for 30 days, and a failed one can be sent again from there. **Rotate secret** replaces the signing secret at once — deliveries fail until the site has the new one.
|
|
317
319
|
|
|
320
|
+
## Live updates
|
|
321
|
+
|
|
322
|
+
The webhook refreshes the site's cache; a page someone already has open still shows what it rendered. Two files make open tabs follow Publish as well. A route that says which release the site serves:
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
// app/api/mapled/release/route.ts
|
|
326
|
+
import { createReleaseHandler } from "@mapled/next/server";
|
|
327
|
+
|
|
328
|
+
export const GET = createReleaseHandler({ key: process.env.MAPLED_KEY! });
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
and one component in the root layout:
|
|
332
|
+
|
|
333
|
+
```tsx
|
|
334
|
+
// app/layout.tsx
|
|
335
|
+
import type { ReactNode } from "react";
|
|
336
|
+
import { MapledLive } from "@mapled/next/live";
|
|
337
|
+
|
|
338
|
+
export default function RootLayout({ children }: { children: ReactNode }) {
|
|
339
|
+
return (
|
|
340
|
+
<html lang="en">
|
|
341
|
+
<body>
|
|
342
|
+
{children}
|
|
343
|
+
<MapledLive />
|
|
344
|
+
</body>
|
|
345
|
+
</html>
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
`<MapledLive />` renders nothing. While the tab is visible it asks the route every 10 seconds (`interval`, in seconds), and when a publish lands it calls `router.refresh()`: Server Components re-render with the new release in place — scroll position and client state stay. A hidden tab doesn't ask; it checks the moment it is shown again. To offer the update instead of applying it under the reader, pass `onPublish`:
|
|
351
|
+
|
|
352
|
+
```tsx
|
|
353
|
+
"use client";
|
|
354
|
+
|
|
355
|
+
import { useRouter } from "next/navigation";
|
|
356
|
+
import { useState } from "react";
|
|
357
|
+
import { MapledLive } from "@mapled/next/live";
|
|
358
|
+
|
|
359
|
+
export function UpdateNotice() {
|
|
360
|
+
const router = useRouter();
|
|
361
|
+
const [fresh, setFresh] = useState(false);
|
|
362
|
+
return (
|
|
363
|
+
<>
|
|
364
|
+
<MapledLive onPublish={() => setFresh(true)} />
|
|
365
|
+
{fresh ? <button onClick={() => { router.refresh(); setFresh(false); }}>New content — refresh</button> : null}
|
|
366
|
+
</>
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
- It is polling, and it is cheap: tabs ask **your** route, never Mapled. The route reuses one answer for `ttl` seconds (default 5) — in the instance and, through `s-maxage`, at the CDN in front of it — and a check that finds nothing new is a 304. However many tabs are open, Mapled hears from the site a few times a minute, and the key's rate limit is left for reads.
|
|
372
|
+
- The route reads the release under the same `mapled` cache tag as the content, so it moves when the webhook refreshes the cache and not before — a tab that refreshes on it never renders the old release again. Live updates therefore need the webhook from [Refresh on publish](#refresh-on-publish); without it both change only when their ISR window (`revalidate`, 3600 by default) runs out.
|
|
373
|
+
- The route answers `{ release, publishedAt }` — the number of publishes and the time of the last one, nothing else — and may be cached by anyone. While Mapled can't be reached it keeps answering the last release it knew.
|
|
374
|
+
- Expect a publish to reach an open tab in about ten seconds with the defaults. `<MapledLive interval={3} />` and `createReleaseHandler({ key, ttl: 1 })` make it quicker at the price of more requests to your site.
|
|
375
|
+
|
|
376
|
+
Outside React, `watchRelease({ onPublish })` from `@mapled/next` is the same watch as a plain function — it returns the function that stops it.
|
|
377
|
+
|
|
318
378
|
## Preview drafts
|
|
319
379
|
|
|
320
380
|
Mount the preview routes:
|
|
@@ -432,7 +492,7 @@ curl -H "x-mapled-key: $MAPLED_KEY" \
|
|
|
432
492
|
|
|
433
493
|
- Lists take `filter[field]=value` or `filter[field][op]=value` (`eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in` — comma-separated, `contains`), `sort=field` / `sort=-field`, `limit` (1–100, default 100) and `offset`. Every read takes `expand` (relation keys, dotted for a second level), `fields` and `release=N` to read a published release by its number. A query the schema can't answer is a 400 `INVALID_QUERY` that says why.
|
|
434
494
|
- Only published content of collections with access **Public** is served; sensitive fields are never in an answer. Image and file values are asset ids — `https://api.mapled.io/files/{id}` is the file, with `?w=`, `h=`, `fit=`, `fmt=`, `q=` for a resized variant.
|
|
435
|
-
- Answers are per key — `Cache-Control: private` — with an `ETag`: send it back as `If-None-Match` and an unchanged answer is a 304. A read pinned with `release=N` never changes and may be cached for good. `GET /v1/delivery/release` is the cheap way to learn that something was published.
|
|
495
|
+
- Answers are per key — `Cache-Control: private` — with an `ETag`: send it back as `If-None-Match` and an unchanged answer is a 304. A read pinned with `release=N` never changes and may be cached for good. `GET /v1/delivery/release` is the cheap way to learn that something was published: relay it from a route of your own server, and `watchRelease({ endpoint, onPublish })` from `@mapled/next` — no framework in it — tells open tabs ([Live updates](#live-updates)).
|
|
436
496
|
- Errors share one envelope: `{ error: { code, message, requestId } }`. A key gets 1,200 requests a minute; past that, 429 `RATE_LIMITED` with `retry-after`.
|
|
437
497
|
- The publish webhook is a `POST` with a JSON body `{ event, project, release, at, id }` and the headers `x-mapled-event` (`release.published`, `project.restored` or `test`), `x-mapled-event-id` (the same on every retry — use it to deduplicate), `x-mapled-attempt` and `x-mapled-signature`: `sha256=` followed by the hex HMAC-SHA256 of the raw body with the signing secret. Compare in constant time, answer 2xx within 5 seconds. `verifySignature` from `@mapled/next/server` does the check anywhere Web Crypto exists.
|
|
438
498
|
- Live data: `GET` / `POST /v1/app/collections/{collection}/records` and `GET` / `PATCH` / `DELETE /v1/app/collections/{collection}/records/{id}` with the server key in `x-mapled-server-key`; writes send `{ "data": { … } }`.
|
|
@@ -448,6 +508,7 @@ Preview (drafts on the site) is built on Next.js draft mode and ships with this
|
|
|
448
508
|
- `assetUrl(id, { width?, height?, fit?, format?, quality?, apiUrl? })` — URL of an image or file value
|
|
449
509
|
- `createRevalidateHandler({ secret, tags? })` — App Router `POST` handler
|
|
450
510
|
- `createPreviewHandler({ apiUrl?, appUrl? })`, `createExitPreviewHandler()` — App Router `GET` handlers of the preview routes
|
|
511
|
+
- `createReleaseHandler({ key, apiUrl?, ttl?, revalidate? })` — App Router `GET` handler of the release route; `<MapledLive endpoint? interval? onPublish? />` from `@mapled/next/live` and `watchRelease({ endpoint?, interval?, onPublish })` ask it
|
|
451
512
|
- `verifySignature(secret, body, signature)` — if you'd rather build your own handler
|
|
452
513
|
|
|
453
514
|
The delivery key only reads published, public content — safe to use anywhere.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Mapled delivery client for Next.js sites.
|
|
2
2
|
Reads published content only — pair it with the revalidation webhook
|
|
3
3
|
handler from "@mapled/next/server" for instant updates on publish. */
|
|
4
|
+
export { watchRelease, type Release, type WatchOptions } from "./watch.js";
|
|
4
5
|
export type MapledRecord<T = Record<string, unknown>> = {
|
|
5
6
|
id: string;
|
|
6
7
|
data: T;
|
|
@@ -158,4 +159,3 @@ export declare function createAppClient<S extends ContentSchema = ContentSchema>
|
|
|
158
159
|
serverKey: string;
|
|
159
160
|
apiUrl?: string;
|
|
160
161
|
}): MapledAppClient<S>;
|
|
161
|
-
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Mapled delivery client for Next.js sites.
|
|
2
2
|
Reads published content only — pair it with the revalidation webhook
|
|
3
3
|
handler from "@mapled/next/server" for instant updates on publish. */
|
|
4
|
+
export { watchRelease } from "./watch.js";
|
|
4
5
|
/** Renamed fields (previous keys): Mapled keeps serving a renamed field
|
|
5
6
|
under its old key — and accepting it in filters, sorts and writes —
|
|
6
7
|
until the alias is removed in Field settings, and names such keys in
|
package/dist/live.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type Release } from "./watch.js";
|
|
2
|
+
export type { Release } from "./watch.js";
|
|
3
|
+
export type MapledLiveProps = {
|
|
4
|
+
/** Where the release route is mounted (default "/api/mapled/release"). */
|
|
5
|
+
endpoint?: string;
|
|
6
|
+
/** Seconds between checks while the tab is visible (default 10, at least 2). */
|
|
7
|
+
interval?: number;
|
|
8
|
+
/** Runs instead of the refresh — to offer "New content — refresh"
|
|
9
|
+
rather than change the page under the reader. */
|
|
10
|
+
onPublish?: (next: Release, previous: number | null) => void;
|
|
11
|
+
};
|
|
12
|
+
export declare function MapledLive({ endpoint, interval, onPublish }: MapledLiveProps): null;
|
package/dist/live.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
/** Open tabs follow Publish. Render it once, in the root layout:
|
|
3
|
+
|
|
4
|
+
app/layout.tsx:
|
|
5
|
+
import { MapledLive } from "@mapled/next/live";
|
|
6
|
+
<body>{children}<MapledLive /></body>
|
|
7
|
+
|
|
8
|
+
It asks the release route (`createReleaseHandler` from
|
|
9
|
+
"@mapled/next/server", mounted at /api/mapled/release) every few
|
|
10
|
+
seconds and, when a publish lands, refreshes the page's server
|
|
11
|
+
components in place — scroll position and client state stay. */
|
|
12
|
+
import { useRouter } from "next/navigation";
|
|
13
|
+
import { useEffect, useRef } from "react";
|
|
14
|
+
import { watchRelease } from "./watch.js";
|
|
15
|
+
export function MapledLive({ endpoint, interval, onPublish }) {
|
|
16
|
+
const router = useRouter();
|
|
17
|
+
const custom = useRef(onPublish);
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
custom.current = onPublish;
|
|
20
|
+
}, [onPublish]);
|
|
21
|
+
useEffect(() => watchRelease({
|
|
22
|
+
endpoint,
|
|
23
|
+
interval,
|
|
24
|
+
onPublish: (next, previous) => {
|
|
25
|
+
if (custom.current)
|
|
26
|
+
custom.current(next, previous);
|
|
27
|
+
else
|
|
28
|
+
router.refresh();
|
|
29
|
+
},
|
|
30
|
+
}), [endpoint, interval, router]);
|
|
31
|
+
return null;
|
|
32
|
+
}
|
package/dist/server.d.ts
CHANGED
|
@@ -25,3 +25,19 @@ export declare function createRevalidateHandler(options: {
|
|
|
25
25
|
client fetch. */
|
|
26
26
|
tags?: string[];
|
|
27
27
|
}): (req: Request) => Promise<Response>;
|
|
28
|
+
/** GET handler for the release route (mount at /api/mapled/release):
|
|
29
|
+
the release this site serves right now, for `<MapledLive />` from
|
|
30
|
+
"@mapled/next/live" to ask about. The pointer is read under the
|
|
31
|
+
"mapled" tag like the content is, so it moves when the publish webhook
|
|
32
|
+
refreshes the cache and not before — a tab that refreshes on it
|
|
33
|
+
renders the new release, never the old one again. One answer is reused
|
|
34
|
+
for `ttl` seconds, in this instance and at the CDN in front of it:
|
|
35
|
+
however many tabs ask, Mapled hears from the site a few times a minute. */
|
|
36
|
+
export declare function createReleaseHandler(options: {
|
|
37
|
+
key: string;
|
|
38
|
+
apiUrl?: string;
|
|
39
|
+
/** Seconds one answer is reused (default 5, at least 1). */
|
|
40
|
+
ttl?: number;
|
|
41
|
+
/** ISR window of the pointer, the same as a read's (default 3600 — the webhook keeps it fresh). */
|
|
42
|
+
revalidate?: number | false;
|
|
43
|
+
}): (req: Request) => Promise<Response>;
|
package/dist/server.js
CHANGED
|
@@ -99,3 +99,72 @@ export function createRevalidateHandler(options) {
|
|
|
99
99
|
return Response.json({ revalidated: true });
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
|
+
/** GET handler for the release route (mount at /api/mapled/release):
|
|
103
|
+
the release this site serves right now, for `<MapledLive />` from
|
|
104
|
+
"@mapled/next/live" to ask about. The pointer is read under the
|
|
105
|
+
"mapled" tag like the content is, so it moves when the publish webhook
|
|
106
|
+
refreshes the cache and not before — a tab that refreshes on it
|
|
107
|
+
renders the new release, never the old one again. One answer is reused
|
|
108
|
+
for `ttl` seconds, in this instance and at the CDN in front of it:
|
|
109
|
+
however many tabs ask, Mapled hears from the site a few times a minute. */
|
|
110
|
+
export function createReleaseHandler(options) {
|
|
111
|
+
if (!options.key)
|
|
112
|
+
throw new Error("Mapled: a delivery key is required.");
|
|
113
|
+
const base = (options.apiUrl ?? "https://api.mapled.io").replace(/\/+$/, "");
|
|
114
|
+
const ttlMs = Math.max(1, options.ttl ?? 5) * 1000;
|
|
115
|
+
let held = null;
|
|
116
|
+
/** when Mapled was last asked — an answer or a failure, either waits a ttl */
|
|
117
|
+
let askedAt = 0;
|
|
118
|
+
let loading = null;
|
|
119
|
+
let complained = false;
|
|
120
|
+
async function load() {
|
|
121
|
+
try {
|
|
122
|
+
const init = {
|
|
123
|
+
headers: { "x-mapled-key": options.key },
|
|
124
|
+
next: { revalidate: options.revalidate ?? 3600, tags: ["mapled"] },
|
|
125
|
+
};
|
|
126
|
+
const res = await fetch(`${base}/v1/delivery/release`, init);
|
|
127
|
+
if (!res.ok)
|
|
128
|
+
throw new Error(`Mapled answered ${res.status}`);
|
|
129
|
+
const body = (await res.json());
|
|
130
|
+
const release = body?.release ?? null;
|
|
131
|
+
const publishedAt = body?.publishedAt ?? null;
|
|
132
|
+
const published = Number.isInteger(release) && release >= 1 && typeof publishedAt === "string";
|
|
133
|
+
if (!published && release !== null)
|
|
134
|
+
throw new Error("Mapled's answer wasn't a release");
|
|
135
|
+
held = published ? { release, publishedAt } : { release: null, publishedAt: null };
|
|
136
|
+
complained = false;
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
// the last answer stays good while Mapled can't be reached
|
|
140
|
+
if (!complained) {
|
|
141
|
+
complained = true;
|
|
142
|
+
console.error(`[mapled] The release route can't read the live release: ${err instanceof Error ? err.message : "request failed"}.`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
askedAt = Date.now();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return async function GET(req) {
|
|
150
|
+
// read first: a handler that looks at its request is never prerendered
|
|
151
|
+
const asked = req.headers.get("if-none-match");
|
|
152
|
+
if (Date.now() - askedAt >= ttlMs) {
|
|
153
|
+
loading ??= load().finally(() => {
|
|
154
|
+
loading = null;
|
|
155
|
+
});
|
|
156
|
+
await loading;
|
|
157
|
+
}
|
|
158
|
+
if (!held) {
|
|
159
|
+
return Response.json({ error: "The live release isn't available right now." }, { status: 502, headers: { "cache-control": "no-store" } });
|
|
160
|
+
}
|
|
161
|
+
// the CDN's copy lives no longer than this instance's
|
|
162
|
+
const left = Math.max(1, Math.ceil((ttlMs - (Date.now() - askedAt)) / 1000));
|
|
163
|
+
const etag = `W/"r${held.release ?? 0}"`;
|
|
164
|
+
const headers = { "cache-control": `public, max-age=0, s-maxage=${left}`, etag };
|
|
165
|
+
if (asked && asked.split(",").some((t) => t.trim().replace(/^W\//, "") === etag.slice(2))) {
|
|
166
|
+
return new Response(null, { status: 304, headers });
|
|
167
|
+
}
|
|
168
|
+
return Response.json(held, { headers });
|
|
169
|
+
};
|
|
170
|
+
}
|
package/dist/watch.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Publish notifications for open tabs: the page asks its own server
|
|
2
|
+
which release is live (the route `createReleaseHandler` from
|
|
3
|
+
"@mapled/next/server" serves) and hears about it when that moves.
|
|
4
|
+
Framework-free on purpose — `<MapledLive />` from "@mapled/next/live"
|
|
5
|
+
is this plus `router.refresh()`. */
|
|
6
|
+
export type Release = {
|
|
7
|
+
release: number;
|
|
8
|
+
publishedAt: string;
|
|
9
|
+
};
|
|
10
|
+
export type WatchOptions = {
|
|
11
|
+
/** Where the release route is mounted (default "/api/mapled/release"). */
|
|
12
|
+
endpoint?: string;
|
|
13
|
+
/** Seconds between checks while the tab is visible (default 10, at least 2). */
|
|
14
|
+
interval?: number;
|
|
15
|
+
/** A publish landed: `next` is live now; `previous` is the release the
|
|
16
|
+
watch knew before — null when nothing was published yet. */
|
|
17
|
+
onPublish: (next: Release, previous: number | null) => void;
|
|
18
|
+
};
|
|
19
|
+
/** Starts watching; returns the function that stops it. The first answer
|
|
20
|
+
is where the watch starts from; `onPublish` runs once per release that
|
|
21
|
+
comes after it. A hidden tab doesn't ask — it checks the moment it is
|
|
22
|
+
shown again — and a route that fails is asked less and less often. */
|
|
23
|
+
export declare function watchRelease(options: WatchOptions): () => void;
|
package/dist/watch.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** Publish notifications for open tabs: the page asks its own server
|
|
2
|
+
which release is live (the route `createReleaseHandler` from
|
|
3
|
+
"@mapled/next/server" serves) and hears about it when that moves.
|
|
4
|
+
Framework-free on purpose — `<MapledLive />` from "@mapled/next/live"
|
|
5
|
+
is this plus `router.refresh()`. */
|
|
6
|
+
const DEFAULT_ENDPOINT = "/api/mapled/release";
|
|
7
|
+
const MAX_BACKOFF_MS = 5 * 60_000;
|
|
8
|
+
/** The route's answer — null before the first publish — or undefined
|
|
9
|
+
when it isn't one. */
|
|
10
|
+
function pointer(body) {
|
|
11
|
+
if (!body || typeof body !== "object")
|
|
12
|
+
return undefined;
|
|
13
|
+
const { release, publishedAt } = body;
|
|
14
|
+
if (release === null)
|
|
15
|
+
return null;
|
|
16
|
+
if (!Number.isInteger(release) || release < 1 || typeof publishedAt !== "string")
|
|
17
|
+
return undefined;
|
|
18
|
+
return { release: release, publishedAt };
|
|
19
|
+
}
|
|
20
|
+
/** Starts watching; returns the function that stops it. The first answer
|
|
21
|
+
is where the watch starts from; `onPublish` runs once per release that
|
|
22
|
+
comes after it. A hidden tab doesn't ask — it checks the moment it is
|
|
23
|
+
shown again — and a route that fails is asked less and less often. */
|
|
24
|
+
export function watchRelease(options) {
|
|
25
|
+
const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;
|
|
26
|
+
const everyMs = Math.max(2, options.interval ?? 10) * 1000;
|
|
27
|
+
const doc = typeof document === "undefined" ? null : document;
|
|
28
|
+
/** undefined until the first answer; null while nothing is published */
|
|
29
|
+
let seen;
|
|
30
|
+
let failures = 0;
|
|
31
|
+
let stopped = false;
|
|
32
|
+
let timer;
|
|
33
|
+
let inFlight = null;
|
|
34
|
+
const visible = () => !doc || doc.visibilityState !== "hidden";
|
|
35
|
+
const schedule = () => {
|
|
36
|
+
if (stopped || !visible())
|
|
37
|
+
return;
|
|
38
|
+
timer = setTimeout(check, Math.min(everyMs * 2 ** failures, MAX_BACKOFF_MS));
|
|
39
|
+
};
|
|
40
|
+
async function check() {
|
|
41
|
+
if (stopped || inFlight)
|
|
42
|
+
return;
|
|
43
|
+
const request = new AbortController();
|
|
44
|
+
inFlight = request;
|
|
45
|
+
let news = null;
|
|
46
|
+
try {
|
|
47
|
+
// no-cache: the browser revalidates by ETag, so a quiet check is a 304
|
|
48
|
+
const res = await fetch(endpoint, { cache: "no-cache", headers: { accept: "application/json" }, signal: request.signal });
|
|
49
|
+
const now = res.ok ? pointer(await res.json()) : undefined;
|
|
50
|
+
if (stopped)
|
|
51
|
+
return;
|
|
52
|
+
if (now === undefined) {
|
|
53
|
+
failures += 1;
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
failures = 0;
|
|
57
|
+
if (seen === undefined) {
|
|
58
|
+
seen = now ? now.release : null;
|
|
59
|
+
}
|
|
60
|
+
else if (now && now.release > (seen ?? 0)) {
|
|
61
|
+
// releases only grow (a rollback is a new one): an answer from a
|
|
62
|
+
// server that hasn't caught up yet never looks like news
|
|
63
|
+
news = { next: now, previous: seen };
|
|
64
|
+
seen = now.release;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
if (stopped)
|
|
70
|
+
return;
|
|
71
|
+
failures += 1;
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
if (inFlight === request)
|
|
75
|
+
inFlight = null;
|
|
76
|
+
}
|
|
77
|
+
schedule();
|
|
78
|
+
// after the next check is set: a callback that throws doesn't end the watch
|
|
79
|
+
if (news)
|
|
80
|
+
options.onPublish(news.next, news.previous);
|
|
81
|
+
}
|
|
82
|
+
const onVisibility = () => {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
if (visible())
|
|
85
|
+
void check();
|
|
86
|
+
};
|
|
87
|
+
doc?.addEventListener("visibilitychange", onVisibility);
|
|
88
|
+
if (visible())
|
|
89
|
+
void check();
|
|
90
|
+
return () => {
|
|
91
|
+
stopped = true;
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
inFlight?.abort();
|
|
94
|
+
doc?.removeEventListener("visibilitychange", onVisibility);
|
|
95
|
+
};
|
|
96
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mapled/next",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Read published Mapled content in a Next.js site \u2014 delivery client, ISR tags, and a revalidation webhook handler.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://mapled.io",
|
|
@@ -27,6 +27,10 @@
|
|
|
27
27
|
"./server": {
|
|
28
28
|
"types": "./dist/server.d.ts",
|
|
29
29
|
"default": "./dist/server.js"
|
|
30
|
+
},
|
|
31
|
+
"./live": {
|
|
32
|
+
"types": "./dist/live.d.ts",
|
|
33
|
+
"default": "./dist/live.js"
|
|
30
34
|
}
|
|
31
35
|
},
|
|
32
36
|
"files": [
|