@usethrottle/builder 0.7.0 → 0.7.2
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 +3 -1
- package/dist/{chunk-KNA3T4M6.cjs → chunk-DZMWUQSG.cjs} +40 -10
- package/dist/{chunk-3PRNCLZO.js → chunk-M6GBKCCG.js} +39 -9
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +27 -5
- package/dist/index.d.ts +27 -5
- package/dist/index.js +1 -1
- package/dist/next.cjs +25 -10
- package/dist/next.d.cts +8 -1
- package/dist/next.d.ts +8 -1
- package/dist/next.js +16 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -12,7 +12,9 @@ const { site, header, footer, slots } = await builder.bundle({ page: 'about', sl
|
|
|
12
12
|
```
|
|
13
13
|
|
|
14
14
|
Errors: `BuilderUnavailableError` (timeout after 3 s, network, 5xx), `BuilderNotFoundError`
|
|
15
|
-
(an unpublished page)
|
|
15
|
+
(an unpublished page). A preview token the Builder refuses (401: expired, invalid, forged) is
|
|
16
|
+
answered by the published site, and `onPreviewExpired` fires once (clear the cookie with
|
|
17
|
+
`clearPreviewCookie()` from `/next` in a route handler or server action). A read that fails within 10 minutes of a
|
|
16
18
|
good one answers the good one (per process) and logs once.
|
|
17
19
|
|
|
18
20
|
## Caching (Next.js)
|
|
@@ -110,6 +110,21 @@ function currentDocument(answer, where) {
|
|
|
110
110
|
return upgraded.doc;
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
+
// src/media.ts
|
|
114
|
+
var MEDIA_HEADER = "x-builder-media";
|
|
115
|
+
function mediaHeaders(mediaBase) {
|
|
116
|
+
return mediaBase === void 0 ? {} : { [MEDIA_HEADER]: "direct" };
|
|
117
|
+
}
|
|
118
|
+
function mediaBaseOf(base, media) {
|
|
119
|
+
if (media === "proxy") return void 0;
|
|
120
|
+
try {
|
|
121
|
+
const url = new URL(base);
|
|
122
|
+
return url.protocol === "https:" ? url.origin : void 0;
|
|
123
|
+
} catch (e) {
|
|
124
|
+
return void 0;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
113
128
|
// src/release.ts
|
|
114
129
|
var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
|
|
115
130
|
var DEFAULT_BUNDLE_TIMEOUT_MS = 6e4;
|
|
@@ -163,8 +178,8 @@ function readBundle(body) {
|
|
|
163
178
|
} : {}
|
|
164
179
|
};
|
|
165
180
|
}
|
|
166
|
-
async function fetchBundle({ base, key, ref, timeoutMs, doFetch }) {
|
|
167
|
-
const headers = { accept: "application/json", [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN };
|
|
181
|
+
async function fetchBundle({ base, key, ref, timeoutMs, doFetch, media }) {
|
|
182
|
+
const headers = { accept: "application/json", [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN, ...mediaHeaders(mediaBaseOf(base, media)) };
|
|
168
183
|
if (key.startsWith("tb_sk_")) headers.authorization = `Bearer ${key}`;
|
|
169
184
|
else headers["X-Builder-Key"] = key;
|
|
170
185
|
const controller = new AbortController();
|
|
@@ -219,7 +234,7 @@ var stored = () => {
|
|
|
219
234
|
};
|
|
220
235
|
function loadOnce(load) {
|
|
221
236
|
const memo = stored();
|
|
222
|
-
const id = `${load.base}|${load.key}|${load.ref}`;
|
|
237
|
+
const id = `${load.base}|${load.key}|${load.ref}|${_nullishCoalesce(load.media, () => ( "direct"))}`;
|
|
223
238
|
let held = memo.get(id);
|
|
224
239
|
if (held === void 0) {
|
|
225
240
|
held = fetchBundle(load);
|
|
@@ -309,10 +324,11 @@ function createBuildClient(options) {
|
|
|
309
324
|
const clock = _nullishCoalesce(options.now, () => ( Date.now));
|
|
310
325
|
const getReleaseBundle = async ({ release } = {}) => {
|
|
311
326
|
if (options.releaseBundle !== void 0) return options.releaseBundle;
|
|
312
|
-
return loadOnce({ base, key: builderKey, ref: releaseRef(release, options.release), timeoutMs, doFetch: options.fetch });
|
|
327
|
+
return loadOnce({ base, key: builderKey, ref: releaseRef(release, options.release), timeoutMs, doFetch: options.fetch, media: options.media });
|
|
313
328
|
};
|
|
314
329
|
return {
|
|
315
330
|
mode: "build",
|
|
331
|
+
mediaBase: mediaBaseOf(base, options.media),
|
|
316
332
|
getReleaseBundle,
|
|
317
333
|
site: async ({ locale } = {}) => siteFor(await getReleaseBundle(), locale, clock()),
|
|
318
334
|
pages: {
|
|
@@ -526,12 +542,13 @@ function createBuilderClient(options) {
|
|
|
526
542
|
}
|
|
527
543
|
function createLiveClient(options) {
|
|
528
544
|
const { builderKey, previewToken } = options;
|
|
545
|
+
const opts = options;
|
|
529
546
|
if (typeof builderKey !== "string" || builderKey === "")
|
|
530
547
|
throw new TypeError("createBuilderClient needs a builderKey");
|
|
531
548
|
if (builderKey.startsWith("tb_sk_"))
|
|
532
549
|
throw new TypeError("createBuilderClient takes the publishable Builder key (tb_pk_\u2026), never a secret key");
|
|
533
550
|
const previewHeader = previewToken !== void 0 && previewToken !== "" ? previewToken : void 0;
|
|
534
|
-
|
|
551
|
+
let tokenExpired = false;
|
|
535
552
|
const base = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL2))).replace(/\/+$/u, "");
|
|
536
553
|
const timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( DEFAULT_TIMEOUT_MS));
|
|
537
554
|
const doFetch = options.fetch;
|
|
@@ -561,13 +578,14 @@ function createLiveClient(options) {
|
|
|
561
578
|
clearTimeout(timer);
|
|
562
579
|
}
|
|
563
580
|
}
|
|
564
|
-
async function fetchAnswer(path, read2) {
|
|
581
|
+
async function fetchAnswer(path, read2, preview) {
|
|
565
582
|
const headers = {
|
|
566
583
|
accept: "application/json",
|
|
567
584
|
"X-Builder-Key": builderKey,
|
|
568
|
-
[SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN
|
|
585
|
+
[SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN,
|
|
586
|
+
...mediaHeaders(mediaBaseOf(base, options.media))
|
|
569
587
|
};
|
|
570
|
-
if (previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
|
|
588
|
+
if (preview && previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
|
|
571
589
|
const url = `${base}${path}${queryString(_nullishCoalesce(read2.query, () => ( {})))}`;
|
|
572
590
|
const init = { method: "GET", headers, ...cacheInit(fitTags(read2.tags), preview) };
|
|
573
591
|
const { body, status } = await once(url, init);
|
|
@@ -583,11 +601,22 @@ function createLiveClient(options) {
|
|
|
583
601
|
}
|
|
584
602
|
async function read(path, options2, shape) {
|
|
585
603
|
const goodKey = `${base}|${builderKey}|${path}${queryString(_nullishCoalesce(options2.query, () => ( {})))}`;
|
|
604
|
+
const preview = previewHeader !== void 0 && !tokenExpired;
|
|
586
605
|
try {
|
|
587
|
-
const value = shape(await fetchAnswer(path, options2));
|
|
606
|
+
const value = shape(await fetchAnswer(path, options2, preview));
|
|
588
607
|
if (!preview) rememberGood(goodKey, value);
|
|
589
608
|
return value;
|
|
590
609
|
} catch (error) {
|
|
610
|
+
if (error instanceof PreviewExpiredError) {
|
|
611
|
+
if (!tokenExpired) {
|
|
612
|
+
tokenExpired = true;
|
|
613
|
+
try {
|
|
614
|
+
_optionalChain([opts, 'access', _11 => _11.onPreviewExpired, 'optionalCall', _12 => _12()]);
|
|
615
|
+
} catch (e2) {
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return read(path, options2, shape);
|
|
619
|
+
}
|
|
591
620
|
if (preview || !(error instanceof BuilderUnavailableError)) throw error;
|
|
592
621
|
const good = recallGood(goodKey, () => {
|
|
593
622
|
console.warn(
|
|
@@ -599,6 +628,7 @@ function createLiveClient(options) {
|
|
|
599
628
|
}
|
|
600
629
|
}
|
|
601
630
|
return {
|
|
631
|
+
mediaBase: mediaBaseOf(base, options.media),
|
|
602
632
|
site: ({ locale } = {}) => read("/v1/site", { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.site] }, readSite),
|
|
603
633
|
pages: {
|
|
604
634
|
list: () => read(
|
|
@@ -728,7 +758,7 @@ async function verifyBuilderNotice(input) {
|
|
|
728
758
|
let matched = false;
|
|
729
759
|
for (const digest of digests) matched = constantTimeEqual(expected, fromHex(digest)) || matched;
|
|
730
760
|
return matched;
|
|
731
|
-
} catch (
|
|
761
|
+
} catch (e3) {
|
|
732
762
|
return false;
|
|
733
763
|
}
|
|
734
764
|
}
|
|
@@ -110,6 +110,21 @@ function currentDocument(answer, where) {
|
|
|
110
110
|
return upgraded.doc;
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
+
// src/media.ts
|
|
114
|
+
var MEDIA_HEADER = "x-builder-media";
|
|
115
|
+
function mediaHeaders(mediaBase) {
|
|
116
|
+
return mediaBase === void 0 ? {} : { [MEDIA_HEADER]: "direct" };
|
|
117
|
+
}
|
|
118
|
+
function mediaBaseOf(base, media) {
|
|
119
|
+
if (media === "proxy") return void 0;
|
|
120
|
+
try {
|
|
121
|
+
const url = new URL(base);
|
|
122
|
+
return url.protocol === "https:" ? url.origin : void 0;
|
|
123
|
+
} catch {
|
|
124
|
+
return void 0;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
113
128
|
// src/release.ts
|
|
114
129
|
var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
|
|
115
130
|
var DEFAULT_BUNDLE_TIMEOUT_MS = 6e4;
|
|
@@ -163,8 +178,8 @@ function readBundle(body) {
|
|
|
163
178
|
} : {}
|
|
164
179
|
};
|
|
165
180
|
}
|
|
166
|
-
async function fetchBundle({ base, key, ref, timeoutMs, doFetch }) {
|
|
167
|
-
const headers = { accept: "application/json", [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN };
|
|
181
|
+
async function fetchBundle({ base, key, ref, timeoutMs, doFetch, media }) {
|
|
182
|
+
const headers = { accept: "application/json", [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN, ...mediaHeaders(mediaBaseOf(base, media)) };
|
|
168
183
|
if (key.startsWith("tb_sk_")) headers.authorization = `Bearer ${key}`;
|
|
169
184
|
else headers["X-Builder-Key"] = key;
|
|
170
185
|
const controller = new AbortController();
|
|
@@ -219,7 +234,7 @@ var stored = () => {
|
|
|
219
234
|
};
|
|
220
235
|
function loadOnce(load) {
|
|
221
236
|
const memo = stored();
|
|
222
|
-
const id = `${load.base}|${load.key}|${load.ref}`;
|
|
237
|
+
const id = `${load.base}|${load.key}|${load.ref}|${load.media ?? "direct"}`;
|
|
223
238
|
let held = memo.get(id);
|
|
224
239
|
if (held === void 0) {
|
|
225
240
|
held = fetchBundle(load);
|
|
@@ -309,10 +324,11 @@ function createBuildClient(options) {
|
|
|
309
324
|
const clock = options.now ?? Date.now;
|
|
310
325
|
const getReleaseBundle = async ({ release } = {}) => {
|
|
311
326
|
if (options.releaseBundle !== void 0) return options.releaseBundle;
|
|
312
|
-
return loadOnce({ base, key: builderKey, ref: releaseRef(release, options.release), timeoutMs, doFetch: options.fetch });
|
|
327
|
+
return loadOnce({ base, key: builderKey, ref: releaseRef(release, options.release), timeoutMs, doFetch: options.fetch, media: options.media });
|
|
313
328
|
};
|
|
314
329
|
return {
|
|
315
330
|
mode: "build",
|
|
331
|
+
mediaBase: mediaBaseOf(base, options.media),
|
|
316
332
|
getReleaseBundle,
|
|
317
333
|
site: async ({ locale } = {}) => siteFor(await getReleaseBundle(), locale, clock()),
|
|
318
334
|
pages: {
|
|
@@ -526,12 +542,13 @@ function createBuilderClient(options) {
|
|
|
526
542
|
}
|
|
527
543
|
function createLiveClient(options) {
|
|
528
544
|
const { builderKey, previewToken } = options;
|
|
545
|
+
const opts = options;
|
|
529
546
|
if (typeof builderKey !== "string" || builderKey === "")
|
|
530
547
|
throw new TypeError("createBuilderClient needs a builderKey");
|
|
531
548
|
if (builderKey.startsWith("tb_sk_"))
|
|
532
549
|
throw new TypeError("createBuilderClient takes the publishable Builder key (tb_pk_\u2026), never a secret key");
|
|
533
550
|
const previewHeader = previewToken !== void 0 && previewToken !== "" ? previewToken : void 0;
|
|
534
|
-
|
|
551
|
+
let tokenExpired = false;
|
|
535
552
|
const base = (options.baseUrl ?? DEFAULT_BASE_URL2).replace(/\/+$/u, "");
|
|
536
553
|
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
537
554
|
const doFetch = options.fetch;
|
|
@@ -561,13 +578,14 @@ function createLiveClient(options) {
|
|
|
561
578
|
clearTimeout(timer);
|
|
562
579
|
}
|
|
563
580
|
}
|
|
564
|
-
async function fetchAnswer(path, read2) {
|
|
581
|
+
async function fetchAnswer(path, read2, preview) {
|
|
565
582
|
const headers = {
|
|
566
583
|
accept: "application/json",
|
|
567
584
|
"X-Builder-Key": builderKey,
|
|
568
|
-
[SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN
|
|
585
|
+
[SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN,
|
|
586
|
+
...mediaHeaders(mediaBaseOf(base, options.media))
|
|
569
587
|
};
|
|
570
|
-
if (previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
|
|
588
|
+
if (preview && previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
|
|
571
589
|
const url = `${base}${path}${queryString(read2.query ?? {})}`;
|
|
572
590
|
const init = { method: "GET", headers, ...cacheInit(fitTags(read2.tags), preview) };
|
|
573
591
|
const { body, status } = await once(url, init);
|
|
@@ -583,11 +601,22 @@ function createLiveClient(options) {
|
|
|
583
601
|
}
|
|
584
602
|
async function read(path, options2, shape) {
|
|
585
603
|
const goodKey = `${base}|${builderKey}|${path}${queryString(options2.query ?? {})}`;
|
|
604
|
+
const preview = previewHeader !== void 0 && !tokenExpired;
|
|
586
605
|
try {
|
|
587
|
-
const value = shape(await fetchAnswer(path, options2));
|
|
606
|
+
const value = shape(await fetchAnswer(path, options2, preview));
|
|
588
607
|
if (!preview) rememberGood(goodKey, value);
|
|
589
608
|
return value;
|
|
590
609
|
} catch (error) {
|
|
610
|
+
if (error instanceof PreviewExpiredError) {
|
|
611
|
+
if (!tokenExpired) {
|
|
612
|
+
tokenExpired = true;
|
|
613
|
+
try {
|
|
614
|
+
opts.onPreviewExpired?.();
|
|
615
|
+
} catch {
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return read(path, options2, shape);
|
|
619
|
+
}
|
|
591
620
|
if (preview || !(error instanceof BuilderUnavailableError)) throw error;
|
|
592
621
|
const good = recallGood(goodKey, () => {
|
|
593
622
|
console.warn(
|
|
@@ -599,6 +628,7 @@ function createLiveClient(options) {
|
|
|
599
628
|
}
|
|
600
629
|
}
|
|
601
630
|
return {
|
|
631
|
+
mediaBase: mediaBaseOf(base, options.media),
|
|
602
632
|
site: ({ locale } = {}) => read("/v1/site", { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.site] }, readSite),
|
|
603
633
|
pages: {
|
|
604
634
|
list: () => read(
|
package/dist/index.cjs
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
var
|
|
17
|
+
var _chunkDZMWUQSGcjs = require('./chunk-DZMWUQSG.cjs');
|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
|
|
@@ -31,4 +31,4 @@ var _chunkKNA3T4M6cjs = require('./chunk-KNA3T4M6.cjs');
|
|
|
31
31
|
|
|
32
32
|
|
|
33
33
|
|
|
34
|
-
exports.BUILDER_SCHEMA_MIN =
|
|
34
|
+
exports.BUILDER_SCHEMA_MIN = _chunkDZMWUQSGcjs.BUILDER_SCHEMA_MIN; exports.BUILDER_TAGS = _chunkDZMWUQSGcjs.BUILDER_TAGS; exports.BuilderNotFoundError = _chunkDZMWUQSGcjs.BuilderNotFoundError; exports.BuilderReleaseNotFoundError = _chunkDZMWUQSGcjs.BuilderReleaseNotFoundError; exports.BuilderUnavailableError = _chunkDZMWUQSGcjs.BuilderUnavailableError; exports.BuilderValidationError = _chunkDZMWUQSGcjs.BuilderValidationError; exports.DEFAULT_BASE_URL = _chunkDZMWUQSGcjs.DEFAULT_BASE_URL; exports.DEFAULT_TIMEOUT_MS = _chunkDZMWUQSGcjs.DEFAULT_TIMEOUT_MS; exports.PreviewExpiredError = _chunkDZMWUQSGcjs.PreviewExpiredError; exports.SUPPORTED_BUNDLE_VERSION = _chunkDZMWUQSGcjs.SUPPORTED_BUNDLE_VERSION; exports.UNTIL_CHANGED_REVALIDATE_S = _chunkDZMWUQSGcjs.UNTIL_CHANGED_REVALIDATE_S; exports.createBuilderClient = _chunkDZMWUQSGcjs.createBuilderClient; exports.scopesToTags = _chunkDZMWUQSGcjs.scopesToTags; exports.templateTag = _chunkDZMWUQSGcjs.templateTag; exports.verifyBuilderNotice = _chunkDZMWUQSGcjs.verifyBuilderNotice;
|
package/dist/index.d.cts
CHANGED
|
@@ -32,9 +32,9 @@ declare class BuilderValidationError extends Error {
|
|
|
32
32
|
constructor(message: string, status?: number);
|
|
33
33
|
}
|
|
34
34
|
/**
|
|
35
|
-
* The preview token is expired or not valid (`401 PREVIEW_EXPIRED`).
|
|
36
|
-
*
|
|
37
|
-
*
|
|
35
|
+
* The preview token is expired or not valid (`401 PREVIEW_EXPIRED`). The live
|
|
36
|
+
* client catches it itself and reads the published site instead (see
|
|
37
|
+
* `onPreviewExpired`), so a store never sees it from `createBuilderClient`.
|
|
38
38
|
*/
|
|
39
39
|
declare class PreviewExpiredError extends Error {
|
|
40
40
|
constructor();
|
|
@@ -128,15 +128,30 @@ type BuilderClientOptions = {
|
|
|
128
128
|
/** Defaults to `https://builder.usethrottle.dev`. */
|
|
129
129
|
baseUrl?: string;
|
|
130
130
|
fetch?: typeof fetch;
|
|
131
|
+
/**
|
|
132
|
+
* `direct` (default) sends `X-Builder-Media: direct`, so images come as cacheable URLs on the Builder's own
|
|
133
|
+
* origin. `proxy` sends nothing and gets the API's redirecting asset URLs.
|
|
134
|
+
*/
|
|
135
|
+
media?: 'direct' | 'proxy';
|
|
131
136
|
/** Per read, body included. Default 3000. */
|
|
132
137
|
timeoutMs?: number;
|
|
133
138
|
/**
|
|
134
139
|
* A preview token (`getPreviewToken()` from `@usethrottle/builder/next`).
|
|
135
140
|
* Every read then sends `X-Builder-Preview`, reads drafts, is never cached
|
|
136
|
-
* and never answers from a last good.
|
|
137
|
-
* `
|
|
141
|
+
* and never answers from a last good. When the Builder refuses the token
|
|
142
|
+
* (expired, invalid or forged: `401`), the read is answered from the
|
|
143
|
+
* published site instead, every later read of this client is a published
|
|
144
|
+
* read, and `onPreviewExpired` is called once. A published outage still
|
|
145
|
+
* throws `BuilderUnavailableError`.
|
|
138
146
|
*/
|
|
139
147
|
previewToken?: string | undefined;
|
|
148
|
+
/**
|
|
149
|
+
* Called once, when the Builder refuses `previewToken`. Use it to clear the
|
|
150
|
+
* cookie where you control the response (`clearPreviewCookie()` from
|
|
151
|
+
* `@usethrottle/builder/next` in a route handler or server action). It must
|
|
152
|
+
* not throw; a throw is swallowed.
|
|
153
|
+
*/
|
|
154
|
+
onPreviewExpired?: (() => void) | undefined;
|
|
140
155
|
};
|
|
141
156
|
type LocaleOptions = {
|
|
142
157
|
locale?: string;
|
|
@@ -144,6 +159,11 @@ type LocaleOptions = {
|
|
|
144
159
|
type BuilderClient = {
|
|
145
160
|
/** `build` for a client made with `mode: 'build'`: it reads a frozen release and never the live API. */
|
|
146
161
|
readonly mode?: 'live' | 'build';
|
|
162
|
+
/**
|
|
163
|
+
* The origin direct media URLs are on (`https://builder.usethrottle.dev`), when this client asks for them.
|
|
164
|
+
* The renderer accepts images there, for `/v1/media/` paths only.
|
|
165
|
+
*/
|
|
166
|
+
readonly mediaBase?: string;
|
|
147
167
|
site(options?: LocaleOptions): Promise<BuilderSite>;
|
|
148
168
|
pages: {
|
|
149
169
|
list(): Promise<BuilderPageSummary[]>;
|
|
@@ -249,6 +269,8 @@ type BuildClientCommon = {
|
|
|
249
269
|
/** Defaults to `https://builder.usethrottle.dev`. */
|
|
250
270
|
baseUrl?: string;
|
|
251
271
|
fetch?: typeof fetch;
|
|
272
|
+
/** As for `createBuilderClient({ media })`: `direct` (default) asks for direct, cacheable media URLs. */
|
|
273
|
+
media?: 'direct' | 'proxy';
|
|
252
274
|
/** The bundle read, body included. Default 60000 (a bundle is the whole site). */
|
|
253
275
|
timeoutMs?: number;
|
|
254
276
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -32,9 +32,9 @@ declare class BuilderValidationError extends Error {
|
|
|
32
32
|
constructor(message: string, status?: number);
|
|
33
33
|
}
|
|
34
34
|
/**
|
|
35
|
-
* The preview token is expired or not valid (`401 PREVIEW_EXPIRED`).
|
|
36
|
-
*
|
|
37
|
-
*
|
|
35
|
+
* The preview token is expired or not valid (`401 PREVIEW_EXPIRED`). The live
|
|
36
|
+
* client catches it itself and reads the published site instead (see
|
|
37
|
+
* `onPreviewExpired`), so a store never sees it from `createBuilderClient`.
|
|
38
38
|
*/
|
|
39
39
|
declare class PreviewExpiredError extends Error {
|
|
40
40
|
constructor();
|
|
@@ -128,15 +128,30 @@ type BuilderClientOptions = {
|
|
|
128
128
|
/** Defaults to `https://builder.usethrottle.dev`. */
|
|
129
129
|
baseUrl?: string;
|
|
130
130
|
fetch?: typeof fetch;
|
|
131
|
+
/**
|
|
132
|
+
* `direct` (default) sends `X-Builder-Media: direct`, so images come as cacheable URLs on the Builder's own
|
|
133
|
+
* origin. `proxy` sends nothing and gets the API's redirecting asset URLs.
|
|
134
|
+
*/
|
|
135
|
+
media?: 'direct' | 'proxy';
|
|
131
136
|
/** Per read, body included. Default 3000. */
|
|
132
137
|
timeoutMs?: number;
|
|
133
138
|
/**
|
|
134
139
|
* A preview token (`getPreviewToken()` from `@usethrottle/builder/next`).
|
|
135
140
|
* Every read then sends `X-Builder-Preview`, reads drafts, is never cached
|
|
136
|
-
* and never answers from a last good.
|
|
137
|
-
* `
|
|
141
|
+
* and never answers from a last good. When the Builder refuses the token
|
|
142
|
+
* (expired, invalid or forged: `401`), the read is answered from the
|
|
143
|
+
* published site instead, every later read of this client is a published
|
|
144
|
+
* read, and `onPreviewExpired` is called once. A published outage still
|
|
145
|
+
* throws `BuilderUnavailableError`.
|
|
138
146
|
*/
|
|
139
147
|
previewToken?: string | undefined;
|
|
148
|
+
/**
|
|
149
|
+
* Called once, when the Builder refuses `previewToken`. Use it to clear the
|
|
150
|
+
* cookie where you control the response (`clearPreviewCookie()` from
|
|
151
|
+
* `@usethrottle/builder/next` in a route handler or server action). It must
|
|
152
|
+
* not throw; a throw is swallowed.
|
|
153
|
+
*/
|
|
154
|
+
onPreviewExpired?: (() => void) | undefined;
|
|
140
155
|
};
|
|
141
156
|
type LocaleOptions = {
|
|
142
157
|
locale?: string;
|
|
@@ -144,6 +159,11 @@ type LocaleOptions = {
|
|
|
144
159
|
type BuilderClient = {
|
|
145
160
|
/** `build` for a client made with `mode: 'build'`: it reads a frozen release and never the live API. */
|
|
146
161
|
readonly mode?: 'live' | 'build';
|
|
162
|
+
/**
|
|
163
|
+
* The origin direct media URLs are on (`https://builder.usethrottle.dev`), when this client asks for them.
|
|
164
|
+
* The renderer accepts images there, for `/v1/media/` paths only.
|
|
165
|
+
*/
|
|
166
|
+
readonly mediaBase?: string;
|
|
147
167
|
site(options?: LocaleOptions): Promise<BuilderSite>;
|
|
148
168
|
pages: {
|
|
149
169
|
list(): Promise<BuilderPageSummary[]>;
|
|
@@ -249,6 +269,8 @@ type BuildClientCommon = {
|
|
|
249
269
|
/** Defaults to `https://builder.usethrottle.dev`. */
|
|
250
270
|
baseUrl?: string;
|
|
251
271
|
fetch?: typeof fetch;
|
|
272
|
+
/** As for `createBuilderClient({ media })`: `direct` (default) asks for direct, cacheable media URLs. */
|
|
273
|
+
media?: 'direct' | 'proxy';
|
|
252
274
|
/** The bundle read, body included. Default 60000 (a bundle is the whole site). */
|
|
253
275
|
timeoutMs?: number;
|
|
254
276
|
/**
|
package/dist/index.js
CHANGED
package/dist/next.cjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var _chunkDZMWUQSGcjs = require('./chunk-DZMWUQSG.cjs');
|
|
10
10
|
|
|
11
11
|
// src/next/index.ts
|
|
12
12
|
require('server-only');
|
|
@@ -49,7 +49,7 @@ function parseNotice(rawBody) {
|
|
|
49
49
|
if (typeof value !== "object" || value === null) return null;
|
|
50
50
|
const { type, generation, scopes } = value;
|
|
51
51
|
if (type !== "builder.changed" || typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0 || !Array.isArray(scopes) || scopes.length === 0 || scopes.length > MAX_SCOPES || !scopes.every(
|
|
52
|
-
(scope) => typeof scope === "string" && scope.length > 0 && scope.length <=
|
|
52
|
+
(scope) => typeof scope === "string" && scope.length > 0 && scope.length <= _chunkDZMWUQSGcjs.TAG_MAX_CHARS
|
|
53
53
|
))
|
|
54
54
|
return null;
|
|
55
55
|
return { generation, scopes };
|
|
@@ -74,12 +74,12 @@ function createRevalidateHandler(options) {
|
|
|
74
74
|
const now = Math.floor(Date.now() / 1e3);
|
|
75
75
|
let verified = false;
|
|
76
76
|
for (const secret of secrets)
|
|
77
|
-
verified = await
|
|
77
|
+
verified = await _chunkDZMWUQSGcjs.verifyBuilderNotice.call(void 0, { rawBody, header, secret, now }) || verified;
|
|
78
78
|
if (!verified) return json(401, { error: "invalid signature" });
|
|
79
79
|
const notice = parseNotice(rawBody);
|
|
80
80
|
if (notice === null) return json(400, { error: "invalid body" });
|
|
81
|
-
const mapped =
|
|
82
|
-
const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [
|
|
81
|
+
const mapped = _chunkDZMWUQSGcjs.scopesToTags.call(void 0, notice.scopes);
|
|
82
|
+
const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [_chunkDZMWUQSGcjs.BUILDER_TAGS.all] : mapped;
|
|
83
83
|
const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag()));
|
|
84
84
|
for (const tag of tags) revalidate(tag);
|
|
85
85
|
return json(200, { revalidated: tags });
|
|
@@ -104,10 +104,10 @@ function createWatchSyncHandler(options) {
|
|
|
104
104
|
let running;
|
|
105
105
|
const run = async (key) => {
|
|
106
106
|
const doFetch = _nullishCoalesce(options.fetch, () => ( fetch));
|
|
107
|
-
const base = (_nullishCoalesce(options.baseUrl, () => (
|
|
107
|
+
const base = (_nullishCoalesce(options.baseUrl, () => ( _chunkDZMWUQSGcjs.DEFAULT_BASE_URL))).replace(/\/+$/u, "");
|
|
108
108
|
const read = async (init) => {
|
|
109
109
|
const response = await doFetch(`${base}/v1/site`, {
|
|
110
|
-
headers: { "X-Builder-Key": key, [
|
|
110
|
+
headers: { "X-Builder-Key": key, [_chunkDZMWUQSGcjs.SCHEMA_MIN_HEADER]: _chunkDZMWUQSGcjs.BUILDER_SCHEMA_MIN },
|
|
111
111
|
signal: AbortSignal.timeout(READ_TIMEOUT_MS),
|
|
112
112
|
...init
|
|
113
113
|
});
|
|
@@ -120,14 +120,14 @@ function createWatchSyncHandler(options) {
|
|
|
120
120
|
let generation;
|
|
121
121
|
let recorded;
|
|
122
122
|
try {
|
|
123
|
-
recorded = await read({ next: { tags: [
|
|
123
|
+
recorded = await read({ next: { tags: [_chunkDZMWUQSGcjs.BUILDER_TAGS.all], revalidate: false } });
|
|
124
124
|
generation = await read({ cache: "no-store" });
|
|
125
125
|
} catch (e2) {
|
|
126
126
|
return json2(502, { error: "The Builder could not be read." });
|
|
127
127
|
}
|
|
128
128
|
if (generation === recorded) return json2(200, { changed: false, generation });
|
|
129
129
|
const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag2()));
|
|
130
|
-
revalidate(
|
|
130
|
+
revalidate(_chunkDZMWUQSGcjs.BUILDER_TAGS.all);
|
|
131
131
|
return json2(200, { changed: true, generation });
|
|
132
132
|
};
|
|
133
133
|
return () => {
|
|
@@ -171,6 +171,19 @@ function previewMiddleware(req) {
|
|
|
171
171
|
}
|
|
172
172
|
});
|
|
173
173
|
}
|
|
174
|
+
function expiredPreviewCookie() {
|
|
175
|
+
return `${PREVIEW_COOKIE}=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax`;
|
|
176
|
+
}
|
|
177
|
+
async function clearPreviewCookie() {
|
|
178
|
+
try {
|
|
179
|
+
const { cookies } = await Promise.resolve().then(() => _interopRequireWildcard(require("next/headers")));
|
|
180
|
+
const store = await cookies();
|
|
181
|
+
store.delete(PREVIEW_COOKIE);
|
|
182
|
+
return true;
|
|
183
|
+
} catch (e3) {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
174
187
|
async function getPreviewToken() {
|
|
175
188
|
const { cookies } = await Promise.resolve().then(() => _interopRequireWildcard(require("next/headers")));
|
|
176
189
|
const store = await cookies();
|
|
@@ -184,4 +197,6 @@ async function getPreviewToken() {
|
|
|
184
197
|
|
|
185
198
|
|
|
186
199
|
|
|
187
|
-
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
exports.PREVIEW_COOKIE = PREVIEW_COOKIE; exports.clearPreviewCookie = clearPreviewCookie; exports.createRevalidateHandler = createRevalidateHandler; exports.createWatchSyncHandler = createWatchSyncHandler; exports.expiredPreviewCookie = expiredPreviewCookie; exports.getPreviewToken = getPreviewToken; exports.previewMiddleware = previewMiddleware; exports.verifyBuilderNotice = _chunkDZMWUQSGcjs.verifyBuilderNotice;
|
package/dist/next.d.cts
CHANGED
|
@@ -62,6 +62,13 @@ declare const PREVIEW_COOKIE = "throttle_builder_preview";
|
|
|
62
62
|
* and a token of an unexpected shape, returns `null`.
|
|
63
63
|
*/
|
|
64
64
|
declare function previewMiddleware(req: Request): Response | null;
|
|
65
|
+
/** A `Set-Cookie` value that deletes the preview cookie, for a middleware or route that builds its own response. */
|
|
66
|
+
declare function expiredPreviewCookie(): string;
|
|
67
|
+
/**
|
|
68
|
+
* Deletes the preview cookie through `cookies()`. Next allows that only in a route handler or server action; in a
|
|
69
|
+
* server component it throws, so this answers `false` there instead (rendering must not fail over a cookie).
|
|
70
|
+
*/
|
|
71
|
+
declare function clearPreviewCookie(): Promise<boolean>;
|
|
65
72
|
/**
|
|
66
73
|
* The preview token of the current request (the `throttle_builder_preview`
|
|
67
74
|
* cookie), for `createBuilderClient({ previewToken })`. Reads `cookies()` from
|
|
@@ -72,4 +79,4 @@ declare function previewMiddleware(req: Request): Response | null;
|
|
|
72
79
|
*/
|
|
73
80
|
declare function getPreviewToken(): Promise<string | undefined>;
|
|
74
81
|
|
|
75
|
-
export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, createWatchSyncHandler, getPreviewToken, previewMiddleware };
|
|
82
|
+
export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, clearPreviewCookie, createRevalidateHandler, createWatchSyncHandler, expiredPreviewCookie, getPreviewToken, previewMiddleware };
|
package/dist/next.d.ts
CHANGED
|
@@ -62,6 +62,13 @@ declare const PREVIEW_COOKIE = "throttle_builder_preview";
|
|
|
62
62
|
* and a token of an unexpected shape, returns `null`.
|
|
63
63
|
*/
|
|
64
64
|
declare function previewMiddleware(req: Request): Response | null;
|
|
65
|
+
/** A `Set-Cookie` value that deletes the preview cookie, for a middleware or route that builds its own response. */
|
|
66
|
+
declare function expiredPreviewCookie(): string;
|
|
67
|
+
/**
|
|
68
|
+
* Deletes the preview cookie through `cookies()`. Next allows that only in a route handler or server action; in a
|
|
69
|
+
* server component it throws, so this answers `false` there instead (rendering must not fail over a cookie).
|
|
70
|
+
*/
|
|
71
|
+
declare function clearPreviewCookie(): Promise<boolean>;
|
|
65
72
|
/**
|
|
66
73
|
* The preview token of the current request (the `throttle_builder_preview`
|
|
67
74
|
* cookie), for `createBuilderClient({ previewToken })`. Reads `cookies()` from
|
|
@@ -72,4 +79,4 @@ declare function previewMiddleware(req: Request): Response | null;
|
|
|
72
79
|
*/
|
|
73
80
|
declare function getPreviewToken(): Promise<string | undefined>;
|
|
74
81
|
|
|
75
|
-
export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, createWatchSyncHandler, getPreviewToken, previewMiddleware };
|
|
82
|
+
export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, clearPreviewCookie, createRevalidateHandler, createWatchSyncHandler, expiredPreviewCookie, getPreviewToken, previewMiddleware };
|
package/dist/next.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
TAG_MAX_CHARS,
|
|
7
7
|
scopesToTags,
|
|
8
8
|
verifyBuilderNotice
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-M6GBKCCG.js";
|
|
10
10
|
|
|
11
11
|
// src/next/index.ts
|
|
12
12
|
import "server-only";
|
|
@@ -171,6 +171,19 @@ function previewMiddleware(req) {
|
|
|
171
171
|
}
|
|
172
172
|
});
|
|
173
173
|
}
|
|
174
|
+
function expiredPreviewCookie() {
|
|
175
|
+
return `${PREVIEW_COOKIE}=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax`;
|
|
176
|
+
}
|
|
177
|
+
async function clearPreviewCookie() {
|
|
178
|
+
try {
|
|
179
|
+
const { cookies } = await import("next/headers");
|
|
180
|
+
const store = await cookies();
|
|
181
|
+
store.delete(PREVIEW_COOKIE);
|
|
182
|
+
return true;
|
|
183
|
+
} catch {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
174
187
|
async function getPreviewToken() {
|
|
175
188
|
const { cookies } = await import("next/headers");
|
|
176
189
|
const store = await cookies();
|
|
@@ -179,8 +192,10 @@ async function getPreviewToken() {
|
|
|
179
192
|
}
|
|
180
193
|
export {
|
|
181
194
|
PREVIEW_COOKIE,
|
|
195
|
+
clearPreviewCookie,
|
|
182
196
|
createRevalidateHandler,
|
|
183
197
|
createWatchSyncHandler,
|
|
198
|
+
expiredPreviewCookie,
|
|
184
199
|
getPreviewToken,
|
|
185
200
|
previewMiddleware,
|
|
186
201
|
verifyBuilderNotice
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usethrottle/builder",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"description": "Headless client for Throttle Builder: read published pages, parts, slots and site settings from a storefront, with Next.js cache, revalidation and preview helpers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
],
|
|
60
60
|
"dependencies": {
|
|
61
61
|
"server-only": "0.0.1",
|
|
62
|
-
"@usethrottle/builder-schema": "^0.4.
|
|
62
|
+
"@usethrottle/builder-schema": "^0.4.6"
|
|
63
63
|
},
|
|
64
64
|
"peerDependencies": {
|
|
65
65
|
"next": ">=14",
|