brease-client 0.2.1 → 0.4.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/README.md CHANGED
@@ -32,6 +32,9 @@ await brease.getPages({ locale: 'en' }) // [{ pageId, locale, slug, url, hidden
32
32
  await brease.getNavigation('main', { locale: 'en' }) // { key, locale, items } | null
33
33
  await brease.getRedirects() // [{ source, destination, status }]
34
34
  await brease.resolve('/en/about') // { slug: 'about', locale: 'en' } | null
35
+ await brease.route(['en', 'about']) // the same from catch-all path segments; null for shared "_" pages
36
+ await brease.routes() // [{ path: ['en', 'about'] }, …]: static params for every published page
37
+ await brease.localeContext(['en', 'about']) // { locale, settings, alternates, homes } for BreaseLocaleProvider
35
38
  await brease.sitemap('https://example.com') // [{ url, alternates }]
36
39
  ```
37
40
 
@@ -39,6 +42,7 @@ await brease.sitemap('https://example.com') // [{ url, alternates }]
39
42
  - 429 and 5xx responses (and network errors) are retried twice with backoff; `Retry-After` is honoured.
40
43
  - 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.
41
44
  - `sitemap()` has no `lastModified`: releases are immutable snapshots and do not track per-page edit times.
45
+ - `getSite()` is cached for a minute, so a locale added in Brease is served without a restart.
42
46
  - `buildPath(settings, slug, locale)` and `resolvePath(settings, pathname)` are exported for routing code that already has the site settings.
43
47
 
44
48
  ## Next.js (App Router)
@@ -103,6 +107,98 @@ export default {
103
107
  }
104
108
  ```
105
109
 
110
+ ### Recommended structure (optional)
111
+
112
+ Brease works with any routing: `getPage()` and friends don't care how a site is built. This structure is what Brease recommends, and what its editor moves a site towards when the site follows Brease conventions. It makes locales a setting: adding one, or changing how URLs are prefixed, needs no code change.
113
+
114
+ ```
115
+ app/
116
+ [[...path]]/
117
+ layout.tsx root layout: <html lang>, BreaseLocaleProvider
118
+ page.tsx every page in every locale; the page's content picks its template
119
+ not-found.tsx
120
+ og/[[...path]]/route.tsx share images (image files can't sit inside an optional catch-all)
121
+ api/…, sitemap.ts, robots.ts, other route handlers unchanged: static routes win over the catch-all
122
+ brease/templates.tsx { home: …, article: … }, the site's own page templates
123
+ ```
124
+
125
+ ```tsx
126
+ // app/[[...path]]/layout.tsx (replaces app/layout.tsx)
127
+ import { BreaseLocaleProvider } from 'brease-client/react'
128
+ import { brease } from '@/lib/brease'
129
+
130
+ type Props = { children: React.ReactNode; params: Promise<{ path?: string[] }> }
131
+
132
+ export default async function RootLayout({ children, params }: Props) {
133
+ const site = await brease.getSite()
134
+ const context = (await brease.localeContext((await params).path)) ?? {
135
+ locale: site.defaultLocale,
136
+ settings: site,
137
+ alternates: {},
138
+ homes: {}
139
+ }
140
+ return (
141
+ <html lang={context.locale}>
142
+ <body>
143
+ <BreaseLocaleProvider value={context}>{children}</BreaseLocaleProvider>
144
+ </body>
145
+ </html>
146
+ )
147
+ }
148
+ ```
149
+
150
+ ```tsx
151
+ // app/[[...path]]/page.tsx (replaces app/page.tsx and app/[slug]/page.tsx)
152
+ import { notFound } from 'next/navigation'
153
+ import { toMetadata } from 'brease-client/next'
154
+ import { templates } from '@/brease/templates'
155
+ import { brease } from '@/lib/brease'
156
+
157
+ export const revalidate = 60
158
+
159
+ type Props = { params: Promise<{ path?: string[] }> }
160
+
161
+ async function load(params: Props['params']) {
162
+ const route = await brease.route((await params).path)
163
+ const page = route && (await brease.getPage<Content>(route.slug, { locale: route.locale }))
164
+ const Template = page && templates[page.content.template]
165
+ return page && route && Template ? { page, locale: route.locale, Template } : null
166
+ }
167
+
168
+ export const generateStaticParams = () => brease.routes()
169
+
170
+ export async function generateMetadata({ params }: Props) {
171
+ const loaded = await load(params)
172
+ return loaded ? toMetadata(loaded.page.resolvedSeo) : {}
173
+ }
174
+
175
+ export default async function Page({ params }: Props) {
176
+ const loaded = await load(params)
177
+ if (!loaded) notFound()
178
+ // Pass the locale to everything else that reads Brease: navigations, shared "_" pages, site SEO.
179
+ return <loaded.Template page={loaded.page} locale={loaded.locale} />
180
+ }
181
+ ```
182
+
183
+ In client components:
184
+
185
+ ```tsx
186
+ import { LocaleSwitcher, useLocale, useLocaleLinks } from 'brease-client/react'
187
+
188
+ const { locale, href } = useLocale()
189
+ href('') // this locale's home: '/', '/en', …
190
+ href('about', 'de') // '/de/about'
191
+
192
+ <LocaleSwitcher className="langs" linkClassName="lang" /> // unstyled links; hidden while one locale has content
193
+ useLocaleLinks() // [{ locale, label, href, current }] for your own markup
194
+ ```
195
+
196
+ - The switcher links each locale's version of the current page, else that locale's home page; locales without content yet are left out.
197
+ - Everything that read a fixed locale (`getPage(…, { locale: 'hu' })`, `getNavigation`, `site.seo.hu`) takes it from the route instead.
198
+ - Links inside content are already locale URLs. Build other internal links with `href()` (client) or `buildPath(site, slug, locale)` (server).
199
+ - Text written into components (button labels, captions) stays as it is; moving it into Brease content is a separate change.
200
+ - `next.config`: `redirects: breaseRedirects()` (from `brease-client/next`) serves the redirects managed in Brease.
201
+
106
202
  ### Revalidation signature
107
203
 
108
204
  After a content-only release goes live, Brease POSTs JSON `{ urls, tags?, releaseId, siteId }` to the site's revalidate URL with two headers:
