brease-client 0.8.2 → 0.9.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 +170 -22
- package/dist/astro.js +2 -3
- package/dist/chunk-ES4KMYDH.js +771 -0
- package/dist/{chunk-QZXUMDB7.js → chunk-VQGKMILO.js} +9 -2
- package/dist/cli.cjs +892 -39
- package/dist/cli.js +262 -20
- package/dist/html.js +1 -2
- package/dist/image.cjs +2 -2
- package/dist/image.d.cts +7 -3
- package/dist/image.d.ts +7 -3
- package/dist/image.js +2 -2
- package/dist/index.cjs +412 -46
- package/dist/index.d.cts +13 -3
- package/dist/index.d.ts +13 -3
- package/dist/index.js +2 -3
- package/dist/next.cjs +89 -42
- package/dist/next.js +4 -4
- package/package.json +1 -1
- package/dist/chunk-CQZLTZGN.js +0 -79
- package/dist/chunk-MWTYINWA.js +0 -383
- package/dist/chunk-N3QOL5EU.js +0 -10
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
import { headTags } from './chunk-VQGKMILO.js';
|
|
2
|
+
import { __publicField } from './chunk-PKBMQBKP.js';
|
|
3
|
+
|
|
4
|
+
// src/env.ts
|
|
5
|
+
function env(name) {
|
|
6
|
+
const proc = globalThis.process;
|
|
7
|
+
const value = proc?.env?.[name];
|
|
8
|
+
return value === "" ? void 0 : value;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// src/errors.ts
|
|
12
|
+
var BreaseError = class _BreaseError extends Error {
|
|
13
|
+
constructor(code, message, status, requestId, details) {
|
|
14
|
+
super(message);
|
|
15
|
+
__publicField(this, "code", code);
|
|
16
|
+
__publicField(this, "status", status);
|
|
17
|
+
__publicField(this, "requestId", requestId);
|
|
18
|
+
__publicField(this, "details", details);
|
|
19
|
+
__publicField(this, "name", "BreaseError");
|
|
20
|
+
}
|
|
21
|
+
static async fromResponse(res) {
|
|
22
|
+
const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-vercel-id") ?? void 0;
|
|
23
|
+
let code = res.status === 429 ? "rate_limited" : res.status >= 500 ? "upstream" : "http_error";
|
|
24
|
+
let message = `Brease API responded ${res.status}`;
|
|
25
|
+
let details;
|
|
26
|
+
try {
|
|
27
|
+
const body = await res.json();
|
|
28
|
+
if (body?.error) {
|
|
29
|
+
code = body.error.code ?? code;
|
|
30
|
+
message = body.error.message ?? message;
|
|
31
|
+
details = body.error.details;
|
|
32
|
+
}
|
|
33
|
+
} catch {
|
|
34
|
+
}
|
|
35
|
+
return new _BreaseError(code, message, res.status, requestId ?? void 0, details);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// src/urls.ts
|
|
40
|
+
function normalizeSlug(input) {
|
|
41
|
+
return input.trim().replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");
|
|
42
|
+
}
|
|
43
|
+
function buildPath(settings, slug, locale) {
|
|
44
|
+
const clean = normalizeSlug(slug);
|
|
45
|
+
if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
|
|
46
|
+
const path = settings.urlTemplate.replace("{locale}", locale).replace("{slug}", clean);
|
|
47
|
+
return `/${normalizeSlug(path)}`;
|
|
48
|
+
}
|
|
49
|
+
const prefixed = settings.localeStrategy === "PREFIX_ALL" || locale !== settings.defaultLocale;
|
|
50
|
+
const parts = [prefixed ? locale : "", clean].filter(Boolean);
|
|
51
|
+
return `/${parts.join("/")}`;
|
|
52
|
+
}
|
|
53
|
+
function customPattern(template) {
|
|
54
|
+
const parts = normalizeSlug(template).split(/(\{locale\}|\{slug\})/);
|
|
55
|
+
const slashBefore = (i) => parts[i] === "{slug}" && !!parts[i - 1]?.endsWith("/");
|
|
56
|
+
const slashAfter = (i) => parts[i] === "{slug}" && !slashBefore(i) && !!parts[i + 1]?.startsWith("/");
|
|
57
|
+
const pattern = parts.map((part, i) => {
|
|
58
|
+
if (part === "{locale}") return "(?<locale>[^/]+)";
|
|
59
|
+
if (part === "{slug}") {
|
|
60
|
+
if (slashBefore(i)) return "(?:/(?<slug>.*))?";
|
|
61
|
+
if (slashAfter(i)) return "(?:(?<slug>.*)/)?";
|
|
62
|
+
return "(?<slug>.*)";
|
|
63
|
+
}
|
|
64
|
+
let text = part;
|
|
65
|
+
if (slashBefore(i + 1)) text = text.slice(0, -1);
|
|
66
|
+
if (slashAfter(i - 1)) text = text.slice(1);
|
|
67
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
68
|
+
}).join("");
|
|
69
|
+
return new RegExp(`^${pattern}$`);
|
|
70
|
+
}
|
|
71
|
+
function safeDecode(value) {
|
|
72
|
+
try {
|
|
73
|
+
return decodeURIComponent(value);
|
|
74
|
+
} catch {
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function resolvePath(settings, pathname) {
|
|
79
|
+
const clean = normalizeSlug(safeDecode(pathname.split(/[?#]/)[0] ?? ""));
|
|
80
|
+
if (settings.localeStrategy === "CUSTOM" && settings.urlTemplate) {
|
|
81
|
+
const match = customPattern(settings.urlTemplate).exec(clean);
|
|
82
|
+
if (match?.groups) {
|
|
83
|
+
return {
|
|
84
|
+
slug: normalizeSlug(match.groups.slug ?? ""),
|
|
85
|
+
locale: match.groups.locale ?? settings.defaultLocale
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return { slug: clean, locale: settings.defaultLocale };
|
|
89
|
+
}
|
|
90
|
+
const [first, ...rest] = clean.split("/");
|
|
91
|
+
if (first && settings.locales.includes(first)) {
|
|
92
|
+
return { slug: rest.join("/"), locale: first };
|
|
93
|
+
}
|
|
94
|
+
return { slug: clean, locale: settings.defaultLocale };
|
|
95
|
+
}
|
|
96
|
+
function canonicalPath(settings, pathname) {
|
|
97
|
+
const path = pathname.split(/[?#]/)[0] ?? "";
|
|
98
|
+
const { slug, locale } = resolvePath(settings, path);
|
|
99
|
+
const canonical = buildPath(settings, slug, locale);
|
|
100
|
+
const trim = (p) => p.length > 1 ? p.replace(/\/+$/, "") : p;
|
|
101
|
+
return trim(safeDecode(path)) === trim(canonical) ? null : canonical;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/analytics.ts
|
|
105
|
+
var MEASUREMENT_ID = /^G-[A-Z0-9]+$/;
|
|
106
|
+
function ga4Tag(site) {
|
|
107
|
+
const id = site.analytics?.ga4;
|
|
108
|
+
if (!id || !MEASUREMENT_ID.test(id)) return null;
|
|
109
|
+
const inline = [
|
|
110
|
+
"window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}",
|
|
111
|
+
"gtag('consent','default',{ad_storage:'denied',ad_user_data:'denied',ad_personalization:'denied',analytics_storage:'denied',wait_for_update:500});",
|
|
112
|
+
"gtag('js',new Date());",
|
|
113
|
+
`gtag('config','${id}');`
|
|
114
|
+
].join("");
|
|
115
|
+
return { id, src: `https://www.googletagmanager.com/gtag/js?id=${id}`, inline };
|
|
116
|
+
}
|
|
117
|
+
function ga4Html(site) {
|
|
118
|
+
const tag = ga4Tag(site);
|
|
119
|
+
return tag ? `<script async src="${tag.src}"></script>
|
|
120
|
+
<script>${tag.inline}</script>` : "";
|
|
121
|
+
}
|
|
122
|
+
function grantAnalytics(granted = true) {
|
|
123
|
+
const gtag = globalThis.gtag;
|
|
124
|
+
gtag?.("consent", "update", { analytics_storage: granted ? "granted" : "denied" });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// src/custom-code.ts
|
|
128
|
+
function customTags(seo) {
|
|
129
|
+
return [seo.customHead, seo.customCode].flatMap((html) => html ? parseTags(html) : []);
|
|
130
|
+
}
|
|
131
|
+
function parseTags(html) {
|
|
132
|
+
const out = [];
|
|
133
|
+
const re = /<(script|style|noscript)\b([^>]*)>([\s\S]*?)<\/\1\s*>|<(meta|link)\b([^>]*?)\/?>/gi;
|
|
134
|
+
for (const m of html.matchAll(re)) {
|
|
135
|
+
if (m[1]) {
|
|
136
|
+
const tag = m[1].toLowerCase();
|
|
137
|
+
out.push({ tag, attrs: attrsOf(m[2] ?? ""), ...m[3]?.trim() ? { content: m[3] } : {} });
|
|
138
|
+
} else if (m[4])
|
|
139
|
+
out.push({ tag: m[4].toLowerCase(), attrs: attrsOf(m[5] ?? "") });
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
function attrsOf(source) {
|
|
144
|
+
const attrs = {};
|
|
145
|
+
for (const m of source.matchAll(/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g))
|
|
146
|
+
attrs[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? "";
|
|
147
|
+
return attrs;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// src/locales.ts
|
|
151
|
+
function localeLinks(context) {
|
|
152
|
+
const { settings, alternates, homes, locale: current } = context;
|
|
153
|
+
return settings.locales.flatMap((l) => {
|
|
154
|
+
const href = alternates[l] ?? homes[l] ?? (l === current ? buildPath(settings, "", l) : null);
|
|
155
|
+
return href ? [{ locale: l, label: nativeName(l), href, current: l === current }] : [];
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
function nativeName(locale) {
|
|
159
|
+
try {
|
|
160
|
+
const name = new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
|
|
161
|
+
return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
|
|
162
|
+
} catch {
|
|
163
|
+
return locale;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
var localeHref = (settings, slug, locale) => buildPath(settings, slug, locale);
|
|
167
|
+
|
|
168
|
+
// src/markers.ts
|
|
169
|
+
function fieldPath(path, pageId) {
|
|
170
|
+
return pageId ? `${pageId}:${path}` : path;
|
|
171
|
+
}
|
|
172
|
+
function navPath(key) {
|
|
173
|
+
return `nav:${key}`;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// src/redirects.ts
|
|
177
|
+
function matchRedirect(redirects, pathname) {
|
|
178
|
+
const path = normalize(pathname);
|
|
179
|
+
for (const r of redirects) {
|
|
180
|
+
const params = matchSource(normalize(r.source), path);
|
|
181
|
+
if (!params) continue;
|
|
182
|
+
const destination = r.destination.replace(
|
|
183
|
+
/:([A-Za-z_][A-Za-z0-9_]*)\*?/g,
|
|
184
|
+
(whole, name) => name in params ? params[name] : whole
|
|
185
|
+
);
|
|
186
|
+
if (normalize(destination) === path) continue;
|
|
187
|
+
return { destination, status: r.status };
|
|
188
|
+
}
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
var normalize = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p) || "/";
|
|
192
|
+
function matchSource(source, path) {
|
|
193
|
+
const want = source.split("/").filter(Boolean);
|
|
194
|
+
const have = path.split("/").filter(Boolean);
|
|
195
|
+
const params = {};
|
|
196
|
+
for (let i = 0; i < want.length; i++) {
|
|
197
|
+
const seg = want[i];
|
|
198
|
+
const rest = /^:([A-Za-z_][A-Za-z0-9_]*)\*$/.exec(seg);
|
|
199
|
+
if (rest) {
|
|
200
|
+
params[rest[1]] = have.slice(i).join("/");
|
|
201
|
+
return params;
|
|
202
|
+
}
|
|
203
|
+
const value = have[i];
|
|
204
|
+
if (value === void 0) return null;
|
|
205
|
+
const param = /^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(seg);
|
|
206
|
+
if (param) params[param[1]] = value;
|
|
207
|
+
else if (safeDecode(value) !== safeDecode(seg)) return null;
|
|
208
|
+
}
|
|
209
|
+
return want.length === have.length ? params : null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// src/sections.ts
|
|
213
|
+
var sectionsAttrs = { "data-brease-sections": "sections" };
|
|
214
|
+
function sectionAttrs(section) {
|
|
215
|
+
return { "data-brease-section": section.id, "data-brease-block": section.type };
|
|
216
|
+
}
|
|
217
|
+
var SECTION_FOLDERS = ["src/brease/sections", "brease/sections"];
|
|
218
|
+
var TYPE_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
219
|
+
var MAP_FILE = /^(index|sections)\.(astro|vue|svelte|[cm]?[jt]sx?)$/i;
|
|
220
|
+
function checkSections(files, pages = {}) {
|
|
221
|
+
const warnings = [];
|
|
222
|
+
const folder = SECTION_FOLDERS.find((f) => Object.keys(files).some((p) => p.startsWith(`${f}/`)));
|
|
223
|
+
if (!folder) return warnings;
|
|
224
|
+
const inFolder = Object.entries(files).map(([p, text]) => [p.slice(folder.length + 1), text]);
|
|
225
|
+
const types = [
|
|
226
|
+
...new Set(
|
|
227
|
+
inFolder.map(([p]) => p.split("/")).filter((s) => s.length > 1).map((s) => s[0])
|
|
228
|
+
)
|
|
229
|
+
];
|
|
230
|
+
const map = inFolder.find(([p]) => MAP_FILE.test(p));
|
|
231
|
+
if (!map)
|
|
232
|
+
warnings.push(
|
|
233
|
+
`${folder} has no map file (index.tsx, index.ts, Sections.astro or the like) rendering the section types`
|
|
234
|
+
);
|
|
235
|
+
const marked = inFolder.some(
|
|
236
|
+
([, text]) => text.includes("data-brease-section") || text.includes("sectionAttrs(")
|
|
237
|
+
);
|
|
238
|
+
if (!marked)
|
|
239
|
+
warnings.push(
|
|
240
|
+
`No component in ${folder} renders data-brease-section (or sectionAttrs), so editors can't add sections`
|
|
241
|
+
);
|
|
242
|
+
for (const type of types) {
|
|
243
|
+
if (!TYPE_NAME.test(type)) {
|
|
244
|
+
warnings.push(`${folder}/${type}: use lowercase letters, numbers and - in section folder names`);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const json = files[`${folder}/${type}/section.json`];
|
|
248
|
+
if (json === void 0) {
|
|
249
|
+
warnings.push(`${folder}/${type} has no section.json`);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
const meta = JSON.parse(json);
|
|
254
|
+
if (typeof meta.name !== "string" || !meta.name.trim())
|
|
255
|
+
warnings.push(`${folder}/${type}/section.json has no name`);
|
|
256
|
+
if (meta.fields !== void 0 && (typeof meta.fields !== "object" || meta.fields === null))
|
|
257
|
+
warnings.push(`${folder}/${type}/section.json: fields must be a JSON Schema object`);
|
|
258
|
+
} catch {
|
|
259
|
+
warnings.push(`${folder}/${type}/section.json is not valid JSON`);
|
|
260
|
+
}
|
|
261
|
+
if (map && !map[1].includes(type)) warnings.push(`${type} is in ${folder} but not in its map file`);
|
|
262
|
+
}
|
|
263
|
+
const known = new Set(types);
|
|
264
|
+
for (const [pageId, locales] of Object.entries(pages)) {
|
|
265
|
+
let reference = null;
|
|
266
|
+
for (const [locale, file] of Object.entries(locales)) {
|
|
267
|
+
const list = file.content?.sections;
|
|
268
|
+
if (list === void 0) continue;
|
|
269
|
+
if (!Array.isArray(list)) {
|
|
270
|
+
warnings.push(`${pageId} (${locale}): sections is not a list`);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
const ids = /* @__PURE__ */ new Set();
|
|
274
|
+
for (const item of list) {
|
|
275
|
+
if (typeof item?.id !== "string" || typeof item.type !== "string") {
|
|
276
|
+
warnings.push(`${pageId} (${locale}): a section has no id or type`);
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (ids.has(item.id)) warnings.push(`${pageId} (${locale}): section ${item.id} appears twice`);
|
|
280
|
+
ids.add(item.id);
|
|
281
|
+
if (!known.has(item.type))
|
|
282
|
+
warnings.push(`${pageId} (${locale}): section type "${item.type}" has no folder`);
|
|
283
|
+
}
|
|
284
|
+
const shape = list.map((s) => `${s?.id}:${s?.type}`).join(",");
|
|
285
|
+
if (reference === null) reference = shape;
|
|
286
|
+
else if (shape !== reference)
|
|
287
|
+
warnings.push(`${pageId}: the sections in ${locale} differ from the other locales`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return warnings;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// src/signature.ts
|
|
294
|
+
var MAX_SKEW_MS = 5 * 6e4;
|
|
295
|
+
async function hmacHex(secret, message) {
|
|
296
|
+
const enc = new TextEncoder();
|
|
297
|
+
const key = await crypto.subtle.importKey(
|
|
298
|
+
"raw",
|
|
299
|
+
enc.encode(secret),
|
|
300
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
301
|
+
false,
|
|
302
|
+
["sign"]
|
|
303
|
+
);
|
|
304
|
+
const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(message)));
|
|
305
|
+
return Array.from(sig, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
306
|
+
}
|
|
307
|
+
async function verifySignature(body, timestamp, signature, secret, now = Date.now()) {
|
|
308
|
+
if (!timestamp || !signature) return false;
|
|
309
|
+
if (!Number.isFinite(Number(timestamp)) || Math.abs(now - Number(timestamp)) > MAX_SKEW_MS) return false;
|
|
310
|
+
const expected = await hmacHex(secret, `${timestamp}.${body}`);
|
|
311
|
+
if (expected.length !== signature.length) return false;
|
|
312
|
+
let diff = 0;
|
|
313
|
+
for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
|
|
314
|
+
return diff === 0;
|
|
315
|
+
}
|
|
316
|
+
async function verifyRevalidate(req, secret) {
|
|
317
|
+
const raw = await req.text();
|
|
318
|
+
const ok = await verifySignature(
|
|
319
|
+
raw,
|
|
320
|
+
req.headers.get("x-brease-timestamp"),
|
|
321
|
+
req.headers.get("x-brease-signature"),
|
|
322
|
+
secret
|
|
323
|
+
);
|
|
324
|
+
if (!ok) return { ok: false, reason: "signature" };
|
|
325
|
+
let body;
|
|
326
|
+
try {
|
|
327
|
+
body = JSON.parse(raw || "{}");
|
|
328
|
+
} catch {
|
|
329
|
+
return { ok: false, reason: "body" };
|
|
330
|
+
}
|
|
331
|
+
const paths = new Set(body.paths ?? []);
|
|
332
|
+
for (const url of body.urls ?? []) {
|
|
333
|
+
try {
|
|
334
|
+
paths.add(new URL(url, "http://localhost").pathname);
|
|
335
|
+
} catch {
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return { ok: true, paths: [...paths], tags: ["brease", ...body.tags ?? []], body };
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// src/template.ts
|
|
342
|
+
var VOID = /* @__PURE__ */ new Set([
|
|
343
|
+
"area",
|
|
344
|
+
"base",
|
|
345
|
+
"br",
|
|
346
|
+
"col",
|
|
347
|
+
"embed",
|
|
348
|
+
"hr",
|
|
349
|
+
"img",
|
|
350
|
+
"input",
|
|
351
|
+
"link",
|
|
352
|
+
"meta",
|
|
353
|
+
"source",
|
|
354
|
+
"track",
|
|
355
|
+
"wbr"
|
|
356
|
+
]);
|
|
357
|
+
var RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title"]);
|
|
358
|
+
var ATTR = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
359
|
+
function parseAttrs(source) {
|
|
360
|
+
const attrs = [];
|
|
361
|
+
for (const m of source.matchAll(ATTR)) {
|
|
362
|
+
attrs.push({ name: m[1], value: m[2] ?? m[3] ?? m[4] ?? null });
|
|
363
|
+
}
|
|
364
|
+
return attrs;
|
|
365
|
+
}
|
|
366
|
+
function parseHtml(html) {
|
|
367
|
+
const root = { kind: "el", tag: "#root", attrs: [], children: [], selfClosing: false, void: false };
|
|
368
|
+
const stack = [root];
|
|
369
|
+
const top = () => stack[stack.length - 1];
|
|
370
|
+
let i = 0;
|
|
371
|
+
const text = (t) => {
|
|
372
|
+
if (t) top().children.push({ kind: "raw", text: t });
|
|
373
|
+
};
|
|
374
|
+
while (i < html.length) {
|
|
375
|
+
const lt = html.indexOf("<", i);
|
|
376
|
+
if (lt === -1) {
|
|
377
|
+
text(html.slice(i));
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
text(html.slice(i, lt));
|
|
381
|
+
if (html.startsWith("<!--", lt)) {
|
|
382
|
+
const end = html.indexOf("-->", lt + 4);
|
|
383
|
+
const stop = end === -1 ? html.length : end + 3;
|
|
384
|
+
text(html.slice(lt, stop));
|
|
385
|
+
i = stop;
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
if (html[lt + 1] === "!" || html[lt + 1] === "?") {
|
|
389
|
+
const end = html.indexOf(">", lt);
|
|
390
|
+
const stop = end === -1 ? html.length : end + 1;
|
|
391
|
+
text(html.slice(lt, stop));
|
|
392
|
+
i = stop;
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
const close = /^<\/([a-zA-Z][\w:-]*)\s*>/.exec(html.slice(lt));
|
|
396
|
+
if (close) {
|
|
397
|
+
const name = close[1].toLowerCase();
|
|
398
|
+
const at = stack.map((e) => e.tag).lastIndexOf(name);
|
|
399
|
+
if (at > 0) stack.length = at;
|
|
400
|
+
i = lt + close[0].length;
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
const open = /^<([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>/.exec(
|
|
404
|
+
html.slice(lt)
|
|
405
|
+
);
|
|
406
|
+
if (!open) {
|
|
407
|
+
text("<");
|
|
408
|
+
i = lt + 1;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
const tag = open[1].toLowerCase();
|
|
412
|
+
const el = {
|
|
413
|
+
kind: "el",
|
|
414
|
+
tag,
|
|
415
|
+
attrs: parseAttrs(open[2] ?? ""),
|
|
416
|
+
children: [],
|
|
417
|
+
selfClosing: open[3] === "/",
|
|
418
|
+
void: VOID.has(tag)
|
|
419
|
+
};
|
|
420
|
+
top().children.push(el);
|
|
421
|
+
i = lt + open[0].length;
|
|
422
|
+
if (el.void || el.selfClosing) continue;
|
|
423
|
+
if (RAW_TEXT.has(tag)) {
|
|
424
|
+
const end = html.toLowerCase().indexOf(`</${tag}`, i);
|
|
425
|
+
const stop = end === -1 ? html.length : end;
|
|
426
|
+
if (stop > i) el.children.push({ kind: "raw", text: html.slice(i, stop) });
|
|
427
|
+
const gt = end === -1 ? html.length : html.indexOf(">", end);
|
|
428
|
+
i = gt === -1 ? html.length : gt + 1;
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
stack.push(el);
|
|
432
|
+
}
|
|
433
|
+
return root.children;
|
|
434
|
+
}
|
|
435
|
+
var escapeText = (v) => v.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
436
|
+
var escapeAttr = (v) => escapeText(v).replace(/"/g, """);
|
|
437
|
+
function serializeHtml(nodes) {
|
|
438
|
+
return nodes.map((n) => {
|
|
439
|
+
if (n.kind === "raw") return n.text;
|
|
440
|
+
const attrs = n.attrs.map(
|
|
441
|
+
(a) => a.value === null ? ` ${a.name}` : ` ${a.name}="${escapeAttr(a.value)}"`
|
|
442
|
+
);
|
|
443
|
+
const open = `<${n.tag}${attrs.join("")}${n.selfClosing ? " /" : ""}>`;
|
|
444
|
+
if (n.void || n.selfClosing) return open;
|
|
445
|
+
return `${open}${serializeHtml(n.children)}</${n.tag}>`;
|
|
446
|
+
}).join("");
|
|
447
|
+
}
|
|
448
|
+
var attr = (el, name) => el.attrs.find((a) => a.name === name);
|
|
449
|
+
function setAttr(el, name, value) {
|
|
450
|
+
const found = attr(el, name);
|
|
451
|
+
if (found) found.value = value;
|
|
452
|
+
else el.attrs.push({ name, value });
|
|
453
|
+
}
|
|
454
|
+
var removeAttr = (el, name) => {
|
|
455
|
+
el.attrs = el.attrs.filter((a) => a.name !== name);
|
|
456
|
+
};
|
|
457
|
+
var elements = (nodes) => nodes.filter((n) => n.kind === "el");
|
|
458
|
+
function valueAt(source, path) {
|
|
459
|
+
let current = source;
|
|
460
|
+
for (const key of path.split(".")) {
|
|
461
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
462
|
+
current = current[key];
|
|
463
|
+
}
|
|
464
|
+
return current;
|
|
465
|
+
}
|
|
466
|
+
var isImage = (v) => !!v && typeof v === "object" && typeof v.url === "string" && !("href" in v);
|
|
467
|
+
var isLink = (v) => !!v && typeof v === "object" && typeof v.href === "string";
|
|
468
|
+
var looksLikeHtml = (v) => /<[a-z][\s\S]*>/i.test(v);
|
|
469
|
+
function setText(el, value, html) {
|
|
470
|
+
el.children = [{ kind: "raw", text: html ? value : escapeText(value) }];
|
|
471
|
+
}
|
|
472
|
+
function renumber(nodes, listPath, index) {
|
|
473
|
+
const from = `${listPath}.0.`;
|
|
474
|
+
const to = `${listPath}.${index}.`;
|
|
475
|
+
for (const el of elements(nodes)) {
|
|
476
|
+
const marker = attr(el, "data-brease");
|
|
477
|
+
if (marker?.value?.includes(from)) marker.value = marker.value.replace(from, to);
|
|
478
|
+
renumber(el.children, listPath, index);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
var clone = (value) => JSON.parse(JSON.stringify(value));
|
|
482
|
+
function itemTemplate(el) {
|
|
483
|
+
const children = elements(el.children);
|
|
484
|
+
const template = children.find((c) => attr(c, "data-brease-item"));
|
|
485
|
+
return template ?? null;
|
|
486
|
+
}
|
|
487
|
+
function renderNavItem(template, item) {
|
|
488
|
+
const copy = clone(template);
|
|
489
|
+
const labels = [];
|
|
490
|
+
const links = [];
|
|
491
|
+
const walk = (el) => {
|
|
492
|
+
if (attr(el, "data-brease-label")) labels.push(el);
|
|
493
|
+
if (el.tag === "a") links.push(el);
|
|
494
|
+
for (const c of elements(el.children)) walk(c);
|
|
495
|
+
};
|
|
496
|
+
walk(copy);
|
|
497
|
+
const link = copy.tag === "a" ? copy : links[0];
|
|
498
|
+
if (link) {
|
|
499
|
+
setAttr(link, "href", item.url);
|
|
500
|
+
if (item.target === "_blank") setAttr(link, "target", "_blank");
|
|
501
|
+
if (!labels.length && !elements(link.children).length) setText(link, item.label, false);
|
|
502
|
+
}
|
|
503
|
+
for (const label of labels) setText(label, item.label, false);
|
|
504
|
+
return copy;
|
|
505
|
+
}
|
|
506
|
+
function renderTemplate(template, data) {
|
|
507
|
+
const nodes = parseHtml(template);
|
|
508
|
+
const head = headTags(data.page.resolvedSeo);
|
|
509
|
+
const resolve = (ref) => {
|
|
510
|
+
const at = ref.indexOf(":");
|
|
511
|
+
if (at === -1) return { value: valueAt(data.page.content, ref), marker: ref };
|
|
512
|
+
const owner = ref.slice(0, at);
|
|
513
|
+
const path = ref.slice(at + 1);
|
|
514
|
+
if (owner === "_global") {
|
|
515
|
+
const global = data.global;
|
|
516
|
+
return {
|
|
517
|
+
value: global ? valueAt(global.content, path) : void 0,
|
|
518
|
+
marker: global ? `${global.pageId}:${path}` : ref
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
return { value: void 0, marker: ref };
|
|
522
|
+
};
|
|
523
|
+
const fill = (el) => {
|
|
524
|
+
const marker = attr(el, "data-brease");
|
|
525
|
+
const ref = marker?.value;
|
|
526
|
+
if (marker && ref?.startsWith("nav:")) {
|
|
527
|
+
const items = data.navigations?.[ref.slice(4)]?.items;
|
|
528
|
+
const template2 = itemTemplate(el);
|
|
529
|
+
if (items && template2) {
|
|
530
|
+
const rendered = items.map((item) => renderNavItem(template2, item));
|
|
531
|
+
el.children = el.children.flatMap(
|
|
532
|
+
(c) => c === template2 ? rendered : c.kind === "el" && attr(c, "data-brease-item") ? [] : [c]
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (marker && ref) {
|
|
538
|
+
const { value, marker: written } = resolve(ref);
|
|
539
|
+
marker.value = written;
|
|
540
|
+
if (Array.isArray(value)) {
|
|
541
|
+
const template2 = itemTemplate(el);
|
|
542
|
+
if (template2) {
|
|
543
|
+
const listPath = written;
|
|
544
|
+
const rendered = value.map((_, index) => {
|
|
545
|
+
const copy = clone(template2);
|
|
546
|
+
if (index > 0) renumber([copy], listPath, index);
|
|
547
|
+
return copy;
|
|
548
|
+
});
|
|
549
|
+
el.children = el.children.flatMap(
|
|
550
|
+
(c) => c === template2 ? rendered : c.kind === "el" && attr(c, "data-brease-item") ? [] : [c]
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
} else if (isImage(value)) {
|
|
554
|
+
if (el.tag === "img" || el.tag === "source") {
|
|
555
|
+
setAttr(el, el.tag === "source" ? "srcset" : "src", value.url);
|
|
556
|
+
if (el.tag === "img") {
|
|
557
|
+
removeAttr(el, "srcset");
|
|
558
|
+
if (value.alt !== void 0) setAttr(el, "alt", value.alt);
|
|
559
|
+
if (value.width) setAttr(el, "width", String(value.width));
|
|
560
|
+
if (value.height) setAttr(el, "height", String(value.height));
|
|
561
|
+
}
|
|
562
|
+
} else {
|
|
563
|
+
const style = (attr(el, "style")?.value ?? "").replace(/background-image\s*:[^;]*;?/i, "").trim();
|
|
564
|
+
setAttr(
|
|
565
|
+
el,
|
|
566
|
+
"style",
|
|
567
|
+
`${style ? `${style.replace(/;?$/, ";")} ` : ""}background-image: url('${value.url}')`
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
} else if (isLink(value)) {
|
|
571
|
+
if (el.tag === "a") {
|
|
572
|
+
setAttr(el, "href", value.href);
|
|
573
|
+
if (value.target === "_blank") setAttr(el, "target", "_blank");
|
|
574
|
+
}
|
|
575
|
+
if (value.label !== void 0 && !elements(el.children).length) setText(el, value.label, false);
|
|
576
|
+
} else if (typeof value === "string" || typeof value === "number") {
|
|
577
|
+
const text = String(value);
|
|
578
|
+
setText(el, text, attr(el, "data-brease-html") !== void 0 || looksLikeHtml(text));
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
for (const child of elements(el.children)) fill(child);
|
|
583
|
+
};
|
|
584
|
+
const walk = (list) => {
|
|
585
|
+
for (let i = 0; i < list.length; i++) {
|
|
586
|
+
const n = list[i];
|
|
587
|
+
if (n.kind === "raw") {
|
|
588
|
+
if (n.text.includes("<!-- brease:head -->")) n.text = n.text.replace("<!-- brease:head -->", head);
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
if (n.tag === "html") setAttr(n, "lang", data.page.locale);
|
|
592
|
+
if (n.tag === "script" || n.tag === "style") continue;
|
|
593
|
+
if (attr(n, "data-brease")) fill(n);
|
|
594
|
+
else walk(n.children);
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
walk(nodes);
|
|
598
|
+
return serializeHtml(nodes);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// src/index.ts
|
|
602
|
+
var RETRY_AFTER_CAP_MS = 1e4;
|
|
603
|
+
var SITE_TTL_MS = 6e4;
|
|
604
|
+
var DRAFT_BRANCH_PREFIX = "brease/draft/";
|
|
605
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
606
|
+
var HOST_GIT_ENV = [
|
|
607
|
+
["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
|
|
608
|
+
["WORKERS_CI_COMMIT_SHA", "WORKERS_CI_BRANCH"],
|
|
609
|
+
["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"]
|
|
610
|
+
];
|
|
611
|
+
function hostGit() {
|
|
612
|
+
for (const [commit, branch] of HOST_GIT_ENV) {
|
|
613
|
+
const sha = env(commit);
|
|
614
|
+
if (sha) return { commit: sha, branch: env(branch) };
|
|
615
|
+
}
|
|
616
|
+
return {};
|
|
617
|
+
}
|
|
618
|
+
var cacheGeneration = 0;
|
|
619
|
+
function clearBreaseCache() {
|
|
620
|
+
cacheGeneration++;
|
|
621
|
+
}
|
|
622
|
+
function createBrease(opts = {}) {
|
|
623
|
+
const apiUrl = (opts.apiUrl ?? env("BREASE_API_URL") ?? "https://api.brease.io").replace(/\/+$/, "");
|
|
624
|
+
const host = hostGit();
|
|
625
|
+
const commit = opts.commit === false ? void 0 : opts.commit ?? host.commit;
|
|
626
|
+
const branch = opts.branch === false ? void 0 : opts.branch ?? host.branch;
|
|
627
|
+
const draftBranch = branch?.startsWith(DRAFT_BRANCH_PREFIX) ? branch : void 0;
|
|
628
|
+
const retries = opts.retries ?? 2;
|
|
629
|
+
const baseMs = opts.retryBaseMs ?? 300;
|
|
630
|
+
const timeoutMs = opts.timeoutMs ?? 5e3;
|
|
631
|
+
const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
632
|
+
function cached(path) {
|
|
633
|
+
let entry;
|
|
634
|
+
let last;
|
|
635
|
+
return () => {
|
|
636
|
+
if (!entry || Date.now() - entry.at > SITE_TTL_MS || entry.generation !== cacheGeneration || env("BREASE_PREVIEW")) {
|
|
637
|
+
const promise = request(path).then(
|
|
638
|
+
(value) => {
|
|
639
|
+
last = { value };
|
|
640
|
+
return value;
|
|
641
|
+
},
|
|
642
|
+
(err) => {
|
|
643
|
+
if (last) return last.value;
|
|
644
|
+
if (entry?.promise === promise) entry = void 0;
|
|
645
|
+
throw err;
|
|
646
|
+
}
|
|
647
|
+
);
|
|
648
|
+
entry = { promise, at: Date.now(), generation: cacheGeneration };
|
|
649
|
+
}
|
|
650
|
+
return entry.promise;
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
async function request(path, query = {}, nullOn404 = false) {
|
|
654
|
+
const token = opts.token ?? env("BREASE_TOKEN");
|
|
655
|
+
if (!token)
|
|
656
|
+
throw new BreaseError("unauthorized", "No Brease token: pass { token } or set BREASE_TOKEN", 401);
|
|
657
|
+
const params = new URLSearchParams();
|
|
658
|
+
for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, v);
|
|
659
|
+
const qs = params.toString();
|
|
660
|
+
const url = `${apiUrl}${path}${qs ? `?${qs}` : ""}`;
|
|
661
|
+
const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
|
|
662
|
+
if (commit) headers["x-brease-commit"] = commit;
|
|
663
|
+
if (draftBranch) headers["x-brease-branch"] = draftBranch;
|
|
664
|
+
for (let attempt = 0; ; attempt++) {
|
|
665
|
+
let res;
|
|
666
|
+
try {
|
|
667
|
+
res = await doFetch(url, { method: "GET", headers, signal: AbortSignal.timeout(timeoutMs) });
|
|
668
|
+
} catch (err) {
|
|
669
|
+
const timedOut = err.name === "TimeoutError";
|
|
670
|
+
if (attempt < retries && !timedOut) {
|
|
671
|
+
await sleep(backoff(attempt));
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
throw new BreaseError("network", `Request to ${url} failed: ${err.message}`, 0);
|
|
675
|
+
}
|
|
676
|
+
if (res.ok) return await res.json();
|
|
677
|
+
if (res.status === 404 && nullOn404) return null;
|
|
678
|
+
if ((res.status === 429 || res.status >= 500) && attempt < retries) {
|
|
679
|
+
const after = Number(res.headers.get("retry-after"));
|
|
680
|
+
await sleep(after > 0 ? Math.min(after * 1e3, RETRY_AFTER_CAP_MS) : backoff(attempt));
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
throw await BreaseError.fromResponse(res);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
function backoff(attempt) {
|
|
687
|
+
return baseMs * 2 ** attempt + Math.random() * baseMs;
|
|
688
|
+
}
|
|
689
|
+
const cachedSite = cached("/content-api/site");
|
|
690
|
+
const cachedRedirects = cached("/content-api/redirects");
|
|
691
|
+
const client = {
|
|
692
|
+
getSite: cachedSite,
|
|
693
|
+
getPage(slug, { locale }) {
|
|
694
|
+
return request("/content-api/page", { slug, locale }, true);
|
|
695
|
+
},
|
|
696
|
+
getPages(o = {}) {
|
|
697
|
+
return request("/content-api/pages", {
|
|
698
|
+
locale: o.locale,
|
|
699
|
+
parentId: o.parentId === null ? "" : o.parentId,
|
|
700
|
+
template: o.template,
|
|
701
|
+
withContent: o.withContent ? "1" : void 0
|
|
702
|
+
});
|
|
703
|
+
},
|
|
704
|
+
getNavigation(key, { locale }) {
|
|
705
|
+
return request(`/content-api/navigations/${encodeURIComponent(key)}`, { locale }, true);
|
|
706
|
+
},
|
|
707
|
+
// Cached for a minute, like the site: a proxy applies redirects per request (matchRedirect).
|
|
708
|
+
getRedirects: cachedRedirects,
|
|
709
|
+
getRelease() {
|
|
710
|
+
return request("/content-api/release");
|
|
711
|
+
},
|
|
712
|
+
async resolve(pathname) {
|
|
713
|
+
const site = await client.getSite();
|
|
714
|
+
const result = resolvePath(site, pathname);
|
|
715
|
+
return site.locales.includes(result.locale) ? result : null;
|
|
716
|
+
},
|
|
717
|
+
async route(path) {
|
|
718
|
+
const joined = Array.isArray(path) ? path.join("/") : path ?? "";
|
|
719
|
+
const result = await client.resolve(`/${joined}`);
|
|
720
|
+
return result && !result.slug.split("/").some((part) => part.startsWith("_")) ? result : null;
|
|
721
|
+
},
|
|
722
|
+
async routes() {
|
|
723
|
+
const refs = await client.getPages();
|
|
724
|
+
return refs.filter((r) => !r.hidden && !r.slug.split("/").some((part) => part.startsWith("_"))).map((r) => ({ path: r.url.split("/").filter(Boolean) }));
|
|
725
|
+
},
|
|
726
|
+
async localeContext(path) {
|
|
727
|
+
const target = await client.route(path);
|
|
728
|
+
if (!target) return null;
|
|
729
|
+
const [site, page, home] = await Promise.all([
|
|
730
|
+
client.getSite(),
|
|
731
|
+
client.getPage(target.slug, { locale: target.locale }),
|
|
732
|
+
client.getPage("", { locale: target.locale })
|
|
733
|
+
]);
|
|
734
|
+
const settings = {
|
|
735
|
+
locales: site.locales,
|
|
736
|
+
defaultLocale: site.defaultLocale,
|
|
737
|
+
localeStrategy: site.localeStrategy,
|
|
738
|
+
urlTemplate: site.urlTemplate
|
|
739
|
+
};
|
|
740
|
+
if (!page && !home) return null;
|
|
741
|
+
const alternates = {};
|
|
742
|
+
for (const [locale, url] of Object.entries(page?.alternates ?? {})) alternates[locale] = pathOf(url);
|
|
743
|
+
const homes = {};
|
|
744
|
+
for (const [locale, url] of Object.entries(home?.alternates ?? {})) homes[locale] = pathOf(url);
|
|
745
|
+
return { locale: target.locale, settings, alternates, homes };
|
|
746
|
+
},
|
|
747
|
+
async sitemap(baseUrl) {
|
|
748
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
749
|
+
const refs = (await client.getPages()).filter(
|
|
750
|
+
(r) => !r.hidden && r.index !== false && !r.slug.split("/").some((part) => part.startsWith("_"))
|
|
751
|
+
);
|
|
752
|
+
const byPage = /* @__PURE__ */ new Map();
|
|
753
|
+
for (const ref of refs) {
|
|
754
|
+
const alternates = byPage.get(ref.pageId) ?? {};
|
|
755
|
+
alternates[ref.locale] = `${base}${ref.url}`;
|
|
756
|
+
byPage.set(ref.pageId, alternates);
|
|
757
|
+
}
|
|
758
|
+
return refs.map((ref) => ({ url: `${base}${ref.url}`, alternates: byPage.get(ref.pageId) ?? {} }));
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
return client;
|
|
762
|
+
}
|
|
763
|
+
function pathOf(url) {
|
|
764
|
+
try {
|
|
765
|
+
return new URL(url, "http://localhost").pathname;
|
|
766
|
+
} catch {
|
|
767
|
+
return url;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
export { BreaseError, SECTION_FOLDERS, buildPath, canonicalPath, checkSections, clearBreaseCache, createBrease, customTags, env, fieldPath, ga4Html, ga4Tag, grantAnalytics, hmacHex, localeHref, localeLinks, matchRedirect, nativeName, navPath, normalizeSlug, renderTemplate, resolvePath, sectionAttrs, sectionsAttrs, verifyRevalidate, verifySignature };
|