brease-client 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -100,6 +100,29 @@ function grantAnalytics(granted = true) {
100
100
  gtag?.("consent", "update", { analytics_storage: granted ? "granted" : "denied" });
101
101
  }
102
102
 
103
+ // src/custom-code.ts
104
+ function customTags(seo) {
105
+ return [seo.customHead, seo.customCode].flatMap((html) => html ? parseTags(html) : []);
106
+ }
107
+ function parseTags(html) {
108
+ const out = [];
109
+ const re = /<(script|style|noscript)\b([^>]*)>([\s\S]*?)<\/\1\s*>|<(meta|link)\b([^>]*?)\/?>/gi;
110
+ for (const m of html.matchAll(re)) {
111
+ if (m[1]) {
112
+ const tag = m[1].toLowerCase();
113
+ out.push({ tag, attrs: attrsOf(m[2] ?? ""), ...m[3]?.trim() ? { content: m[3] } : {} });
114
+ } else if (m[4])
115
+ out.push({ tag: m[4].toLowerCase(), attrs: attrsOf(m[5] ?? "") });
116
+ }
117
+ return out;
118
+ }
119
+ function attrsOf(source) {
120
+ const attrs = {};
121
+ for (const m of source.matchAll(/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g))
122
+ attrs[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? "";
123
+ return attrs;
124
+ }
125
+
103
126
  // src/locales.ts
104
127
  function localeLinks(context) {
105
128
  const { settings, alternates, homes, locale: current } = context;
@@ -118,6 +141,50 @@ function nativeName(locale) {
118
141
  }
119
142
  var localeHref = (settings, slug, locale) => buildPath(settings, slug, locale);
120
143
 
144
+ // src/markers.ts
145
+ function fieldPath(path, pageId) {
146
+ return pageId ? `${pageId}:${path}` : path;
147
+ }
148
+ function navPath(key) {
149
+ return `nav:${key}`;
150
+ }
151
+
152
+ // src/redirects.ts
153
+ function matchRedirect(redirects, pathname) {
154
+ const path = normalize(pathname);
155
+ for (const r of redirects) {
156
+ const params = matchSource(normalize(r.source), path);
157
+ if (!params) continue;
158
+ const destination = r.destination.replace(
159
+ /:([A-Za-z_][A-Za-z0-9_]*)\*?/g,
160
+ (whole, name) => name in params ? params[name] : whole
161
+ );
162
+ if (normalize(destination) === path) continue;
163
+ return { destination, status: r.status };
164
+ }
165
+ return null;
166
+ }
167
+ var normalize = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p) || "/";
168
+ function matchSource(source, path) {
169
+ const want = source.split("/").filter(Boolean);
170
+ const have = path.split("/").filter(Boolean);
171
+ const params = {};
172
+ for (let i = 0; i < want.length; i++) {
173
+ const seg = want[i];
174
+ const rest = /^:([A-Za-z_][A-Za-z0-9_]*)\*$/.exec(seg);
175
+ if (rest) {
176
+ params[rest[1]] = have.slice(i).join("/");
177
+ return params;
178
+ }
179
+ const value = have[i];
180
+ if (value === void 0) return null;
181
+ const param = /^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(seg);
182
+ if (param) params[param[1]] = value;
183
+ else if (decodeURIComponent(value) !== decodeURIComponent(seg)) return null;
184
+ }
185
+ return want.length === have.length ? params : null;
186
+ }
187
+
121
188
  // src/sections.ts
122
189
  var sectionsAttrs = { "data-brease-sections": "sections" };
123
190
  function sectionAttrs(section) {
@@ -196,6 +263,63 @@ function checkSections(files, pages = {}) {
196
263
  return warnings;
197
264
  }
198
265
 
266
+ // src/signature.ts
267
+ var MAX_SKEW_MS = 5 * 6e4;
268
+ async function hmacHex(secret, message) {
269
+ const enc = new TextEncoder();
270
+ const key = await crypto.subtle.importKey(
271
+ "raw",
272
+ enc.encode(secret),
273
+ { name: "HMAC", hash: "SHA-256" },
274
+ false,
275
+ ["sign"]
276
+ );
277
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(message)));
278
+ return Array.from(sig, (b) => b.toString(16).padStart(2, "0")).join("");
279
+ }
280
+ async function verifySignature(body, timestamp, signature, secret, now = Date.now()) {
281
+ if (!timestamp || !signature) return false;
282
+ if (!Number.isFinite(Number(timestamp)) || Math.abs(now - Number(timestamp)) > MAX_SKEW_MS) return false;
283
+ const expected = await hmacHex(secret, `${timestamp}.${body}`);
284
+ if (expected.length !== signature.length) return false;
285
+ let diff = 0;
286
+ for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
287
+ return diff === 0;
288
+ }
289
+ async function verifyRevalidate(req, secret) {
290
+ const raw = await req.text();
291
+ const ok = await verifySignature(
292
+ raw,
293
+ req.headers.get("x-brease-timestamp"),
294
+ req.headers.get("x-brease-signature"),
295
+ secret
296
+ );
297
+ if (!ok) return { ok: false, reason: "signature" };
298
+ let body;
299
+ try {
300
+ body = JSON.parse(raw || "{}");
301
+ } catch {
302
+ return { ok: false, reason: "body" };
303
+ }
304
+ const paths = new Set(body.paths ?? []);
305
+ for (const url of body.urls ?? []) {
306
+ try {
307
+ paths.add(new URL(url, "http://localhost").pathname);
308
+ } catch {
309
+ }
310
+ }
311
+ return { ok: true, paths: [...paths], tags: ["brease", ...body.tags ?? []], body };
312
+ }
313
+
314
+ // src/structured-data.ts
315
+ var jsonLdText = (data) => JSON.stringify(data).replace(/</g, "\\u003c");
316
+ function jsonLd(seo) {
317
+ return (seo.structuredData ?? []).map((data) => ({ data, json: jsonLdText(data) }));
318
+ }
319
+ function jsonLdHtml(seo) {
320
+ return jsonLd(seo).map((d) => `<script type="application/ld+json">${d.json}</script>`).join("\n");
321
+ }
322
+
199
323
  // src/index.ts
