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/README.md +92 -27
- package/dist/astro.d.cts +1 -1
- package/dist/astro.d.ts +1 -1
- package/dist/{chunk-GJ3SOWDB.js → chunk-MWTYINWA.js} +142 -4
- package/dist/html.d.cts +1 -1
- package/dist/html.d.ts +1 -1
- package/dist/image.cjs +8 -2
- package/dist/image.d.cts +6 -1
- package/dist/image.d.ts +6 -1
- package/dist/image.js +8 -2
- package/dist/index.cjs +149 -3
- package/dist/index.d.cts +47 -3
- package/dist/index.d.ts +47 -3
- package/dist/index.js +1 -1
- package/dist/next.cjs +73 -50
- package/dist/next.d.cts +3 -4
- package/dist/next.d.ts +3 -4
- package/dist/next.js +9 -49
- package/dist/{types-ecfDXrLa.d.cts → types-D5mwpqAP.d.cts} +31 -3
- package/dist/{types-ecfDXrLa.d.ts → types-D5mwpqAP.d.ts} +31 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Typed client for the Brease delivery API. Zero runtime dependencies, ESM + CJS,
|
|
|
6
6
|
pnpm add brease-client
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
Set
|
|
9
|
+
Set these environment variables (Brease writes them into your Vercel project at onboarding):
|
|
10
10
|
|
|
11
11
|
| Variable | Purpose |
|
|
12
12
|
| --- | --- |
|
|
@@ -26,22 +26,27 @@ const brease = createBrease({
|
|
|
26
26
|
fetch // optional custom fetch, e.g. to add framework cache options
|
|
27
27
|
})
|
|
28
28
|
|
|
29
|
-
await brease.getSite() // name, locales, defaultLocale, localeStrategy, global SEO
|
|
29
|
+
await brease.getSite() // name, url (the public address), locales, defaultLocale, localeStrategy, global SEO, analytics
|
|
30
30
|
await brease.getPage<Home>('', { locale: 'en' }) // Page<Home> | null ('' is the home page)
|
|
31
|
-
await brease.getPages({ locale: 'en' }) // [{ pageId, locale, slug, url, hidden }]
|
|
31
|
+
await brease.getPages({ locale: 'en' }) // [{ pageId, locale, slug, url, hidden, name, index, parentId, order, template }]
|
|
32
|
+
await brease.getPages({ locale: 'en', parentId: news.pageId, withContent: true }) // a news list, with each page's content
|
|
32
33
|
await brease.getNavigation('main', { locale: 'en' }) // { key, locale, items } | null
|
|
33
|
-
await brease.getRedirects() // [{ source, destination, status }]
|
|
34
|
+
await brease.getRedirects() // [{ source, destination, status }], cached for a minute
|
|
34
35
|
await brease.resolve('/en/about') // { slug: 'about', locale: 'en' } | null
|
|
35
36
|
await brease.route(['en', 'about']) // the same from catch-all path segments; null for shared "_" pages
|
|
36
37
|
await brease.routes() // [{ path: ['en', 'about'] }, …]: static params for every published page
|
|
37
38
|
await brease.localeContext(['en', 'about']) // { locale, settings, alternates, homes } for BreaseLocaleProvider
|
|
38
|
-
await brease.sitemap(
|
|
39
|
+
await brease.sitemap(site.url) // [{ url, alternates }]: pages search may show
|
|
39
40
|
```
|
|
40
41
|
|
|
41
42
|
- `null` means 404. Every other failure throws a `BreaseError` with `status`, `code`, `requestId` and `details`.
|
|
42
43
|
- 429 and 5xx responses (and network errors) are retried twice with backoff; `Retry-After` is honoured.
|
|
43
44
|
- Commit pinning: the `x-brease-commit` header is sent from `VERCEL_GIT_COMMIT_SHA`, so every deployment reads the content release that was built and tested with its code.
|
|
44
|
-
- `sitemap()` has no `lastModified`: releases are immutable snapshots and do not track per-page edit times.
|
|
45
|
+
- `sitemap()` lists only pages search may show: not hidden, not kept out of search (`index: false`, the page's "Show in search results" switch), and no site-wide `_` pages. It has no `lastModified`: releases are immutable snapshots and do not track per-page edit times.
|
|
46
|
+
- `getPages({ parentId, template, withContent })` narrows the list to a page's children or one template, and with
|
|
47
|
+
`withContent` adds each page's content (one locale, hidden pages left out, up to 100 pages): build news, team or
|
|
48
|
+
job lists from it instead of fetching every page.
|
|
49
|
+
- `site.url` is the site's public address (its primary domain), the one Brease uses in canonical URLs and hreflang; use it for the sitemap and `metadataBase` rather than an env variable of your own.
|
|
45
50
|
- `getSite()` is cached for a minute, so a locale added in Brease is served without a restart.
|
|
46
51
|
- `buildPath(settings, slug, locale)` and `resolvePath(settings, pathname)` are exported for routing code that already has the site settings.
|
|
47
52
|
|
|
@@ -72,8 +77,7 @@ async function load(params: Props['params']) {
|
|
|
72
77
|
}
|
|
73
78
|
|
|
74
79
|
export async function generateStaticParams() {
|
|
75
|
-
|
|
76
|
-
return pages.filter((p) => !p.hidden).map((p) => ({ slug: p.url.split('/').filter(Boolean) }))
|
|
80
|
+
return (await brease.routes()).map((r) => ({ slug: r.path })) // published pages, without site-wide "_" pages
|
|
77
81
|
}
|
|
78
82
|
|
|
79
83
|
export async function generateMetadata({ params }: Props) {
|
|
@@ -88,29 +92,59 @@ export default async function Page({ params }: Props) {
|
|
|
88
92
|
}
|
|
89
93
|
```
|
|
90
94
|
|
|
95
|
+
`page.resolvedSeo` is final: the title already has the site's title template applied (unless the page chose to show
|
|
96
|
+
its title as written), and every field falls back to the site's defaults. Render it as is; don't add your own
|
|
97
|
+
template or a home-page exception in code.
|
|
98
|
+
|
|
91
99
|
```ts
|
|
92
|
-
// app/api/revalidate/route.ts
|
|
100
|
+
// app/api/brease/revalidate/route.ts: the path Brease calls after a content release
|
|
93
101
|
import { revalidateHandler } from 'brease-client/next'
|
|
94
102
|
|
|
95
|
-
export const POST = revalidateHandler() // uses BREASE_REVALIDATE_SECRET
|
|
103
|
+
export const POST = revalidateHandler() // uses BREASE_REVALIDATE_SECRET; refreshes at once
|
|
96
104
|
```
|
|
97
105
|
|
|
106
|
+
Other frameworks: `verifyRevalidate(request, secret)` (root export) checks the signature and returns the paths and
|
|
107
|
+
cache tags to refresh, or why not (401 for a bad signature, 400 for a bad body).
|
|
108
|
+
|
|
109
|
+
Redirects managed in Brease apply per request, so a new one works as soon as it's published (within a minute), with
|
|
110
|
+
no rebuild:
|
|
111
|
+
|
|
98
112
|
```ts
|
|
99
|
-
//
|
|
100
|
-
import {
|
|
113
|
+
// proxy.ts (middleware.ts before Next 16)
|
|
114
|
+
import { type NextRequest, NextResponse } from 'next/server'
|
|
115
|
+
import { matchRedirect } from 'brease-client'
|
|
116
|
+
import { brease } from '@/lib/brease'
|
|
101
117
|
|
|
102
|
-
export
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
return redirects.map((r) => ({ source: r.source, destination: r.destination, permanent: r.status === 301 || r.status === 308 }))
|
|
106
|
-
}
|
|
118
|
+
export async function proxy(req: NextRequest) {
|
|
119
|
+
const hit = matchRedirect(await brease.getRedirects().catch(() => []), req.nextUrl.pathname)
|
|
120
|
+
return hit ? NextResponse.redirect(new URL(hit.destination, req.url), hit.status) : NextResponse.next()
|
|
107
121
|
}
|
|
122
|
+
|
|
123
|
+
export const config = { matcher: ['/((?!_next|api|.*\\..*).*)'] }
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Sources may use parameters as in Next's redirects (`/blog/:slug`, `/docs/:rest*`). `breaseRedirects()` (from
|
|
127
|
+
`brease-client/next`, for `next.config`) still works, but only reads redirects at build time.
|
|
128
|
+
|
|
129
|
+
`route()` also resolves other forms of a page's URL (`/en/about` where English has no prefix, `/about` where every
|
|
130
|
+
locale is prefixed); `resolvedSeo.canonical` points search engines at the real one. To redirect those forms too,
|
|
131
|
+
add this to the same proxy, before `NextResponse.next()`:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { canonicalPath } from 'brease-client'
|
|
135
|
+
|
|
136
|
+
const site = await brease.getSite()
|
|
137
|
+
const canonical = canonicalPath(site, req.nextUrl.pathname)
|
|
138
|
+
if (canonical && (await brease.getPages()).some((p) => p.url === canonical))
|
|
139
|
+
return NextResponse.redirect(new URL(canonical + req.nextUrl.search, req.url), 308)
|
|
108
140
|
```
|
|
109
141
|
|
|
110
142
|
### Structured data (JSON-LD)
|
|
111
143
|
|
|
112
|
-
|
|
113
|
-
|
|
144
|
+
Structured data is content: the page's own entries (its SEO in Brease) and the site's (site SEO) come together in
|
|
145
|
+
`page.resolvedSeo.structuredData`. `toMetadata` can't output scripts, so render them with `jsonLd` (framework-free,
|
|
146
|
+
from the root export) on every page; each item's `json` is escaped for use inside a script tag. Entities your code
|
|
147
|
+
already emits shouldn't be added in Brease too.
|
|
114
148
|
|
|
115
149
|
```tsx
|
|
116
150
|
import { jsonLd } from 'brease-client'
|
|
@@ -122,6 +156,23 @@ import { jsonLd } from 'brease-client'
|
|
|
122
156
|
|
|
123
157
|
`headTags` (HTML) and `breaseHead` (Astro) already include it; `jsonLdHtml(seo)` gives only the scripts.
|
|
124
158
|
|
|
159
|
+
### Custom code
|
|
160
|
+
|
|
161
|
+
Site-wide head code and a page's own code (both from SEO settings in Brease) run on the live site only when the site
|
|
162
|
+
renders them. `toMetadata` can't, so render `customTags(page.resolvedSeo)` (root export) as real elements:
|
|
163
|
+
|
|
164
|
+
```tsx
|
|
165
|
+
import { customTags } from 'brease-client'
|
|
166
|
+
|
|
167
|
+
{customTags(page.resolvedSeo).map(({ tag: Tag, attrs, content }, i) => {
|
|
168
|
+
const props = Object.fromEntries(Object.entries(attrs).map(([k, v]) => [k, v === '' ? true : v]))
|
|
169
|
+
return content ? <Tag key={i} {...props} dangerouslySetInnerHTML={{ __html: content }} /> : <Tag key={i} {...props} />
|
|
170
|
+
})}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Only `script`, `style`, `meta`, `link` and `noscript` tags are kept. `headTags` (HTML) and `breaseHead` (Astro)
|
|
174
|
+
include the code already.
|
|
175
|
+
|
|
125
176
|
### Google Analytics (GA4)
|
|
126
177
|
|
|
127
178
|
When GA4 is linked in Brease (Connections → Google) with "Add the tag to the site" on, the site response carries
|
|
@@ -244,7 +295,7 @@ A locale switcher is then a few lines in any framework: a list of `<a href={l.hr
|
|
|
244
295
|
- Everything that read a fixed locale (`getPage(…, { locale: 'hu' })`, `getNavigation`, `site.seo.hu`) takes it from the route instead.
|
|
245
296
|
- Links inside content are already locale URLs. Build other internal links with `localeHref(settings, slug, locale)`.
|
|
246
297
|
- Text written into components (button labels, captions) stays as it is; moving it into Brease content is a separate change.
|
|
247
|
-
- `
|
|
298
|
+
- `proxy.ts`: `matchRedirect(await brease.getRedirects(), pathname)` applies the redirects managed in Brease per request (see above).
|
|
248
299
|
|
|
249
300
|
### Revalidation signature
|
|
250
301
|
|
|
@@ -289,13 +340,17 @@ const html = `<head>${headTags(page.resolvedSeo, { xDefault: 'https://example.co
|
|
|
289
340
|
|
|
290
341
|
The Brease editor's Edit tool finds content through `data-brease` attributes:
|
|
291
342
|
|
|
292
|
-
- `data-brease=
|
|
293
|
-
- `data-brease=
|
|
294
|
-
- `data-brease
|
|
343
|
+
- `data-brease={fieldPath('hero.title')}` on an element that renders a field of the page being shown (a path into `page.content`, e.g. `hero.title` or `sections.2.items.0.label`)
|
|
344
|
+
- `data-brease={fieldPath('footer.copyright', global.pageId)}` for a field of another page, such as site-wide content (`_global`): the path is prefixed with that page's id (`<pageId>:footer.copyright`). Take the id from the page you fetched, never a fixed one.
|
|
345
|
+
- `data-brease={navPath('footer')}` (`nav:footer`) on the element that wraps a navigation menu; clicking it opens that navigation's editor
|
|
346
|
+
- `data-brease-block`: a section root carries its section type (`{section.type}`); other blocks (header, footer, a hero outside the sections list) carry their component name. A hint for the AI.
|
|
295
347
|
- `data-brease-sections="sections"` and `data-brease-section="<id>"`: the section list and its sections (see Sections)
|
|
296
348
|
|
|
297
349
|
```tsx
|
|
298
|
-
|
|
350
|
+
import { fieldPath, navPath } from 'brease-client'
|
|
351
|
+
|
|
352
|
+
<nav data-brease={navPath('footer')}>{footer.items.map(/* … */)}</nav>
|
|
353
|
+
<p data-brease={fieldPath('footer.copyright', global.pageId)}>{global.content.footer.copyright}</p>
|
|
299
354
|
```
|
|
300
355
|
|
|
301
356
|
## Sections
|
|
@@ -311,7 +366,7 @@ src/brease/sections/ (or brease/sections/)
|
|
|
311
366
|
```
|
|
312
367
|
|
|
313
368
|
- A page's sections are one list, `content.sections: [{ id, type, ...fields }]`, with the same ids in the same order in every locale. Fixed parts (a page title, header, footer, site-wide content) stay outside it.
|
|
314
|
-
- `fields` describes the section's fields; Brease builds new sections from it (lorem ipsum, a placeholder image, `default`s, `enum`s' first values, `minItems` list items). Images are `{ assetId, url, alt }
|
|
369
|
+
- `fields` describes the section's fields; Brease builds new sections from it (lorem ipsum, a placeholder image, `default`s, `enum`s' first values, `minItems` list items). Images are `{ assetId, url, alt, width?, height? }` (`BreaseImage`), links `{ label, href }` (`BreaseLink`; an internal link also carries the page's `pageId`, and the delivery API sets its `href` for the requested locale), rich text `{ "type": "string", "format": "html" }`.
|
|
315
370
|
- `"shared": true` keeps one content for every page that shows the type, on the site-wide page (`_global`) under `content.shared.<type>`; pages list only `{ id, type }` for it, and its markers use the other-page prefix (`<_global pageId>:shared.<type>.<field>`).
|
|
316
371
|
- Markers: the list's element carries `data-brease-sections="sections"`, each section's root `data-brease-section={id}` and `data-brease-block={type}`, fields inside `data-brease="sections.<index>.<field>"`.
|
|
317
372
|
|
|
@@ -338,10 +393,20 @@ export function Sections({ sections }: { sections: BreaseSection[] }) {
|
|
|
338
393
|
import { imageProps, srcset } from 'brease-client/image'
|
|
339
394
|
|
|
340
395
|
const props = imageProps(page.content.hero.image, { sizes: '(min-width: 768px) 50vw, 100vw' })
|
|
341
|
-
// <img src={props.src} srcSet={props.srcSet} sizes={props.sizes} />
|
|
396
|
+
// <img src={props.src} srcSet={props.srcSet} sizes={props.sizes} alt={props.alt} width={props.width} height={props.height} />
|
|
342
397
|
```
|
|
343
398
|
|
|
344
|
-
|
|
399
|
+
An image field is `{ assetId, url, alt, width?, height? }` (`BreaseImage`); `imageProps` takes the field or a plain
|
|
400
|
+
URL. Brease files are served as-is from storage, which doesn't resize images: the helpers return the URL unchanged
|
|
401
|
+
with an empty `srcset`. For responsive images, let your framework resize them, e.g. `next/image` with the host of
|
|
402
|
+
your Brease image URLs in `images.remotePatterns`.
|
|
403
|
+
|
|
404
|
+
## Content links
|
|
405
|
+
|
|
406
|
+
Link fields are `{ label, href }`. A link to another page of the site also carries that page's `pageId`, and the
|
|
407
|
+
delivery API sets `href` to the page's URL in the locale you asked for, so renaming or moving a page never breaks a
|
|
408
|
+
link and every locale links to its own version. External links are only the `href`. Rich text links to pages carry
|
|
409
|
+
`data-brease-page="<pageId>"`, and their `href` is filled in the same way.
|
|
345
410
|
|
|
346
411
|
## Without JavaScript
|
|
347
412
|
|
package/dist/astro.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { HeadOptions } from './html.cjs';
|
|
2
2
|
export { HeadTag, headTagList, headTags } from './html.cjs';
|
|
3
|
-
import { R as ResolvedSeo } from './types-
|
|
3
|
+
import { R as ResolvedSeo } from './types-D5mwpqAP.cjs';
|
|
4
4
|
|
|
5
5
|
declare function breaseHead(seo: ResolvedSeo, opts?: HeadOptions): string;
|
|
6
6
|
|
package/dist/astro.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { HeadOptions } from './html.js';
|
|
2
2
|
export { HeadTag, headTagList, headTags } from './html.js';
|
|
3
|
-
import { R as ResolvedSeo } from './types-
|
|
3
|
+
import { R as ResolvedSeo } from './types-D5mwpqAP.js';
|
|
4
4
|
|
|
5
5
|
declare function breaseHead(seo: ResolvedSeo, opts?: HeadOptions): string;
|
|
6
6
|
|
|
@@ -72,6 +72,13 @@ function resolvePath(settings, pathname) {
|
|
|
72
72
|
}
|
|
73
73
|
return { slug: clean, locale: settings.defaultLocale };
|
|
74
74
|
}
|
|
75
|
+
function canonicalPath(settings, pathname) {
|
|
76
|
+
const path = pathname.split(/[?#]/)[0] ?? "";
|
|
77
|
+
const { slug, locale } = resolvePath(settings, path);
|
|
78
|
+
const canonical = buildPath(settings, slug, locale);
|
|
79
|
+
const trim = (p) => p.length > 1 ? p.replace(/\/+$/, "") : p;
|
|
80
|
+
return trim(decodeURIComponent(path)) === trim(canonical) ? null : canonical;
|
|
81
|
+
}
|
|
75
82
|
|
|
76
83
|
// src/analytics.ts
|
|
77
84
|
var MEASUREMENT_ID = /^G-[A-Z0-9]+$/;
|
|
@@ -96,6 +103,29 @@ function grantAnalytics(granted = true) {
|
|
|
96
103
|
gtag?.("consent", "update", { analytics_storage: granted ? "granted" : "denied" });
|
|
97
104
|
}
|
|
98
105
|
|
|
106
|
+
// src/custom-code.ts
|
|
107
|
+
function customTags(seo) {
|
|
108
|
+
return [seo.customHead, seo.customCode].flatMap((html) => html ? parseTags(html) : []);
|
|
109
|
+
}
|
|
110
|
+
function parseTags(html) {
|
|
111
|
+
const out = [];
|
|
112
|
+
const re = /<(script|style|noscript)\b([^>]*)>([\s\S]*?)<\/\1\s*>|<(meta|link)\b([^>]*?)\/?>/gi;
|
|
113
|
+
for (const m of html.matchAll(re)) {
|
|
114
|
+
if (m[1]) {
|
|
115
|
+
const tag = m[1].toLowerCase();
|
|
116
|
+
out.push({ tag, attrs: attrsOf(m[2] ?? ""), ...m[3]?.trim() ? { content: m[3] } : {} });
|
|
117
|
+
} else if (m[4])
|
|
118
|
+
out.push({ tag: m[4].toLowerCase(), attrs: attrsOf(m[5] ?? "") });
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
function attrsOf(source) {
|
|
123
|
+
const attrs = {};
|
|
124
|
+
for (const m of source.matchAll(/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g))
|
|
125
|
+
attrs[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? "";
|
|
126
|
+
return attrs;
|
|
127
|
+
}
|
|
128
|
+
|
|
99
129
|
// src/locales.ts
|
|
100
130
|
function localeLinks(context) {
|
|
101
131
|
const { settings, alternates, homes, locale: current } = context;
|
|
@@ -114,6 +144,98 @@ function nativeName(locale) {
|
|
|
114
144
|
}
|
|
115
145
|
var localeHref = (settings, slug, locale) => buildPath(settings, slug, locale);
|
|
116
146
|
|
|
147
|
+
// src/markers.ts
|
|
148
|
+
function fieldPath(path, pageId) {
|
|
149
|
+
return pageId ? `${pageId}:${path}` : path;
|
|
150
|
+
}
|
|
151
|
+
function navPath(key) {
|
|
152
|
+
return `nav:${key}`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// src/redirects.ts
|
|
156
|
+
function matchRedirect(redirects, pathname) {
|
|
157
|
+
const path = normalize(pathname);
|
|
158
|
+
for (const r of redirects) {
|
|
159
|
+
const params = matchSource(normalize(r.source), path);
|
|
160
|
+
if (!params) continue;
|
|
161
|
+
const destination = r.destination.replace(
|
|
162
|
+
/:([A-Za-z_][A-Za-z0-9_]*)\*?/g,
|
|
163
|
+
(whole, name) => name in params ? params[name] : whole
|
|
164
|
+
);
|
|
165
|
+
if (normalize(destination) === path) continue;
|
|
166
|
+
return { destination, status: r.status };
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
var normalize = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p) || "/";
|
|
171
|
+
function matchSource(source, path) {
|
|
172
|
+
const want = source.split("/").filter(Boolean);
|
|
173
|
+
const have = path.split("/").filter(Boolean);
|
|
174
|
+
const params = {};
|
|
175
|
+
for (let i = 0; i < want.length; i++) {
|
|
176
|
+
const seg = want[i];
|
|
177
|
+
const rest = /^:([A-Za-z_][A-Za-z0-9_]*)\*$/.exec(seg);
|
|
178
|
+
if (rest) {
|
|
179
|
+
params[rest[1]] = have.slice(i).join("/");
|
|
180
|
+
return params;
|
|
181
|
+
}
|
|
182
|
+
const value = have[i];
|
|
183
|
+
if (value === void 0) return null;
|
|
184
|
+
const param = /^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(seg);
|
|
185
|
+
if (param) params[param[1]] = value;
|
|
186
|
+
else if (decodeURIComponent(value) !== decodeURIComponent(seg)) return null;
|
|
187
|
+
}
|
|
188
|
+
return want.length === have.length ? params : null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// src/signature.ts
|
|
192
|
+
var MAX_SKEW_MS = 5 * 6e4;
|
|
193
|
+
async function hmacHex(secret, message) {
|
|
194
|
+
const enc = new TextEncoder();
|
|
195
|
+
const key = await crypto.subtle.importKey(
|
|
196
|
+
"raw",
|
|
197
|
+
enc.encode(secret),
|
|
198
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
199
|
+
false,
|
|
200
|
+
["sign"]
|
|
201
|
+
);
|
|
202
|
+
const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(message)));
|
|
203
|
+
return Array.from(sig, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
204
|
+
}
|
|
205
|
+
async function verifySignature(body, timestamp, signature, secret, now = Date.now()) {
|
|
206
|
+
if (!timestamp || !signature) return false;
|
|
207
|
+
if (!Number.isFinite(Number(timestamp)) || Math.abs(now - Number(timestamp)) > MAX_SKEW_MS) return false;
|
|
208
|
+
const expected = await hmacHex(secret, `${timestamp}.${body}`);
|
|
209
|
+
if (expected.length !== signature.length) return false;
|
|
210
|
+
let diff = 0;
|
|
211
|
+
for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
|
|
212
|
+
return diff === 0;
|
|
213
|
+
}
|
|
214
|
+
async function verifyRevalidate(req, secret) {
|
|
215
|
+
const raw = await req.text();
|
|
216
|
+
const ok = await verifySignature(
|
|
217
|
+
raw,
|
|
218
|
+
req.headers.get("x-brease-timestamp"),
|
|
219
|
+
req.headers.get("x-brease-signature"),
|
|
220
|
+
secret
|
|
221
|
+
);
|
|
222
|
+
if (!ok) return { ok: false, reason: "signature" };
|
|
223
|
+
let body;
|
|
224
|
+
try {
|
|
225
|
+
body = JSON.parse(raw || "{}");
|
|
226
|
+
} catch {
|
|
227
|
+
return { ok: false, reason: "body" };
|
|
228
|
+
}
|
|
229
|
+
const paths = new Set(body.paths ?? []);
|
|
230
|
+
for (const url of body.urls ?? []) {
|
|
231
|
+
try {
|
|
232
|
+
paths.add(new URL(url, "http://localhost").pathname);
|
|
233
|
+
} catch {
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return { ok: true, paths: [...paths], tags: ["brease", ...body.tags ?? []], body };
|
|
237
|
+
}
|
|
238
|
+
|
|
117
239
|
// src/index.ts
|
|
118
240
|
var RETRY_AFTER_CAP_MS = 1e4;
|
|
119
241
|
var SITE_TTL_MS = 6e4;
|
|
@@ -125,6 +247,7 @@ function createBrease(opts = {}) {
|
|
|
125
247
|
const baseMs = opts.retryBaseMs ?? 300;
|
|
126
248
|
const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
127
249
|
let site;
|
|
250
|
+
let redirects;
|
|
128
251
|
async function request(path, query = {}, nullOn404 = false) {
|
|
129
252
|
const token = opts.token ?? env("BREASE_TOKEN");
|
|
130
253
|
if (!token)
|
|
@@ -174,13 +297,26 @@ function createBrease(opts = {}) {
|
|
|
174
297
|
return request("/content-api/page", { slug, locale }, true);
|
|
175
298
|
},
|
|
176
299
|
getPages(o = {}) {
|
|
177
|
-
return request("/content-api/pages", {
|
|
300
|
+
return request("/content-api/pages", {
|
|
301
|
+
locale: o.locale,
|
|
302
|
+
parentId: o.parentId,
|
|
303
|
+
template: o.template,
|
|
304
|
+
withContent: o.withContent ? "1" : void 0
|
|
305
|
+
});
|
|
178
306
|
},
|
|
179
307
|
getNavigation(key, { locale }) {
|
|
180
308
|
return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
|
|
181
309
|
},
|
|
310
|
+
// Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
|
|
182
311
|
getRedirects() {
|
|
183
|
-
|
|
312
|
+
if (!redirects || Date.now() - redirects.at > SITE_TTL_MS) {
|
|
313
|
+
const promise = request("/content-api/redirects").catch((err) => {
|
|
314
|
+
if (redirects?.promise === promise) redirects = void 0;
|
|
315
|
+
throw err;
|
|
316
|
+
});
|
|
317
|
+
redirects = { promise, at: Date.now() };
|
|
318
|
+
}
|
|
319
|
+
return redirects.promise;
|
|
184
320
|
},
|
|
185
321
|
getRelease() {
|
|
186
322
|
return request("/content-api/release");
|
|
@@ -222,7 +358,9 @@ function createBrease(opts = {}) {
|
|
|
222
358
|
},
|
|
223
359
|
async sitemap(baseUrl) {
|
|
224
360
|
const base = baseUrl.replace(/\/+$/, "");
|
|
225
|
-
const refs = (await client.getPages()).filter(
|
|
361
|
+
const refs = (await client.getPages()).filter(
|
|
362
|
+
(r) => !r.hidden && r.index !== false && !r.slug.split("/").some((part) => part.startsWith("_"))
|
|
363
|
+
);
|
|
226
364
|
const byPage = /* @__PURE__ */ new Map();
|
|
227
365
|
for (const ref of refs) {
|
|
228
366
|
const alternates = byPage.get(ref.pageId) ?? {};
|
|
@@ -242,4 +380,4 @@ function pathOf(url) {
|
|
|
242
380
|
}
|
|
243
381
|
}
|
|
244
382
|
|
|
245
|
-
export { BreaseError, buildPath, createBrease, env, ga4Html, ga4Tag, grantAnalytics, localeHref, localeLinks, nativeName, normalizeSlug, resolvePath };
|
|
383
|
+
export { BreaseError, buildPath, canonicalPath, createBrease, customTags, env, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, resolvePath, verifyRevalidate, verifySignature };
|
package/dist/html.d.cts
CHANGED
package/dist/html.d.ts
CHANGED
package/dist/image.cjs
CHANGED
|
@@ -8,8 +8,14 @@ function imageUrl(src, _opts = {}) {
|
|
|
8
8
|
function srcset(_src, _opts = {}) {
|
|
9
9
|
return "";
|
|
10
10
|
}
|
|
11
|
-
function imageProps(
|
|
12
|
-
|
|
11
|
+
function imageProps(image, opts = {}) {
|
|
12
|
+
const src = typeof image === "string" ? image : image.url;
|
|
13
|
+
const extra = typeof image === "string" ? {} : {
|
|
14
|
+
...image.alt !== void 0 ? { alt: image.alt } : {},
|
|
15
|
+
...image.width ? { width: image.width } : {},
|
|
16
|
+
...image.height ? { height: image.height } : {}
|
|
17
|
+
};
|
|
18
|
+
return { src: imageUrl(src), srcSet: srcset(), sizes: opts.sizes ?? "100vw", ...extra };
|
|
13
19
|
}
|
|
14
20
|
|
|
15
21
|
exports.DEFAULT_WIDTHS = DEFAULT_WIDTHS;
|
package/dist/image.d.cts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { B as BreaseImage } from './types-D5mwpqAP.cjs';
|
|
2
|
+
|
|
1
3
|
type Resize = 'cover' | 'contain' | 'fill';
|
|
2
4
|
type ImageOptions = {
|
|
3
5
|
width?: number;
|
|
@@ -12,7 +14,7 @@ declare function srcset(_src: string, _opts?: {
|
|
|
12
14
|
quality?: number;
|
|
13
15
|
resize?: Resize;
|
|
14
16
|
}): string;
|
|
15
|
-
declare function imageProps(
|
|
17
|
+
declare function imageProps(image: string | BreaseImage, opts?: {
|
|
16
18
|
sizes?: string;
|
|
17
19
|
widths?: number[];
|
|
18
20
|
width?: number;
|
|
@@ -22,6 +24,9 @@ declare function imageProps(src: string, opts?: {
|
|
|
22
24
|
src: string;
|
|
23
25
|
srcSet: string;
|
|
24
26
|
sizes: string;
|
|
27
|
+
alt?: string;
|
|
28
|
+
width?: number;
|
|
29
|
+
height?: number;
|
|
25
30
|
};
|
|
26
31
|
|
|
27
32
|
export { DEFAULT_WIDTHS, type ImageOptions, type Resize, imageProps, imageUrl, srcset };
|
package/dist/image.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { B as BreaseImage } from './types-D5mwpqAP.js';
|
|
2
|
+
|
|
1
3
|
type Resize = 'cover' | 'contain' | 'fill';
|
|
2
4
|
type ImageOptions = {
|
|
3
5
|
width?: number;
|
|
@@ -12,7 +14,7 @@ declare function srcset(_src: string, _opts?: {
|
|
|
12
14
|
quality?: number;
|
|
13
15
|
resize?: Resize;
|
|
14
16
|
}): string;
|
|
15
|
-
declare function imageProps(
|
|
17
|
+
declare function imageProps(image: string | BreaseImage, opts?: {
|
|
16
18
|
sizes?: string;
|
|
17
19
|
widths?: number[];
|
|
18
20
|
width?: number;
|
|
@@ -22,6 +24,9 @@ declare function imageProps(src: string, opts?: {
|
|
|
22
24
|
src: string;
|
|
23
25
|
srcSet: string;
|
|
24
26
|
sizes: string;
|
|
27
|
+
alt?: string;
|
|
28
|
+
width?: number;
|
|
29
|
+
height?: number;
|
|
25
30
|
};
|
|
26
31
|
|
|
27
32
|
export { DEFAULT_WIDTHS, type ImageOptions, type Resize, imageProps, imageUrl, srcset };
|
package/dist/image.js
CHANGED
|
@@ -8,8 +8,14 @@ function imageUrl(src, _opts = {}) {
|
|
|
8
8
|
function srcset(_src, _opts = {}) {
|
|
9
9
|
return "";
|
|
10
10
|
}
|
|
11
|
-
function imageProps(
|
|
12
|
-
|
|
11
|
+
function imageProps(image, opts = {}) {
|
|
12
|
+
const src = typeof image === "string" ? image : image.url;
|
|
13
|
+
const extra = typeof image === "string" ? {} : {
|
|
14
|
+
...image.alt !== void 0 ? { alt: image.alt } : {},
|
|
15
|
+
...image.width ? { width: image.width } : {},
|
|
16
|
+
...image.height ? { height: image.height } : {}
|
|
17
|
+
};
|
|
18
|
+
return { src: imageUrl(src), srcSet: srcset(), sizes: opts.sizes ?? "100vw", ...extra };
|
|
13
19
|
}
|
|
14
20
|
|
|
15
21
|
export { DEFAULT_WIDTHS, imageProps, imageUrl, srcset };
|