@@ -142,6 +238,17 @@ const html = `<head>${headTags(page.resolvedSeo, { xDefault: 'https://example.co
142
238
 
143
239
  `customHead` and `customCode` from the site's SEO settings are inserted as raw HTML (they are authored by the site's team); pass `{ includeCustom: false }` to leave them out.
144
240
 
241
+ ## Editor markers
242
+
243
+ The Brease editor's Edit tool finds content through `data-brease` attributes:
244
+
245
+ - `data-brease="hero.title"` on an element that renders a page content field (a path into `page.content`)
246
+ - `data-brease="nav:footer"` on the element that wraps a navigation menu; clicking it opens that navigation's editor
247
+
248
+ ```tsx
249
+ <nav data-brease="nav:footer">{footer.items.map(/* … */)}</nav>
250
+ ```
251
+
145
252
  ## Images
146
253
 
147
254
  ```ts
@@ -0,0 +1,204 @@
1
+ import { __publicField } from './chunk-PKBMQBKP.js';
2
+
3
+ // src/env.ts
4
+ function env(name) {
5
+ const proc = globalThis.process;
6
+ const value = proc?.env?.[name];
7
+ return value === "" ? void 0 : value;
8
+ }
9
+
10
+ // src/errors.ts
11
+ var BreaseError = class _BreaseError extends Error {
12
+ constructor(code, message, status, requestId, details) {
13
+ super(message);
14
+ __publicField(this, "code", code);
15
+ __publicField(this, "status", status);
16
+ __publicField(this, "requestId", requestId);
17
+ __publicField(this, "details", details);
18
+ __publicField(this, "name", "BreaseError");
19
+ }
20
+ static async fromResponse(res) {
21
+ const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-vercel-id") ?? void 0;
22
+ let code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "upstream" : "http_error";
23
+ let message = `Brease API responded ${res.status}`;
24
+ let details;
25
+ try {
26
+ const body = await res.json();
27
+ if (body?.error) {
28
+ code = body.error.code ?? code;
29
+ message = body.error.message ?? message;
30
+ details = body.error.details;
31
+ }
32
+ } catch {
33
+ }
34
+ return new _BreaseError(code, message, res.status, requestId ?? void 0, details);
35
+ }
36
+ };
37
+
38
+ // src/urls.ts
39
+ function normalizeSlug(input) {
40
+ return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
41
+ }
42
+ function buildPath(settings, slug, locale) {
43
+ const clean = normalizeSlug(slug);
44
+ if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
45
+ const path = settings.urlTemplate.replace("{locale}", locale).replace("{slug}", clean);
46
+ return `/${normalizeSlug(path)}`;
47
+ }
48
+ const prefixed = settings.localeStrategy === "PREFIX_ALL" || locale !== settings.defaultLocale;
49
+ const parts = [prefixed ? locale : "", clean].filter(Boolean);
50
+ return `/${parts.join("/")}`;
51
+ }
52
+ function resolvePath(settings, pathname) {
53
+ const clean = normalizeSlug(decodeURIComponent(pathname.split(/[?#]/)[0] ?? ""));
54
+ if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
55
+ const pattern = normalizeSlug(settings.urlTemplate).split(/(\{locale\}|\{slug\})/).map((part) => {
56
+ if (part === "{locale}") return "(?<locale>[^/]+)";
57
+ if (part === "{slug}") return "(?<slug>.*)";
58
+ return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
59
+ }).join("");
60
+ const match = new RegExp(`^${pattern}$`).exec(clean);
61
+ if (match?.groups) {
62
+ return {
63
+ slug: normalizeSlug(match.groups.slug ?? ""),
64
+ locale: match.groups.locale ?? settings.defaultLocale
65
+ };
66
+ }
67
+ return { slug: clean, locale: settings.defaultLocale };
68
+ }
69
+ const [first, ...rest] = clean.split("/");
70
+ if (first && settings.locales.includes(first)) {
71
+ return { slug: rest.join("/"), locale: first };
72
+ }
73
+ return { slug: clean, locale: settings.defaultLocale };
74
+ }
75
+
76
+ // src/index.ts
77
+ var RETRY_AFTER_CAP_MS = 1e4;
78
+ var SITE_TTL_MS = 6e4;
79
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
80
+ function createBrease(opts = {}) {
81
+ const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
82
+ const commit = opts.commit === false ? void 0 : opts.commit ?? env("VERCEL_GIT_COMMIT_SHA");
83
+ const retries = opts.retries ?? 2;
84
+ const baseMs = opts.retryBaseMs ?? 300;
85
+ const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
86
+ let site;
87
+ async function request(path, query = {}, nullOn404 = false) {
88
+ const token = opts.token ?? env("BREASE_TOKEN");
89
+ if (!token)
90
+ throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
91
+ const params = new URLSearchParams();
92
+ for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
93
+ const qs = params.toString();
94
+ const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
95
+ const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
96
+ if (commit) headers["x-brease-commit"] = commit;
97
+ for (let attempt = 0; ; attempt++) {
98
+ let res;
99
+ try {
100
+ res = await doFetch(url, { method: "GET", headers });
101
+ } catch (err) {
102
+ if (attempt < retries) {
103
+ await sleep(backoff(attempt));
104
+ continue;
105
+ }
106
+ throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
107
+ }
108
+ if (res.ok) return await res.json();
109
+ if (res.status === 404 && nullOn404) return null;
110
+ if ((res.status === 429 || res.status >= 500) && attempt < retries) {
111
+ const after = Number(res.headers.get("retry-after"));
112
+ await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
113
+ continue;
114
+ }
115
+ throw await BreaseError.fromResponse(res);
116
+ }
117
+ }
118
+ function backoff(attempt) {
119
+ return baseMs * 2 ** attempt + Math.random() * baseMs;
120
+ }
121
+ const client = {
122
+ getSite() {
123
+ if (!site || Date.now() - site.at > SITE_TTL_MS) {
124
+ const promise = request("/content-api/site").catch((err) => {
125
+ if (site?.promise === promise) site = void 0;
126
+ throw err;
127
+ });
128
+ site = { promise, at: Date.now() };
129
+ }
130
+ return site.promise;
131
+ },
132
+ getPage(slug, { locale }) {
133
+ return request("/content-api/page", { slug, locale }, true);
134
+ },
135
+ getPages(o = {}) {
136
+ return request("/content-api/pages", { locale: o.locale });
137
+ },
138
+ getNavigation(key, { locale }) {
139
+ return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
140
+ },
141
+ getRedirects() {
142
+ return request("/content-api/redirects");
143
+ },
144
+ getRelease() {
145
+ return request("/content-api/release");
146
+ },
147
+ async resolve(pathname) {
148
+ const site2 = await client.getSite();
149
+ const result = resolvePath(site2, pathname);
150
+ return site2.locales.includes(result.locale) ? result : null;
151
+ },
152
+ async route(path) {
153
+ const joined = Array.isArray(path) ? path.map((p) => decodeURIComponent(p)).join("/") : path ?? "";
154
+ const result = await client.resolve(`/${joined}`);
155
+ return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
156
+ },
157
+ async routes() {
158
+ const refs = await client.getPages();
159
+ return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
160
+ },
161
+ async localeContext(path) {
162
+ const target = await client.route(path);
163
+ if (!target) return null;
164
+ const [site2, page, home] = await Promise.all([
165
+ client.getSite(),
166
+ client.getPage(target.slug, { locale: target.locale }),
167
+ client.getPage("", { locale: target.locale })
168
+ ]);
169
+ const settings = {
170
+ locales: site2.locales,
171
+ defaultLocale: site2.defaultLocale,
172
+ localeStrategy: site2.localeStrategy,
173
+ urlTemplate: site2.urlTemplate
174
+ };
175
+ if (!page && !home) return null;
176
+ const alternates = {};
177
+ for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
178
+ const homes = {};
179
+ for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
180
+ return { locale: target.locale, settings, alternates, homes };
181
+ },
182
+ async sitemap(baseUrl) {
183
+ const base = baseUrl.replace(/\/+$/, "");
184
+ const refs = (await client.getPages()).filter((r) => !r.hidden);
185
+ const byPage = /* @__PURE__ */ new Map();
186
+ for (const ref of refs) {
187
+ const alternates = byPage.get(ref.pageId) ?? {};
188
+ alternates[ref.locale] = `${base}${ref.url}`;
189
+ byPage.set(ref.pageId, alternates);
190
+ }
191
+ return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
192
+ }
193
+ };
194
+ return client;
195
+ }
196
+ function pathOf(url) {
197
+ try {
198
+ return new URL(url, "http://localhost").pathname;
199
+ } catch {
200
+ return url;
201
+ }
202
+ }
203
+
204
+ export { BreaseError, buildPath, createBrease, env, normalizeSlug, resolvePath };
package/dist/index.cjs CHANGED
@@ -79,6 +79,7 @@ function resolvePath(settings, pathname) {
79
79
 
80
80
  // src/index.ts
81
81
  var RETRY_AFTER_CAP_MS = 1e4;
82
+ var SITE_TTL_MS = 6e4;
82
83
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
83
84
  function createBrease(opts = {}) {
84
85
  const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
@@ -86,7 +87,7 @@ function createBrease(opts = {}) {
86
87
  const retries = opts.retries ?? 2;
87
88
  const baseMs = opts.retryBaseMs ?? 300;
88
89
  const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
89
- let sitePromise;
90
+ let site;
90
91
  async function request(path, query = {}, nullOn404 = false) {
91
92
  const token = opts.token ?? env("BREASE_TOKEN");
92
93
  if (!token)
@@ -123,11 +124,14 @@ function createBrease(opts = {}) {
123
124
  }
124
125
  const client = {
125
126
  getSite() {
126
- sitePromise ?? (sitePromise = request("/content-api/site").catch((err) => {
127
- sitePromise = void 0;
128
- throw err;
129
- }));
130
- return sitePromise;
127
+ if (!site || Date.now() - site.at > SITE_TTL_MS) {
128
+ const promise = request("/content-api/site").catch((err) => {
129
+ if (site?.promise === promise) site = void 0;
130
+ throw err;
131
+ });
132
+ site = { promise, at: Date.now() };
133
+ }
134
+ return site.promise;
131
135
  },
132
136
  getPage(slug, { locale }) {
133
137
  return request("/content-api/page", { slug, locale }, true);
@@ -145,9 +149,39 @@ function createBrease(opts = {}) {
145
149
  return request("/content-api/release");
146
150
  },
147
151
  async resolve(pathname) {
148
- const site = await client.getSite();
149
- const result = resolvePath(site, pathname);
150
- return site.locales.includes(result.locale) ? result : null;
152
+ const site2 = await client.getSite();
153
+ const result = resolvePath(site2, pathname);
154
+ return site2.locales.includes(result.locale) ? result : null;
155
+ },
156
+ async route(path) {
157
+ const joined = Array.isArray(path) ? path.map((p) => decodeURIComponent(p)).join("/") : path ?? "";
158
+ const result = await client.resolve(`/${joined}`);
159
+ return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
160
+ },
161
+ async routes() {
162
+ const refs = await client.getPages();
163
+ return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
164
+ },
165
+ async localeContext(path) {
166
+ const target = await client.route(path);
167
+ if (!target) return null;
168
+ const [site2, page, home] = await Promise.all([
169
+ client.getSite(),
170
+ client.getPage(target.slug, { locale: target.locale }),
171
+ client.getPage("", { locale: target.locale })
172
+ ]);
173
+ const settings = {
174
+ locales: site2.locales,
175
+ defaultLocale: site2.defaultLocale,
176
+ localeStrategy: site2.localeStrategy,
177
+ urlTemplate: site2.urlTemplate
178
+ };
179
+ if (!page && !home) return null;
180
+ const alternates = {};
181
+ for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
182
+ const homes = {};
183
+ for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
184
+ return { locale: target.locale, settings, alternates, homes };
151
185
  },
152
186
  async sitemap(baseUrl) {
153
187
  const base = baseUrl.replace(/\/+$/, "");
@@ -163,6 +197,13 @@ function createBrease(opts = {}) {
163
197
  };
164
198
  return client;
165
199
  }
200
+ function pathOf(url) {
201
+ try {
202
+ return new URL(url, "http://localhost").pathname;
203
+ } catch {
204
+ return url;
205
+ }
206
+ }
166
207
 
167
208
  exports.BreaseError = BreaseError;
168
209
  exports.buildPath = buildPath;
package/dist/index.d.cts CHANGED
@@ -18,6 +18,12 @@ declare function resolvePath(settings: UrlSettings, pathname: string): {
18
18
  locale: string;
19
19
  };
20
20
 
21
+ type LocaleContext = {
22
+ locale: string;
23
+ settings: UrlSettings;
24
+ alternates: Record<string, string>;
25
+ homes: Record<string, string>;
26
+ };
21
27
  type BreaseOptions = {
22
28
  token?: string;
23
29
  apiUrl?: string;
@@ -43,8 +49,16 @@ interface Brease {
43
49
  slug: string;
44
50
  locale: string;
45
51
  } | null>;
52
+ route(path?: string | string[]): Promise<{
53
+ slug: string;
54
+ locale: string;
55
+ } | null>;
56
+ routes(): Promise<{
57
+ path: string[];
58
+ }[]>;
59
+ localeContext(path?: string | string[]): Promise<LocaleContext | null>;
46
60
  sitemap(baseUrl: string): Promise<SitemapEntry[]>;
47
61
  }
48
62
  declare function createBrease(opts?: BreaseOptions): Brease;
49
63
 
50
- export { type Brease, BreaseError, type BreaseOptions, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, createBrease, normalizeSlug, resolvePath };
64
+ export { type Brease, BreaseError, type BreaseOptions, type LocaleContext, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, createBrease, normalizeSlug, resolvePath };
package/dist/index.d.ts CHANGED
@@ -18,6 +18,12 @@ declare function resolvePath(settings: UrlSettings, pathname: string): {
18
18
  locale: string;
19
19
  };
20
20
 
21
+ type LocaleContext = {
22
+ locale: string;
23
+ settings: UrlSettings;
24
+ alternates: Record<string, string>;
25
+ homes: Record<string, string>;
26
+ };
21
27
  type BreaseOptions = {
22
28
  token?: string;
23
29
  apiUrl?: string;
@@ -43,8 +49,16 @@ interface Brease {
43
49
  slug: string;
44
50
  locale: string;
45
51
  } | null>;
52
+ route(path?: string | string[]): Promise<{
53
+ slug: string;
54
+ locale: string;
55
+ } | null>;
56
+ routes(): Promise<{
57
+ path: string[];
58
+ }[]>;
59
+ localeContext(path?: string | string[]): Promise<LocaleContext | null>;
46
60
  sitemap(baseUrl: string): Promise<SitemapEntry[]>;
47
61
  }
48
62
  declare function createBrease(opts?: BreaseOptions): Brease;
49
63
 
50
- export { type Brease, BreaseError, type BreaseOptions, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, createBrease, normalizeSlug, resolvePath };
64
+ export { type Brease, BreaseError, type BreaseOptions, type LocaleContext, Navigation, Page, PageRef, Redirect, Release, Site, SitemapEntry, UrlSettings, buildPath, createBrease, normalizeSlug, resolvePath };
package/dist/index.js CHANGED
@@ -1,157 +1,2 @@
1
- import { env } from './chunk-L7GXI4GK.js';
2
- import { __publicField } from './chunk-PKBMQBKP.js';
3
-
4
- // src/errors.ts
5
- var BreaseError = class _BreaseError extends Error {
6
- constructor(code, message, status, requestId, details) {
7
- super(message);
8
- __publicField(this, "code", code);
9
- __publicField(this, "status", status);
10
- __publicField(this, "requestId", requestId);
11
- __publicField(this, "details", details);
12
- __publicField(this, "name", "BreaseError");
13
- }
14
- static async fromResponse(res) {
15
- const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-vercel-id") ?? void 0;
16
- let code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "upstream" : "http_error";
17
- let message = `Brease API responded ${res.status}`;
18
- let details;
19
- try {
20
- const body = await res.json();
21
- if (body?.error) {
22
- code = body.error.code ?? code;
23
- message = body.error.message ?? message;
24
- details = body.error.details;
25
- }
26
- } catch {
27
- }
28
- return new _BreaseError(code, message, res.status, requestId ?? void 0, details);
29
- }
30
- };
31
-
32
- // src/urls.ts
33
- function normalizeSlug(input) {
34
- return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
35
- }
36
- function buildPath(settings, slug, locale) {
37
- const clean = normalizeSlug(slug);
38
- if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
39
- const path = settings.urlTemplate.replace("{locale}", locale).replace("{slug}", clean);
40
- return `/${normalizeSlug(path)}`;
41
- }
42
- const prefixed = settings.localeStrategy === "PREFIX_ALL" || locale !== settings.defaultLocale;
43
- const parts = [prefixed ? locale : "", clean].filter(Boolean);
44
- return `/${parts.join("/")}`;
45
- }
46
- function resolvePath(settings, pathname) {
47
- const clean = normalizeSlug(decodeURIComponent(pathname.split(/[?#]/)[0] ?? ""));
48
- if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
49
- const pattern = normalizeSlug(settings.urlTemplate).split(/(\{locale\}|\{slug\})/).map((part) => {
50
- if (part === "{locale}") return "(?<locale>[^/]+)";
51
- if (part === "{slug}") return "(?<slug>.*)";
52
- return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
53
- }).join("");
54
- const match = new RegExp(`^${pattern}$`).exec(clean);
55
- if (match?.groups) {
56
- return {
57
- slug: normalizeSlug(match.groups.slug ?? ""),
58
- locale: match.groups.locale ?? settings.defaultLocale
59
- };
60
- }
61
- return { slug: clean, locale: settings.defaultLocale };
62
- }
63
- const [first, ...rest] = clean.split("/");
64
- if (first && settings.locales.includes(first)) {
65
- return { slug: rest.join("/"), locale: first };
66
- }
67
- return { slug: clean, locale: settings.defaultLocale };
68
- }
69
-
70
- // src/index.ts
71
- var RETRY_AFTER_CAP_MS = 1e4;
72
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
73
- function createBrease(opts = {}) {
74
- const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
75
- const commit = opts.commit === false ? void 0 : opts.commit ?? env("VERCEL_GIT_COMMIT_SHA");
76
- const retries = opts.retries ?? 2;
77
- const baseMs = opts.retryBaseMs ?? 300;
78
- const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
79
- let sitePromise;
80
- async function request(path, query = {}, nullOn404 = false) {
81
- const token = opts.token ?? env("BREASE_TOKEN");
82
- if (!token)
83
- throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
84
- const params = new URLSearchParams();
85
- for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
86
- const qs = params.toString();
87
- const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
88
- const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
89
- if (commit) headers["x-brease-commit"] = commit;
90
- for (let attempt = 0; ; attempt++) {
91
- let res;
92
- try {
93
- res = await doFetch(url, { method: "GET", headers });
94
- } catch (err) {
95
- if (attempt < retries) {
96
- await sleep(backoff(attempt));
97
- continue;
98
- }
99
- throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
100
- }
101
- if (res.ok) return await res.json();
102
- if (res.status === 404 && nullOn404) return null;
103
- if ((res.status === 429 || res.status >= 500) && attempt < retries) {
104
- const after = Number(res.headers.get("retry-after"));
105
- await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
106
- continue;
107
- }
108
- throw await BreaseError.fromResponse(res);
109
- }
110
- }
111
- function backoff(attempt) {
112
- return baseMs * 2 ** attempt + Math.random() * baseMs;
113
- }
114
- const client = {
115
- getSite() {
116
- sitePromise ?? (sitePromise = request("/content-api/site").catch((err) => {
117
- sitePromise = void 0;
118
- throw err;
119
- }));
120
- return sitePromise;
121
- },
122
- getPage(slug, { locale }) {
123
- return request("/content-api/page", { slug, locale }, true);
124
- },
125
- getPages(o = {}) {
126
- return request("/content-api/pages", { locale: o.locale });
127
- },
128
- getNavigation(key, { locale }) {
129
- return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
130
- },
131
- getRedirects() {
132
- return request("/content-api/redirects");
133
- },
134
- getRelease() {
135
- return request("/content-api/release");
136
- },
137
- async resolve(pathname) {
138
- const site = await client.getSite();
139
- const result = resolvePath(site, pathname);
140
- return site.locales.includes(result.locale) ? result : null;
141
- },
142
- async sitemap(baseUrl) {
143
- const base = baseUrl.replace(/\/+$/, "");
144
- const refs = (await client.getPages()).filter((r) => !r.hidden);
145
- const byPage = /* @__PURE__ */ new Map();
146
- for (const ref of refs) {
147
- const alternates = byPage.get(ref.pageId) ?? {};
148
- alternates[ref.locale] = `${base}${ref.url}`;
149
- byPage.set(ref.pageId, alternates);
150
- }
151
- return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
152
- }
153
- };
154
- return client;
155
- }
156
-
157
- export { BreaseError, buildPath, createBrease, normalizeSlug, resolvePath };
1
+ export { BreaseError, buildPath, createBrease, normalizeSlug, resolvePath } from './chunk-N6C2X6KA.js';
2
+ import './chunk-PKBMQBKP.js';
package/dist/next.cjs CHANGED
@@ -1,5 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+
3
7
  // src/env.ts
4
8
  function env(name) {
5
9
  const proc = globalThis.process;
@@ -7,6 +11,190 @@ function env(name) {
7
11
  return value === "" ? void 0 : value;
8
12
  }
9
13
 
14
+ // src/errors.ts
15
+ var BreaseError = class _BreaseError extends Error {
16
+ constructor(code, message, status, requestId, details) {
17
+ super(message);
18
+ __publicField(this, "code", code);
19
+ __publicField(this, "status", status);
20
+ __publicField(this, "requestId", requestId);
21
+ __publicField(this, "details", details);
22
+ __publicField(this, "name", "BreaseError");
23
+ }
24
+ static async fromResponse(res) {
25
+ const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-vercel-id") ?? void 0;
26
+ let code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "upstream" : "http_error";
27
+ let message = `Brease API responded ${res.status}`;
28
+ let details;
29
+ try {
30
+ const body = await res.json();
31
+ if (body?.error) {
32
+ code = body.error.code ?? code;
33
+ message = body.error.message ?? message;
34
+ details = body.error.details;
35
+ }
36
+ } catch {
37
+ }
38
+ return new _BreaseError(code, message, res.status, requestId ?? void 0, details);
39
+ }
40
+ };
41
+
42
+ // src/urls.ts
43
+ function normalizeSlug(input) {
44
+ return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
45
+ }
46
+ function resolvePath(settings, pathname) {
47
+ const clean = normalizeSlug(decodeURIComponent(pathname.split(/[?#]/)[0] ?? ""));
48
+ if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
49
+ const pattern = normalizeSlug(settings.urlTemplate).split(/(\{locale\}|\{slug\})/).map((part) => {
50
+ if (part === "{locale}") return "(?<locale>[^/]+)";
51
+ if (part === "{slug}") return "(?<slug>.*)";
52
+ return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
53
+ }).join("");
54
+ const match = new RegExp(`^${pattern}$`).exec(clean);
55
+ if (match?.groups) {
56
+ return {
57
+ slug: normalizeSlug(match.groups.slug ?? ""),
58
+ locale: match.groups.locale ?? settings.defaultLocale
59
+ };
60
+ }
61
+ return { slug: clean, locale: settings.defaultLocale };
62
+ }
63
+ const [first, ...rest] = clean.split("/");
64
+ if (first && settings.locales.includes(first)) {
65
+ return { slug: rest.join("/"), locale: first };
66
+ }
67
+ return { slug: clean, locale: settings.defaultLocale };
68
+ }
69
+
70
+ // src/index.ts
71
+ var RETRY_AFTER_CAP_MS = 1e4;
72
+ var SITE_TTL_MS = 6e4;
73
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
74
+ function createBrease(opts = {}) {
75
+ const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
76
+ const commit = opts.commit === false ? void 0 : opts.commit ?? env("VERCEL_GIT_COMMIT_SHA");
77
+ const retries = opts.retries ?? 2;
78
+ const baseMs = opts.retryBaseMs ?? 300;
79
+ const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
80
+ let site;
81
+ async function request(path, query = {}, nullOn404 = false) {
82
+ const token = opts.token ?? env("BREASE_TOKEN");
83
+ if (!token)
84
+ throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
85
+ const params = new URLSearchParams();
86
+ for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
87
+ const qs = params.toString();
88
+ const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
89
+ const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
90
+ if (commit) headers["x-brease-commit"] = commit;
91
+ for (let attempt = 0; ; attempt++) {
92
+ let res;
93
+ try {
94
+ res = await doFetch(url, { method: "GET", headers });
95
+ } catch (err) {
96
+ if (attempt < retries) {
97
+ await sleep(backoff(attempt));
98
+ continue;
99
+ }
100
+ throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
101
+ }
102
+ if (res.ok) return await res.json();
103
+ if (res.status === 404 && nullOn404) return null;
104
+ if ((res.status === 429 || res.status >= 500) && attempt < retries) {
105
+ const after = Number(res.headers.get("retry-after"));
106
+ await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
107
+ continue;
108
+ }
109
+ throw await BreaseError.fromResponse(res);
110
+ }
111
+ }
112
+ function backoff(attempt) {
113
+ return baseMs * 2 ** attempt + Math.random() * baseMs;
114
+ }
115
+ const client = {
116
+ getSite() {
117
+ if (!site || Date.now() - site.at > SITE_TTL_MS) {
118
+ const promise = request("/content-api/site").catch((err) => {
119
+ if (site?.promise === promise) site = void 0;
120
+ throw err;
121
+ });
122
+ site = { promise, at: Date.now() };
123
+ }
124
+ return site.promise;
125
+ },
126
+ getPage(slug, { locale }) {
127
+ return request("/content-api/page", { slug, locale }, true);
128
+ },
129
+ getPages(o = {}) {
130
+ return request("/content-api/pages", { locale: o.locale });
131
+ },
132
+ getNavigation(key, { locale }) {
133
+ return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
134
+ },
135
+ getRedirects() {
136
+ return request("/content-api/redirects");
137
+ },
138
+ getRelease() {
139
+ return request("/content-api/release");
140
+ },
141
+ async resolve(pathname) {
142
+ const site2 = await client.getSite();
143
+ const result = resolvePath(site2, pathname);
144
+ return site2.locales.includes(result.locale) ? result : null;
145
+ },
146
+ async route(path) {
147
+ const joined = Array.isArray(path) ? path.map((p) => decodeURIComponent(p)).join("/") : path ?? "";
148
+ const result = await client.resolve(`/${joined}`);
149
+ return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
150
+ },
151
+ async routes() {
152
+ const refs = await client.getPages();
153
+ return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
154
+ },
155
+ async localeContext(path) {
156
+ const target = await client.route(path);
157
+ if (!target) return null;
158
+ const [site2, page, home] = await Promise.all([
159
+ client.getSite(),
160
+ client.getPage(target.slug, { locale: target.locale }),
161
+ client.getPage("", { locale: target.locale })
162
+ ]);
163
+ const settings = {
164
+ locales: site2.locales,
165
+ defaultLocale: site2.defaultLocale,
166
+ localeStrategy: site2.localeStrategy,
167
+ urlTemplate: site2.urlTemplate
168
+ };
169
+ if (!page && !home) return null;
170
+ const alternates = {};
171
+ for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
172
+ const homes = {};
173
+ for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
174
+ return { locale: target.locale, settings, alternates, homes };
175
+ },
176
+ async sitemap(baseUrl) {
177
+ const base = baseUrl.replace(/\/+$/, "");
178
+ const refs = (await client.getPages()).filter((r) => !r.hidden);
179
+ const byPage = /* @__PURE__ */ new Map();
180
+ for (const ref of refs) {
181
+ const alternates = byPage.get(ref.pageId) ?? {};
182
+ alternates[ref.locale] = `${base}${ref.url}`;
183
+ byPage.set(ref.pageId, alternates);
184
+ }
185
+ return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
186
+ }
187
+ };
188
+ return client;
189
+ }
190
+ function pathOf(url) {
191
+ try {
192
+ return new URL(url, "http://localhost").pathname;
193
+ } catch {
194
+ return url;
195
+ }
196
+ }
197
+
10
198
  // src/next.ts
11
199
  var compact = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
12
200
  function toMetadata(seo, opts = {}) {
@@ -100,8 +288,20 @@ async function hmacHex(secret, message) {
100
288
  function json(status, data) {
101
289
  return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
102
290
  }
291
+ function breaseRedirects(client = createBrease()) {
292
+ return async () => {
293
+ try {
294
+ const redirects = await client.getRedirects();
295
+ return redirects.map((r) => ({ source: r.source, destination: r.destination, statusCode: r.status }));
296
+ } catch (err) {
297
+ console.warn(`Brease redirects unavailable: ${err.message}`);
298
+ return [];
299
+ }
300
+ };
301
+ }
103
302
 
104
303
  exports.breaseFetch = breaseFetch;
304
+ exports.breaseRedirects = breaseRedirects;
105
305
  exports.hmacHex = hmacHex;
106
306
  exports.revalidateHandler = revalidateHandler;
107
307
  exports.toMetadata = toMetadata;
package/dist/next.d.cts CHANGED
@@ -1,3 +1,4 @@
1
+ import { Brease } from './index.cjs';
1
2
  import { R as ResolvedSeo } from './types-V0ELFvwy.cjs';
2
3
 
3
4
  type BreaseMetadata = {
@@ -43,5 +44,10 @@ declare function breaseFetch(tags?: string[], revalidate?: number | false): type
43
44
  declare function revalidateHandler(secret?: string): (req: Request) => Promise<Response>;
44
45
  declare function verifySignature(body: string, timestamp: string | null, signature: string | null, secret: string, now?: number): Promise<boolean>;
45
46
  declare function hmacHex(secret: string, message: string): Promise<string>;
47
+ declare function breaseRedirects(client?: Pick<Brease, 'getRedirects'>): () => Promise<{
48
+ source: string;
49
+ destination: string;
50
+ statusCode: 301 | 302 | 307 | 308;
51
+ }[]>;
46
52
 
47
- export { type BreaseMetadata, breaseFetch, hmacHex, revalidateHandler, toMetadata, verifySignature };
53
+ export { type BreaseMetadata, breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
package/dist/next.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { Brease } from './index.js';
1
2
  import { R as ResolvedSeo } from './types-V0ELFvwy.js';
2
3
 
3
4
  type BreaseMetadata = {
@@ -43,5 +44,10 @@ declare function breaseFetch(tags?: string[], revalidate?: number | false): type
43
44
  declare function revalidateHandler(secret?: string): (req: Request) => Promise<Response>;
44
45
  declare function verifySignature(body: string, timestamp: string | null, signature: string | null, secret: string, now?: number): Promise<boolean>;
45
46
  declare function hmacHex(secret: string, message: string): Promise<string>;
47
+ declare function breaseRedirects(client?: Pick<Brease, 'getRedirects'>): () => Promise<{
48
+ source: string;
49
+ destination: string;
50
+ statusCode: 301 | 302 | 307 | 308;
51
+ }[]>;
46
52
 
47
- export { type BreaseMetadata, breaseFetch, hmacHex, revalidateHandler, toMetadata, verifySignature };
53
+ export { type BreaseMetadata, breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
package/dist/next.js CHANGED
@@ -1,4 +1,4 @@
1
- import { env } from './chunk-L7GXI4GK.js';
1
+ import { env, createBrease } from './chunk-N6C2X6KA.js';
2
2
  import './chunk-PKBMQBKP.js';
3
3
 
4
4
  // src/next.ts
@@ -94,5 +94,16 @@ async function hmacHex(secret, message) {
94
94
  function json(status, data) {
95
95
  return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
96
96
  }
97
+ function breaseRedirects(client = createBrease()) {
98
+ return async () => {
99
+ try {
100
+ const redirects = await client.getRedirects();
101
+ return redirects.map((r) => ({ source: r.source, destination: r.destination, statusCode: r.status }));
102
+ } catch (err) {
103
+ console.warn(`Brease redirects unavailable: ${err.message}`);
104
+ return [];
105
+ }
106
+ };
107
+ }
97
108
 
98
- export { breaseFetch, hmacHex, revalidateHandler, toMetadata, verifySignature };
109
+ export { breaseFetch, breaseRedirects, hmacHex, revalidateHandler, toMetadata, verifySignature };
package/dist/react.cjs ADDED
@@ -0,0 +1,110 @@
1
+ 'use client'
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/react.tsx
22
+ var react_exports = {};
23
+ __export(react_exports, {
24
+ BreaseLocaleProvider: () => BreaseLocaleProvider,
25
+ LocaleSwitcher: () => LocaleSwitcher,
26
+ localeLinks: () => localeLinks,
27
+ nativeName: () => nativeName,
28
+ useLocale: () => useLocale,
29
+ useLocaleLinks: () => useLocaleLinks
30
+ });
31
+ module.exports = __toCommonJS(react_exports);
32
+ var import_react = require("react");
33
+
34
+ // src/urls.ts
35
+ function normalizeSlug(input) {
36
+ return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
37
+ }
38
+ function buildPath(settings, slug, locale) {
39
+ const clean = normalizeSlug(slug);
40
+ if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
41
+ const path = settings.urlTemplate.replace("{locale}", locale).replace("{slug}", clean);
42
+ return `/${normalizeSlug(path)}`;
43
+ }
44
+ const prefixed = settings.localeStrategy === "PREFIX_ALL" || locale !== settings.defaultLocale;
45
+ const parts = [prefixed ? locale : "", clean].filter(Boolean);
46
+ return `/${parts.join("/")}`;
47
+ }
48
+
49
+ // src/react.tsx
50
+ var import_jsx_runtime = require("react/jsx-runtime");
51
+ var Context = (0, import_react.createContext)(null);
52
+ function BreaseLocaleProvider({ value, children }) {
53
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Context.Provider, { value, children });
54
+ }
55
+ function useLocale() {
56
+ const value = (0, import_react.useContext)(Context);
57
+ if (!value) throw new Error("useLocale() needs a <BreaseLocaleProvider> above it");
58
+ return {
59
+ ...value,
60
+ locales: value.settings.locales,
61
+ href: (slug, locale = value.locale) => buildPath(value.settings, slug, locale)
62
+ };
63
+ }
64
+ function useLocaleLinks() {
65
+ const { locale, settings, alternates, homes } = useLocale();
66
+ return localeLinks(settings, { alternates, homes }, locale);
67
+ }
68
+ function localeLinks(settings, paths, current) {
69
+ return settings.locales.flatMap((l) => {
70
+ const href = paths.alternates[l] ?? paths.homes[l] ?? (l === current ? buildPath(settings, "", l) : null);
71
+ return href ? [{ locale: l, label: nativeName(l), href, current: l === current }] : [];
72
+ });
73
+ }
74
+ function nativeName(locale) {
75
+ try {
76
+ const name = new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
77
+ return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
78
+ } catch {
79
+ return locale;
80
+ }
81
+ }
82
+ function LocaleSwitcher({
83
+ className,
84
+ linkClassName,
85
+ label = "Language"
86
+ }) {
87
+ const links = useLocaleLinks();
88
+ if (links.length < 2) return null;
89
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("nav", { "aria-label": label, className, children: links.map((l) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
90
+ "a",
91
+ {
92
+ href: l.href,
93
+ hrefLang: l.locale,
94
+ lang: l.locale,
95
+ "aria-current": l.current ? "page" : void 0,
96
+ className: linkClassName,
97
+ children: l.label
98
+ },
99
+ l.locale
100
+ )) });
101
+ }
102
+ // Annotate the CommonJS export names for ESM import in node:
103
+ 0 && (module.exports = {
104
+ BreaseLocaleProvider,
105
+ LocaleSwitcher,
106
+ localeLinks,
107
+ nativeName,
108
+ useLocale,
109
+ useLocaleLinks
110
+ });
@@ -0,0 +1,43 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+
4
+ type LocaleStrategy = 'PREFIX_EXCEPT_DEFAULT' | 'PREFIX_ALL' | 'CUSTOM';
5
+ type UrlSettings = {
6
+ locales: string[];
7
+ defaultLocale: string;
8
+ localeStrategy: LocaleStrategy;
9
+ urlTemplate?: string | null;
10
+ };
11
+
12
+ type LocaleContext = {
13
+ locale: string;
14
+ settings: UrlSettings;
15
+ alternates: Record<string, string>;
16
+ homes: Record<string, string>;
17
+ };
18
+
19
+ declare function BreaseLocaleProvider({ value, children }: {
20
+ value: LocaleContext;
21
+ children: ReactNode;
22
+ }): react.JSX.Element;
23
+ type LocaleInfo = LocaleContext & {
24
+ locales: string[];
25
+ href: (slug: string, locale?: string) => string;
26
+ };
27
+ declare function useLocale(): LocaleInfo;
28
+ type LocaleLink = {
29
+ locale: string;
30
+ label: string;
31
+ href: string;
32
+ current: boolean;
33
+ };
34
+ declare function useLocaleLinks(): LocaleLink[];
35
+ declare function localeLinks(settings: UrlSettings, paths: Pick<LocaleContext, 'alternates' | 'homes'>, current: string): LocaleLink[];
36
+ declare function nativeName(locale: string): string;
37
+ declare function LocaleSwitcher({ className, linkClassName, label }: {
38
+ className?: string;
39
+ linkClassName?: string;
40
+ label?: string;
41
+ }): react.JSX.Element | null;
42
+
43
+ export { BreaseLocaleProvider, type LocaleInfo, type LocaleLink, LocaleSwitcher, localeLinks, nativeName, useLocale, useLocaleLinks };
@@ -0,0 +1,43 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+
4
+ type LocaleStrategy = 'PREFIX_EXCEPT_DEFAULT' | 'PREFIX_ALL' | 'CUSTOM';
5
+ type UrlSettings = {
6
+ locales: string[];
7
+ defaultLocale: string;
8
+ localeStrategy: LocaleStrategy;
9
+ urlTemplate?: string | null;
10
+ };
11
+
12
+ type LocaleContext = {
13
+ locale: string;
14
+ settings: UrlSettings;
15
+ alternates: Record<string, string>;
16
+ homes: Record<string, string>;
17
+ };
18
+
19
+ declare function BreaseLocaleProvider({ value, children }: {
20
+ value: LocaleContext;
21
+ children: ReactNode;
22
+ }): react.JSX.Element;
23
+ type LocaleInfo = LocaleContext & {
24
+ locales: string[];
25
+ href: (slug: string, locale?: string) => string;
26
+ };
27
+ declare function useLocale(): LocaleInfo;
28
+ type LocaleLink = {
29
+ locale: string;
30
+ label: string;
31
+ href: string;
32
+ current: boolean;
33
+ };
34
+ declare function useLocaleLinks(): LocaleLink[];
35
+ declare function localeLinks(settings: UrlSettings, paths: Pick<LocaleContext, 'alternates' | 'homes'>, current: string): LocaleLink[];
36
+ declare function nativeName(locale: string): string;
37
+ declare function LocaleSwitcher({ className, linkClassName, label }: {
38
+ className?: string;
39
+ linkClassName?: string;
40
+ label?: string;
41
+ }): react.JSX.Element | null;
42
+
43
+ export { BreaseLocaleProvider, type LocaleInfo, type LocaleLink, LocaleSwitcher, localeLinks, nativeName, useLocale, useLocaleLinks };
package/dist/react.js ADDED
@@ -0,0 +1,81 @@
1
+ 'use client'
2
+
3
+ // src/react.tsx
4
+ import { createContext, useContext } from "react";
5
+
6
+ // src/urls.ts
7
+ function normalizeSlug(input) {
8
+ return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
9
+ }
10
+ function buildPath(settings, slug, locale) {
11
+ const clean = normalizeSlug(slug);
12
+ if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
13
+ const path = settings.urlTemplate.replace("{locale}", locale).replace("{slug}", clean);
14
+ return `/${normalizeSlug(path)}`;
15
+ }
16
+ const prefixed = settings.localeStrategy === "PREFIX_ALL" || locale !== settings.defaultLocale;
17
+ const parts = [prefixed ? locale : "", clean].filter(Boolean);
18
+ return `/${parts.join("/")}`;
19
+ }
20
+
21
+ // src/react.tsx
22
+ import { jsx } from "react/jsx-runtime";
23
+ var Context = createContext(null);
24
+ function BreaseLocaleProvider({ value, children }) {
25
+ return /* @__PURE__ */ jsx(Context.Provider, { value, children });
26
+ }
27
+ function useLocale() {
28
+ const value = useContext(Context);
29
+ if (!value) throw new Error("useLocale() needs a <BreaseLocaleProvider> above it");
30
+ return {
31
+ ...value,
32
+ locales: value.settings.locales,
33
+ href: (slug, locale = value.locale) => buildPath(value.settings, slug, locale)
34
+ };
35
+ }
36
+ function useLocaleLinks() {
37
+ const { locale, settings, alternates, homes } = useLocale();
38
+ return localeLinks(settings, { alternates, homes }, locale);
39
+ }
40
+ function localeLinks(settings, paths, current) {
41
+ return settings.locales.flatMap((l) => {
42
+ const href = paths.alternates[l] ?? paths.homes[l] ?? (l === current ? buildPath(settings, "", l) : null);
43
+ return href ? [{ locale: l, label: nativeName(l), href, current: l === current }] : [];
44
+ });
45
+ }
46
+ function nativeName(locale) {
47
+ try {
48
+ const name = new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
49
+ return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
50
+ } catch {
51
+ return locale;
52
+ }
53
+ }
54
+ function LocaleSwitcher({
55
+ className,
56
+ linkClassName,
57
+ label = "Language"
58
+ }) {
59
+ const links = useLocaleLinks();
60
+ if (links.length < 2) return null;
61
+ return /* @__PURE__ */ jsx("nav", { "aria-label": label, className, children: links.map((l) => /* @__PURE__ */ jsx(
62
+ "a",
63
+ {
64
+ href: l.href,
65
+ hrefLang: l.locale,
66
+ lang: l.locale,
67
+ "aria-current": l.current ? "page" : void 0,
68
+ className: linkClassName,
69
+ children: l.label
70
+ },
71
+ l.locale
72
+ )) });
73
+ }
74
+ export {
75
+ BreaseLocaleProvider,
76
+ LocaleSwitcher,
77
+ localeLinks,
78
+ nativeName,
79
+ useLocale,
80
+ useLocaleLinks
81
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brease-client",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Brease delivery API client for Next.js, Astro and any fetch-capable runtime",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -46,6 +46,11 @@
46
46
  "types": "./dist/image.d.ts",
47
47
  "import": "./dist/image.js",
48
48
  "require": "./dist/image.cjs"
49
+ },
50
+ "./react": {
51
+ "types": "./dist/react.d.ts",
52
+ "import": "./dist/react.js",
53
+ "require": "./dist/react.cjs"
49
54
  }
50
55
  },
51
56
  "files": [
@@ -56,16 +61,24 @@
56
61
  "node": ">=18"
57
62
  },
58
63
  "peerDependencies": {
59
- "next": ">=14"
64
+ "next": ">=14",
65
+ "react": ">=18"
60
66
  },
61
67
  "peerDependenciesMeta": {
62
68
  "next": {
63
69
  "optional": true
70
+ },
71
+ "react": {
72
+ "optional": true
64
73
  }
65
74
  },
66
75
  "devDependencies": {
67
76
  "@biomejs/biome": "^2.5.14",
68
77
  "@types/node": "^22.20.4",
78
+ "@types/react": "^19.3.0",
79
+ "@types/react-dom": "^19.3.0",
80
+ "react": "^19.3.0",
81
+ "react-dom": "^19.3.0",
69
82
  "tsup": "^8.5.1",
70
83
  "typescript": "^5.9.3",
71
84
  "vitest": "^5.0.1"
@@ -1,8 +0,0 @@
1
- // src/env.ts
2
- function env(name) {
3
- const proc = globalThis.process;
4
- const value = proc?.env?.[name];
5
- return value === "" ? void 0 : value;
6
- }
7
-
8
- export { env };