brease-client 0.7.1 → 0.8.1

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/dist/index.cjs CHANGED
@@ -76,6 +76,13 @@ function resolvePath(settings, pathname) {
76
76
  }
77
77
  return { slug: clean, locale: settings.defaultLocale };
78
78
  }
79
+ function canonicalPath(settings, pathname) {
80
+ const path = pathname.split(/[?#]/)[0] ?? "";
81
+ const { slug, locale } = resolvePath(settings, path);
82
+ const canonical = buildPath(settings, slug, locale);
83
+ const trim = (p) => p.length > 1 ? p.replace(/\/+$/, "") : p;
84
+ return trim(decodeURIComponent(path)) === trim(canonical) ? null : canonical;
85
+ }
79
86
 
80
87
  // src/analytics.ts
81
88
  var MEASUREMENT_ID = /^G-[A-Z0-9]+$/;
@@ -100,6 +107,29 @@ function grantAnalytics(granted = true) {
100
107
  gtag?.("consent", "update", { analytics_storage: granted ? "granted" : "denied" });
101
108
  }
102
109
 
110
+ // src/custom-code.ts
111
+ function customTags(seo) {
112
+ return [seo.customHead, seo.customCode].flatMap((html) => html ? parseTags(html) : []);
113
+ }
114
+ function parseTags(html) {
115
+ const out = [];
116
+ const re = /<(script|style|noscript)\b([^>]*)>([\s\S]*?)<\/\1\s*>|<(meta|link)\b([^>]*?)\/?>/gi;
117
+ for (const m of html.matchAll(re)) {
118
+ if (m[1]) {
119
+ const tag = m[1].toLowerCase();
120
+ out.push({ tag, attrs: attrsOf(m[2] ?? ""), ...m[3]?.trim() ? { content: m[3] } : {} });
121
+ } else if (m[4])
122
+ out.push({ tag: m[4].toLowerCase(), attrs: attrsOf(m[5] ?? "") });
123
+ }
124
+ return out;
125
+ }
126
+ function attrsOf(source) {
127
+ const attrs = {};
128
+ for (const m of source.matchAll(/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g))
129
+ attrs[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? "";
130
+ return attrs;
131
+ }
132
+
103
133
  // src/locales.ts
104
134
  function localeLinks(context) {
105
135
  const { settings, alternates, homes, locale: current } = context;
@@ -118,6 +148,50 @@ function nativeName(locale) {
118
148
  }
119
149
  var localeHref = (settings, slug, locale) => buildPath(settings, slug, locale);
120
150
 
151
+ // src/markers.ts
152
+ function fieldPath(path, pageId) {
153
+ return pageId ? `${pageId}:${path}` : path;
154
+ }
155
+ function navPath(key) {
156
+ return `nav:${key}`;
157
+ }
158
+
159
+ // src/redirects.ts
160
+ function matchRedirect(redirects, pathname) {
161
+ const path = normalize(pathname);
162
+ for (const r of redirects) {
163
+ const params = matchSource(normalize(r.source), path);
164
+ if (!params) continue;
165
+ const destination = r.destination.replace(
166
+ /:([A-Za-z_][A-Za-z0-9_]*)\*?/g,
167
+ (whole, name) => name in params ? params[name] : whole
168
+ );
169
+ if (normalize(destination) === path) continue;
170
+ return { destination, status: r.status };
171
+ }
172
+ return null;
173
+ }
174
+ var normalize = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p) || "/";
175
+ function matchSource(source, path) {
176
+ const want = source.split("/").filter(Boolean);
177
+ const have = path.split("/").filter(Boolean);
178
+ const params = {};
179
+ for (let i = 0; i < want.length; i++) {
180
+ const seg = want[i];
181
+ const rest = /^:([A-Za-z_][A-Za-z0-9_]*)\*$/.exec(seg);
182
+ if (rest) {
183
+ params[rest[1]] = have.slice(i).join("/");
184
+ return params;
185
+ }
186
+ const value = have[i];
187
+ if (value === void 0) return null;
188
+ const param = /^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(seg);
189
+ if (param) params[param[1]] = value;
190
+ else if (decodeURIComponent(value) !== decodeURIComponent(seg)) return null;
191
+ }
192
+ return want.length === have.length ? params : null;
193
+ }
194
+
121
195
  // src/sections.ts
122
196
  var sectionsAttrs = { "data-brease-sections": "sections" };
123
197
  function sectionAttrs(section) {
@@ -196,6 +270,54 @@ function checkSections(files, pages = {}) {
196
270
  return warnings;
197
271
  }
198
272
 
273
+ // src/signature.ts
274
+ var MAX_SKEW_MS = 5 * 6e4;
275
+ async function hmacHex(secret, message) {
276
+ const enc = new TextEncoder();
277
+ const key = await crypto.subtle.importKey(
278
+ "raw",
279
+ enc.encode(secret),
280
+ { name: "HMAC", hash: "SHA-256" },
281
+ false,
282
+ ["sign"]
283
+ );
284
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(message)));
285
+ return Array.from(sig, (b) => b.toString(16).padStart(2, "0")).join("");
286
+ }
287
+ async function verifySignature(body, timestamp, signature, secret, now = Date.now()) {
288
+ if (!timestamp || !signature) return false;
289
+ if (!Number.isFinite(Number(timestamp)) || Math.abs(now - Number(timestamp)) > MAX_SKEW_MS) return false;
290
+ const expected = await hmacHex(secret, `${timestamp}.${body}`);
291
+ if (expected.length !== signature.length) return false;
292
+ let diff = 0;
293
+ for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
294
+ return diff === 0;
295
+ }
296
+ async function verifyRevalidate(req, secret) {
297
+ const raw = await req.text();
298
+ const ok = await verifySignature(
299
+ raw,
300
+ req.headers.get("x-brease-timestamp"),
301
+ req.headers.get("x-brease-signature"),
302
+ secret
303
+ );
304
+ if (!ok) return { ok: false, reason: "signature" };
305
+ let body;
306
+ try {
307
+ body = JSON.parse(raw || "{}");
308
+ } catch {
309
+ return { ok: false, reason: "body" };
310
+ }
311
+ const paths = new Set(body.paths ?? []);
312
+ for (const url of body.urls ?? []) {
313
+ try {
314
+ paths.add(new URL(url, "http://localhost").pathname);
315
+ } catch {
316
+ }
317
+ }
318
+ return { ok: true, paths: [...paths], tags: ["brease", ...body.tags ?? []], body };
319
+ }
320
+
199
321
  // src/structured-data.ts
200
322
  var jsonLdText = (data) => JSON.stringify(data).replace(/</g, "\\u003c");
201
323
  function jsonLd(seo) {
@@ -216,6 +338,7 @@ function createBrease(opts = {}) {
216
338
  const baseMs = opts.retryBaseMs ?? 300;
217
339
  const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
218
340
  let site;
341
+ let redirects;
219
342
  async function request(path, query = {}, nullOn404 = false) {
220
343
  const token = opts.token ?? env("BREASE_TOKEN");
221
344
  if (!token)
@@ -265,13 +388,26 @@ function createBrease(opts = {}) {
265
388
  return request("/content-api/page", { slug, locale }, true);
266
389
  },
267
390
  getPages(o = {}) {
268
- return request("/content-api/pages", { locale: o.locale });
391
+ return request("/content-api/pages", {
392
+ locale: o.locale,
393
+ parentId: o.parentId,
394
+ template: o.template,
395
+ withContent: o.withContent ? "1" : void 0
396
+ });
269
397
  },
270
398
  getNavigation(key, { locale }) {
271
399
  return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
272
400
  },
401
+ // Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
273
402
  getRedirects() {
274
- return request("/content-api/redirects");
403
+ if (!redirects || Date.now() - redirects.at > SITE_TTL_MS) {
404
+ const promise = request("/content-api/redirects").catch((err) => {
405
+ if (redirects?.promise === promise) redirects = void 0;
406
+ throw err;
407
+ });
408
+ redirects = { promise, at: Date.now() };
409
+ }
410
+ return redirects.promise;
275
411
  },
276
412
  getRelease() {
277
413
  return request("/content-api/release");
@@ -313,7 +449,9 @@ function createBrease(opts = {}) {
313
449
  },
314
450
  async sitemap(baseUrl) {
315
451
  const base = baseUrl.replace(/\/+$/, "");
316
- const refs = (await client.getPages()).filter((r) => !r.hidden);
452
+ const refs = (await client.getPages()).filter(
453
+ (r) => !r.hidden && r.index !== false && !r.slug.split("/").some((part) => part.startsWith("_"))
454
+ );
317
455
  const byPage = /* @__PURE__ */ new Map();
318
456
  for (const ref of refs) {
319
457
  const alternates = byPage.get(ref.pageId) ?? {};
@@ -335,17 +473,25 @@ function pathOf(url) {
335
473
 
336
474
  exports.BreaseError = BreaseError;
337
475
  exports.buildPath = buildPath;
476
+ exports.canonicalPath = canonicalPath;
338
477
  exports.checkSections = checkSections;
339
478
  exports.createBrease = createBrease;
479
+ exports.customTags = customTags;
480
+ exports.fieldPath = fieldPath;
340
481
  exports.ga4Html = ga4Html;
341
482
  exports.ga4Tag = ga4Tag;
342
483
  exports.grantAnalytics = grantAnalytics;
484
+ exports.hmacHex = hmacHex;
343
485
  exports.jsonLd = jsonLd;
344
486
  exports.jsonLdHtml = jsonLdHtml;
345
487
  exports.localeHref = localeHref;
346
488
  exports.localeLinks = localeLinks;
489
+ exports.matchRedirect = matchRedirect;
347
490
  exports.nativeName = nativeName;
491
+ exports.navPath = navPath;
348
492
  exports.normalizeSlug = normalizeSlug;
349
493
  exports.resolvePath = resolvePath;
350
494
  exports.sectionAttrs = sectionAttrs;
351
495
  exports.sectionsAttrs = sectionsAttrs;
496
+ exports.verifyRevalidate = verifyRevalidate;
497
+ exports.verifySignature = verifySignature;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as Site, U as UrlSettings, R as ResolvedSeo, P as Page, a as PageRef, N as Navigation, b as Redirect, c as Release, d as SitemapEntry } from './types-ecfDXrLa.cjs';
2
- export { L as LocaleStrategy, e as NavigationItem, O as OpenGraph, f as PageSeo, g as Robots, h as SiteSeo, T as Twitter } from './types-ecfDXrLa.cjs';
1
+ import { S as Site, R as ResolvedSeo, U as UrlSettings, a as Redirect, P as Page, b as PageRef, N as Navigation, c as Release, d as SitemapEntry } from './types-D5mwpqAP.cjs';
2
+ export { B as BreaseImage, e as BreaseLink, L as LocaleStrategy, f as NavigationItem, O as OpenGraph, g as PageSeo, h as Robots, i as SiteSeo, T as Twitter } from './types-D5mwpqAP.cjs';
3
3
 
4
4
  type Ga4Tag = {
5
5
  id: string;
@@ -10,6 +10,13 @@ declare function ga4Tag(site: Pick<Site, 'analytics'>): Ga4Tag | null;
10
10
  declare function ga4Html(site: Pick<Site, 'analytics'>): string;
11
11
  declare function grantAnalytics(granted?: boolean): void;
12
12
 
13
+ type CustomTag = {
14
+ tag: 'script' | 'style' | 'meta' | 'link' | 'noscript';
15
+ attrs: Record<string, string>;
16
+ content?: string;
17
+ };
18
+ declare function customTags(seo: Pick<ResolvedSeo, 'customHead' | 'customCode'>): CustomTag[];
19
+
13
20
  declare class BreaseError extends Error {
14
21
  code: string;
15
22
  status: number;
@@ -30,6 +37,14 @@ declare function localeLinks(context: LocaleContext): LocaleLink[];
30
37
  declare function nativeName(locale: string): string;
31
38
  declare const localeHref: (settings: UrlSettings, slug: string, locale: string) => string;
32
39
 
40
+ declare function fieldPath(path: string, pageId?: string): string;
41
+ declare function navPath(key: string): string;
42
+
43
+ declare function matchRedirect(redirects: Redirect[], pathname: string): {
44
+ destination: string;
45
+ status: Redirect['status'];
46
+ } | null;
47
+
33
48
  type BreaseSection<T = Record<string, unknown>> = {
34
49
  id: string;
35
50
  type: string;
@@ -49,6 +64,31 @@ type PageLocales = Record<string, Record<string, {
49
64
  }>>;
50
65
  declare function checkSections(files: Record<string, string>, pages?: PageLocales): string[];
51
66
 
67
+ type RevalidateBody = {
68
+ urls?: string[];
69
+ paths?: string[];
70
+ tags?: string[];
71
+ releaseId?: string;
72
+ siteId?: string;
73
+ };
74
+ declare function hmacHex(secret: string, message: string): Promise<string>;
75
+ declare function verifySignature(body: string, timestamp: string | null, signature: string | null, secret: string, now?: number): Promise<boolean>;
76
+ type RevalidateTarget = {
77
+ ok: true;
78
+ paths: string[];
79
+ tags: string[];
80
+ body: RevalidateBody;
81
+ } | {
82
+ ok: false;
83
+ reason: 'signature' | 'body';
84
+ };
85
+ declare function verifyRevalidate(req: {
86
+ text(): Promise<string>;
87
+ headers: {
88
+ get(name: string): string | null;
89
+ };
90
+ }, secret: string): Promise<RevalidateTarget>;
91
+
52
92
  type JsonLd = {
53
93
  data: Record<string, unknown>;
54
94
  json: string;
@@ -62,6 +102,7 @@ declare function resolvePath(settings: UrlSettings, pathname: string): {
62
102
  slug: string;
63
103
  locale: string;
64
104
  };
105
+ declare function canonicalPath(settings: UrlSettings, pathname: string): string | null;
65
106
 
66
107
  type LocaleContext = {
67
108
  locale: string;
@@ -84,6 +125,9 @@ interface Brease {
84
125
  }): Promise<Page<T> | null>;
85
126
  getPages(opts?: {
86
127
  locale?: string;
128
+ parentId?: string;
129
+ template?: string;
130
+ withContent?: boolean;
87
131
  }): Promise<PageRef[]>;
88
132
  getNavigation(key: string, opts: {
89
133
  locale: string;
@@ -106,4 +150,4 @@ interface Brease {
106
150
  }
107
151
  declare function createBrease(opts?: BreaseOptions): Brease;
108
152
 
109
- export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type Ga4Tag, type JsonLd, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, ResolvedSeo, Site, SitemapEntry, UrlSettings, buildPath, checkSections, createBrease, ga4Html, ga4Tag, grantAnalytics, jsonLd, jsonLdHtml, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath, sectionAttrs, sectionsAttrs };
153
+ export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type CustomTag, type Ga4Tag, type JsonLd, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, ResolvedSeo, type RevalidateBody, type RevalidateTarget, Site, SitemapEntry, UrlSettings, buildPath, canonicalPath, checkSections, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, jsonLd, jsonLdHtml, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, sectionAttrs, sectionsAttrs, verifyRevalidate, verifySignature };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as Site, U as UrlSettings, R as ResolvedSeo, P as Page, a as PageRef, N as Navigation, b as Redirect, c as Release, d as SitemapEntry } from './types-ecfDXrLa.js';
2
- export { L as LocaleStrategy, e as NavigationItem, O as OpenGraph, f as PageSeo, g as Robots, h as SiteSeo, T as Twitter } from './types-ecfDXrLa.js';
1
+ import { S as Site, R as ResolvedSeo, U as UrlSettings, a as Redirect, P as Page, b as PageRef, N as Navigation, c as Release, d as SitemapEntry } from './types-D5mwpqAP.js';
2
+ export { B as BreaseImage, e as BreaseLink, L as LocaleStrategy, f as NavigationItem, O as OpenGraph, g as PageSeo, h as Robots, i as SiteSeo, T as Twitter } from './types-D5mwpqAP.js';
3
3
 
4
4
  type Ga4Tag = {
5
5
  id: string;
@@ -10,6 +10,13 @@ declare function ga4Tag(site: Pick<Site, 'analytics'>): Ga4Tag | null;
10
10
  declare function ga4Html(site: Pick<Site, 'analytics'>): string;
11
11
  declare function grantAnalytics(granted?: boolean): void;
12
12
 
13
+ type CustomTag = {
14
+ tag: 'script' | 'style' | 'meta' | 'link' | 'noscript';
15
+ attrs: Record<string, string>;
16
+ content?: string;
17
+ };
18
+ declare function customTags(seo: Pick<ResolvedSeo, 'customHead' | 'customCode'>): CustomTag[];
19
+
13
20
  declare class BreaseError extends Error {
14
21
  code: string;
15
22
  status: number;
@@ -30,6 +37,14 @@ declare function localeLinks(context: LocaleContext): LocaleLink[];
30
37
  declare function nativeName(locale: string): string;
31
38
  declare const localeHref: (settings: UrlSettings, slug: string, locale: string) => string;
32
39
 
40
+ declare function fieldPath(path: string, pageId?: string): string;
41
+ declare function navPath(key: string): string;
42
+
43
+ declare function matchRedirect(redirects: Redirect[], pathname: string): {
44
+ destination: string;
45
+ status: Redirect['status'];
46
+ } | null;
47
+
33
48
  type BreaseSection<T = Record<string, unknown>> = {
34
49
  id: string;
35
50
  type: string;
@@ -49,6 +64,31 @@ type PageLocales = Record<string, Record<string, {
49
64
  }>>;
50
65
  declare function checkSections(files: Record<string, string>, pages?: PageLocales): string[];
51
66
 
67
+ type RevalidateBody = {
68
+ urls?: string[];
69
+ paths?: string[];
70
+ tags?: string[];
71
+ releaseId?: string;
72
+ siteId?: string;
73
+ };
74
+ declare function hmacHex(secret: string, message: string): Promise<string>;
75
+ declare function verifySignature(body: string, timestamp: string | null, signature: string | null, secret: string, now?: number): Promise<boolean>;
76
+ type RevalidateTarget = {
77
+ ok: true;
78
+ paths: string[];
79
+ tags: string[];
80
+ body: RevalidateBody;
81
+ } | {
82
+ ok: false;
83
+ reason: 'signature' | 'body';
84
+ };
85
+ declare function verifyRevalidate(req: {
86
+ text(): Promise<string>;
87
+ headers: {
88
+ get(name: string): string | null;
89
+ };
90
+ }, secret: string): Promise<RevalidateTarget>;
91
+
52
92
  type JsonLd = {
53
93
  data: Record<string, unknown>;
54
94
  json: string;
@@ -62,6 +102,7 @@ declare function resolvePath(settings: UrlSettings, pathname: string): {
62
102
  slug: string;
63
103
  locale: string;
64
104
  };
105
+ declare function canonicalPath(settings: UrlSettings, pathname: string): string | null;
65
106
 
66
107
  type LocaleContext = {
67
108
  locale: string;
@@ -84,6 +125,9 @@ interface Brease {
84
125
  }): Promise<Page<T> | null>;
85
126
  getPages(opts?: {
86
127
  locale?: string;
128
+ parentId?: string;
129
+ template?: string;
130
+ withContent?: boolean;
87
131
  }): Promise<PageRef[]>;
88
132
  getNavigation(key: string, opts: {
89
133
  locale: string;
@@ -106,4 +150,4 @@ interface Brease {
106
150
  }
107
151
  declare function createBrease(opts?: BreaseOptions): Brease;
108
152
 
109
- export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type Ga4Tag, type JsonLd, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, ResolvedSeo, Site, SitemapEntry, UrlSettings, buildPath, checkSections, createBrease, ga4Html, ga4Tag, grantAnalytics, jsonLd, jsonLdHtml, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath, sectionAttrs, sectionsAttrs };
153
+ export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type CustomTag, type Ga4Tag, type JsonLd, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, ResolvedSeo, type RevalidateBody, type RevalidateTarget, Site, SitemapEntry, UrlSettings, buildPath, canonicalPath, checkSections, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, jsonLd, jsonLdHtml, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, sectionAttrs, sectionsAttrs, verifyRevalidate, verifySignature };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { BreaseError, buildPath, createBrease, ga4Html, ga4Tag, grantAnalytics, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath } from './chunk-GJ3SOWDB.js';
1
+ export { BreaseError, buildPath, canonicalPath, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, verifyRevalidate, verifySignature } from './chunk-MWTYINWA.js';
2
2
  export { checkSections, sectionAttrs, sectionsAttrs } from './chunk-CQZLTZGN.js';
3
3
  export { jsonLd, jsonLdHtml } from './chunk-N3QOL5EU.js';
4
4
  import './chunk-PKBMQBKP.js';
package/dist/next.cjs CHANGED
@@ -67,6 +67,54 @@ function resolvePath(settings, pathname) {
67
67
  return { slug: clean, locale: settings.defaultLocale };
68
68
  }
69
69
 
70
+ // src/signature.ts
71
+ var MAX_SKEW_MS = 5 * 6e4;
72
+ async function hmacHex(secret, message) {
73
+ const enc = new TextEncoder();
74
+ const key = await crypto.subtle.importKey(
75
+ "raw",
76
+ enc.encode(secret),
77
+ { name: "HMAC", hash: "SHA-256" },
78
+ false,
79
+ ["sign"]
80
+ );
81
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(message)));
82
+ return Array.from(sig, (b) => b.toString(16).padStart(2, "0")).join("");
83
+ }
84
+ async function verifySignature(body, timestamp, signature, secret, now = Date.now()) {
85
+ if (!timestamp || !signature) return false;
86
+ if (!Number.isFinite(Number(timestamp)) || Math.abs(now - Number(timestamp)) > MAX_SKEW_MS) return false;
87
+ const expected = await hmacHex(secret, `${timestamp}.${body}`);
88
+ if (expected.length !== signature.length) return false;
89
+ let diff = 0;
90
+ for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
91
+ return diff === 0;
92
+ }
93
+ async function verifyRevalidate(req, secret) {
94
+ const raw = await req.text();
95
+ const ok = await verifySignature(
96
+ raw,
97
+ req.headers.get("x-brease-timestamp"),
98
+ req.headers.get("x-brease-signature"),
99
+ secret
100
+ );
101
+ if (!ok) return { ok: false, reason: "signature" };
102
+ let body;
103
+ try {
104
+ body = JSON.parse(raw || "{}");
105
+ } catch {
106
+ return { ok: false, reason: "body" };
107
+ }
108
+ const paths = new Set(body.paths ?? []);
109
+ for (const url of body.urls ?? []) {
110
+ try {
111
+ paths.add(new URL(url, "http://localhost").pathname);
112
+ } catch {
113
+ }
114
+ }
115
+ return { ok: true, paths: [...paths], tags: ["brease", ...body.tags ?? []], body };
116
+ }
117
+
70
118
  // src/index.ts
71
119
  var RETRY_AFTER_CAP_MS = 1e4;
72
120
  var SITE_TTL_MS = 6e4;
@@ -78,6 +126,7 @@ function createBrease(opts = {}) {
78
126
  const baseMs = opts.retryBaseMs ?? 300;
79
127
  const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
80
128
  let site;
129
+ let redirects;
81
130
  async function request(path, query = {}, nullOn404 = false) {
82
131
  const token = opts.token ?? env("BREASE_TOKEN");
83
132
  if (!token)
@@ -127,13 +176,26 @@ function createBrease(opts = {}) {
127
176
  return request("/content-api/page", { slug, locale }, true);
128
177
  },
129
178
  getPages(o = {}) {
130
- return request("/content-api/pages", { locale: o.locale });
179
+ return request("/content-api/pages", {
180
+ locale: o.locale,
181
+ parentId: o.parentId,
182
+ template: o.template,
183
+ withContent: o.withContent ? "1" : void 0
184
+ });
131
185
  },
132
186
  getNavigation(key, { locale }) {
133
187
  return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
134
188
  },
189
+ // Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
135
190
  getRedirects() {
136
- return request("/content-api/redirects");
191
+ if (!redirects || Date.now() - redirects.at > SITE_TTL_MS) {
192
+ const promise = request("/content-api/redirects").catch((err) => {
193
+ if (redirects?.promise === promise) redirects = void 0;
194
+ throw err;
195
+ });
196
+ redirects = { promise, at: Date.now() };
197
+ }
198
+ return redirects.promise;
137
199
  },
138
200
  getRelease() {
139
201
  return request("/content-api/release");
@@ -175,7 +237,9 @@ function createBrease(opts = {}) {
175
237
  },
176
238
  async sitemap(baseUrl) {
177
239
  const base = baseUrl.replace(/\/+$/, "");
178
- const refs = (await client.getPages()).filter((r) => !r.hidden);
240
+ const refs = (await client.getPages()).filter(
241
+ (r) => !r.hidden && r.index !== false && !r.slug.split("/").some((part) => part.startsWith("_"))
242
+ );
179
243
  const byPage = /* @__PURE__ */ new Map();
180
244
  for (const ref of refs) {
181
245
  const alternates = byPage.get(ref.pageId) ?? {};
@@ -230,61 +294,20 @@ function breaseFetch(tags = [], revalidate) {
230
294
  next: { tags: ["brease", ...tags], ...revalidate !== void 0 ? { revalidate } : {} }
231
295
  });
232
296
  }
233
- var MAX_SKEW_MS = 5 * 6e4;
234
297
  function revalidateHandler(secret) {
235
298
  return async (req) => {
236
299
  const key = secret ?? env("BREASE_REVALIDATE_SECRET");
237
300
  if (!key)
238
301
  return json(500, { error: { code: "internal", message: "BREASE_REVALIDATE_SECRET is not set" } });
239
- const raw = await req.text();
240
- const ok = await verifySignature(
241
- raw,
242
- req.headers.get("x-brease-timestamp"),
243
- req.headers.get("x-brease-signature"),
244
- key
245
- );
246
- if (!ok) return json(401, { error: { code: "unauthorized", message: "Invalid or expired signature" } });
247
- let body;
248
- try {
249
- body = JSON.parse(raw || "{}");
250
- } catch {
251
- return json(400, { error: { code: "validation", message: "Body must be JSON" } });
252
- }
253
- const paths = new Set(body.paths ?? []);
254
- for (const url of body.urls ?? []) {
255
- try {
256
- paths.add(new URL(url, "http://localhost").pathname);
257
- } catch {
258
- }
259
- }
260
- const tags = /* @__PURE__ */ new Set(["brease", ...body.tags ?? []]);
302
+ const target = await verifyRevalidate(req, key);
303
+ if (!target.ok)
304
+ return target.reason === "body" ? json(400, { error: { code: "validation", message: "Body must be JSON" } }) : json(401, { error: { code: "unauthorized", message: "Invalid or expired signature" } });
261
305
  const cache = await import('next/cache');
262
- for (const path of paths) cache.revalidatePath(path);
263
- for (const tag of tags) cache.revalidateTag(tag, "max");
264
- return json(200, { revalidated: true, paths: [...paths], tags: [...tags] });
306
+ for (const path of target.paths) cache.revalidatePath(path);
307
+ for (const tag of target.tags) cache.revalidateTag(tag, { expire: 0 });
308
+ return json(200, { revalidated: true, paths: target.paths, tags: target.tags });
265
309
  };
266
310
  }
267
- async function verifySignature(body, timestamp, signature, secret, now = Date.now()) {
268
- if (!timestamp || !signature) return false;
269
- if (!Number.isFinite(Number(timestamp)) || Math.abs(now - Number(timestamp)) > MAX_SKEW_MS) return false;
270
- const expected = await hmacHex(secret, `${timestamp}.${body}`);
271
- if (expected.length !== signature.length) return false;
272
- let diff = 0;
273
- for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
274
- return diff === 0;
275
- }
276
- async function hmacHex(secret, message) {
277
- const enc = new TextEncoder();
278
- const key = await crypto.subtle.importKey(
279
- "raw",
280
- enc.encode(secret),
281
- { name: "HMAC", hash: "SHA-256" },
282
- false,
283
- ["sign"]
284
- );
285
- const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(message)));
286
- return Array.from(sig, (b) => b.toString(16).padStart(2, "0")).join("");
287
- }
288
311
  function json(status, data) {
289
312
  return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
290
313
  }
package/dist/next.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Brease } from './index.cjs';
2
- import { R as ResolvedSeo } from './types-ecfDXrLa.cjs';
2
+ export { hmacHex, verifySignature } from './index.cjs';
3
+ import { R as ResolvedSeo } from './types-D5mwpqAP.cjs';
3
4
 
4
5
  type BreaseMetadata = {
5
6
  title: {
@@ -42,12 +43,10 @@ declare function toMetadata(seo: ResolvedSeo, opts?: {
42
43
  }): BreaseMetadata;
43
44
  declare function breaseFetch(tags?: string[], revalidate?: number | false): typeof fetch;
44
45
  declare function revalidateHandler(secret?: string): (req: Request) => Promise<Response>;
45
- declare function verifySignature(body: string, timestamp: string | null, signature: string | null, secret: string, now?: number): Promise<boolean>;
46
- declare function hmacHex(secret: string, message: string): Promise<string>;
47
46
  declare function breaseRedirects(client?: Pick<Brease, 'getRedirects'>): () => Promise<{
48
47
  source: string;
49
48
  destination: string;
50
49
  statusCode: 301 | 302 | 307 | 308;
51
50
  }[]>;
52
51
 
53
- export { type BreaseMetadata, breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
52
+ export { type BreaseMetadata, breaseFetch, breaseRedirects, revalidateHandler, toMetadata };
package/dist/next.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Brease } from './index.js';
2
- import { R as ResolvedSeo } from './types-ecfDXrLa.js';
2
+ export { hmacHex, verifySignature } from './index.js';
3
+ import { R as ResolvedSeo } from './types-D5mwpqAP.js';
3
4
 
4
5
  type BreaseMetadata = {
5
6
  title: {
@@ -42,12 +43,10 @@ declare function toMetadata(seo: ResolvedSeo, opts?: {
42
43
  }): BreaseMetadata;
43
44
  declare function breaseFetch(tags?: string[], revalidate?: number | false): typeof fetch;
44
45
  declare function revalidateHandler(secret?: string): (req: Request) => Promise<Response>;
45
- declare function verifySignature(body: string, timestamp: string | null, signature: string | null, secret: string, now?: number): Promise<boolean>;
46
- declare function hmacHex(secret: string, message: string): Promise<string>;
47
46
  declare function breaseRedirects(client?: Pick<Brease, 'getRedirects'>): () => Promise<{
48
47
  source: string;
49
48
  destination: string;
50
49
  statusCode: 301 | 302 | 307 | 308;
51
50
  }[]>;
52
51
 
53
- export { type BreaseMetadata, breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
52
+ export { type BreaseMetadata, breaseFetch, breaseRedirects, revalidateHandler, toMetadata };