200
324
  var RETRY_AFTER_CAP_MS = 1e4;
201
325
  var SITE_TTL_MS = 6e4;
@@ -207,6 +331,7 @@ function createBrease(opts = {}) {
207
331
  const baseMs = opts.retryBaseMs ?? 300;
208
332
  const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
209
333
  let site;
334
+ let redirects;
210
335
  async function request(path, query = {}, nullOn404 = false) {
211
336
  const token = opts.token ?? env("BREASE_TOKEN");
212
337
  if (!token)
@@ -261,8 +386,16 @@ function createBrease(opts = {}) {
261
386
  getNavigation(key, { locale }) {
262
387
  return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
263
388
  },
389
+ // Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
264
390
  getRedirects() {
265
- return request("/content-api/redirects");
391
+ if (!redirects || Date.now() - redirects.at > SITE_TTL_MS) {
392
+ const promise = request("/content-api/redirects").catch((err) => {
393
+ if (redirects?.promise === promise) redirects = void 0;
394
+ throw err;
395
+ });
396
+ redirects = { promise, at: Date.now() };
397
+ }
398
+ return redirects.promise;
266
399
  },
267
400
  getRelease() {
268
401
  return request("/content-api/release");
@@ -304,7 +437,9 @@ function createBrease(opts = {}) {
304
437
  },
305
438
  async sitemap(baseUrl) {
306
439
  const base = baseUrl.replace(/\/+$/, "");
307
- const refs = (await client.getPages()).filter((r) => !r.hidden);
440
+ const refs = (await client.getPages()).filter(
441
+ (r) => !r.hidden && r.index !== false && !r.slug.split("/").some((part) => part.startsWith("_"))
442
+ );
308
443
  const byPage = /* @__PURE__ */ new Map();
309
444
  for (const ref of refs) {
310
445
  const alternates = byPage.get(ref.pageId) ?? {};
@@ -328,13 +463,22 @@ exports.BreaseError = BreaseError;
328
463
  exports.buildPath = buildPath;
329
464
  exports.checkSections = checkSections;
330
465
  exports.createBrease = createBrease;
466
+ exports.customTags = customTags;
467
+ exports.fieldPath = fieldPath;
331
468
  exports.ga4Html = ga4Html;
332
469
  exports.ga4Tag = ga4Tag;
333
470
  exports.grantAnalytics = grantAnalytics;
471
+ exports.hmacHex = hmacHex;
472
+ exports.jsonLd = jsonLd;
473
+ exports.jsonLdHtml = jsonLdHtml;
334
474
  exports.localeHref = localeHref;
335
475
  exports.localeLinks = localeLinks;
476
+ exports.matchRedirect = matchRedirect;
336
477
  exports.nativeName = nativeName;
478
+ exports.navPath = navPath;
337
479
  exports.normalizeSlug = normalizeSlug;
338
480
  exports.resolvePath = resolvePath;
339
481
  exports.sectionAttrs = sectionAttrs;
340
482
  exports.sectionsAttrs = sectionsAttrs;
483
+ exports.verifyRevalidate = verifyRevalidate;
484
+ exports.verifySignature = verifySignature;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as Site, U as UrlSettings, 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, R as ResolvedSeo, 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-DeS_3KtO.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-DeS_3KtO.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,38 @@ 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
+
92
+ type JsonLd = {
93
+ data: Record<string, unknown>;
94
+ json: string;
95
+ };
96
+ declare function jsonLd(seo: Pick<ResolvedSeo, 'structuredData'>): JsonLd[];
97
+ declare function jsonLdHtml(seo: Pick<ResolvedSeo, 'structuredData'>): string;
98
+
52
99
  declare function normalizeSlug(input: string): string;
53
100
  declare function buildPath(settings: UrlSettings, slug: string, locale: string): string;
54
101
  declare function resolvePath(settings: UrlSettings, pathname: string): {
@@ -99,4 +146,4 @@ interface Brease {
99
146
  }
100
147
  declare function createBrease(opts?: BreaseOptions): Brease;
101
148
 
102
- export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type Ga4Tag, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, checkSections, createBrease, ga4Html, ga4Tag, grantAnalytics, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath, sectionAttrs, sectionsAttrs };
149
+ 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, 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, 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, R as ResolvedSeo, 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-DeS_3KtO.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-DeS_3KtO.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,38 @@ 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
+
92
+ type JsonLd = {
93
+ data: Record<string, unknown>;
94
+ json: string;
95
+ };
96
+ declare function jsonLd(seo: Pick<ResolvedSeo, 'structuredData'>): JsonLd[];
97
+ declare function jsonLdHtml(seo: Pick<ResolvedSeo, 'structuredData'>): string;
98
+
52
99
  declare function normalizeSlug(input: string): string;
53
100
  declare function buildPath(settings: UrlSettings, slug: string, locale: string): string;
54
101
  declare function resolvePath(settings: UrlSettings, pathname: string): {
@@ -99,4 +146,4 @@ interface Brease {
99
146
  }
100
147
  declare function createBrease(opts?: BreaseOptions): Brease;
101
148
 
102
- export { type Brease, BreaseError, type BreaseOptions, type BreaseSection, type Ga4Tag, type LocaleContext, type LocaleLink, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, checkSections, createBrease, ga4Html, ga4Tag, grantAnalytics, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath, sectionAttrs, sectionsAttrs };
149
+ 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, 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,3 +1,4 @@
1
- export { BreaseError, buildPath, createBrease, ga4Html, ga4Tag, grantAnalytics, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath } from './chunk-7BBL2LET.js';
1
+ export { BreaseError, buildPath, createBrease, customTags, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, verifyRevalidate, verifySignature } from './chunk-SO4BD4ME.js';
2
2
  export { checkSections, sectionAttrs, sectionsAttrs } from './chunk-CQZLTZGN.js';
3
+ export { jsonLd, jsonLdHtml } from './chunk-N3QOL5EU.js';
3
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)
@@ -132,8 +181,16 @@ function createBrease(opts = {}) {
132
181
  getNavigation(key, { locale }) {
133
182
  return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
134
183
  },
184
+ // Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
135
185
  getRedirects() {
136
- return request("/content-api/redirects");
186
+ if (!redirects || Date.now() - redirects.at > SITE_TTL_MS) {
187
+ const promise = request("/content-api/redirects").catch((err) => {
188
+ if (redirects?.promise === promise) redirects = void 0;
189
+ throw err;
190
+ });
191
+ redirects = { promise, at: Date.now() };
192
+ }
193
+ return redirects.promise;
137
194
  },
138
195
  getRelease() {
139
196
  return request("/content-api/release");
@@ -175,7 +232,9 @@ function createBrease(opts = {}) {
175
232
  },
176
233
  async sitemap(baseUrl) {
177
234
  const base = baseUrl.replace(/\/+$/, "");
178
- const refs = (await client.getPages()).filter((r) => !r.hidden);
235
+ const refs = (await client.getPages()).filter(
236
+ (r) => !r.hidden && r.index !== false && !r.slug.split("/").some((part) => part.startsWith("_"))
237
+ );
179
238
  const byPage = /* @__PURE__ */ new Map();
180
239
  for (const ref of refs) {
181
240
  const alternates = byPage.get(ref.pageId) ?? {};
@@ -230,61 +289,20 @@ function breaseFetch(tags = [], revalidate) {
230
289
  next: { tags: ["brease", ...tags], ...revalidate !== void 0 ? { revalidate } : {} }
231
290
  });
232
291
  }
233
- var MAX_SKEW_MS = 5 * 6e4;
234
292
  function revalidateHandler(secret) {
235
293
  return async (req) => {
236
294
  const key = secret ?? env("BREASE_REVALIDATE_SECRET");
237
295
  if (!key)
238
296
  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 ?? []]);
297
+ const target = await verifyRevalidate(req, key);
298
+ if (!target.ok)
299
+ 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
300
  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] });
301
+ for (const path of target.paths) cache.revalidatePath(path);
302
+ for (const tag of target.tags) cache.revalidateTag(tag, { expire: 0 });
303
+ return json(200, { revalidated: true, paths: target.paths, tags: target.tags });
265
304
  };
266
305
  }
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
306
  function json(status, data) {
289
307
  return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
290
308
  }
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-DeS_3KtO.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-DeS_3KtO.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 };
package/dist/next.js CHANGED
@@ -1,5 +1,7 @@
1
- import { env, createBrease } from './chunk-7BBL2LET.js';
1
+ import { env, verifyRevalidate, createBrease } from './chunk-SO4BD4ME.js';
2
+ export { hmacHex, verifySignature } from './chunk-SO4BD4ME.js';
2
3
  import './chunk-CQZLTZGN.js';
4
+ import './chunk-N3QOL5EU.js';
3
5
  import './chunk-PKBMQBKP.js';
4
6
 
5
7
  // src/next.ts
@@ -37,61 +39,20 @@ function breaseFetch(tags = [], revalidate) {
37
39
  next: { tags: ["brease", ...tags], ...revalidate !== void 0 ? { revalidate } : {} }
38
40
  });
39
41
  }
