@usethrottle/builder 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,6 +22,15 @@ var BuilderNotFoundError = class extends Error {
22
22
  this.slug = slug;
23
23
  }
24
24
  };
25
+ var BuilderValidationError = class extends Error {
26
+ constructor(message, status = 400) {
27
+ super(message);
28
+ /** The HTTP status, always 400 today. */
29
+ __publicField(this, "status");
30
+ this.name = "BuilderValidationError";
31
+ this.status = status;
32
+ }
33
+ };
25
34
  var PreviewExpiredError = class extends Error {
26
35
  constructor() {
27
36
  super("The Builder preview link has expired");
@@ -46,6 +55,10 @@ function cacheInit(tags, preview) {
46
55
  return { next: { revalidate: UNTIL_CHANGED_REVALIDATE_S, tags: [...tags] } };
47
56
  }
48
57
 
58
+ // src/schema-min.ts
59
+ var BUILDER_SCHEMA_MIN = "0.4.0";
60
+ var SCHEMA_MIN_HEADER = "x-builder-schema-min";
61
+
49
62
  // src/release.ts
50
63
  import { emptyDocument as emptyDocument2 } from "@usethrottle/builder-schema";
51
64
 
@@ -65,6 +78,11 @@ function checkName(kind, value) {
65
78
  throw new TypeError(`A Builder ${kind} is a non-empty string of at most ${String(MAX_NAME_CHARS)} characters`);
66
79
  return value;
67
80
  }
81
+ function checkPath(value) {
82
+ if (typeof value !== "string" || !value.startsWith("/") || value.length > 512)
83
+ throw new TypeError('A Builder page path starts with "/" and has at most 512 characters');
84
+ return value;
85
+ }
68
86
  function checkTemplateName(value) {
69
87
  if (!TEMPLATE_NAMES.includes(value))
70
88
  throw new TypeError(`A Builder template is one of: ${TEMPLATE_NAMES.join(", ")}`);
@@ -146,7 +164,7 @@ function readBundle(body) {
146
164
  };
147
165
  }
148
166
  async function fetchBundle({ base, key, ref, timeoutMs, doFetch }) {
149
- const headers = { accept: "application/json" };
167
+ const headers = { accept: "application/json", [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN };
150
168
  if (key.startsWith("tb_sk_")) headers.authorization = `Bearer ${key}`;
151
169
  else headers["X-Builder-Key"] = key;
152
170
  const controller = new AbortController();
@@ -306,6 +324,17 @@ function createBuildClient(options) {
306
324
  get: async (slug, { locale } = {}) => {
307
325
  const bundle = await getReleaseBundle();
308
326
  return pageFor(bundle, checkName("page slug", slug), chainOf(bundle, locale));
327
+ },
328
+ // The bundle holds each page's `path`; an old slug's redirect (`redirects`) answers its `/{slug}` path. A
329
+ // release made before pages carried a path has none to match, and every path answers not found.
330
+ getByPath: async (path, { locale } = {}) => {
331
+ checkPath(path);
332
+ const bundle = await getReleaseBundle();
333
+ const page = bundle.pages.find((candidate) => candidate.path === path);
334
+ if (page !== void 0) return pageFor(bundle, page.slug, chainOf(bundle, locale));
335
+ const old = path.slice(1);
336
+ if (!old.includes("/") && Object.hasOwn(bundle.redirects, old)) return { redirectTo: bundle.redirects[old] };
337
+ throw new BuilderNotFoundError(path);
309
338
  }
310
339
  },
311
340
  parts: {
@@ -354,6 +383,8 @@ var BUILDER_TAGS = {
354
383
  all: TAG,
355
384
  site: `${TAG}:site`,
356
385
  pages: `${TAG}:pages`,
386
+ /** Every read by path: its page is not known before the answer, so a change to any page clears these. */
387
+ paths: `${TAG}:paths`,
357
388
  page: (slug) => `${TAG}:page:${slug}`,
358
389
  part: (name) => `${TAG}:part:${name}`,
359
390
  slot: (name) => `${TAG}:slot:${name}`,
@@ -373,8 +404,8 @@ function scopesToTags(scopes) {
373
404
  out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
374
405
  else if (colon < 0 && (scope === "header" || scope === "footer"))
375
406
  out.push(BUILDER_TAGS.part(scope));
376
- else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
377
- else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
407
+ else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages, BUILDER_TAGS.paths);
408
+ else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest), BUILDER_TAGS.paths);
378
409
  else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
379
410
  else if (rest !== "" && name === "template") out.push(BUILDER_TAGS.template(rest));
380
411
  else out.push(BUILDER_TAGS.all);
@@ -531,13 +562,19 @@ function createLiveClient(options) {
531
562
  }
532
563
  }
533
564
  async function fetchAnswer(path, read2) {
534
- const headers = { accept: "application/json", "X-Builder-Key": builderKey };
565
+ const headers = {
566
+ accept: "application/json",
567
+ "X-Builder-Key": builderKey,
568
+ [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN
569
+ };
535
570
  if (previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
536
571
  const url = `${base}${path}${queryString(read2.query ?? {})}`;
537
572
  const init = { method: "GET", headers, ...cacheInit(fitTags(read2.tags), preview) };
538
573
  const { body, status } = await once(url, init);
539
574
  if (status === 401 && preview) throw new PreviewExpiredError();
540
575
  if (status === 404 && read2.pageSlug !== void 0) throw new BuilderNotFoundError(read2.pageSlug);
576
+ if (status === 400 && read2.validated === true)
577
+ throw new BuilderValidationError(`Builder refused the request for ${path} (400)`);
541
578
  if (status < 200 || status >= 300)
542
579
  throw new BuilderUnavailableError("status", `Builder answered ${String(status)}`, { status });
543
580
  if (!isRecord(body) && !Array.isArray(body))
@@ -573,6 +610,17 @@ function createLiveClient(options) {
573
610
  `/v1/pages/${encodeURIComponent(checkName("page slug", slug))}`,
574
611
  { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.page(slug)], pageSlug: slug },
575
612
  readPage2
613
+ ),
614
+ getByPath: async (path, { locale } = {}) => read(
615
+ "/v1/page-by-path",
616
+ {
617
+ query: { path: checkPath(path), locale },
618
+ // The page's own tag is not known before the answer: `paths` is cleared by a `pages` and by any `page:<slug>` change.
619
+ tags: [BUILDER_TAGS.all, BUILDER_TAGS.pages, BUILDER_TAGS.paths],
620
+ pageSlug: path,
621
+ validated: true
622
+ },
623
+ readPage2
576
624
  )
577
625
  },
578
626
  parts: {
@@ -688,9 +736,12 @@ async function verifyBuilderNotice(input) {
688
736
  export {
689
737
  BuilderUnavailableError,
690
738
  BuilderNotFoundError,
739
+ BuilderValidationError,
691
740
  PreviewExpiredError,
692
741
  BuilderReleaseNotFoundError,
693
742
  UNTIL_CHANGED_REVALIDATE_S,
743
+ BUILDER_SCHEMA_MIN,
744
+ SCHEMA_MIN_HEADER,
694
745
  SUPPORTED_BUNDLE_VERSION,
695
746
  TAG_MAX_CHARS,
696
747
  BUILDER_TAGS,
@@ -22,6 +22,15 @@ var BuilderNotFoundError = class extends Error {
22
22
  this.slug = slug;
23
23
  }
24
24
  };
25
+ var BuilderValidationError = class extends Error {
26
+ constructor(message, status = 400) {
27
+ super(message);
28
+ /** The HTTP status, always 400 today. */
29
+ __publicField(this, "status");
30
+ this.name = "BuilderValidationError";
31
+ this.status = status;
32
+ }
33
+ };
25
34
  var PreviewExpiredError = class extends Error {
26
35
  constructor() {
27
36
  super("The Builder preview link has expired");
@@ -46,6 +55,10 @@ function cacheInit(tags, preview) {
46
55
  return { next: { revalidate: UNTIL_CHANGED_REVALIDATE_S, tags: [...tags] } };
47
56
  }
48
57
 
58
+ // src/schema-min.ts
59
+ var BUILDER_SCHEMA_MIN = "0.4.0";
60
+ var SCHEMA_MIN_HEADER = "x-builder-schema-min";
61
+
49
62
  // src/release.ts
50
63
  var _builderschema = require('@usethrottle/builder-schema');
51
64
 
@@ -65,6 +78,11 @@ function checkName(kind, value) {
65
78
  throw new TypeError(`A Builder ${kind} is a non-empty string of at most ${String(MAX_NAME_CHARS)} characters`);
66
79
  return value;
67
80
  }
81
+ function checkPath(value) {
82
+ if (typeof value !== "string" || !value.startsWith("/") || value.length > 512)
83
+ throw new TypeError('A Builder page path starts with "/" and has at most 512 characters');
84
+ return value;
85
+ }
68
86
  function checkTemplateName(value) {
69
87
  if (!_builderschema.TEMPLATE_NAMES.includes(value))
70
88
  throw new TypeError(`A Builder template is one of: ${_builderschema.TEMPLATE_NAMES.join(", ")}`);
@@ -146,7 +164,7 @@ function readBundle(body) {
146
164
  };
147
165
  }
148
166
  async function fetchBundle({ base, key, ref, timeoutMs, doFetch }) {
149
- const headers = { accept: "application/json" };
167
+ const headers = { accept: "application/json", [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN };
150
168
  if (key.startsWith("tb_sk_")) headers.authorization = `Bearer ${key}`;
151
169
  else headers["X-Builder-Key"] = key;
152
170
  const controller = new AbortController();
@@ -306,6 +324,17 @@ function createBuildClient(options) {
306
324
  get: async (slug, { locale } = {}) => {
307
325
  const bundle = await getReleaseBundle();
308
326
  return pageFor(bundle, checkName("page slug", slug), chainOf(bundle, locale));
327
+ },
328
+ // The bundle holds each page's `path`; an old slug's redirect (`redirects`) answers its `/{slug}` path. A
329
+ // release made before pages carried a path has none to match, and every path answers not found.
330
+ getByPath: async (path, { locale } = {}) => {
331
+ checkPath(path);
332
+ const bundle = await getReleaseBundle();
333
+ const page = bundle.pages.find((candidate) => candidate.path === path);
334
+ if (page !== void 0) return pageFor(bundle, page.slug, chainOf(bundle, locale));
335
+ const old = path.slice(1);
336
+ if (!old.includes("/") && Object.hasOwn(bundle.redirects, old)) return { redirectTo: bundle.redirects[old] };
337
+ throw new BuilderNotFoundError(path);
309
338
  }
310
339
  },
311
340
  parts: {
@@ -354,6 +383,8 @@ var BUILDER_TAGS = {
354
383
  all: TAG,
355
384
  site: `${TAG}:site`,
356
385
  pages: `${TAG}:pages`,
386
+ /** Every read by path: its page is not known before the answer, so a change to any page clears these. */
387
+ paths: `${TAG}:paths`,
357
388
  page: (slug) => `${TAG}:page:${slug}`,
358
389
  part: (name) => `${TAG}:part:${name}`,
359
390
  slot: (name) => `${TAG}:slot:${name}`,
@@ -373,8 +404,8 @@ function scopesToTags(scopes) {
373
404
  out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
374
405
  else if (colon < 0 && (scope === "header" || scope === "footer"))
375
406
  out.push(BUILDER_TAGS.part(scope));
376
- else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
377
- else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
407
+ else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages, BUILDER_TAGS.paths);
408
+ else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest), BUILDER_TAGS.paths);
378
409
  else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
379
410
  else if (rest !== "" && name === "template") out.push(BUILDER_TAGS.template(rest));
380
411
  else out.push(BUILDER_TAGS.all);
@@ -531,13 +562,19 @@ function createLiveClient(options) {
531
562
  }
532
563
  }
533
564
  async function fetchAnswer(path, read2) {
534
- const headers = { accept: "application/json", "X-Builder-Key": builderKey };
565
+ const headers = {
566
+ accept: "application/json",
567
+ "X-Builder-Key": builderKey,
568
+ [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN
569
+ };
535
570
  if (previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
536
571
  const url = `${base}${path}${queryString(_nullishCoalesce(read2.query, () => ( {})))}`;
537
572
  const init = { method: "GET", headers, ...cacheInit(fitTags(read2.tags), preview) };
538
573
  const { body, status } = await once(url, init);
539
574
  if (status === 401 && preview) throw new PreviewExpiredError();
540
575
  if (status === 404 && read2.pageSlug !== void 0) throw new BuilderNotFoundError(read2.pageSlug);
576
+ if (status === 400 && read2.validated === true)
577
+ throw new BuilderValidationError(`Builder refused the request for ${path} (400)`);
541
578
  if (status < 200 || status >= 300)
542
579
  throw new BuilderUnavailableError("status", `Builder answered ${String(status)}`, { status });
543
580
  if (!isRecord(body) && !Array.isArray(body))
@@ -573,6 +610,17 @@ function createLiveClient(options) {
573
610
  `/v1/pages/${encodeURIComponent(checkName("page slug", slug))}`,
574
611
  { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.page(slug)], pageSlug: slug },
575
612
  readPage2
613
+ ),
614
+ getByPath: async (path, { locale } = {}) => read(
615
+ "/v1/page-by-path",
616
+ {
617
+ query: { path: checkPath(path), locale },
618
+ // The page's own tag is not known before the answer: `paths` is cleared by a `pages` and by any `page:<slug>` change.
619
+ tags: [BUILDER_TAGS.all, BUILDER_TAGS.pages, BUILDER_TAGS.paths],
620
+ pageSlug: path,
621
+ validated: true
622
+ },
623
+ readPage2
576
624
  )
577
625
  },
578
626
  parts: {
@@ -700,4 +748,7 @@ async function verifyBuilderNotice(input) {
700
748
 
701
749
 
702
750
 
703
- exports.BuilderUnavailableError = BuilderUnavailableError; exports.BuilderNotFoundError = BuilderNotFoundError; exports.PreviewExpiredError = PreviewExpiredError; exports.BuilderReleaseNotFoundError = BuilderReleaseNotFoundError; exports.UNTIL_CHANGED_REVALIDATE_S = UNTIL_CHANGED_REVALIDATE_S; exports.SUPPORTED_BUNDLE_VERSION = SUPPORTED_BUNDLE_VERSION; exports.TAG_MAX_CHARS = TAG_MAX_CHARS; exports.BUILDER_TAGS = BUILDER_TAGS; exports.templateTag = templateTag; exports.scopesToTags = scopesToTags; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL2; exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; exports.createBuilderClient = createBuilderClient; exports.verifyBuilderNotice = verifyBuilderNotice;
751
+
752
+
753
+
754
+ exports.BuilderUnavailableError = BuilderUnavailableError; exports.BuilderNotFoundError = BuilderNotFoundError; exports.BuilderValidationError = BuilderValidationError; exports.PreviewExpiredError = PreviewExpiredError; exports.BuilderReleaseNotFoundError = BuilderReleaseNotFoundError; exports.UNTIL_CHANGED_REVALIDATE_S = UNTIL_CHANGED_REVALIDATE_S; exports.BUILDER_SCHEMA_MIN = BUILDER_SCHEMA_MIN; exports.SCHEMA_MIN_HEADER = SCHEMA_MIN_HEADER; exports.SUPPORTED_BUNDLE_VERSION = SUPPORTED_BUNDLE_VERSION; exports.TAG_MAX_CHARS = TAG_MAX_CHARS; exports.BUILDER_TAGS = BUILDER_TAGS; exports.templateTag = templateTag; exports.scopesToTags = scopesToTags; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL2; exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; exports.createBuilderClient = createBuilderClient; exports.verifyBuilderNotice = verifyBuilderNotice;
package/dist/index.cjs CHANGED
@@ -12,9 +12,9 @@
12
12
 
13
13
 
14
14
 
15
- var _chunk53B64NRGcjs = require('./chunk-53B64NRG.cjs');
16
15
 
17
16
 
17
+ var _chunkKNA3T4M6cjs = require('./chunk-KNA3T4M6.cjs');
18
18
 
19
19
 
20
20
 
@@ -27,4 +27,8 @@ var _chunk53B64NRGcjs = require('./chunk-53B64NRG.cjs');
27
27
 
28
28
 
29
29
 
30
- exports.BUILDER_TAGS = _chunk53B64NRGcjs.BUILDER_TAGS; exports.BuilderNotFoundError = _chunk53B64NRGcjs.BuilderNotFoundError; exports.BuilderReleaseNotFoundError = _chunk53B64NRGcjs.BuilderReleaseNotFoundError; exports.BuilderUnavailableError = _chunk53B64NRGcjs.BuilderUnavailableError; exports.DEFAULT_BASE_URL = _chunk53B64NRGcjs.DEFAULT_BASE_URL; exports.DEFAULT_TIMEOUT_MS = _chunk53B64NRGcjs.DEFAULT_TIMEOUT_MS; exports.PreviewExpiredError = _chunk53B64NRGcjs.PreviewExpiredError; exports.SUPPORTED_BUNDLE_VERSION = _chunk53B64NRGcjs.SUPPORTED_BUNDLE_VERSION; exports.UNTIL_CHANGED_REVALIDATE_S = _chunk53B64NRGcjs.UNTIL_CHANGED_REVALIDATE_S; exports.createBuilderClient = _chunk53B64NRGcjs.createBuilderClient; exports.scopesToTags = _chunk53B64NRGcjs.scopesToTags; exports.templateTag = _chunk53B64NRGcjs.templateTag; exports.verifyBuilderNotice = _chunk53B64NRGcjs.verifyBuilderNotice;
30
+
31
+
32
+
33
+
34
+ exports.BUILDER_SCHEMA_MIN = _chunkKNA3T4M6cjs.BUILDER_SCHEMA_MIN; exports.BUILDER_TAGS = _chunkKNA3T4M6cjs.BUILDER_TAGS; exports.BuilderNotFoundError = _chunkKNA3T4M6cjs.BuilderNotFoundError; exports.BuilderReleaseNotFoundError = _chunkKNA3T4M6cjs.BuilderReleaseNotFoundError; exports.BuilderUnavailableError = _chunkKNA3T4M6cjs.BuilderUnavailableError; exports.BuilderValidationError = _chunkKNA3T4M6cjs.BuilderValidationError; exports.DEFAULT_BASE_URL = _chunkKNA3T4M6cjs.DEFAULT_BASE_URL; exports.DEFAULT_TIMEOUT_MS = _chunkKNA3T4M6cjs.DEFAULT_TIMEOUT_MS; exports.PreviewExpiredError = _chunkKNA3T4M6cjs.PreviewExpiredError; exports.SUPPORTED_BUNDLE_VERSION = _chunkKNA3T4M6cjs.SUPPORTED_BUNDLE_VERSION; exports.UNTIL_CHANGED_REVALIDATE_S = _chunkKNA3T4M6cjs.UNTIL_CHANGED_REVALIDATE_S; exports.createBuilderClient = _chunkKNA3T4M6cjs.createBuilderClient; exports.scopesToTags = _chunkKNA3T4M6cjs.scopesToTags; exports.templateTag = _chunkKNA3T4M6cjs.templateTag; exports.verifyBuilderNotice = _chunkKNA3T4M6cjs.verifyBuilderNotice;
package/dist/index.d.cts CHANGED
@@ -22,6 +22,15 @@ declare class BuilderNotFoundError extends Error {
22
22
  readonly slug: string | undefined;
23
23
  constructor(slug?: string);
24
24
  }
25
+ /**
26
+ * The Builder refused a read as invalid (`400`), for example a path it cannot match. It is an answer about the
27
+ * request, not an outage: it is never softened to a last good answer, and a route treats it as not found.
28
+ */
29
+ declare class BuilderValidationError extends Error {
30
+ /** The HTTP status, always 400 today. */
31
+ readonly status: number;
32
+ constructor(message: string, status?: number);
33
+ }
25
34
  /**
26
35
  * The preview token is expired or not valid (`401 PREVIEW_EXPIRED`). A preview
27
36
  * read never falls back to the published page: the caller shows that the link
@@ -141,8 +150,10 @@ type BuilderClient = {
141
150
  get(slug: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
142
151
  /**
143
152
  * The page that answers at its own path (`/about`), or a redirect when the path is an old one of a page
144
- * (`slug_redirects`). Optional: a client without it is read through `list()` (the summaries carry `path`).
145
- * Rejects with `BuilderNotFoundError` when no page has the path.
153
+ * (`slug_redirects`). Optional in this type so a custom client may omit it (a route then reads `list()`, whose
154
+ * summaries carry `path`); every client `createBuilderClient` makes has it (`PageByPathClient`).
155
+ * Rejects with `BuilderNotFoundError` when no page has the path, and with `BuilderValidationError` when the
156
+ * Builder refuses the path (`400`).
146
157
  */
147
158
  getByPath?(path: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
148
159
  };
@@ -160,6 +171,12 @@ type BuilderClient = {
160
171
  templates?: readonly TemplateName[];
161
172
  }): Promise<BuilderBundle>;
162
173
  };
174
+ /** A `BuilderClient` that has `pages.getByPath`: what `createBuilderClient` returns. */
175
+ type PageByPathClient = BuilderClient & {
176
+ pages: {
177
+ getByPath(path: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
178
+ };
179
+ };
163
180
  /** A published part or slot as a release holds it. */
164
181
  type ReleaseDocument = {
165
182
  version: number;
@@ -259,7 +276,7 @@ type BuildClientOptions = BuildClientCommon & ({
259
276
  releaseBundle: ReleaseBundle;
260
277
  builderKey?: string;
261
278
  });
262
- type BuildBuilderClient = BuilderClient & {
279
+ type BuildBuilderClient = PageByPathClient & {
263
280
  readonly mode: 'build';
264
281
  /**
265
282
  * The release's bundle, read once per process and kept in memory. The release
@@ -280,7 +297,7 @@ declare const DEFAULT_TIMEOUT_MS = 3000;
280
297
  * mode, the client reads the live API.
281
298
  */
282
299
  declare function createBuilderClient(options: BuildClientOptions): BuildBuilderClient;
283
- declare function createBuilderClient(options: BuilderClientOptions): BuilderClient;
300
+ declare function createBuilderClient(options: BuilderClientOptions): PageByPathClient;
284
301
 
285
302
  /** The bundle format this SDK reads (`BUNDLE_VERSION` of the Builder). */
286
303
  declare const SUPPORTED_BUNDLE_VERSION = 1;
@@ -289,6 +306,8 @@ declare const BUILDER_TAGS: {
289
306
  readonly all: "throttle-builder";
290
307
  readonly site: "throttle-builder:site";
291
308
  readonly pages: "throttle-builder:pages";
309
+ /** Every read by path: its page is not known before the answer, so a change to any page clears these. */
310
+ readonly paths: "throttle-builder:paths";
292
311
  readonly page: (slug: string) => string;
293
312
  readonly part: (name: string) => string;
294
313
  readonly slot: (name: string) => string;
@@ -307,4 +326,12 @@ declare function scopesToTags(scopes: readonly string[]): string[];
307
326
  /** Next's `revalidate` for a published read: only a safety net behind the change notices. */
308
327
  declare const UNTIL_CHANGED_REVALIDATE_S = 3600;
309
328
 
310
- export { BUILDER_TAGS, type BuildBuilderClient, type BuildClientOptions, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, BuilderReleaseNotFoundError, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageRedirect, type PartName, PreviewExpiredError, type ReleaseBundle, type ReleaseDocument, type ReleasePage, type ReleaseTemplate, SUPPORTED_BUNDLE_VERSION, type TemplateAnswer, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags, templateTag };
329
+ /**
330
+ * The `x-builder-schema-min` request header: the builder-schema version this package reads. The Builder Worker
331
+ * serves v2 published site settings only to a client that sends a version of at least 0.4.0 (R2); one that sends
332
+ * none gets the v1 downgrade. Kept equal to `packages/builder-schema/package.json` by `schema-min-header.test.ts`:
333
+ * bump both together.
334
+ */
335
+ declare const BUILDER_SCHEMA_MIN = "0.4.0";
336
+
337
+ export { BUILDER_SCHEMA_MIN, BUILDER_TAGS, type BuildBuilderClient, type BuildClientOptions, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, BuilderReleaseNotFoundError, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, BuilderValidationError, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageByPathClient, type PageRedirect, type PartName, PreviewExpiredError, type ReleaseBundle, type ReleaseDocument, type ReleasePage, type ReleaseTemplate, SUPPORTED_BUNDLE_VERSION, type TemplateAnswer, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags, templateTag };
package/dist/index.d.ts CHANGED
@@ -22,6 +22,15 @@ declare class BuilderNotFoundError extends Error {
22
22
  readonly slug: string | undefined;
23
23
  constructor(slug?: string);
24
24
  }
25
+ /**
26
+ * The Builder refused a read as invalid (`400`), for example a path it cannot match. It is an answer about the
27
+ * request, not an outage: it is never softened to a last good answer, and a route treats it as not found.
28
+ */
29
+ declare class BuilderValidationError extends Error {
30
+ /** The HTTP status, always 400 today. */
31
+ readonly status: number;
32
+ constructor(message: string, status?: number);
33
+ }
25
34
  /**
26
35
  * The preview token is expired or not valid (`401 PREVIEW_EXPIRED`). A preview
27
36
  * read never falls back to the published page: the caller shows that the link
@@ -141,8 +150,10 @@ type BuilderClient = {
141
150
  get(slug: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
142
151
  /**
143
152
  * The page that answers at its own path (`/about`), or a redirect when the path is an old one of a page
144
- * (`slug_redirects`). Optional: a client without it is read through `list()` (the summaries carry `path`).
145
- * Rejects with `BuilderNotFoundError` when no page has the path.
153
+ * (`slug_redirects`). Optional in this type so a custom client may omit it (a route then reads `list()`, whose
154
+ * summaries carry `path`); every client `createBuilderClient` makes has it (`PageByPathClient`).
155
+ * Rejects with `BuilderNotFoundError` when no page has the path, and with `BuilderValidationError` when the
156
+ * Builder refuses the path (`400`).
146
157
  */
147
158
  getByPath?(path: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
148
159
  };
@@ -160,6 +171,12 @@ type BuilderClient = {
160
171
  templates?: readonly TemplateName[];
161
172
  }): Promise<BuilderBundle>;
162
173
  };
174
+ /** A `BuilderClient` that has `pages.getByPath`: what `createBuilderClient` returns. */
175
+ type PageByPathClient = BuilderClient & {
176
+ pages: {
177
+ getByPath(path: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
178
+ };
179
+ };
163
180
  /** A published part or slot as a release holds it. */
164
181
  type ReleaseDocument = {
165
182
  version: number;
@@ -259,7 +276,7 @@ type BuildClientOptions = BuildClientCommon & ({
259
276
  releaseBundle: ReleaseBundle;
260
277
  builderKey?: string;
261
278
  });
262
- type BuildBuilderClient = BuilderClient & {
279
+ type BuildBuilderClient = PageByPathClient & {
263
280
  readonly mode: 'build';
264
281
  /**
265
282
  * The release's bundle, read once per process and kept in memory. The release
@@ -280,7 +297,7 @@ declare const DEFAULT_TIMEOUT_MS = 3000;
280
297
  * mode, the client reads the live API.
281
298
  */
282
299
  declare function createBuilderClient(options: BuildClientOptions): BuildBuilderClient;
283
- declare function createBuilderClient(options: BuilderClientOptions): BuilderClient;
300
+ declare function createBuilderClient(options: BuilderClientOptions): PageByPathClient;
284
301
 
285
302
  /** The bundle format this SDK reads (`BUNDLE_VERSION` of the Builder). */
286
303
  declare const SUPPORTED_BUNDLE_VERSION = 1;
@@ -289,6 +306,8 @@ declare const BUILDER_TAGS: {
289
306
  readonly all: "throttle-builder";
290
307
  readonly site: "throttle-builder:site";
291
308
  readonly pages: "throttle-builder:pages";
309
+ /** Every read by path: its page is not known before the answer, so a change to any page clears these. */
310
+ readonly paths: "throttle-builder:paths";
292
311
  readonly page: (slug: string) => string;
293
312
  readonly part: (name: string) => string;
294
313
  readonly slot: (name: string) => string;
@@ -307,4 +326,12 @@ declare function scopesToTags(scopes: readonly string[]): string[];
307
326
  /** Next's `revalidate` for a published read: only a safety net behind the change notices. */
308
327
  declare const UNTIL_CHANGED_REVALIDATE_S = 3600;
309
328
 
310
- export { BUILDER_TAGS, type BuildBuilderClient, type BuildClientOptions, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, BuilderReleaseNotFoundError, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageRedirect, type PartName, PreviewExpiredError, type ReleaseBundle, type ReleaseDocument, type ReleasePage, type ReleaseTemplate, SUPPORTED_BUNDLE_VERSION, type TemplateAnswer, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags, templateTag };
329
+ /**
330
+ * The `x-builder-schema-min` request header: the builder-schema version this package reads. The Builder Worker
331
+ * serves v2 published site settings only to a client that sends a version of at least 0.4.0 (R2); one that sends
332
+ * none gets the v1 downgrade. Kept equal to `packages/builder-schema/package.json` by `schema-min-header.test.ts`:
333
+ * bump both together.
334
+ */
335
+ declare const BUILDER_SCHEMA_MIN = "0.4.0";
336
+
337
+ export { BUILDER_SCHEMA_MIN, BUILDER_TAGS, type BuildBuilderClient, type BuildClientOptions, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, BuilderReleaseNotFoundError, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, BuilderValidationError, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageByPathClient, type PageRedirect, type PartName, PreviewExpiredError, type ReleaseBundle, type ReleaseDocument, type ReleasePage, type ReleaseTemplate, SUPPORTED_BUNDLE_VERSION, type TemplateAnswer, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags, templateTag };
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import {
2
+ BUILDER_SCHEMA_MIN,
2
3
  BUILDER_TAGS,
3
4
  BuilderNotFoundError,
4
5
  BuilderReleaseNotFoundError,
5
6
  BuilderUnavailableError,
7
+ BuilderValidationError,
6
8
  DEFAULT_BASE_URL,
7
9
  DEFAULT_TIMEOUT_MS,
8
10
  PreviewExpiredError,
@@ -12,12 +14,14 @@ import {
12
14
  scopesToTags,
13
15
  templateTag,
14
16
  verifyBuilderNotice
15
- } from "./chunk-RXLU55OZ.js";
17
+ } from "./chunk-3PRNCLZO.js";
16
18
  export {
19
+ BUILDER_SCHEMA_MIN,
17
20
  BUILDER_TAGS,
18
21
  BuilderNotFoundError,
19
22
  BuilderReleaseNotFoundError,
20
23
  BuilderUnavailableError,
24
+ BuilderValidationError,
21
25
  DEFAULT_BASE_URL,
22
26
  DEFAULT_TIMEOUT_MS,
23
27
  PreviewExpiredError,
package/dist/next.cjs CHANGED
@@ -4,7 +4,9 @@
4
4
 
5
5
 
6
6
 
7
- var _chunk53B64NRGcjs = require('./chunk-53B64NRG.cjs');
7
+
8
+
9
+ var _chunkKNA3T4M6cjs = require('./chunk-KNA3T4M6.cjs');
8
10
 
9
11
  // src/next/index.ts
10
12
  require('server-only');
@@ -47,7 +49,7 @@ function parseNotice(rawBody) {
47
49
  if (typeof value !== "object" || value === null) return null;
48
50
  const { type, generation, scopes } = value;
49
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(
50
- (scope) => typeof scope === "string" && scope.length > 0 && scope.length <= _chunk53B64NRGcjs.TAG_MAX_CHARS
52
+ (scope) => typeof scope === "string" && scope.length > 0 && scope.length <= _chunkKNA3T4M6cjs.TAG_MAX_CHARS
51
53
  ))
52
54
  return null;
53
55
  return { generation, scopes };
@@ -72,12 +74,12 @@ function createRevalidateHandler(options) {
72
74
  const now = Math.floor(Date.now() / 1e3);
73
75
  let verified = false;
74
76
  for (const secret of secrets)
75
- verified = await _chunk53B64NRGcjs.verifyBuilderNotice.call(void 0, { rawBody, header, secret, now }) || verified;
77
+ verified = await _chunkKNA3T4M6cjs.verifyBuilderNotice.call(void 0, { rawBody, header, secret, now }) || verified;
76
78
  if (!verified) return json(401, { error: "invalid signature" });
77
79
  const notice = parseNotice(rawBody);
78
80
  if (notice === null) return json(400, { error: "invalid body" });
79
- const mapped = _chunk53B64NRGcjs.scopesToTags.call(void 0, notice.scopes);
80
- const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [_chunk53B64NRGcjs.BUILDER_TAGS.all] : mapped;
81
+ const mapped = _chunkKNA3T4M6cjs.scopesToTags.call(void 0, notice.scopes);
82
+ const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [_chunkKNA3T4M6cjs.BUILDER_TAGS.all] : mapped;
81
83
  const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag()));
82
84
  for (const tag of tags) revalidate(tag);
83
85
  return json(200, { revalidated: tags });
@@ -102,10 +104,10 @@ function createWatchSyncHandler(options) {
102
104
  let running;
103
105
  const run = async (key) => {
104
106
  const doFetch = _nullishCoalesce(options.fetch, () => ( fetch));
105
- const base = (_nullishCoalesce(options.baseUrl, () => ( _chunk53B64NRGcjs.DEFAULT_BASE_URL))).replace(/\/+$/u, "");
107
+ const base = (_nullishCoalesce(options.baseUrl, () => ( _chunkKNA3T4M6cjs.DEFAULT_BASE_URL))).replace(/\/+$/u, "");
106
108
  const read = async (init) => {
107
109
  const response = await doFetch(`${base}/v1/site`, {
108
- headers: { "X-Builder-Key": key },
110
+ headers: { "X-Builder-Key": key, [_chunkKNA3T4M6cjs.SCHEMA_MIN_HEADER]: _chunkKNA3T4M6cjs.BUILDER_SCHEMA_MIN },
109
111
  signal: AbortSignal.timeout(READ_TIMEOUT_MS),
110
112
  ...init
111
113
  });
@@ -118,14 +120,14 @@ function createWatchSyncHandler(options) {
118
120
  let generation;
119
121
  let recorded;
120
122
  try {
121
- recorded = await read({ next: { tags: [_chunk53B64NRGcjs.BUILDER_TAGS.all], revalidate: false } });
123
+ recorded = await read({ next: { tags: [_chunkKNA3T4M6cjs.BUILDER_TAGS.all], revalidate: false } });
122
124
  generation = await read({ cache: "no-store" });
123
125
  } catch (e2) {
124
126
  return json2(502, { error: "The Builder could not be read." });
125
127
  }
126
128
  if (generation === recorded) return json2(200, { changed: false, generation });
127
129
  const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag2()));
128
- revalidate(_chunk53B64NRGcjs.BUILDER_TAGS.all);
130
+ revalidate(_chunkKNA3T4M6cjs.BUILDER_TAGS.all);
129
131
  return json2(200, { changed: true, generation });
130
132
  };
131
133
  return () => {
@@ -182,4 +184,4 @@ async function getPreviewToken() {
182
184
 
183
185
 
184
186
 
185
- exports.PREVIEW_COOKIE = PREVIEW_COOKIE; exports.createRevalidateHandler = createRevalidateHandler; exports.createWatchSyncHandler = createWatchSyncHandler; exports.getPreviewToken = getPreviewToken; exports.previewMiddleware = previewMiddleware; exports.verifyBuilderNotice = _chunk53B64NRGcjs.verifyBuilderNotice;
187
+ exports.PREVIEW_COOKIE = PREVIEW_COOKIE; exports.createRevalidateHandler = createRevalidateHandler; exports.createWatchSyncHandler = createWatchSyncHandler; exports.getPreviewToken = getPreviewToken; exports.previewMiddleware = previewMiddleware; exports.verifyBuilderNotice = _chunkKNA3T4M6cjs.verifyBuilderNotice;
package/dist/next.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import {
2
+ BUILDER_SCHEMA_MIN,
2
3
  BUILDER_TAGS,
3
4
  DEFAULT_BASE_URL,
5
+ SCHEMA_MIN_HEADER,
4
6
  TAG_MAX_CHARS,
5
7
  scopesToTags,
6
8
  verifyBuilderNotice
7
- } from "./chunk-RXLU55OZ.js";
9
+ } from "./chunk-3PRNCLZO.js";
8
10
 
9
11
  // src/next/index.ts
10
12
  import "server-only";
@@ -105,7 +107,7 @@ function createWatchSyncHandler(options) {
105
107
  const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
106
108
  const read = async (init) => {
107
109
  const response = await doFetch(`${base}/v1/site`, {
108
- headers: { "X-Builder-Key": key },
110
+ headers: { "X-Builder-Key": key, [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN },
109
111
  signal: AbortSignal.timeout(READ_TIMEOUT_MS),
110
112
  ...init
111
113
  });
package/dist/watch.cjs CHANGED
@@ -28,6 +28,12 @@ __export(generation_watch_exports, {
28
28
  });
29
29
  module.exports = __toCommonJS(generation_watch_exports);
30
30
  var import_react = require("react");
31
+
32
+ // src/schema-min.ts
33
+ var BUILDER_SCHEMA_MIN = "0.4.0";
34
+ var SCHEMA_MIN_HEADER = "x-builder-schema-min";
35
+
36
+ // src/generation-watch.ts
31
37
  var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
32
38
  var MIN_INTERVAL_MS = 3e4;
33
39
  var DEFAULT_INTERVAL_MS = 6e4;
@@ -74,7 +80,7 @@ function watchGeneration({
74
80
  }
75
81
  async function readSiteGeneration(baseUrl, builderKey) {
76
82
  const response = await fetch(`${baseUrl.replace(/\/+$/u, "")}/v1/site`, {
77
- headers: { "X-Builder-Key": builderKey },
83
+ headers: { "X-Builder-Key": builderKey, [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN },
78
84
  cache: "no-cache"
79
85
  });
80
86
  if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
package/dist/watch.js CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  // src/generation-watch.ts
4
4
  import { useEffect, useRef } from "react";
5
+
6
+ // src/schema-min.ts
7
+ var BUILDER_SCHEMA_MIN = "0.4.0";
8
+ var SCHEMA_MIN_HEADER = "x-builder-schema-min";
9
+
10
+ // src/generation-watch.ts
5
11
  var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
6
12
  var MIN_INTERVAL_MS = 3e4;
7
13
  var DEFAULT_INTERVAL_MS = 6e4;
@@ -48,7 +54,7 @@ function watchGeneration({
48
54
  }
49
55
  async function readSiteGeneration(baseUrl, builderKey) {
50
56
  const response = await fetch(`${baseUrl.replace(/\/+$/u, "")}/v1/site`, {
51
- headers: { "X-Builder-Key": builderKey },
57
+ headers: { "X-Builder-Key": builderKey, [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN },
52
58
  cache: "no-cache"
53
59
  });
54
60
  if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usethrottle/builder",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
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.0"
62
+ "@usethrottle/builder-schema": "^0.4.1"
63
63
  },
64
64
  "peerDependencies": {
65
65
  "next": ">=14",