@thecms/next 0.0.0-stage → 0.20.1-dev.122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js ADDED
@@ -0,0 +1,1177 @@
1
+ import {
2
+ CmsBlocks,
3
+ cmsContext,
4
+ markForEditor,
5
+ registerComponents,
6
+ setCmsContext,
7
+ textsOf
8
+ } from "./chunk-NLO5OID2.js";
9
+
10
+ // src/server.ts
11
+ import { cache } from "react";
12
+ import { cookies, headers } from "next/headers";
13
+ import { notFound, permanentRedirect, redirect } from "next/navigation";
14
+ import {
15
+ createSdk,
16
+ platformUrl,
17
+ previewRequestAllowed,
18
+ CmsError,
19
+ FRAME_HEADER,
20
+ LIST_PARAM,
21
+ PREVIEW_COOKIE,
22
+ PREVIEW_PARAM,
23
+ PLATFORM_API,
24
+ SITE_HEADER,
25
+ siteHeader,
26
+ UNKNOWN_VISITOR,
27
+ UNKNOWN_VISITOR_HEADER
28
+ } from "@thecms/sdk";
29
+
30
+ // src/site-texts.ts
31
+ import { createElement } from "react";
32
+ import { CmsSiteTextsProvider } from "./client.js";
33
+
34
+ // src/config.ts
35
+ var SITE_TEXT_KEYS = {
36
+ notFound: ["title", "body", "home"],
37
+ error: ["title", "body", "retry"],
38
+ geoBlocked: ["title", "body"]
39
+ };
40
+ function siteTextsOf(t, of) {
41
+ const group = (g) => Object.fromEntries(SITE_TEXT_KEYS[g].map((k) => [k, t(`${g}.${k}`)]));
42
+ return { ...of, notFound: group("notFound"), error: group("error"), geoBlocked: group("geoBlocked") };
43
+ }
44
+
45
+ // src/site-texts.ts
46
+ function siteTextOf(site, path) {
47
+ const locales = site.locales ?? [];
48
+ let first2 = path.split(/[/?#]/).find(Boolean) ?? "";
49
+ try {
50
+ first2 = decodeURIComponent(first2);
51
+ } catch {
52
+ }
53
+ const locale = locales.find((l) => l.toLowerCase() === first2.toLowerCase()) ?? site.defaultLocale;
54
+ const homeOf = (l) => ({ locale: l, path: l === site.defaultLocale ? "/" : `/${l}` });
55
+ return {
56
+ locale,
57
+ ...textsOf(site, locale),
58
+ name: site.name ?? null,
59
+ homes: [locale, ...locales.filter((l) => l !== locale)].map(homeOf)
60
+ };
61
+ }
62
+ var siteOfServer = null;
63
+ function registerSite(site) {
64
+ siteOfServer = site;
65
+ }
66
+ async function CmsSiteTexts({ path, children }) {
67
+ if (!siteOfServer) throw new Error("theCMS.: CmsSiteTexts needs the site \u2014 createNextCms({ publicKey }) or createNextCms({ sites }) first");
68
+ const text = siteTextOf(await siteOfServer(), path);
69
+ const texts = siteTextsOf(text.t, { locale: text.locale, name: text.name, homes: text.homes });
70
+ return createElement(CmsSiteTextsProvider, { texts }, children);
71
+ }
72
+
73
+ // src/page-text.ts
74
+ var VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
75
+ var RAW = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "noscript"]);
76
+ var SKIP = /* @__PURE__ */ new Set([
77
+ "head",
78
+ "script",
79
+ "style",
80
+ "noscript",
81
+ "template",
82
+ "svg",
83
+ "math",
84
+ "iframe",
85
+ "object",
86
+ "embed",
87
+ "video",
88
+ "audio",
89
+ "canvas",
90
+ "img",
91
+ "picture",
92
+ "source",
93
+ "form",
94
+ "button",
95
+ "select",
96
+ "input",
97
+ "textarea",
98
+ "label",
99
+ "option",
100
+ "dialog",
101
+ "map"
102
+ ]);
103
+ var BLOCK = /* @__PURE__ */ new Set([
104
+ "address",
105
+ "article",
106
+ "aside",
107
+ "blockquote",
108
+ "body",
109
+ "dd",
110
+ "details",
111
+ "div",
112
+ "dl",
113
+ "dt",
114
+ "fieldset",
115
+ "figcaption",
116
+ "figure",
117
+ "footer",
118
+ "header",
119
+ "hgroup",
120
+ "html",
121
+ "li",
122
+ "main",
123
+ "nav",
124
+ "ol",
125
+ "p",
126
+ "pre",
127
+ "section",
128
+ "summary",
129
+ "table",
130
+ "tbody",
131
+ "td",
132
+ "tfoot",
133
+ "th",
134
+ "thead",
135
+ "tr",
136
+ "ul",
137
+ "h1",
138
+ "h2",
139
+ "h3",
140
+ "h4",
141
+ "h5",
142
+ "h6",
143
+ "hr"
144
+ ]);
145
+ var PHRASE = /* @__PURE__ */ new Set([
146
+ "a",
147
+ "abbr",
148
+ "b",
149
+ "bdi",
150
+ "bdo",
151
+ "cite",
152
+ "code",
153
+ "data",
154
+ "dfn",
155
+ "em",
156
+ "i",
157
+ "kbd",
158
+ "mark",
159
+ "q",
160
+ "s",
161
+ "samp",
162
+ "strong",
163
+ "sub",
164
+ "sup",
165
+ "u",
166
+ "var"
167
+ ]);
168
+ var CARD_PART = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6", "p", "div", "article", "section", "header", "footer", "figure", "ul", "ol", "dl", "table", "blockquote"]);
169
+ var glues = (left, right) => /[^\s([{“‘"'«¿¡]$/.test(left) && /^[^\s.,;:!?)\]}”’"'»%…]/.test(right);
170
+ var LIST_STATE = /^[\w-]+\.[\w-]+$/;
171
+ var SHORT = 120;
172
+ function monthsOf(lang) {
173
+ const names = /* @__PURE__ */ new Set();
174
+ for (const l of new Set([lang?.trim(), "en"].filter((x) => !!x))) {
175
+ for (const month of ["long", "short"]) {
176
+ let f;
177
+ try {
178
+ f = new Intl.DateTimeFormat(l, { month, timeZone: "UTC" });
179
+ } catch {
180
+ continue;
181
+ }
182
+ for (let m = 0; m < 12; m++) names.add(f.format(Date.UTC(2020, m, 15)).toLowerCase().replace(/\.$/, ""));
183
+ }
184
+ }
185
+ return names;
186
+ }
187
+ function datesWhole(parts, months) {
188
+ const kind = (t) => /^\d{1,2}\.?$/.test(t) && parseInt(t, 10) >= 1 && parseInt(t, 10) <= 31 ? "day" : /^\d{4}$/.test(t) ? "year" : months.has(t.toLowerCase().replace(/\.$/, "")) ? "month" : null;
189
+ const kinds = (p) => {
190
+ const k = p.trim().split(/\s+/).map(kind);
191
+ return k.length <= 3 && k.every(Boolean) ? k : null;
192
+ };
193
+ const out = [];
194
+ let group = [];
195
+ let seen = [];
196
+ const end = () => {
197
+ if (group.length > 1 && seen.includes("month") && (seen.includes("day") || seen.includes("year"))) out.push(group.join(" "));
198
+ else out.push(...group);
199
+ group = [];
200
+ seen = [];
201
+ };
202
+ for (const part of parts) {
203
+ const k = kinds(part);
204
+ if (!k || new Set(k).size < k.length) {
205
+ end();
206
+ out.push(part);
207
+ continue;
208
+ }
209
+ if (k.some((x) => seen.includes(x))) end();
210
+ group.push(part);
211
+ seen.push(...k);
212
+ }
213
+ end();
214
+ return out;
215
+ }
216
+ var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", ndash: "\u2013", mdash: "\u2014", hellip: "\u2026", rsquo: "\u2019", lsquo: "\u2018", rdquo: "\u201D", ldquo: "\u201C", copy: "\xA9", reg: "\xAE", trade: "\u2122", euro: "\u20AC", middot: "\xB7", bull: "\u2022" };
217
+ var decode = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
218
+ if (e[0] === "#") {
219
+ const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
220
+ return Number.isFinite(n) ? String.fromCodePoint(n) : m;
221
+ }
222
+ return ENTITIES[e.toLowerCase()] ?? m;
223
+ });
224
+ function parseHtml(html) {
225
+ const root = { tag: "#root", attrs: {}, children: [] };
226
+ const stack = [root];
227
+ const top = () => stack[stack.length - 1];
228
+ const re = /<!--([\s\S]*?)-->|<!\[CDATA\[[\s\S]*?\]\]>|<![^>]*>|<\/([a-zA-Z][\w:-]*)\s*>|<([a-zA-Z][\w:-]*)((?:\s+[^\s=/>]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*(\/?)>/g;
229
+ let at = 0;
230
+ let m;
231
+ while (m = re.exec(html)) {
232
+ if (m.index > at) top().children.push({ text: decode(html.slice(at, m.index)) });
233
+ at = re.lastIndex;
234
+ if (m[1] !== void 0) {
235
+ top().children.push({ comment: m[1] });
236
+ continue;
237
+ }
238
+ if (m[2]) {
239
+ const tag2 = m[2].toLowerCase();
240
+ const i = stack.map((e) => e.tag).lastIndexOf(tag2);
241
+ if (i > 0) stack.length = i;
242
+ continue;
243
+ }
244
+ if (!m[3]) continue;
245
+ const tag = m[3].toLowerCase();
246
+ const attrs = {};
247
+ for (const a of (m[4] ?? "").matchAll(/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g)) {
248
+ attrs[a[1].toLowerCase()] = decode(a[2] ?? a[3] ?? a[4] ?? "");
249
+ }
250
+ const el = { tag, attrs, children: [] };
251
+ top().children.push(el);
252
+ if (RAW.has(tag)) {
253
+ const end = html.toLowerCase().indexOf(`</${tag}`, at);
254
+ const stop = end < 0 ? html.length : end;
255
+ el.children.push({ text: html.slice(at, stop) });
256
+ const close = html.indexOf(">", stop);
257
+ at = re.lastIndex = close < 0 ? html.length : close + 1;
258
+ continue;
259
+ }
260
+ if (!VOID.has(tag) && !m[5]) stack.push(el);
261
+ }
262
+ if (at < html.length) top().children.push({ text: decode(html.slice(at)) });
263
+ return root;
264
+ }
265
+ var isEl = (n) => "tag" in n;
266
+ var isText = (n) => "text" in n;
267
+ var isComment = (n) => "comment" in n;
268
+ function unstream(root) {
269
+ const streamed = /* @__PURE__ */ new Map();
270
+ const take = (el) => {
271
+ el.children = el.children.filter((c) => {
272
+ if (isEl(c) && c.tag === "div" && "hidden" in c.attrs && /^S:/.test(c.attrs.id ?? "")) {
273
+ streamed.set(c.attrs.id.slice(2), c.children);
274
+ return false;
275
+ }
276
+ if (isEl(c)) take(c);
277
+ return true;
278
+ });
279
+ };
280
+ take(root);
281
+ const swap = (el) => {
282
+ const out = [];
283
+ for (let i = 0; i < el.children.length; i++) {
284
+ const c = el.children[i];
285
+ if (isComment(c) && c.comment === "$?") {
286
+ let j = i + 1;
287
+ let id;
288
+ for (; j < el.children.length; j++) {
289
+ const n = el.children[j];
290
+ if (isEl(n) && n.tag === "template" && /^B:/.test(n.attrs.id ?? "")) id = n.attrs.id.slice(2);
291
+ if (isComment(n) && n.comment === "/$") break;
292
+ }
293
+ out.push(...id !== void 0 ? streamed.get(id) ?? [] : []);
294
+ i = j;
295
+ continue;
296
+ }
297
+ if (isEl(c)) swap(c);
298
+ out.push(c);
299
+ }
300
+ el.children = out;
301
+ };
302
+ swap(root);
303
+ }
304
+ var isEmbed = (v) => /^https?:\/\/\S+$/.test(v.trim()) && /\/embed\b|[?&]output=embed\b|[?&]pb=/i.test(v);
305
+ var hidden = (el) => "hidden" in el.attrs && !/^S:/.test(el.attrs.id ?? "") || el.attrs["aria-hidden"] === "true" && el.tag !== "figcaption" || /display\s*:\s*none|visibility\s*:\s*hidden/i.test(el.attrs.style ?? "");
306
+ function first(el, test) {
307
+ for (const c of el.children) {
308
+ if (!isEl(c) || hidden(c) || SKIP.has(c.tag) && c.tag !== "img") continue;
309
+ if (test(c)) return c;
310
+ const found = first(c, test);
311
+ if (found) return found;
312
+ }
313
+ return void 0;
314
+ }
315
+ var isCard = (a) => !!first(a, (e) => CARD_PART.has(e.tag));
316
+ var Writer = class _Writer {
317
+ constructor(base, months) {
318
+ this.base = base;
319
+ this.months = months;
320
+ }
321
+ blocks = [];
322
+ inline = "";
323
+ /** an element boundary was crossed since the last text: two texts glued across it go on two lines */
324
+ edge = false;
325
+ /** where the last words of a list's link end in `inline` (the next ones join them with a comma) */
326
+ stateEnd = -1;
327
+ text(t) {
328
+ if (this.edge && t.trim() && glues(this.inline, t)) this.inline += "\n";
329
+ if (t.trim()) this.edge = false;
330
+ this.inline += t;
331
+ }
332
+ href(raw) {
333
+ if (!raw || raw.startsWith("#") || /^\s*javascript:/i.test(raw)) return null;
334
+ try {
335
+ const u = new URL(raw, this.base);
336
+ if (!/^(https?|mailto|tel):$/.test(u.protocol)) return null;
337
+ return u.toString();
338
+ } catch {
339
+ return null;
340
+ }
341
+ }
342
+ /** The text of a subtree on one line (a link's, a heading's, a cell's). */
343
+ textOf(el) {
344
+ let out = "";
345
+ let edge = false;
346
+ const add = (t) => {
347
+ if (!t) return;
348
+ if (edge && glues(out, t)) out += " ";
349
+ edge = false;
350
+ out += t;
351
+ };
352
+ const walk = (n) => {
353
+ if (isText(n)) add(n.text);
354
+ else if (isEl(n) && !SKIP.has(n.tag) && !hidden(n)) {
355
+ if (n.tag === "br") out += " ";
356
+ else if (n.tag === "a") add(this.link(n));
357
+ else {
358
+ const apart = BLOCK.has(n.tag) || !PHRASE.has(n.tag);
359
+ if (apart) edge = true;
360
+ n.children.forEach(walk);
361
+ if (apart) edge = true;
362
+ }
363
+ }
364
+ };
365
+ el.children.forEach(walk);
366
+ return out.replace(/\s+/g, " ").trim();
367
+ }
368
+ /**
369
+ * A link: `[text](address)`, the address alone without a name; an embed's
370
+ * address: nothing. Its name: its text (a card's: its title), else its
371
+ * aria-label or title, else the alt of the image it is made of.
372
+ */
373
+ link(a) {
374
+ const words = this.stateWords(a);
375
+ if (words !== null) return words;
376
+ const label = isCard(a) ? this.textOf(this.titleOf(a) ?? a) : this.textOf({ ...a, tag: "span" });
377
+ const alt = first(a, (e) => e.tag === "img" && !!e.attrs.alt?.trim())?.attrs.alt?.trim();
378
+ const text = label || a.attrs["aria-label"]?.trim() || a.attrs.title?.trim() || alt || "";
379
+ const href = this.href(a.attrs.href);
380
+ if (href && isEmbed(href)) return "";
381
+ if (!href) return text;
382
+ return text ? `[${text.replace(/[[\]]/g, "")}](${href})` : `<${href}>`;
383
+ }
384
+ /** A link that only moves a list of the page (SA10): its words (an arrow alone: its aria-label), else null. */
385
+ stateWords(a) {
386
+ const href = this.href(a.attrs.href);
387
+ if (!href) return null;
388
+ const u = new URL(href);
389
+ if (u.origin !== this.base.origin || !LIST_STATE.test(u.searchParams.get("f") ?? "")) return null;
390
+ const text = this.textOf({ ...a, tag: "span" });
391
+ return /[\p{L}\p{N}]/u.test(text) ? text : a.attrs["aria-label"]?.trim() || a.attrs.title?.trim() || "";
392
+ }
393
+ flush() {
394
+ this.edge = false;
395
+ this.stateEnd = -1;
396
+ const lines = datesWhole(this.inline.split("\n").map((l) => l.replace(/[ \t]+/g, " ").trim()).filter(Boolean), this.months);
397
+ this.inline = "";
398
+ if (!lines.length) return;
399
+ this.blocks.push(lines.length > 1 && lines.length <= 6 && lines.every((l) => l.length <= SHORT) ? lines.join(", ") : lines.join("\n"));
400
+ }
401
+ list(el, depth) {
402
+ this.flush();
403
+ const ordered = el.tag === "ol";
404
+ const lines = [];
405
+ let n = 0;
406
+ const items = (container) => {
407
+ for (const c of container.children) {
408
+ if (!isEl(c) || SKIP.has(c.tag) || hidden(c)) continue;
409
+ if (c.tag !== "li") {
410
+ if (c.tag === "ul" || c.tag === "ol") continue;
411
+ items(c);
412
+ continue;
413
+ }
414
+ const own = { ...c, children: c.children.filter((x) => !(isEl(x) && (x.tag === "ul" || x.tag === "ol"))) };
415
+ const text = this.textOf(own);
416
+ if (text) lines.push(`${" ".repeat(depth)}${ordered ? `${++n}.` : "-"} ${text}`);
417
+ for (const sub of c.children) if (isEl(sub) && (sub.tag === "ul" || sub.tag === "ol") && !hidden(sub)) lines.push(...this.sublist(sub, depth + 1));
418
+ }
419
+ };
420
+ items(el);
421
+ if (lines.length) this.blocks.push(lines.join("\n"));
422
+ }
423
+ sublist(el, depth) {
424
+ const w = new _Writer(this.base, this.months);
425
+ w.list(el, depth);
426
+ return w.blocks.flatMap((b) => b.split("\n"));
427
+ }
428
+ write(node) {
429
+ if (isText(node)) {
430
+ this.text(node.text.replace(/\s+/g, " "));
431
+ return;
432
+ }
433
+ if (!isEl(node) || SKIP.has(node.tag) || hidden(node)) return;
434
+ const { tag } = node;
435
+ if (/^h[1-6]$/.test(tag)) {
436
+ this.flush();
437
+ const text = this.textOf(node);
438
+ if (text) this.blocks.push(`${"#".repeat(Number(tag[1]))} ${text}`);
439
+ return;
440
+ }
441
+ if (tag === "ul" || tag === "ol") {
442
+ this.list(node, 0);
443
+ return;
444
+ }
445
+ if (tag === "br") {
446
+ this.inline += "\n";
447
+ return;
448
+ }
449
+ if (tag === "hr") {
450
+ this.flush();
451
+ return;
452
+ }
453
+ if (tag === "a") {
454
+ const words = this.stateWords(node);
455
+ if (words !== null) {
456
+ if (!words) return;
457
+ if (this.stateEnd >= 0 && !this.inline.slice(this.stateEnd).trim()) this.inline = `${this.inline.slice(0, this.stateEnd)}, `;
458
+ else this.edge = true;
459
+ this.text(words);
460
+ this.edge = true;
461
+ this.stateEnd = this.inline.length;
462
+ return;
463
+ }
464
+ if (isCard(node)) this.card(node);
465
+ else this.text(` ${this.link(node)} `);
466
+ return;
467
+ }
468
+ if (tag === "strong" || tag === "b") {
469
+ const t = this.textOf(node);
470
+ if (t) this.text(` **${t}** `);
471
+ return;
472
+ }
473
+ if (tag === "em" || tag === "i") {
474
+ const t = this.textOf(node);
475
+ if (t) this.text(` *${t}* `);
476
+ return;
477
+ }
478
+ if (tag === "dl") {
479
+ this.terms(node);
480
+ return;
481
+ }
482
+ if (tag === "pre") {
483
+ this.flush();
484
+ const t = this.rawText(node).replace(/\n+$/, "");
485
+ if (t.trim()) this.blocks.push(`\`\`\`
486
+ ${t}
487
+ \`\`\``);
488
+ return;
489
+ }
490
+ if (tag === "tr") {
491
+ this.flush();
492
+ const cells = node.children.filter((c) => isEl(c) && (c.tag === "td" || c.tag === "th")).map((c) => this.textOf(c)).filter(Boolean);
493
+ if (cells.length) this.blocks.push(cells.join(" | "));
494
+ return;
495
+ }
496
+ if (tag === "blockquote") {
497
+ this.flush();
498
+ const w = new _Writer(this.base, this.months);
499
+ node.children.forEach((c) => w.write(c));
500
+ const text = w.done();
501
+ if (text) this.blocks.push(text.split("\n").map((l) => l ? `> ${l}` : ">").join("\n"));
502
+ return;
503
+ }
504
+ const block = BLOCK.has(tag);
505
+ if (block) this.flush();
506
+ else if (!PHRASE.has(tag)) this.edge = true;
507
+ node.children.forEach((c) => this.write(c));
508
+ if (block) this.flush();
509
+ else if (!PHRASE.has(tag)) this.edge = true;
510
+ }
511
+ /** A card's title: its first heading, else its first part with a text. */
512
+ titleOf(a) {
513
+ return first(a, (e) => /^h[1-6]$/.test(e.tag) && !!this.textOf(e)) ?? first(a, (e) => (BLOCK.has(e.tag) || !PHRASE.has(e.tag)) && !first(e, (x) => CARD_PART.has(x.tag)) && !!this.textOf(e));
514
+ }
515
+ /** A card all inside a link: its title linked (a heading stays one), then the rest of it as the page shows it. */
516
+ card(a) {
517
+ this.flush();
518
+ const href = this.href(a.attrs.href);
519
+ const title = this.titleOf(a);
520
+ const name = title ? this.textOf(title) : "";
521
+ if (href && isEmbed(href)) return;
522
+ const linked = name && href ? `[${name.replace(/[[\]]/g, "")}](${href})` : name;
523
+ if (linked) this.blocks.push(title && /^h[1-6]$/.test(title.tag) ? `${"#".repeat(Number(title.tag[1]))} ${linked}` : linked);
524
+ const rest = (el) => ({ ...el, children: el.children.filter((c) => c !== title).map((c) => isEl(c) ? rest(c) : c) });
525
+ const w = new _Writer(this.base, this.months);
526
+ rest(a).children.forEach((c) => w.write(c));
527
+ w.flush();
528
+ let run = [];
529
+ const out = () => {
530
+ if (run.length) this.blocks.push(run.join(", "));
531
+ run = [];
532
+ };
533
+ for (const part of datesWhole(w.blocks, this.months)) {
534
+ if (!part.includes("\n") && part.length <= SHORT && !/^(#|- |> |\d+\. |```)/.test(part) && run.length < 6) run.push(part);
535
+ else {
536
+ out();
537
+ this.blocks.push(part);
538
+ }
539
+ }
540
+ out();
541
+ }
542
+ /** A term list: one line per term, "term: value" (several values joined). */
543
+ terms(dl) {
544
+ this.flush();
545
+ const lines = [];
546
+ let term = "";
547
+ let values = [];
548
+ const end = () => {
549
+ if (term || values.length) lines.push(term && values.length ? `${term}: ${values.join(", ")}` : term || values.join(", "));
550
+ term = "";
551
+ values = [];
552
+ };
553
+ const walk = (el) => {
554
+ for (const c of el.children) {
555
+ if (!isEl(c) || SKIP.has(c.tag) || hidden(c)) continue;
556
+ if (c.tag === "dt") {
557
+ if (values.length) end();
558
+ const t = this.textOf(c);
559
+ term = term ? `${term}, ${t}` : t;
560
+ } else if (c.tag === "dd") {
561
+ const t = this.textOf(c);
562
+ if (t) values.push(t);
563
+ } else walk(c);
564
+ }
565
+ };
566
+ walk(dl);
567
+ end();
568
+ if (lines.length) this.blocks.push(lines.join("\n"));
569
+ }
570
+ rawText(el) {
571
+ return el.children.map((c) => isText(c) ? c.text : isEl(c) && !SKIP.has(c.tag) ? c.tag === "br" ? "\n" : this.rawText(c) : "").join("");
572
+ }
573
+ done() {
574
+ this.flush();
575
+ return this.blocks.map((b) => b.replace(/ +([,.;:!?)])/g, "$1").replace(/\( +/g, "(")).join("\n\n");
576
+ }
577
+ };
578
+ function pageMarkdown(input) {
579
+ const root = parseHtml(input.html.length > 5e6 ? input.html.slice(0, 5e6) : input.html);
580
+ unstream(root);
581
+ const body = findTag(root, "body") ?? root;
582
+ const writer = new Writer(new URL(input.url), monthsOf(findTag(root, "html")?.attrs.lang));
583
+ body.children.forEach((c) => writer.write(c));
584
+ const text = writer.done();
585
+ return `Source: ${input.url}
586
+
587
+ ${text}`.replace(/\n{3,}/g, "\n\n").trim() + "\n";
588
+ }
589
+ function findTag(el, tag) {
590
+ for (const c of el.children) {
591
+ if (!isEl(c)) continue;
592
+ if (c.tag === tag) return c;
593
+ const found = findTag(c, tag);
594
+ if (found) return found;
595
+ }
596
+ return void 0;
597
+ }
598
+
599
+ // src/server.ts
600
+ var NEXT_VERSION = "0.20.1-dev.122";
601
+ var READER_COOKIE = "cms_reader";
602
+ var ENTRY_URL = "/api/cms/preview";
603
+ function decodeSegment(segment) {
604
+ try {
605
+ return decodeURIComponent(segment);
606
+ } catch {
607
+ return segment;
608
+ }
609
+ }
610
+ var fromNowhere = (h) => h.get(UNKNOWN_VISITOR_HEADER)?.trim().toLowerCase() === UNKNOWN_VISITOR;
611
+ function sitePageOrigins(req, siteUrl) {
612
+ const url = new URL(req.url);
613
+ const origins = [];
614
+ if (siteUrl) {
615
+ try {
616
+ origins.push(new URL(siteUrl).origin);
617
+ } catch {
618
+ }
619
+ }
620
+ const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().replace(/:$/, "");
621
+ if (proto === "https" || proto === "http") origins.push(`${proto}://${url.host}`);
622
+ origins.push(url.origin);
623
+ return [...new Set(origins)];
624
+ }
625
+ function sameAddress(from, location) {
626
+ if (!location) return null;
627
+ let to;
628
+ try {
629
+ to = new URL(location, from);
630
+ } catch {
631
+ return null;
632
+ }
633
+ const bare = (p) => p.replace(/\/+$/, "") || "/";
634
+ return to.host === from.host && bare(to.pathname) === bare(from.pathname) && to.search === from.search && to.href !== from.href ? to : null;
635
+ }
636
+ async function ownPage(doFetch, origins, path) {
637
+ const passed = [];
638
+ for (const origin of origins) {
639
+ let page = new URL(path, origin);
640
+ const start = page.origin;
641
+ const where = () => page.origin === start ? start : `${start} \u2192 ${page.origin}`;
642
+ let hop = 0;
643
+ for (; hop <= 2; hop++) {
644
+ const init = { headers: { Accept: "text/html", [UNKNOWN_VISITOR_HEADER]: UNKNOWN_VISITOR }, redirect: "manual", cache: "no-store" };
645
+ const res = await doFetch(page.toString(), init).catch(() => null);
646
+ if (!res) {
647
+ passed.push(`unreachable ${where()}`);
648
+ break;
649
+ }
650
+ if (res.status >= 300 && res.status < 400) {
651
+ const next = sameAddress(page, res.headers.get("location"));
652
+ if (!next) return { reason: `page-redirect ${res.status} at ${where()}` };
653
+ page = next;
654
+ continue;
655
+ }
656
+ if (res.status !== 200) return { reason: `page-status ${res.status} at ${where()}` };
657
+ if (!(res.headers.get("content-type") ?? "").includes("text/html")) return { reason: `not-html at ${where()}` };
658
+ return { res, page };
659
+ }
660
+ if (hop > 2) passed.push(`redirects ${where()}`);
661
+ }
662
+ return { reason: `page-not-reached: ${passed.join(", ")}` };
663
+ }
664
+ var TEXT_KEPT_MS = 6e4;
665
+ var TEXT_CACHE = "public, max-age=60";
666
+ var TEXT_CDN_CACHE = "max-age=60, stale-while-revalidate=60, stale-if-error=86400";
667
+ function visitorIp(h) {
668
+ return h.get("x-forwarded-for")?.split(",")[0]?.trim() || h.get("x-real-ip") || void 0;
669
+ }
670
+ function isHttps(req) {
671
+ const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
672
+ return (proto ?? new URL(req.url).protocol.replace(":", "")) === "https";
673
+ }
674
+ function isLocal(req) {
675
+ return /^(localhost|127\.0\.0\.1|\[::1\])$/.test(new URL(req.url).hostname);
676
+ }
677
+ function cookieOptions(secure, maxAge) {
678
+ return { httpOnly: true, secure, sameSite: "lax", path: "/", ...maxAge ? { maxAge } : {} };
679
+ }
680
+ function previewCookieOptions(req, maxAge) {
681
+ return isHttps(req) || isLocal(req) ? { httpOnly: true, secure: true, sameSite: "none", partitioned: true, path: "/", ...maxAge !== void 0 ? { maxAge } : {} } : { httpOnly: true, secure: false, sameSite: "lax", path: "/", ...maxAge !== void 0 ? { maxAge } : {} };
682
+ }
683
+ function siteBase(url) {
684
+ if (!url) return null;
685
+ try {
686
+ return new URL(url.endsWith("/") ? url : url + "/");
687
+ } catch {
688
+ return null;
689
+ }
690
+ }
691
+ var OG_LOCALES = { it: "it_IT", en: "en_US", de: "de_DE", fr: "fr_FR", es: "es_ES", pt: "pt_PT", nl: "nl_NL" };
692
+ function ogLocale(locale) {
693
+ const m = /^([a-z]{2,3})[-_]([a-z]{2})$/i.exec(locale);
694
+ if (m) return `${m[1].toLowerCase()}_${m[2].toUpperCase()}`;
695
+ return OG_LOCALES[locale.toLowerCase()];
696
+ }
697
+ function normalHost(host) {
698
+ return host.trim().toLowerCase();
699
+ }
700
+ var HOST_SHAPE = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?$|^\[[0-9a-f:]+\](:\d{1,5})?$/;
701
+ function createNextCms(options) {
702
+ const declared = /* @__PURE__ */ new Map();
703
+ if (options.sites !== void 0) {
704
+ if (options.publicKey !== void 0) throw new Error("theCMS.: createNextCms takes `publicKey` (one site) or `sites` (several), not both");
705
+ for (const [host, key] of Object.entries(options.sites)) {
706
+ const h = normalHost(host);
707
+ if (!HOST_SHAPE.test(h)) throw new Error(`theCMS.: "${host}" in createNextCms({ sites }) is not a host \u2014 hostname or hostname:port, as the Host header brings it (no scheme, no path)`);
708
+ if (!key) throw new Error(`theCMS.: createNextCms({ sites }) has no public key for "${host}"`);
709
+ if (declared.has(h) && declared.get(h) !== key) throw new Error(`theCMS.: "${host}" is declared twice in createNextCms({ sites })`);
710
+ declared.set(h, key);
711
+ }
712
+ if (declared.size === 0) throw new Error("theCMS.: createNextCms({ sites }) declares no site");
713
+ } else if (options.publicKey === void 0) {
714
+ throw new Error("theCMS.: createNextCms needs `publicKey` (one site) or `sites` ({ host: publicKey })");
715
+ }
716
+ const several = options.sites !== void 0;
717
+ const keys = several ? [...new Set(declared.values())] : [options.publicKey];
718
+ if (options.components) registerComponents(keys, options.components);
719
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
720
+ const announcing = (input, init) => {
721
+ if (!input.includes("/v1/_sites/")) return doFetch(input, init);
722
+ const headers2 = new Headers(init?.headers);
723
+ headers2.set(SITE_HEADER, siteHeader("next", NEXT_VERSION));
724
+ return doFetch(input, { ...init, headers: headers2 });
725
+ };
726
+ const states = /* @__PURE__ */ new Map();
727
+ const stateOfKey = (publicKey) => {
728
+ let state = states.get(publicKey);
729
+ if (!state) {
730
+ const sdk = createSdk({ publicKey, secretKey: options.secretKey, fetch: announcing, track: false });
731
+ state = { publicKey, sdk, site: cache(() => sdk.site()), texts: /* @__PURE__ */ new Map() };
732
+ states.set(publicKey, state);
733
+ }
734
+ return state;
735
+ };
736
+ const vary = (headers2) => several ? { ...headers2, Vary: "Host" } : headers2;
737
+ const markdown = (text) => new Response(text, { headers: vary({ "Content-Type": "text/markdown; charset=utf-8", "Cache-Control": TEXT_CACHE, "CDN-Cache-Control": TEXT_CDN_CACHE }) });
738
+ const stateOfHost = (host) => {
739
+ if (!several) return stateOfKey(options.publicKey);
740
+ const key = host ? declared.get(normalHost(host)) : void 0;
741
+ return key ? stateOfKey(key) : null;
742
+ };
743
+ const stateOfRequest = (req) => {
744
+ if (!several) return stateOfKey(options.publicKey);
745
+ let host = req.headers.get("host");
746
+ if (!host) {
747
+ try {
748
+ host = new URL(req.url).host;
749
+ } catch {
750
+ host = null;
751
+ }
752
+ }
753
+ return stateOfHost(host);
754
+ };
755
+ const notDeclared = () => new Response("Not found", { status: 404, headers: { "Cache-Control": "no-store", Vary: "Host" } });
756
+ const current = cache(async () => {
757
+ if (!several) return stateOfKey(options.publicKey);
758
+ const state = stateOfHost((await headers()).get("host"));
759
+ if (!state) notFound();
760
+ return state;
761
+ });
762
+ const site = cache(async () => (await current()).site());
763
+ registerSite(site);
764
+ const clientOf = (state) => ({ publicKey: state.publicKey });
765
+ const resolve = cache(async (path, lists) => {
766
+ const { sdk } = await current();
767
+ const states2 = lists ? { lists: lists.split(" ") } : {};
768
+ const h = await headers();
769
+ if (fromNowhere(h)) return sdk.page(path, { unknownVisitor: true, track: false, ...states2 });
770
+ const forwardedFor = visitorIp(h);
771
+ const allowed2 = previewRequestAllowed(h.get("sec-fetch-dest"), { frame: h.get(FRAME_HEADER) });
772
+ const preview = allowed2 ? (await cookies()).get(PREVIEW_COOKIE)?.value : void 0;
773
+ if (preview) {
774
+ try {
775
+ return await sdk.page(path, { preview, forwardedFor, track: false, ...states2 });
776
+ } catch (err) {
777
+ if (err.status !== 401) throw err;
778
+ }
779
+ }
780
+ return sdk.page(path, { forwardedFor, track: false, ...states2 });
781
+ });
782
+ async function listsOf(props) {
783
+ const raw = (await props.searchParams)?.[LIST_PARAM];
784
+ return (Array.isArray(raw) ? raw : raw ? [raw] : []).filter((t) => /^[\w.-]+$/.test(t)).slice(0, 10).join(" ");
785
+ }
786
+ async function pathOf(props) {
787
+ const params = await props.params;
788
+ const segments = Object.values(params).find(Array.isArray) ?? [];
789
+ return "/" + segments.map((s) => encodeURIComponent(decodeSegment(s))).join("/");
790
+ }
791
+ async function readerToken() {
792
+ return (await cookies()).get(READER_COOKIE)?.value;
793
+ }
794
+ const cms = {
795
+ /**
796
+ * The SDK of the request's site, for everything else (lists, records with the secret key…) — MULTISITE (D638):
797
+ * the one the request's host chose (an undeclared host is "not found").
798
+ */
799
+ sdkOf: async () => (await current()).sdk,
800
+ /**
801
+ * SITE-KEY (D253): what holds for the whole site — its address, its preview
802
+ * route, its sitemap, the languages, the globals and the messages. Once per
803
+ * request: the layout, the page and the metadata share it. MULTISITE (D638):
804
+ * the request's site — `app` is the application's slug, the layout puts it
805
+ * on `<html data-site={…}>` (D641).
806
+ */
807
+ site,
808
+ /**
809
+ * KIT (D382): the site's texts for an address where there is no page of
810
+ * the CMS (the layout, not found, an error, a page blocked in the
811
+ * visitor's country): the address's language (its first segment when it is
812
+ * a language of the site, else the default one), `t` / `g` in it as in
813
+ * `cmsContext()`, the Site name, the homes of the languages (the address's
814
+ * first). From `site()`: no request more.
815
+ */
816
+ async siteText(path) {
817
+ return siteTextOf(await site(), path);
818
+ },
819
+ /**
820
+ * The page at the route's path. Redirects and "not found" are answered
821
+ * with Next's own functions (they never return); a page blocked in the
822
+ * visitor's country comes back as `{ kind: "geoBlocked" }`. The editor's
823
+ * link into a page (`?preview=`) passes through the site's CMS route, which
824
+ * keeps the token in the preview's cookie (D254, D289); in a tab the token
825
+ * is ignored (D290). E6 (D306): `?f=<token>` (a list link's `token`, the
826
+ * site puts it in its own address) — the page comes with that list's
827
+ * block at that state, in the same answer.
828
+ */
829
+ async page(props) {
830
+ const address = await pathOf(props);
831
+ const token = (await props.searchParams)?.[PREVIEW_PARAM];
832
+ if (typeof token === "string" && token && previewRequestAllowed((await headers()).get("sec-fetch-dest"), { entry: true })) {
833
+ redirect(`${ENTRY_URL}?path=${encodeURIComponent(address)}&token=${encodeURIComponent(token)}`);
834
+ }
835
+ const [r, siteAnswer] = await Promise.all([resolve(address, await listsOf(props)), site()]);
836
+ if (r.kind === "redirect") (r.status === 301 ? permanentRedirect : redirect)(r.location);
837
+ if (r.kind === "notFound") notFound();
838
+ if (r.kind === "geoBlocked") {
839
+ if (fromNowhere(await headers())) notFound();
840
+ return { kind: "geoBlocked", country: r.country, continent: r.continent };
841
+ }
842
+ if (r.kind !== "page") notFound();
843
+ const client = clientOf(await current());
844
+ if (r.page._preview) markForEditor(r.page, client);
845
+ const page = { ...r.page, kind: "page", _cms: client };
846
+ setCmsContext(page, siteAnswer, decodeSegment(address));
847
+ return page;
848
+ },
849
+ /**
850
+ * `export const generateMetadata = cms.metadata` (NEXT-META D327–D329): title, description, the
851
+ * canonical and hreflang made absolute on the Site URL (`metadataBase`), Open Graph (url, type,
852
+ * locale, siteName, an article's dates, image), the Twitter card.
853
+ */
854
+ metadata: async (props) => {
855
+ const address = await pathOf(props);
856
+ const [r, siteAnswer] = await Promise.all([resolve(address, await listsOf(props)), site()]);
857
+ if (r.kind !== "page") return {};
858
+ const { seo, _route, recordDates } = r.page;
859
+ const base = siteBase(siteAnswer.url);
860
+ const absolute = (path) => base && path.startsWith("/") ? base.href.replace(/\/$/, "") + path : path;
861
+ const canonical = seo.canonicalUrl ?? _route?.canonical;
862
+ const image = seo.ogImage ? platformUrl(seo.ogImage) : null;
863
+ const locale = ogLocale(_route?.locale ?? r.page._locale.resolved);
864
+ const others = [...new Set((_route?.alternates ?? []).filter((a) => a.locale !== "x-default" && a.locale !== _route?.locale).map((a) => ogLocale(a.locale)).filter((l) => !!l))];
865
+ const article = r.page.record !== null;
866
+ const openGraph = {
867
+ type: article ? "article" : "website",
868
+ ...canonical ? { url: absolute(canonical) } : {},
869
+ ...seo.title ? { title: seo.title } : {},
870
+ ...seo.description ? { description: seo.description } : {},
871
+ ...siteAnswer.name ? { siteName: siteAnswer.name } : {},
872
+ ...locale ? { locale } : {},
873
+ ...others.length ? { alternateLocale: others } : {},
874
+ ...article && recordDates?.published ? { publishedTime: recordDates.published } : {},
875
+ ...article && recordDates?.modified ? { modifiedTime: recordDates.modified } : {},
876
+ ...image ? { images: [image] } : {}
877
+ };
878
+ return {
879
+ ...base ? { metadataBase: base } : {},
880
+ // SITE-EDITOR (D292): a page with the drafts is never indexed
881
+ ...r.page._preview ? { robots: { index: false, follow: false } } : {},
882
+ ...seo.title ? { title: seo.title } : {},
883
+ ...seo.description ? { description: seo.description } : {},
884
+ ...canonical ? {
885
+ alternates: {
886
+ canonical: absolute(canonical),
887
+ ..._route?.alternates.length ? { languages: Object.fromEntries(_route.alternates.map((a) => [a.locale, absolute(a.path)])) } : {}
888
+ }
889
+ } : {},
890
+ openGraph,
891
+ // D329: the large card only with an image
892
+ twitter: {
893
+ card: image ? "summary_large_image" : "summary",
894
+ ...seo.title ? { title: seo.title } : {},
895
+ ...seo.description ? { description: seo.description } : {},
896
+ ...image ? { images: [image] } : {}
897
+ }
898
+ };
899
+ },
900
+ /** An address the CMS gave (an image, a file, an og image), absolute. */
901
+ url: platformUrl,
902
+ /** The signed-in reader of the site, or null (D192). */
903
+ async reader() {
904
+ const token = await readerToken();
905
+ if (!token) return null;
906
+ try {
907
+ return (await (await current()).sdk.auth.me(token)).user;
908
+ } catch {
909
+ return null;
910
+ }
911
+ },
912
+ /**
913
+ * SIGN-IN (D347): where a "Sign in with …" button of the site goes — one
914
+ * of `site().signIn` (`key`), back to `returnTo` (a path of the site).
915
+ * The platform signs the reader in and returns to the site's CMS route
916
+ * (`/api/cms/signed-in`), which sets the reader's cookie; a refusal comes
917
+ * back to `returnTo` with `?signin=closed|domain|unverified|revoked|failed`.
918
+ */
919
+ async signInUrl(key, returnTo = "/") {
920
+ return (await current()).sdk.signInUrl(key, returnTo);
921
+ },
922
+ /** Another page or filter of a list: a link the CMS built (and signed), read with the visitor's address. */
923
+ async follow(link) {
924
+ return (await current()).sdk.follow(link, { forwardedFor: visitorIp(await headers()) });
925
+ },
926
+ /** The values of protected fields the reader bought (paywall keys of the page); null without a signed-in reader. */
927
+ async unlock(keys2) {
928
+ const token = await readerToken();
929
+ if (!token || keys2.length === 0) return null;
930
+ return (await current()).sdk.unlock(keys2, token, { forwardedFor: visitorIp(await headers()) });
931
+ },
932
+ /**
933
+ * PAYMENTS (D361): buy a product for the signed-in reader (from a server
934
+ * action: `redirect((await cms.checkout(id, "/thanks"))!.redirectUrl)`) —
935
+ * priced for the reader's country (their address forwarded: the secret key
936
+ * makes the CMS trust it), back to `returnTo` with `?order=<id>`; null
937
+ * without a signed-in reader. A refusal is a `CmsError` with
938
+ * `details.reason`. Without code: a form posting `productId` and `return`
939
+ * to `/api/cms/checkout` (the optional route) does the same.
940
+ */
941
+ async checkout(productId, returnTo = "/") {
942
+ const token = await readerToken();
943
+ if (!token) return null;
944
+ return (await current()).sdk.checkout(productId, returnTo, token, { forwardedFor: visitorIp(await headers()) });
945
+ },
946
+ /** D360: the signed-in reader's purchases, newest first (in force, until when, still on sale); null without a reader. */
947
+ async purchases() {
948
+ const token = await readerToken();
949
+ return token ? (await current()).sdk.purchases(token) : null;
950
+ },
951
+ /** D355: one of the signed-in reader's orders (the return page's `?order=<id>`); null without a reader or for an order not theirs. */
952
+ async order(id) {
953
+ const token = await readerToken();
954
+ if (!token) return null;
955
+ try {
956
+ return await (await current()).sdk.order(id, token);
957
+ } catch (err) {
958
+ if (err instanceof CmsError && err.status === 404) return null;
959
+ throw err;
960
+ }
961
+ },
962
+ /**
963
+ * D257: `export const GET = cms.sitemap` in `app/sitemap.xml/route.ts` — the
964
+ * CMS's sitemap from the site's own address; 404 when the application
965
+ * publishes none.
966
+ */
967
+ sitemap: async () => {
968
+ const state = several ? stateOfHost((await headers()).get("host")) : stateOfKey(options.publicKey);
969
+ if (!state) return notDeclared();
970
+ const xml = await state.sdk.sitemap();
971
+ if (xml === null) return new Response("Not found", { status: 404, headers: vary({}) });
972
+ return new Response(xml, { headers: vary({ "Content-Type": "application/xml; charset=utf-8", "Cache-Control": "public, max-age=3600" }) });
973
+ },
974
+ /**
975
+ * D257: `export default cms.robots` in `app/robots.ts` — the whole site, the
976
+ * sitemap in when there is one; SEO-AI (D490): with AI readers off, the AI
977
+ * crawlers shut out (the platform's list), the rest unchanged.
978
+ */
979
+ robots: async () => {
980
+ const s = await site();
981
+ const all = { userAgent: "*", allow: "/" };
982
+ return {
983
+ rules: !s.aiReaders && s.aiCrawlers?.length ? [{ userAgent: s.aiCrawlers, disallow: "/" }, all] : all,
984
+ ...s.sitemap && s.url ? { sitemap: `${s.url}/sitemap.xml` } : {}
985
+ };
986
+ },
987
+ /**
988
+ * SEO-AI (D491): `export const GET = cms.llms` in `app/llms.txt/route.ts` —
989
+ * the site's pages for AI readers (`?part=n` of an index); 404 while AI readers are off.
990
+ */
991
+ llms: async (req) => {
992
+ const state = stateOfRequest(req);
993
+ if (!state) return notDeclared();
994
+ const part = Number(new URL(req.url).searchParams.get("part")) || void 0;
995
+ const text = await state.sdk.llms(part);
996
+ if (text === null) return new Response("Not found", { status: 404, headers: vary({}) });
997
+ return new Response(text, { headers: vary({ "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=3600" }) });
998
+ },
999
+ /**
1000
+ * SEO-AI (D492, SA7 D506): `export const GET = cms.pageText` in
1001
+ * `app/llms/[[...path]]/route.ts` — the clean text of the page at the rest
1002
+ * of the address (`/llms/it/chi-siamo` → `/it/chi-siamo`, `/llms` → the
1003
+ * home): EXACTLY what the page shows, the site's own code included. The
1004
+ * site's public page is asked as a visitor from nowhere known (no cookie,
1005
+ * no preview: paid fields stay closed, only what every country reads) and
1006
+ * its HTML becomes markdown. A page answering 404, a redirect or blocked
1007
+ * by country → 404; AI readers off → 404. Kept a minute per instance and
1008
+ * cached like a public page: an AI reader never redraws it each time.
1009
+ */
1010
+ pageText: async (req, ctx) => {
1011
+ const state = stateOfRequest(req);
1012
+ if (!state) return notDeclared();
1013
+ const { sdk, texts } = state;
1014
+ const segments = (await ctx.params).path ?? [];
1015
+ const path = `/${segments.map((x) => encodeURIComponent(decodeSegment(x))).join("/")}`;
1016
+ const none = (reason) => {
1017
+ const branch = reason.split(/[: ]/)[0];
1018
+ console.warn(JSON.stringify({ event: "cms.page_text.none", path, reason }));
1019
+ return new Response("Not found", { status: 404, headers: vary({ "X-CMS-Text": branch }) });
1020
+ };
1021
+ if (segments[0] === "llms") return none("text-of-text");
1022
+ if (fromNowhere(req.headers)) return none("own-request");
1023
+ const s = await sdk.site();
1024
+ if (!s.aiReaders) return none("ai-readers-off");
1025
+ const kept = texts.get(path);
1026
+ if (kept && kept.until > Date.now()) return markdown(kept.text);
1027
+ const found = await ownPage(doFetch, sitePageOrigins(req, s.url), path);
1028
+ if ("reason" in found) return none(found.reason);
1029
+ const { res, page } = found;
1030
+ const text = pageMarkdown({ html: await res.text(), url: `${(s.url ?? page.origin).replace(/\/+$/, "")}${path}` });
1031
+ if (texts.size >= 500) texts.delete(texts.keys().next().value);
1032
+ texts.set(path, { text, until: Date.now() + TEXT_KEPT_MS });
1033
+ return markdown(text);
1034
+ },
1035
+ /** `export const { GET, POST } = cms.handler` in `app/api/cms/[...cms]/route.ts` (D189–D192; SIGN-IN D347: `signed-in`; PAYMENTS D361: `checkout`). */
1036
+ handler: createHandler({ secretKey: options.secretKey, keys, several, doFetch, siteOf: stateOfRequest, notDeclared, vary })
1037
+ };
1038
+ Object.defineProperty(cms, "sdk", several ? { get() {
1039
+ throw new Error("theCMS.: with `sites` there is one SDK per site \u2014 use `await cms.sdkOf()`, the request's");
1040
+ }, enumerable: false } : { value: stateOfKey(options.publicKey).sdk, enumerable: true });
1041
+ return cms;
1042
+ }
1043
+ function allowed(method, path, tenant, publicKeys) {
1044
+ const t = encodeURIComponent(tenant);
1045
+ if (method === "POST") return path === `/v1/${t}/public/visits`;
1046
+ if (publicKeys.some((k) => path === `/v1/_sites/${encodeURIComponent(k)}`)) return true;
1047
+ return new RegExp(`^/v1/${t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(views/[^/]+/(route|site)|public/(changes|preview/changes|records/[^/]+))$`).test(path);
1048
+ }
1049
+ function createHandler(deps) {
1050
+ async function proxy(req, path, sdk) {
1051
+ const { workspace } = await sdk.site();
1052
+ if (!allowed(req.method, path, workspace, deps.keys)) return Response.json({ error: { code: "NOT_FOUND", message: "Not found" } }, { status: 404, headers: deps.vary({}) });
1053
+ const h = new Headers({ Accept: "application/json" });
1054
+ if (deps.secretKey) h.set("X-Api-Key", deps.secretKey);
1055
+ else h.set("X-CMS-Proxied", "1");
1056
+ const ip = visitorIp(req.headers);
1057
+ if (ip) h.set("X-Forwarded-For", ip);
1058
+ const contentType = req.headers.get("content-type");
1059
+ if (req.method === "POST") {
1060
+ h.set("Content-Type", contentType?.startsWith("text/plain") ? "text/plain" : "application/json");
1061
+ const token = (await cookies()).get(READER_COOKIE)?.value;
1062
+ if (token) h.set("Authorization", `Bearer ${token}`);
1063
+ }
1064
+ const search = new URL(req.url).search;
1065
+ const res = await deps.doFetch(`${PLATFORM_API}${path}${search}`, {
1066
+ method: req.method,
1067
+ headers: h,
1068
+ ...req.method === "POST" ? { body: await req.text() } : {}
1069
+ });
1070
+ const out = new Headers();
1071
+ for (const name of ["content-type", "cache-control", "retry-after", "vary"]) {
1072
+ const v = res.headers.get(name);
1073
+ if (v) out.set(name, v);
1074
+ }
1075
+ if (deps.several) out.set("vary", [.../* @__PURE__ */ new Set([...(out.get("vary")?.split(",") ?? []).map((x) => x.trim()).filter(Boolean), "Host"])].join(", "));
1076
+ return new Response(res.body, { status: res.status, headers: out });
1077
+ }
1078
+ const sitePath = (p) => p && p.startsWith("/") && !p.startsWith("//") && !p.includes("\\") ? p : "/";
1079
+ async function GET(req, ctx) {
1080
+ const segments = (await ctx.params).cms ?? [];
1081
+ const sub = segments.join("/");
1082
+ const state = deps.siteOf(req);
1083
+ if (!state) return deps.notDeclared();
1084
+ const sdk = state.sdk;
1085
+ if (sub === "ping") return Response.json({ ok: true }, { headers: deps.vary({ "Cache-Control": "no-store" }) });
1086
+ if (sub === "signed-in") {
1087
+ const q = new URL(req.url).searchParams;
1088
+ const to = sitePath(q.get("to"));
1089
+ const code = q.get("code");
1090
+ try {
1091
+ if (!code) throw new Error("no code");
1092
+ const session = await sdk.exchangeSignIn(code, { forwardedFor: visitorIp(req.headers) });
1093
+ (await cookies()).set(READER_COOKIE, session.accessToken, cookieOptions(isHttps(req), session.expiresIn));
1094
+ return redirectTo(to);
1095
+ } catch {
1096
+ const failed = new URL(to, "http://site");
1097
+ failed.searchParams.set("signin", "failed");
1098
+ return redirectTo(`${failed.pathname}${failed.search}${failed.hash}`);
1099
+ }
1100
+ }
1101
+ if (sub === "preview") {
1102
+ const q = new URL(req.url).searchParams;
1103
+ const token = q.get("token");
1104
+ if (!token) return Response.json({ error: { code: "VALIDATION_ERROR", message: "token is required" } }, { status: 422 });
1105
+ const path = sitePath(q.get("path"));
1106
+ if (!previewRequestAllowed(req.headers.get("sec-fetch-dest"), { entry: true })) return redirectTo(path);
1107
+ const status = await sdk.previewStatus(token);
1108
+ if (!status.active) return redirectTo(path);
1109
+ const seconds = Math.max(1, Math.floor((Date.parse(status.expiresAt) - Date.now()) / 1e3));
1110
+ (await cookies()).set(PREVIEW_COOKIE, token, previewCookieOptions(req, seconds));
1111
+ return redirectTo(path);
1112
+ }
1113
+ return proxy(req, "/" + segments.map(encodeURIComponent).join("/"), sdk);
1114
+ }
1115
+ async function POST(req, ctx) {
1116
+ const segments = (await ctx.params).cms ?? [];
1117
+ const sub = segments.join("/");
1118
+ const state = deps.siteOf(req);
1119
+ if (!state) return deps.notDeclared();
1120
+ const sdk = state.sdk;
1121
+ if (sub === "logout") {
1122
+ (await cookies()).delete(READER_COOKIE);
1123
+ return Response.json({ ok: true });
1124
+ }
1125
+ if (sub === "checkout") {
1126
+ const form = await readForm(req);
1127
+ const back = sitePath(form.get("return"));
1128
+ const refused = (reason) => {
1129
+ const to = new URL(back, "http://site");
1130
+ to.searchParams.set("checkout", reason);
1131
+ return seeOther(`${to.pathname}${to.search}${to.hash}`);
1132
+ };
1133
+ const token = (await cookies()).get(READER_COOKIE)?.value;
1134
+ const productId = form.get("productId");
1135
+ if (!token) return refused("sign_in");
1136
+ if (!productId) return refused("failed");
1137
+ try {
1138
+ const { redirectUrl } = await sdk.checkout(productId, back, token, { forwardedFor: visitorIp(req.headers) });
1139
+ return seeOther(redirectUrl);
1140
+ } catch (err) {
1141
+ const reason = err instanceof CmsError && typeof err.details?.reason === "string" ? err.details.reason : err instanceof CmsError && err.status === 401 ? "sign_in" : "failed";
1142
+ return refused(reason);
1143
+ }
1144
+ }
1145
+ return proxy(req, "/" + segments.map(encodeURIComponent).join("/"), sdk);
1146
+ }
1147
+ return { GET, POST };
1148
+ }
1149
+ function seeOther(location) {
1150
+ return new Response(null, { status: 303, headers: { Location: location, "Cache-Control": "no-store" } });
1151
+ }
1152
+ async function readForm(req) {
1153
+ if ((req.headers.get("content-type") ?? "").includes("application/json")) {
1154
+ const body = await req.json().catch(() => ({}));
1155
+ return { get: (name) => typeof body[name] === "string" ? body[name] : null };
1156
+ }
1157
+ const data = await req.formData().catch(() => null);
1158
+ return { get: (name) => {
1159
+ const v = data?.get(name);
1160
+ return typeof v === "string" ? v : null;
1161
+ } };
1162
+ }
1163
+ function redirectTo(path) {
1164
+ return new Response(null, { status: 307, headers: { Location: path, "Cache-Control": "no-store" } });
1165
+ }
1166
+ export {
1167
+ CmsBlocks,
1168
+ CmsSiteTexts,
1169
+ NEXT_VERSION,
1170
+ PREVIEW_COOKIE,
1171
+ READER_COOKIE,
1172
+ SITE_TEXT_KEYS,
1173
+ cmsContext,
1174
+ createNextCms,
1175
+ ogLocale,
1176
+ sitePageOrigins
1177
+ };