40
- var MAX_SKEW_MS = 5 * 6e4;
41
42
  function revalidateHandler(secret) {
42
43
  return async (req) => {
43
44
  const key = secret ?? env("BREASE_REVALIDATE_SECRET");
44
45
  if (!key)
45
46
  return json(500, { error: { code: "internal", message: "BREASE_REVALIDATE_SECRET is not set" } });
46
- const raw = await req.text();
47
- const ok = await verifySignature(
48
- raw,
49
- req.headers.get("x-brease-timestamp"),
50
- req.headers.get("x-brease-signature"),
51
- key
52
- );
53
- if (!ok) return json(401, { error: { code: "unauthorized", message: "Invalid or expired signature" } });
54
- let body;
55
- try {
56
- body = JSON.parse(raw || "{}");
57
- } catch {
58
- return json(400, { error: { code: "validation", message: "Body must be JSON" } });
59
- }
60
- const paths = new Set(body.paths ?? []);
61
- for (const url of body.urls ?? []) {
62
- try {
63
- paths.add(new URL(url, "http://localhost").pathname);
64
- } catch {
65
- }
66
- }
67
- const tags = /* @__PURE__ */ new Set(["brease", ...body.tags ?? []]);
47
+ const target = await verifyRevalidate(req, key);
48
+ if (!target.ok)
49
+ return target.reason === "body" ? json(400, { error: { code: "validation", message: "Body must be JSON" } }) : json(401, { error: { code: "unauthorized", message: "Invalid or expired signature" } });
68
50
  const cache = await import('next/cache');
69
- for (const path of paths) cache.revalidatePath(path);
70
- for (const tag of tags) cache.revalidateTag(tag, "max");
71
- return json(200, { revalidated: true, paths: [...paths], tags: [...tags] });
51
+ for (const path of target.paths) cache.revalidatePath(path);
52
+ for (const tag of target.tags) cache.revalidateTag(tag, { expire: 0 });
53
+ return json(200, { revalidated: true, paths: target.paths, tags: target.tags });
72
54
  };
73
55
  }
74
- async function verifySignature(body, timestamp, signature, secret, now = Date.now()) {
75
- if (!timestamp || !signature) return false;
76
- if (!Number.isFinite(Number(timestamp)) || Math.abs(now - Number(timestamp)) > MAX_SKEW_MS) return false;
77
- const expected = await hmacHex(secret, `${timestamp}.${body}`);
78
- if (expected.length !== signature.length) return false;
79
- let diff = 0;
80
- for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
81
- return diff === 0;
82
- }
83
- async function hmacHex(secret, message) {
84
- const enc = new TextEncoder();
85
- const key = await crypto.subtle.importKey(
86
- "raw",
87
- enc.encode(secret),
88
- { name: "HMAC", hash: "SHA-256" },
89
- false,
90
- ["sign"]
91
- );
92
- const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(message)));
93
- return Array.from(sig, (b) => b.toString(16).padStart(2, "0")).join("");
94
- }
95
56
  function json(status, data) {
96
57
  return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
97
58
  }
@@ -107,4 +68,4 @@ function breaseRedirects(client = createBrease()) {
107
68
  };
108
69
  }
109
70
 
110
- export { breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
71
+ export { breaseFetch, breaseRedirects, revalidateHandler, toMetadata };