@tdacorp/hyle-sdk 0.12.0 → 0.17.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.
Files changed (43) hide show
  1. package/README.md +46 -12
  2. package/dist/check-routes-bin.js +31 -18
  3. package/dist/{chunk-S7PCCEHP.js → chunk-6VOHFFA5.js} +4 -3
  4. package/dist/{chunk-ZQFYH4FX.js → chunk-DMK4XQLU.js} +497 -327
  5. package/dist/{chunk-N7ZQUAGM.js → chunk-MGSUQBDW.js} +19 -7
  6. package/dist/{chunk-R5EMI4HQ.js → chunk-PJMJMP66.js} +3 -1
  7. package/dist/comments.cjs +6 -4
  8. package/dist/comments.js +6 -5
  9. package/dist/{diagram-viewer-DYX6R63Y.js → diagram-viewer-FJPED4SN.js} +46 -26
  10. package/dist/{embed-jCaSI31t.d.cts → embed-BmdwA2G9.d.cts} +51 -5
  11. package/dist/{embed-DL5QIZRJ.d.ts → embed-DNTZ2UXv.d.ts} +51 -5
  12. package/dist/index.cjs +19 -7
  13. package/dist/index.d.cts +15 -8
  14. package/dist/index.d.ts +15 -8
  15. package/dist/index.js +1 -1
  16. package/dist/labels-nmukKYgL.d.cts +37 -0
  17. package/dist/labels-nmukKYgL.d.ts +37 -0
  18. package/dist/mermaid-diagram.cjs +59 -30
  19. package/dist/mermaid-diagram.d.cts +4 -37
  20. package/dist/mermaid-diagram.d.ts +4 -37
  21. package/dist/mermaid-diagram.js +7 -5
  22. package/dist/mermaid-image.cjs +1382 -0
  23. package/dist/mermaid-image.d.cts +29 -0
  24. package/dist/mermaid-image.d.ts +29 -0
  25. package/dist/mermaid-image.js +94 -0
  26. package/dist/next.cjs +1235 -789
  27. package/dist/next.d.cts +149 -24
  28. package/dist/next.d.ts +149 -24
  29. package/dist/next.js +887 -612
  30. package/dist/react.cjs +336 -196
  31. package/dist/react.d.cts +39 -7
  32. package/dist/react.d.ts +39 -7
  33. package/dist/react.js +1 -1
  34. package/dist/{resolve-DvmuBlpO.d.ts → resolve-Ae7UFjsQ.d.ts} +5 -5
  35. package/dist/{resolve-f6IJ6SL9.d.cts → resolve-euZ4-aC9.d.cts} +5 -5
  36. package/dist/styles.css +11 -22
  37. package/dist/{types-5D6ZD0Wi.d.cts → types-Czt887Iv.d.cts} +32 -3
  38. package/dist/{types-5D6ZD0Wi.d.ts → types-Czt887Iv.d.ts} +32 -3
  39. package/dist/use-cache.cjs +1 -1
  40. package/dist/use-cache.d.cts +2 -2
  41. package/dist/use-cache.d.ts +2 -2
  42. package/dist/use-cache.js +2 -2
  43. package/package.json +1 -1
package/dist/next.js CHANGED
@@ -8,14 +8,22 @@ import {
8
8
  HyleCommentsView,
9
9
  HyleListView,
10
10
  ListPage,
11
+ absoluteUrl,
12
+ articleAuthor,
13
+ bareOrigin,
14
+ hreflangLanguages,
15
+ modifiedAt,
11
16
  parseListing,
12
- stringsFor
13
- } from "./chunk-ZQFYH4FX.js";
17
+ readingMinutes,
18
+ stringsFor,
19
+ validOgImage,
20
+ wordCountOf
21
+ } from "./chunk-DMK4XQLU.js";
14
22
  import {
15
23
  DEFAULT_REVALIDATE,
16
24
  fetchResolver,
17
25
  workspaceTags
18
- } from "./chunk-S7PCCEHP.js";
26
+ } from "./chunk-6VOHFFA5.js";
19
27
  import {
20
28
  Cp1ClientError,
21
29
  checkBaseUrl,
@@ -26,10 +34,11 @@ import {
26
34
  listPublicationPaths,
27
35
  readCapped,
28
36
  signReaderAssertion
29
- } from "./chunk-N7ZQUAGM.js";
37
+ } from "./chunk-MGSUQBDW.js";
30
38
  import {
31
39
  ASSET_CONTENT_TYPES,
32
- ASSET_FILE
40
+ ASSET_FILE,
41
+ ASSET_ROUTE_PREFIX
33
42
  } from "./chunk-67IOIAVW.js";
34
43
 
35
44
  // src/next/page.tsx
@@ -72,6 +81,12 @@ function safeRedirectTarget(to) {
72
81
  function resolverFor(options) {
73
82
  return options.resolver ?? fetchResolver(options);
74
83
  }
84
+ function articleImage(options, article) {
85
+ const { canonical_path, locale, title, updated_at } = article.publication;
86
+ const edited = Date.parse(updated_at);
87
+ const fallback = { url: `/api/hyle/og${canonical_path.split("/").map(encodeURIComponent).join("/")}?locale=${encodeURIComponent(locale)}${Number.isNaN(edited) ? "" : `&v=${edited}`}`, width: 1200, height: 630, alt: title };
88
+ return validOgImage(options.ogImage ? options.ogImage(article) : options.ogImageRoute ? fallback : void 0, bareOrigin(options.siteOrigin));
89
+ }
75
90
  var CURSOR = /^[A-Za-z0-9_-]{1,256}$/;
76
91
  var validCursor = (value) => typeof value === "string" && CURSOR.test(value) ? value : void 0;
77
92
  var LOCALE_TAG = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
@@ -91,180 +106,639 @@ function isRejectedRequest(error) {
91
106
  return error instanceof Cp1ClientError && error.status >= 400 && error.status < 500 && ![401, 403, 429].includes(error.status);
92
107
  }
93
108
 
94
- // src/next/page.tsx
95
- import { jsx } from "react/jsx-runtime";
96
- function hylePage(options) {
97
- const resolve = resolverFor(options);
98
- return async function HylePage({ params, searchParams }) {
99
- const { path, locale, toHref } = routeContext(options, await params ?? {});
100
- if (path === void 0) notFound();
101
- try {
102
- const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
103
- const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
104
- switch (result.kind) {
105
- case "article": {
106
- const props = { article: result, components: options.components, slots: options.slots, locale, toHref };
107
- return options.layout === "docs" ? /* @__PURE__ */ jsx(DocsPage, { ...props }) : /* @__PURE__ */ jsx(ArticlePage, { ...props, origin: options.siteOrigin, ...options.engagement ? { engagement: options.engagement } : {} });
108
- }
109
- case "list": {
110
- const list = options.list?.title ? { ...result, section: { ...result.section, title: options.list.title } } : result;
111
- const next = options.paginate === "searchParams" ? validCursor(result.next_cursor) : void 0;
112
- const olderHref = next ? `${toHref(path)}?cursor=${next}` : void 0;
113
- return /* @__PURE__ */ jsx(ListPage, { list, ...olderHref ? { olderHref } : {}, ...options.list?.description ? { description: options.list.description } : {}, components: options.components, slots: options.slots, locale, toHref });
114
- }
115
- case "redirect": {
116
- const to = safeRedirectTarget(result.to);
117
- if (to === void 0) throw new Cp1ClientError("INVALID_RESPONSE", "hyle returned an unsafe redirect target", 502, "");
118
- const target = safeRedirectTarget(toHref(to));
119
- if (target === void 0) throw new Cp1ClientError("INVALID_RESPONSE", "hyle returned an unsafe redirect target", 502, "");
120
- if (target === toHref(path)) notFound();
121
- return result.status === 301 ? permanentRedirect(target) : redirect(target);
109
+ // src/next/embed.tsx
110
+ import { unstable_rethrow as unstable_rethrow2 } from "next/navigation";
111
+
112
+ // src/next/engage.ts
113
+ var ENGAGE_CSRF_HEADER = "x-hyle-engage";
114
+ var DEFAULT_TIMEOUT_MS = 1e4;
115
+ var DEFAULT_SHARE_MS = 3e3;
116
+ var MAX_SHARED = 100;
117
+ var MAX_SHARED_BYTES = 8 * 1024 * 1024;
118
+ var MAX_SHARED_ENTRY_BYTES = 256 * 1024;
119
+ var MAX_BODY_BYTES = 20 * 1024;
120
+ var MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
121
+ var MAX_COMMENT_CHARACTERS = 4e3;
122
+ var MAX_PATH_LENGTH2 = 1024;
123
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
124
+ var CONTROL = /[\u0000-\u001f\u007f\\]/;
125
+ var HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };
126
+ var isSwitchedOff = (value) => {
127
+ const v = value?.trim().toLowerCase() ?? "";
128
+ return v !== "" && v !== "1" && v !== "true";
129
+ };
130
+ var json = (status, body, extra = {}) => new Response(JSON.stringify(body), { status, headers: { ...HEADERS, "Content-Type": "application/json; charset=utf-8", ...extra } });
131
+ var refuse = (status, code, extra = {}) => json(status, { error: { code } }, extra);
132
+ function isSitePath(value) {
133
+ if (typeof value !== "string" || value.length > MAX_PATH_LENGTH2 || !value.startsWith("/") || value.startsWith("//")) return false;
134
+ if (CONTROL.test(value) || /[?#]/.test(value)) return false;
135
+ return !value.split("/").some((segment) => segment === "." || segment === "..");
136
+ }
137
+ function match(segments) {
138
+ const [a, b, ...rest] = segments;
139
+ if (a === "session" && b === void 0) return { local: "session", action: () => "session", methods: ["GET"], rebuild: () => void 0 };
140
+ if (a === "comments" && b === void 0) {
141
+ return {
142
+ action: (m) => m === "GET" ? "comments.list" : "comments.create",
143
+ methods: ["GET", "POST"],
144
+ rebuild: (method, body, url) => {
145
+ if (method === "GET") {
146
+ const keys = [...url.searchParams.keys()];
147
+ const path = url.searchParams.get("path");
148
+ return keys.length === 1 && isSitePath(path) ? { upstream: "/comments", query: new URLSearchParams({ path }) } : void 0;
122
149
  }
123
- case "notfound":
124
- case "disabled":
125
- notFound();
150
+ const clean = pick(body, ["path", "body", "parent_id"], ["path", "body"]);
151
+ if (!clean || !isSitePath(clean.path) || !isCommentText(clean.body)) return void 0;
152
+ if (clean.parent_id === null) delete clean.parent_id;
153
+ if (clean.parent_id !== void 0 && !(typeof clean.parent_id === "string" && UUID.test(clean.parent_id))) return void 0;
154
+ return { upstream: "/comments", body: clean };
126
155
  }
127
- } catch (error) {
128
- if (isRejectedRequest(error)) notFound();
129
- if (!options.onError) throw error;
130
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
131
- return options.onError(error);
132
- }
133
- };
156
+ };
157
+ }
158
+ if (a === "comments" && typeof b === "string" && UUID.test(b) && rest.length === 0) {
159
+ return {
160
+ action: (m) => m === "PATCH" ? "comments.edit" : "comments.delete",
161
+ methods: ["PATCH", "DELETE"],
162
+ rebuild: (method, body) => {
163
+ if (method === "DELETE") return body === void 0 ? { upstream: `/comments/${b}` } : void 0;
164
+ const clean = pick(body, ["body"], ["body"]);
165
+ return clean && isCommentText(clean.body) ? { upstream: `/comments/${b}`, body: clean } : void 0;
166
+ }
167
+ };
168
+ }
169
+ if (a === "reactions" && b === void 0) {
170
+ return {
171
+ action: (m) => m === "PUT" ? "reactions.add" : "reactions.remove",
172
+ methods: ["PUT", "DELETE"],
173
+ rebuild: (_method, body) => {
174
+ const type = body?.subject_type;
175
+ const clean = type === "article" ? pick(body, ["subject_type", "path"], ["subject_type", "path"]) : type === "comment" ? pick(body, ["subject_type", "comment_id"], ["subject_type", "comment_id"]) : void 0;
176
+ if (!clean) return void 0;
177
+ const valid = type === "article" ? isSitePath(clean.path) : typeof clean.comment_id === "string" && UUID.test(clean.comment_id);
178
+ return valid ? { upstream: "/reactions", body: clean } : void 0;
179
+ }
180
+ };
181
+ }
182
+ return void 0;
134
183
  }
135
-
136
- // src/next/sitemap.ts
137
- var ISO_DATE = /^\d{4}-\d{2}-\d{2}T/;
138
- function httpsOrigin(origin) {
139
- let url;
184
+ function pick(body, allowed, required) {
185
+ if (!body || Object.keys(body).some((k) => !allowed.includes(k)) || !required.every((k) => k in body)) return void 0;
186
+ return Object.fromEntries(allowed.filter((k) => k in body).map((k) => [k, body[k]]));
187
+ }
188
+ function isCommentText(value) {
189
+ return typeof value === "string" && value.trim().length > 0 && [...value].length <= MAX_COMMENT_CHARACTERS && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value);
190
+ }
191
+ function sameOriginProblem(req, write, allowedOrigins) {
192
+ const site = req.headers.get("sec-fetch-site");
193
+ if (site !== null && site !== "same-origin") return true;
194
+ if (!write) return false;
195
+ const origin = req.headers.get("origin");
196
+ if (origin === null) return true;
197
+ let parsed;
140
198
  try {
141
- url = new URL(origin);
199
+ parsed = new URL(origin);
142
200
  } catch {
143
- throw new TypeError("hyleSitemap: `origin` must be an https origin such as https://example.com");
144
- }
145
- if (url.protocol !== "https:" || url.origin !== origin.replace(/\/$/, "")) {
146
- throw new TypeError("hyleSitemap: `origin` must be an https origin with no path, query or credentials");
201
+ return true;
147
202
  }
148
- return url.origin;
203
+ if (req.headers.get(ENGAGE_CSRF_HEADER) !== "1") return true;
204
+ if (allowedOrigins) return !allowedOrigins.some((o) => safeOrigin(o) === parsed.origin);
205
+ const host = req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || req.headers.get("host") || new URL(req.url).host;
206
+ const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
207
+ if (proto && proto !== parsed.protocol.slice(0, -1)) return true;
208
+ return parsed.host !== host;
149
209
  }
150
- async function hyleSitemap(options) {
151
- const origin = httpsOrigin(options.origin);
152
- const resolve = resolverFor(options);
153
- const locale = typeof options.locale === "string" ? options.locale : void 0;
154
- const { basePath, toHref } = routeContext({ ...options, locale: () => locale }, {});
155
- const client = { resolve: ({ path, locale: l, limit, cursor }) => resolve(path, l, limit, cursor) };
156
- const { paths, complete } = await listPublicationPaths({ client, basePath, ...options.sections ? { sections: options.sections } : {}, ...locale ? { locale } : {} });
157
- if (!complete && (options.onIncomplete === "throw" || options.onIncomplete === void 0 && paths.length === 0)) {
158
- throw new Error("hyleSitemap: hyle could not be listed completely (see onIncomplete)");
210
+ var safeOrigin = (value) => {
211
+ try {
212
+ return new URL(value).origin;
213
+ } catch {
214
+ return void 0;
159
215
  }
160
- return paths.map(({ path, publishedAt }) => ({
161
- url: origin + encodeURI(toHref(path)),
162
- ...ISO_DATE.test(publishedAt) && !Number.isNaN(Date.parse(publishedAt)) ? { lastModified: publishedAt } : {}
163
- }));
164
- }
165
-
166
- // src/next/metadata.ts
167
- function hyleMetadata(options) {
168
- const resolve = resolverFor(options);
169
- return async function generateMetadata({ params, searchParams }) {
170
- const { path, locale, toHref } = routeContext(options, await params ?? {});
171
- if (path === void 0) return {};
172
- try {
173
- const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
174
- const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
175
- if (result.kind === "list") {
176
- const title = (options.list?.title || result.section.title) + (cursor ? ` - ${stringsFor(locale).older}` : "");
177
- const description2 = options.list?.description;
178
- return {
179
- title,
180
- ...description2 ? { description: description2 } : {},
181
- alternates: { canonical: toHref(path) + (cursor ? `?cursor=${cursor}` : "") },
182
- openGraph: { title, ...description2 ? { description: description2 } : {} }
183
- };
184
- }
185
- if (result.kind !== "article") return {};
186
- const { publication: pub, alternates, default_locale } = result;
187
- const canonical = toHref(pub.canonical_path, pub.locale);
188
- const defaultAlternate = alternates.find((a) => a.locale === default_locale);
189
- const xDefault = defaultAlternate ? toHref(defaultAlternate.canonical_path, defaultAlternate.locale) : canonical;
190
- const description = pub.description ?? void 0;
191
- const author = typeof result.frontmatter.author === "string" ? result.frontmatter.author : void 0;
192
- const modified = pub.updated_at && !(Date.parse(pub.updated_at) < Date.parse(pub.published_at)) ? pub.updated_at : void 0;
193
- return {
194
- title: pub.title,
195
- ...description ? { description } : {},
196
- alternates: {
197
- canonical,
198
- ...alternates.length > 1 ? { languages: { ...Object.fromEntries(alternates.map((a) => [a.locale, toHref(a.canonical_path, a.locale)])), "x-default": xDefault } } : {}
199
- },
200
- openGraph: {
201
- type: "article",
202
- title: pub.title,
203
- ...description ? { description } : {},
204
- url: canonical,
205
- locale: pub.locale,
206
- publishedTime: pub.published_at,
207
- ...modified ? { modifiedTime: modified } : {},
208
- ...author ? { authors: [author] } : {}
209
- }
210
- };
211
- } catch (error) {
212
- if (isRejectedRequest(error)) return {};
213
- throw error;
216
+ };
217
+ async function readBody(req, expected) {
218
+ if (!expected) return { kind: "ok", body: void 0 };
219
+ if (!/^application\/json(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return { kind: "refused", response: refuse(415, "UNSUPPORTED_MEDIA_TYPE") };
220
+ if (Number(req.headers.get("content-length")) > MAX_BODY_BYTES) return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
221
+ if (!req.body) return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
222
+ const reader = req.body.getReader();
223
+ const chunks = [];
224
+ let total = 0;
225
+ for (; ; ) {
226
+ const { done, value } = await reader.read();
227
+ if (done) break;
228
+ total += value.byteLength;
229
+ if (total > MAX_BODY_BYTES) {
230
+ await reader.cancel().catch(() => {
231
+ });
232
+ return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
214
233
  }
215
- };
216
- }
217
-
218
- // src/next/feed.ts
219
- import { unstable_rethrow as unstable_rethrow2 } from "next/navigation";
220
- var xml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
221
- var tag = (name, value) => `<${name}>${xml(value)}</${name}>`;
222
- var response = (body, status, headers) => new Response(body, { status, ...headers ? { headers } : {} });
223
- async function hyleFeed(options) {
224
- const origin = options.siteOrigin;
225
- if (!origin || !BARE_HTTPS_ORIGIN.test(origin)) {
226
- console.error("hyle: hyleFeed needs `siteOrigin`, a bare https origin such as https://example.com");
227
- return response(null, 404);
234
+ chunks.push(value);
228
235
  }
229
- const { path, locale, toHref } = routeContext(options, {});
230
- if (path === void 0) return response(null, 404);
231
- const url = (sitePath) => origin + encodeURI(toHref(sitePath));
232
236
  try {
233
- const result = await resolverFor(options)(path, locale, options.limit ?? 50);
234
- if (result.kind !== "list") return response(null, 503);
235
- const items = result.items.filter((item) => item.canonical_path.startsWith("/")).map((item) => {
236
- const link = url(item.canonical_path);
237
- const published = new Date(item.published_at);
238
- return `<item>${tag("title", item.title)}${tag("link", link)}<guid isPermaLink="true">${xml(link)}</guid>${Number.isNaN(published.getTime()) ? "" : tag("pubDate", published.toUTCString())}${item.description ? tag("description", item.description) : ""}</item>`;
239
- });
240
- const channel = [
241
- tag("title", options.list?.title || result.section.title),
242
- tag("link", url(path)),
243
- tag("description", options.list?.description ?? ""),
244
- locale ? tag("language", locale) : "",
245
- `<atom:link href="${xml(origin + encodeURI(options.feedPath ?? "/feed.xml"))}" rel="self" type="application/rss+xml"/>`,
246
- ...items
247
- ].join("");
248
- return response(
249
- `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel>${channel}</channel></rss>`,
250
- 200,
251
- { "content-type": "application/rss+xml; charset=utf-8" }
252
- );
253
- } catch (error) {
254
- unstable_rethrow2(error);
255
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
256
- return response(null, 503);
237
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
238
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return { kind: "ok", body: parsed };
239
+ } catch {
257
240
  }
241
+ return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
258
242
  }
259
-
260
- // src/next/revalidate.ts
261
- import { revalidateTag } from "next/cache";
262
- var isSwitchedOff = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
263
- function createRevalidateRoute(options) {
264
- let cached;
265
- return {
243
+ var SUB_CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
244
+ function validReader(r) {
245
+ if (!r || typeof r.sub !== "string" || typeof r.name !== "string") return null;
246
+ if (r.sub.length < 1 || [...r.sub].length > 255 || SUB_CONTROL.test(r.sub)) return null;
247
+ const name = cleanDisplayName(r.name);
248
+ return name === void 0 ? null : { sub: r.sub, name };
249
+ }
250
+ function relayFailure(status, retryAfter) {
251
+ if (status === 400) return refuse(400, "VALIDATION_ERROR");
252
+ if (status === 404) return refuse(404, "NOT_FOUND");
253
+ if (status === 409) return refuse(409, "INVALID_TRANSITION");
254
+ if (status === 413) return refuse(413, "PAYLOAD_TOO_LARGE");
255
+ if (status === 429) {
256
+ const seconds = Math.min(3600, Math.max(1, Math.trunc(Number(retryAfter)) || 60));
257
+ return refuse(429, "RATE_LIMITED", { "Retry-After": String(seconds) });
258
+ }
259
+ return refuse(502, "UPSTREAM_ERROR");
260
+ }
261
+ function createEngagementRoute(options) {
262
+ let ready;
263
+ const fetchImpl = options.fetch ?? fetch;
264
+ const cache = /* @__PURE__ */ new Map();
265
+ let cacheBytes = 0;
266
+ const clearCache = () => {
267
+ cache.clear();
268
+ cacheBytes = 0;
269
+ };
270
+ async function listing(viewer, call) {
271
+ if (!viewer) return call(void 0);
272
+ let out = await call(viewer.sign("read"));
273
+ if (out.status === 401) out = await call(viewer.sign("read"));
274
+ if (out.status !== 401 && out.status !== 404 && !(out.status === 429 && out.throttle === "viewer")) return out;
275
+ return { ...await call(void 0), noShare: true };
276
+ }
277
+ function shared(key, call) {
278
+ const ttl = options.cacheTtlMs ?? DEFAULT_SHARE_MS;
279
+ if (ttl <= 0) return call();
280
+ const hit = cache.get(key);
281
+ if (hit && Date.now() - hit.at < ttl) {
282
+ cache.delete(key);
283
+ cache.set(key, hit);
284
+ return hit.result;
285
+ }
286
+ if (hit) forget(key, hit);
287
+ const entry = { at: Date.now(), result: call(), bytes: 0 };
288
+ cache.set(key, entry);
289
+ entry.result.then(
290
+ (o) => {
291
+ if (cache.get(key) !== entry) return;
292
+ if (o.status !== 200 && o.status !== 404 || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
293
+ entry.bytes = o.text.length;
294
+ cacheBytes += entry.bytes;
295
+ while ((cacheBytes > MAX_SHARED_BYTES || cache.size > MAX_SHARED) && cache.size > 0) {
296
+ const oldest = cache.entries().next().value;
297
+ forget(oldest[0], oldest[1]);
298
+ }
299
+ },
300
+ () => forget(key, entry)
301
+ );
302
+ return entry.result;
303
+ }
304
+ function forget(key, entry) {
305
+ if (cache.get(key) !== entry) return;
306
+ cache.delete(key);
307
+ cacheBytes -= entry.bytes;
308
+ }
309
+ function configured() {
310
+ if (ready !== void 0) return ready;
311
+ try {
312
+ const baseUrl = options.baseUrl?.trim() ?? "";
313
+ checkBaseUrl(baseUrl);
314
+ if (!options.token?.trim() || !options.workspaceId?.trim() || !options.signingKey) throw new TypeError("not provisioned");
315
+ ready = { base: baseUrl.replace(/\/+$/, ""), key: engagementSigningKey(options.signingKey.trim()) };
316
+ } catch {
317
+ ready = null;
318
+ }
319
+ return ready;
320
+ }
321
+ async function reader(req, config) {
322
+ try {
323
+ const found = validReader(await options.getReader(req));
324
+ if (!found) return null;
325
+ const claims = { sub: found.sub, name: found.name, workspace: options.workspaceId.trim() };
326
+ const sign = (scope) => signReaderAssertion(config.key, claims, void 0, scope);
327
+ return { reader: found, assertion: sign(), sign };
328
+ } catch {
329
+ return null;
330
+ }
331
+ }
332
+ async function handle(req, ctx) {
333
+ const env = options.env ?? process.env;
334
+ if (isSwitchedOff(env.HYLE_ENGAGE_ENABLED) || isSwitchedOff(env.HYLE_CONTENT_ENABLED)) return refuse(404, "NOT_FOUND");
335
+ const config = configured();
336
+ const route = match((await ctx.params).path ?? []);
337
+ if (!config || !route) return refuse(404, "NOT_FOUND");
338
+ if (!route.methods.includes(req.method)) return refuse(405, "METHOD_NOT_ALLOWED", { Allow: route.methods.join(", ") });
339
+ const write = req.method !== "GET";
340
+ if (sameOriginProblem(req, write, options.allowedOrigins)) return refuse(403, "FORBIDDEN");
341
+ if (options.onRequest) {
342
+ try {
343
+ const early = await options.onRequest(req, { action: route.action(req.method) });
344
+ if (early instanceof Response) {
345
+ const headers = new Headers(early.headers);
346
+ headers.set("cache-control", "no-store");
347
+ return new Response(early.body, { status: early.status, headers });
348
+ }
349
+ } catch {
350
+ return refuse(502, "UPSTREAM_ERROR");
351
+ }
352
+ }
353
+ if (route.local === "session") {
354
+ const who = await reader(req, config);
355
+ return json(200, { data: { reader: who ? { name: who.reader.name } : null } });
356
+ }
357
+ let assertion;
358
+ let viewer = null;
359
+ if (route.action(req.method) === "comments.list") viewer = await reader(req, config);
360
+ if (write) {
361
+ const who = await reader(req, config);
362
+ if (!who) return refuse(401, "UNAUTHENTICATED");
363
+ assertion = who.assertion;
364
+ }
365
+ const url = new URL(req.url);
366
+ const hasBody = write && !(req.method === "DELETE" && (await ctx.params).path?.[0] === "comments");
367
+ const body = await readBody(req, hasBody);
368
+ if (body.kind === "refused") return body.response;
369
+ const built = route.rebuild(req.method, body.body, url);
370
+ if (!built) return refuse(400, "VALIDATION_ERROR");
371
+ const baseHeaders = new Headers({ authorization: `Bearer ${options.token.trim()}`, accept: "application/json" });
372
+ if (built.body) baseHeaders.set("content-type", "application/json");
373
+ const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
374
+ const call = async (withAssertion = assertion) => {
375
+ const headers = new Headers(baseHeaders);
376
+ if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
377
+ const res = await fetchImpl(target, {
378
+ method: req.method,
379
+ headers,
380
+ ...built.body ? { body: JSON.stringify(built.body) } : {},
381
+ redirect: "error",
382
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
383
+ });
384
+ return { status: res.status, ok: res.ok, text: await readCapped(res, MAX_RESPONSE_BYTES), retryAfter: res.headers.get("retry-after"), throttle: res.headers.get("hyle-throttle") };
385
+ };
386
+ try {
387
+ const out = route.action(req.method) === "comments.list" ? await shared(`${viewer?.reader.sub ?? ""}
388
+ ${built.query.toString()}`, () => listing(viewer, call)) : await call();
389
+ if (!out.ok) return relayFailure(out.status, out.retryAfter);
390
+ if (write) clearCache();
391
+ const data = JSON.parse(out.text).data;
392
+ return typeof data === "object" && data !== null ? json(out.status === 201 ? 201 : 200, { data }) : refuse(502, "UPSTREAM_ERROR");
393
+ } catch {
394
+ return refuse(502, "UPSTREAM_ERROR");
395
+ }
396
+ }
397
+ return { GET: handle, POST: handle, PATCH: handle, PUT: handle, DELETE: handle };
398
+ }
399
+
400
+ // src/next/embed.tsx
401
+ import { jsx } from "react/jsx-runtime";
402
+ async function resolveEmbed(options, run) {
403
+ try {
404
+ return { result: await run() };
405
+ } catch (error) {
406
+ if (isRejectedRequest(error)) return {};
407
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
408
+ return { failure: options.onError ? options.onError(error) : null };
409
+ }
410
+ }
411
+ async function HyleList({ options, limit = 5, locale, layout, title, headingLevel, moreHref, cursor, olderHref }) {
412
+ const resolve = resolverFor(options);
413
+ const route = routeContext(locale ? { ...options, locale } : options, {});
414
+ const path = sitePathFrom(route.basePath, void 0);
415
+ if (path === void 0) return null;
416
+ const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale, limit, validCursor(cursor)));
417
+ if (failure !== void 0) return failure;
418
+ const next = olderHref && result?.kind === "list" ? validCursor(result.next_cursor) : void 0;
419
+ return /* @__PURE__ */ jsx(HyleListView, { items: result?.kind === "list" ? result.items : [], layout, title, headingLevel, moreHref, olderHref: next ? olderHref?.(next) : void 0, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
420
+ }
421
+ async function HyleArticle({ options, path, locale, headingLevel }) {
422
+ if (!isSitePath(path)) return null;
423
+ const resolve = resolverFor(options);
424
+ const route = routeContext(locale ? { ...options, locale } : options, {});
425
+ const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale));
426
+ if (failure !== void 0) return failure;
427
+ if (result?.kind !== "article") return null;
428
+ return /* @__PURE__ */ jsx(HyleArticleView, { article: result, headingLevel, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
429
+ }
430
+ var MAX_LISTING_BYTES = 4 * 1024 * 1024;
431
+ var COMMENTS_TIMEOUT_MS = 1e4;
432
+ async function HyleComments({ options, path, revalidate = 60, interactive }) {
433
+ checkBaseUrl(options.baseUrl);
434
+ if (!options.token) throw new TypeError("token is required");
435
+ if (!isSitePath(path)) return null;
436
+ const locale = options.locale ?? "en";
437
+ let listing;
438
+ let fetchedAt;
439
+ try {
440
+ const init = {
441
+ headers: { authorization: `Bearer ${options.token}`, accept: "application/json" },
442
+ redirect: "error",
443
+ signal: AbortSignal.timeout(COMMENTS_TIMEOUT_MS),
444
+ next: { revalidate }
445
+ };
446
+ const res = await fetch(`${options.baseUrl.replace(/\/+$/, "")}/cp1/engage/comments?${new URLSearchParams({ path })}`, init);
447
+ if (!res.ok) {
448
+ if (res.status !== 404) console.error(`hyle: comments answered HTTP ${res.status}`);
449
+ return null;
450
+ }
451
+ listing = parseListing(JSON.parse(await readCapped(res, MAX_LISTING_BYTES)).data);
452
+ const date = Date.parse(res.headers.get("date") ?? "");
453
+ fetchedAt = Number.isFinite(date) ? date : void 0;
454
+ } catch (error) {
455
+ unstable_rethrow2(error);
456
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
457
+ return null;
458
+ }
459
+ if (!listing) return null;
460
+ if (!interactive) return /* @__PURE__ */ jsx(HyleCommentsView, { listing, locale });
461
+ const config = interactive === true ? {} : interactive;
462
+ return /* @__PURE__ */ jsx("div", { className: "hyle hyle-embed", children: /* @__PURE__ */ jsx(Comments, { path, endpoint: config.endpoint ?? "/api/hyle/engage", signInHref: config.signInHref, locale, labels: stringsFor(locale).comments, initial: listing, initialAt: fetchedAt }) });
463
+ }
464
+
465
+ // src/next/page.tsx
466
+ import { jsx as jsx2 } from "react/jsx-runtime";
467
+ function hylePage(options) {
468
+ const resolve = resolverFor(options);
469
+ async function relatedItems(article) {
470
+ const { limit = 5, title } = options.related ?? {};
471
+ const section = article.breadcrumbs[0]?.canonical_path ?? (normalizeBasePath(options.basePath) || "/");
472
+ const { result } = await resolveEmbed(options, () => resolve(section, article.publication.locale, limit + 1));
473
+ const items = result?.kind === "list" ? result.items.filter((item) => item.canonical_path !== article.publication.canonical_path).slice(0, limit) : [];
474
+ return { title, items };
475
+ }
476
+ return async function HylePage({ params, searchParams }) {
477
+ const { path, locale, toHref } = routeContext(options, await params ?? {});
478
+ if (path === void 0) notFound();
479
+ try {
480
+ const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
481
+ const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
482
+ switch (result.kind) {
483
+ case "article": {
484
+ const image = articleImage(options, result);
485
+ const related = options.related && options.layout !== "docs" ? await relatedItems(result) : void 0;
486
+ const props = { article: result, components: options.components, slots: options.slots, locale, toHref };
487
+ return options.layout === "docs" ? /* @__PURE__ */ jsx2(DocsPage, { ...props }) : /* @__PURE__ */ jsx2(ArticlePage, { ...props, origin: options.siteOrigin, jsonLd: options.jsonLd, imageUrl: image?.url, imageWidth: image?.width, imageHeight: image?.height, related, ...options.engagement ? { engagement: options.engagement } : {} });
488
+ }
489
+ case "list": {
490
+ const list = options.list?.title ? { ...result, section: { ...result.section, title: options.list.title } } : result;
491
+ const next = options.paginate === "searchParams" ? validCursor(result.next_cursor) : void 0;
492
+ const olderHref = next ? `${toHref(path)}?cursor=${next}` : void 0;
493
+ return /* @__PURE__ */ jsx2(ListPage, { list, ...olderHref ? { olderHref } : {}, ...options.list?.description ? { description: options.list.description } : {}, components: options.components, slots: options.slots, locale, toHref, origin: options.siteOrigin, path, jsonLd: options.jsonLd, cursor });
494
+ }
495
+ case "redirect": {
496
+ const to = safeRedirectTarget(result.to);
497
+ if (to === void 0) throw new Cp1ClientError("INVALID_RESPONSE", "hyle returned an unsafe redirect target", 502, "");
498
+ const target = safeRedirectTarget(toHref(to));
499
+ if (target === void 0) throw new Cp1ClientError("INVALID_RESPONSE", "hyle returned an unsafe redirect target", 502, "");
500
+ if (target === toHref(path)) notFound();
501
+ return result.status === 301 ? permanentRedirect(target) : redirect(target);
502
+ }
503
+ case "notfound":
504
+ case "disabled":
505
+ notFound();
506
+ }
507
+ } catch (error) {
508
+ if (isRejectedRequest(error)) notFound();
509
+ if (!options.onError) throw error;
510
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
511
+ return options.onError(error);
512
+ }
513
+ };
514
+ }
515
+
516
+ // src/next/sitemap.ts
517
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}T/;
518
+ var isoTime = (value) => value && ISO_DATE.test(value) ? Date.parse(value) : NaN;
519
+ function httpsOrigin(origin) {
520
+ let url;
521
+ try {
522
+ url = new URL(origin);
523
+ } catch {
524
+ throw new TypeError("hyleSitemap: `origin` must be an https origin such as https://example.com");
525
+ }
526
+ if (url.protocol !== "https:" || url.origin !== origin.replace(/\/$/, "")) {
527
+ throw new TypeError("hyleSitemap: `origin` must be an https origin with no path, query or credentials");
528
+ }
529
+ return url.origin;
530
+ }
531
+ async function hyleSitemap(options) {
532
+ const origin = httpsOrigin(options.origin);
533
+ const resolve = resolverFor(options);
534
+ const locale = typeof options.locale === "string" ? options.locale : void 0;
535
+ const { basePath, toHref } = routeContext({ ...options, locale: () => locale }, {});
536
+ const client = { resolve: ({ path, locale: l, limit, cursor }) => resolve(path, l, limit, cursor) };
537
+ const { paths, complete } = await listPublicationPaths({ client, basePath, ...locale ? { locale } : {} });
538
+ if (!complete && (options.onIncomplete === "throw" || options.onIncomplete === void 0 && paths.length === 0)) {
539
+ throw new Error("hyleSitemap: hyle could not be listed completely (see onIncomplete)");
540
+ }
541
+ const memberUrl = (a) => origin + encodeURI(toHref(a.path, a.locale));
542
+ return paths.map(({ path, publishedAt, updatedAt, alternates }) => {
543
+ const latest = [publishedAt, updatedAt].filter((v) => !Number.isNaN(isoTime(v))).sort((x, y) => isoTime(y) - isoTime(x))[0];
544
+ const modified = latest && new Date(latest).toISOString();
545
+ const url = origin + encodeURI(toHref(path));
546
+ return {
547
+ url,
548
+ ...modified ? { lastModified: modified } : {},
549
+ // Same gate as the page's hreflang: a group of one is not an alternate set.
550
+ ...alternates && alternates.length > 1 ? { alternates: { languages: options.defaultLocale === void 0 ? Object.fromEntries(alternates.map((a) => [a.locale, memberUrl(a)])) : hreflangLanguages(alternates, options.defaultLocale, url, memberUrl) } } : {}
551
+ };
552
+ });
553
+ }
554
+
555
+ // src/next/metadata.ts
556
+ var titled = (template, title) => template?.includes("%s") ? { absolute: template.replace("%s", () => title) } : title;
557
+ var LARGE_PREVIEW = "max-image-preview:large";
558
+ var addDirective = (inherited) => {
559
+ const tokens = (inherited ?? "").split(",").map((t) => t.trim()).filter(Boolean);
560
+ return (tokens.includes(LARGE_PREVIEW) ? tokens : [...tokens, LARGE_PREVIEW]).join(", ");
561
+ };
562
+ var ROBOTS_KEYS = /* @__PURE__ */ new Set(["noarchive", "nosnippet", "noimageindex", "nocache", "notranslate", "indexifembedded", "nositelinkssearchbox", "unavailable_after", "max-video-preview", "max-image-preview", "max-snippet"]);
563
+ var ROBOTS_ALIASES = {
564
+ none: { index: false, follow: false },
565
+ all: { index: true, follow: true },
566
+ index: { index: true },
567
+ noindex: { index: false },
568
+ follow: { follow: true },
569
+ nofollow: { follow: false }
570
+ };
571
+ function composeRobots(inherited) {
572
+ const basic = addDirective(inherited?.basic);
573
+ const object = {};
574
+ for (const token of basic.split(", ")) {
575
+ const colon = token.indexOf(":");
576
+ const key = colon < 0 ? token : token.slice(0, colon);
577
+ if (ROBOTS_KEYS.has(key)) object[key] = colon < 0 ? true : token.slice(colon + 1);
578
+ else if (ROBOTS_ALIASES[key] && colon < 0) Object.assign(object, ROBOTS_ALIASES[key]);
579
+ else return basic;
580
+ }
581
+ return { ...object, googleBot: addDirective(inherited?.googleBot) };
582
+ }
583
+ function hyleFeedLink(options, locale) {
584
+ const { feed } = options;
585
+ if (!feed || typeof feed.path === "function" && !locale) return void 0;
586
+ const href = typeof feed.path === "function" ? feed.path(locale) : feed.path;
587
+ const origin = bareOrigin(options.siteOrigin);
588
+ return { url: origin ? absoluteUrl(origin, href) : href, title: feed.title ?? (options.siteName ? `${options.siteName} feed` : "Feed") };
589
+ }
590
+ function hyleMetadata(options) {
591
+ const resolve = resolverFor(options);
592
+ const origin = bareOrigin(options.siteOrigin);
593
+ return async function generateMetadata({ params, searchParams }, parent) {
594
+ const { path, locale, toHref } = routeContext(options, await params ?? {});
595
+ if (path === void 0) return {};
596
+ const link = (sitePath, linkLocale) => {
597
+ const href = toHref(sitePath, linkLocale);
598
+ return origin ? absoluteUrl(origin, href) : href;
599
+ };
600
+ const withTypes = async (alternates, markdown) => {
601
+ const feed = hyleFeedLink(options, locale);
602
+ const types = {
603
+ ...parent ? (await parent).alternates?.types : void 0,
604
+ ...feed ? { "application/rss+xml": [feed] } : {},
605
+ ...markdown ? { "text/markdown": [{ url: markdown }] } : {}
606
+ };
607
+ return Object.keys(types).length ? { ...alternates, types } : alternates;
608
+ };
609
+ try {
610
+ const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
611
+ const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
612
+ const parentMeta = parent ? await parent : void 0;
613
+ const parentImages = parentMeta?.openGraph?.images;
614
+ if (result.kind === "list") {
615
+ const title = (options.list?.title || result.section.title) + (cursor ? ` - ${stringsFor(locale).older}` : "");
616
+ const description2 = options.list?.description;
617
+ const ogLocale = locale && options.ogLocale?.(locale) || locale;
618
+ const canonical2 = link(path) + (cursor ? `?cursor=${cursor}` : "");
619
+ return {
620
+ title: titled(options.titleTemplate, title),
621
+ ...description2 ? { description: description2 } : {},
622
+ alternates: await withTypes({ canonical: canonical2 }),
623
+ openGraph: {
624
+ type: "website",
625
+ title,
626
+ ...description2 ? { description: description2 } : {},
627
+ url: canonical2,
628
+ ...options.siteName ? { siteName: options.siteName } : {},
629
+ ...ogLocale ? { locale: ogLocale } : {},
630
+ ...parentImages?.length ? { images: parentImages } : {}
631
+ }
632
+ };
633
+ }
634
+ if (result.kind !== "article") return {};
635
+ const { publication: pub, alternates, default_locale } = result;
636
+ const canonical = link(pub.canonical_path, pub.locale);
637
+ const description = pub.description ?? void 0;
638
+ const author = articleAuthor(result, options.jsonLd)?.name;
639
+ const modified = modifiedAt(pub);
640
+ const image = articleImage(options, result);
641
+ const alternateLocale = options.ogLocale ? alternates.filter((a) => a.locale !== pub.locale).flatMap((a) => options.ogLocale?.(a.locale) ?? []) : [];
642
+ const { twitter } = options;
643
+ const inherited = parentMeta?.robots;
644
+ const section = result.breadcrumbs[0]?.title;
645
+ const words = wordCountOf(pub);
646
+ return {
647
+ title: titled(options.titleTemplate, pub.title),
648
+ ...description ? { description } : {},
649
+ // Next replaces a parent's robots per key, so keep the inherited directives (a host's noindex) and add ours once.
650
+ robots: composeRobots(inherited),
651
+ alternates: await withTypes(
652
+ {
653
+ canonical,
654
+ ...alternates.length > 1 ? { languages: hreflangLanguages(alternates, default_locale, canonical, (a) => link(a.canonical_path, a.locale)) } : {}
655
+ },
656
+ options.markdownTwin ? `${canonical}.md` : void 0
657
+ ),
658
+ openGraph: {
659
+ type: "article",
660
+ title: pub.title,
661
+ ...description ? { description } : {},
662
+ url: canonical,
663
+ ...options.siteName ? { siteName: options.siteName } : {},
664
+ locale: options.ogLocale?.(pub.locale) ?? pub.locale,
665
+ ...alternateLocale.length ? { alternateLocale } : {},
666
+ publishedTime: pub.published_at,
667
+ ...modified ? { modifiedTime: modified } : {},
668
+ ...section ? { section } : {},
669
+ ...author ? { authors: [author] } : {},
670
+ ...image ? { images: [image] } : parentImages?.length ? { images: parentImages } : {}
671
+ },
672
+ // Next replaces a parent's `other` whole, so the inherited keys are carried over.
673
+ ...words ? { other: { ...parentMeta?.other, "twitter:label1": stringsFor(locale).readingTimeLabel, "twitter:data1": stringsFor(locale).readingTime.replace("{n}", String(readingMinutes(words))) } } : {},
674
+ ...image ? {
675
+ twitter: {
676
+ card: "summary_large_image",
677
+ ...twitter?.site ? { site: twitter.site } : {},
678
+ ...twitter?.creator ? { creator: twitter.creator } : {},
679
+ title: pub.title,
680
+ ...description ? { description } : {},
681
+ images: [image]
682
+ }
683
+ } : {}
684
+ };
685
+ } catch (error) {
686
+ if (isRejectedRequest(error)) return {};
687
+ throw error;
688
+ }
689
+ };
690
+ }
691
+
692
+ // src/next/feed.ts
693
+ import { unstable_rethrow as unstable_rethrow3 } from "next/navigation";
694
+ var xml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
695
+ var tag = (name, value) => `<${name}>${xml(value)}</${name}>`;
696
+ var response = (body, status, headers) => new Response(body, { status, ...headers ? { headers } : {} });
697
+ async function hyleFeed(options) {
698
+ const origin = options.siteOrigin;
699
+ if (!origin || !BARE_HTTPS_ORIGIN.test(origin)) {
700
+ console.error("hyle: hyleFeed needs `siteOrigin`, a bare https origin such as https://example.com");
701
+ return response(null, 404);
702
+ }
703
+ const { path, locale, toHref } = routeContext(options, {});
704
+ if (path === void 0) return response(null, 404);
705
+ const url = (sitePath) => origin + encodeURI(toHref(sitePath));
706
+ try {
707
+ const result = await resolverFor(options)(path, locale, options.limit ?? 50);
708
+ if (result.kind !== "list") return response(null, 503);
709
+ const items = result.items.filter((item) => item.canonical_path.startsWith("/")).map((item) => {
710
+ const link = url(item.canonical_path);
711
+ const published = new Date(item.published_at);
712
+ return `<item>${tag("title", item.title)}${tag("link", link)}<guid isPermaLink="true">${xml(link)}</guid>${Number.isNaN(published.getTime()) ? "" : tag("pubDate", published.toUTCString())}${item.description ? tag("description", item.description) : ""}</item>`;
713
+ });
714
+ const channel = [
715
+ tag("title", options.list?.title || result.section.title),
716
+ tag("link", url(path)),
717
+ tag("description", options.list?.description ?? ""),
718
+ locale ? tag("language", locale) : "",
719
+ `<atom:link href="${xml(origin + encodeURI(options.feedPath ?? "/feed.xml"))}" rel="self" type="application/rss+xml"/>`,
720
+ ...items
721
+ ].join("");
722
+ return response(
723
+ `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel>${channel}</channel></rss>`,
724
+ 200,
725
+ { "content-type": "application/rss+xml; charset=utf-8" }
726
+ );
727
+ } catch (error) {
728
+ unstable_rethrow3(error);
729
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
730
+ return response(null, 503);
731
+ }
732
+ }
733
+
734
+ // src/next/revalidate.ts
735
+ import { revalidateTag } from "next/cache";
736
+ var isSwitchedOff2 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
737
+ function createRevalidateRoute(options) {
738
+ let cached;
739
+ return {
266
740
  async POST(req) {
267
- if (isSwitchedOff((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return new Response(null, { status: 404 });
741
+ if (isSwitchedOff2((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return new Response(null, { status: 404 });
268
742
  const workspaceId = options.workspaceId?.trim();
269
743
  const secrets = options.secrets.map((s) => s?.trim()).filter((s) => Boolean(s));
270
744
  if (!workspaceId && secrets.length === 0) return new Response(null, { status: 404 });
@@ -284,10 +758,16 @@ import { notFound as notFound2 } from "next/navigation";
284
758
  // src/next/mount-match.ts
285
759
  function activeMounts(mounts) {
286
760
  const out = [];
287
- for (const { prefix, default_section } of mounts) {
761
+ for (const { prefix, default_section, name, locales } of mounts) {
288
762
  try {
289
763
  const normalized = normalizeBasePath(prefix);
290
- out.push({ prefix: normalized, defaultSection: default_section, depth: normalized === "" ? 0 : normalized.split("/").length - 1 });
764
+ out.push({
765
+ prefix: normalized,
766
+ defaultSection: default_section,
767
+ depth: normalized === "" ? 0 : normalized.split("/").length - 1,
768
+ ...name ? { name } : {},
769
+ ...locales ? { locales } : {}
770
+ });
291
771
  } catch (error) {
292
772
  console.error(`hyle: ignoring a mount with an invalid prefix (${error instanceof Error ? error.name : "Error"})`);
293
773
  }
@@ -302,7 +782,7 @@ function isReserved(path, reserved) {
302
782
  // src/next/root.ts
303
783
  var MOUNTS_MAX_STALE_MS = 15 * 60 * 1e3;
304
784
  var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
305
- var NONE = { mounts: [], reserved: [] };
785
+ var NONE = { mounts: [], reserved: [], defaultLocale: "" };
306
786
  var lastKnownGood = /* @__PURE__ */ new Map();
307
787
  function mountsLoader(config) {
308
788
  if (!config.workspaceId) throw new TypeError("hyleRootPage: `workspaceId` is required for the fetch cache");
@@ -316,7 +796,7 @@ function mountsLoader(config) {
316
796
  lastKnownGood.delete(key);
317
797
  return NONE;
318
798
  }
319
- const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved };
799
+ const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale };
320
800
  lastKnownGood.set(key, { loaded, at: Date.now() });
321
801
  return loaded;
322
802
  } catch (error) {
@@ -342,31 +822,57 @@ function setup(options) {
342
822
  if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
343
823
  return { configs, param, loaders: configs.map(mountsLoader) };
344
824
  }
345
- function createRouter(options, make) {
825
+ var sectionsOf = (config, mount) => [
826
+ ...config.sections ?? [],
827
+ ...SECTION_SLUG.test(mount.defaultSection) ? [mount.defaultSection] : []
828
+ ];
829
+ function mountOptionsOf(config, mount) {
830
+ const { mountOptions, ...rest } = config;
831
+ return { ...rest, ...mountOptions?.[mount.prefix === "" ? "/" : mount.prefix], basePath: mount.prefix, sections: sectionsOf(config, mount) };
832
+ }
833
+ function rootMounts(options) {
346
834
  const { configs, param, loaders } = setup(options);
835
+ return {
836
+ param,
837
+ async locate(path) {
838
+ const loaded = await Promise.all(loaders.map((load) => load()));
839
+ let best;
840
+ loaded.forEach(({ mounts, reserved }, index2) => {
841
+ if (isReserved(path, reserved)) return;
842
+ for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
843
+ });
844
+ if (!best) return void 0;
845
+ const { index, mount } = best;
846
+ return { options: mountOptionsOf(configs[index], mount), mount, index };
847
+ },
848
+ async all() {
849
+ const out = [];
850
+ for (const [index, load] of loaders.entries()) {
851
+ const { mounts, defaultLocale } = await load();
852
+ for (const mount of mounts) out.push({ options: mountOptionsOf(configs[index], mount), mount, index, defaultLocale });
853
+ }
854
+ return out;
855
+ }
856
+ };
857
+ }
858
+ function createRouter(options, make) {
859
+ const mounts = rootMounts(options);
347
860
  const handlers = /* @__PURE__ */ new Map();
348
861
  return async function route(params) {
349
- const raw = params[param];
862
+ const raw = params[mounts.param];
350
863
  const segments = typeof raw === "string" ? [raw] : raw;
351
864
  const path = sitePathFrom("", segments);
352
865
  if (path === void 0 || path === "/" || !segments) return void 0;
353
- const loaded = await Promise.all(loaders.map((load) => load()));
354
- let best;
355
- loaded.forEach(({ mounts, reserved }, index2) => {
356
- if (isReserved(path, reserved)) return;
357
- for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
358
- });
359
- if (!best) return void 0;
360
- const { index, mount } = best;
361
- const config = configs[index];
866
+ const hit = await mounts.locate(path);
867
+ if (!hit) return void 0;
868
+ const { mount, index } = hit;
362
869
  const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
363
870
  let handler = handlers.get(id);
364
871
  if (!handler) {
365
- const sections = [...config.sections ?? [], ...SECTION_SLUG.test(mount.defaultSection) ? [mount.defaultSection] : []];
366
- handler = make({ ...config, basePath: mount.prefix, sections });
872
+ handler = make(hit.options);
367
873
  handlers.set(id, handler);
368
874
  }
369
- return { handler, params: { ...params, [param]: segments.slice(mount.depth) } };
875
+ return { handler, params: { ...params, [mounts.param]: segments.slice(mount.depth) } };
370
876
  };
371
877
  }
372
878
  function hyleRootPage(options) {
@@ -376,454 +882,218 @@ function hyleRootPage(options) {
376
882
  if (!hit) notFound2();
377
883
  return hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} });
378
884
  };
379
- }
380
- function hyleRootMetadata(options) {
381
- const route = createRouter(options, hyleMetadata);
382
- return async function generateMetadata({ params }) {
383
- const hit = await route(await params ?? {});
384
- return hit ? hit.handler({ params: Promise.resolve(hit.params) }) : {};
385
- };
386
- }
387
- async function hyleRootSitemap(options, sitemap) {
388
- const { configs, loaders } = setup(options);
389
- const entries = /* @__PURE__ */ new Map();
390
- for (const [index, load] of loaders.entries()) {
391
- const config = configs[index];
392
- for (const mount of (await load()).mounts) {
393
- const sections = [...config.sections ?? [], ...SECTION_SLUG.test(mount.defaultSection) ? [mount.defaultSection] : []];
394
- for (const entry of await hyleSitemap({ ...config, basePath: mount.prefix, sections, ...sitemap })) entries.set(entry.url, entry);
395
- }
396
- }
397
- return [...entries.values()];
398
- }
399
-
400
- // src/next/asset.ts
401
- var DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
402
- var DEFAULT_TIMEOUT_MS = 3e4;
403
- var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
404
- var PARTIAL_CACHE_CONTROL = "no-store";
405
- var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
406
- var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
407
- var isSwitchedOff2 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
408
- function capped(body, max) {
409
- let seen = 0;
410
- return body.pipeThrough(
411
- new TransformStream({
412
- transform(chunk, controller) {
413
- seen += chunk.byteLength;
414
- if (seen > max) return controller.error(new Error("asset too large"));
415
- controller.enqueue(chunk);
416
- }
417
- })
418
- );
419
- }
420
- function createAssetRoute(options) {
421
- let client;
422
- const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
423
- async function serve(req, ctx, head) {
424
- if (isSwitchedOff2((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
425
- const file = (await ctx.params).file;
426
- if (typeof file !== "string" || !ASSET_FILE.test(file)) return empty(404);
427
- try {
428
- client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
429
- } catch {
430
- return empty(404);
431
- }
432
- let upstream;
433
- try {
434
- upstream = await client.asset(file, {
435
- timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
436
- headers: { range: req.headers.get("range"), "if-range": req.headers.get("if-range"), "if-none-match": req.headers.get("if-none-match") }
437
- });
438
- } catch {
439
- return empty(502);
440
- }
441
- const drop = () => void upstream.body?.cancel().catch(() => {
442
- });
443
- const etag = upstream.headers.get("etag");
444
- if (upstream.status === 304) {
445
- drop();
446
- return new Response(null, { status: 304, headers: { "Cache-Control": CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS, ...etag ? { ETag: etag } : {} } });
447
- }
448
- if (upstream.status === 404 || upstream.status === 416) {
449
- drop();
450
- const range = upstream.status === 416 ? upstream.headers.get("content-range") : null;
451
- return empty(upstream.status, range ? { "Content-Range": range } : {});
452
- }
453
- const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
454
- const length = Number(upstream.headers.get("content-length"));
455
- const expectedStatus = upstream.status === 200 || upstream.status === 206;
456
- if (!expectedStatus || !upstream.body || !type || !ASSET_CONTENT_TYPES.has(type) || Number.isFinite(length) && length > maxBytes) {
457
- drop();
458
- return empty(502);
459
- }
460
- const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
461
- if (etag) headers.set("ETag", etag);
462
- const contentRange = upstream.headers.get("content-range");
463
- if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
464
- if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
465
- if (head) {
466
- drop();
467
- return new Response(null, { status: upstream.status, headers });
468
- }
469
- return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
470
- }
471
- return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
472
- }
473
-
474
- // src/next/embed.tsx
475
- import { unstable_rethrow as unstable_rethrow3 } from "next/navigation";
476
-
477
- // src/next/engage.ts
478
- var ENGAGE_CSRF_HEADER = "x-hyle-engage";
479
- var DEFAULT_TIMEOUT_MS2 = 1e4;
480
- var DEFAULT_SHARE_MS = 3e3;
481
- var MAX_SHARED = 100;
482
- var MAX_SHARED_BYTES = 8 * 1024 * 1024;
483
- var MAX_SHARED_ENTRY_BYTES = 256 * 1024;
484
- var MAX_BODY_BYTES = 20 * 1024;
485
- var MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
486
- var MAX_COMMENT_CHARACTERS = 4e3;
487
- var MAX_PATH_LENGTH2 = 1024;
488
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
489
- var CONTROL = /[\u0000-\u001f\u007f\\]/;
490
- var HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };
491
- var isSwitchedOff3 = (value) => {
492
- const v = value?.trim().toLowerCase() ?? "";
493
- return v !== "" && v !== "1" && v !== "true";
494
- };
495
- var json = (status, body, extra = {}) => new Response(JSON.stringify(body), { status, headers: { ...HEADERS, "Content-Type": "application/json; charset=utf-8", ...extra } });
496
- var refuse = (status, code, extra = {}) => json(status, { error: { code } }, extra);
497
- function isSitePath(value) {
498
- if (typeof value !== "string" || value.length > MAX_PATH_LENGTH2 || !value.startsWith("/") || value.startsWith("//")) return false;
499
- if (CONTROL.test(value) || /[?#]/.test(value)) return false;
500
- return !value.split("/").some((segment) => segment === "." || segment === "..");
501
- }
502
- function match(segments) {
503
- const [a, b, ...rest] = segments;
504
- if (a === "session" && b === void 0) return { local: "session", action: () => "session", methods: ["GET"], rebuild: () => void 0 };
505
- if (a === "comments" && b === void 0) {
506
- return {
507
- action: (m) => m === "GET" ? "comments.list" : "comments.create",
508
- methods: ["GET", "POST"],
509
- rebuild: (method, body, url) => {
510
- if (method === "GET") {
511
- const keys = [...url.searchParams.keys()];
512
- const path = url.searchParams.get("path");
513
- return keys.length === 1 && isSitePath(path) ? { upstream: "/comments", query: new URLSearchParams({ path }) } : void 0;
514
- }
515
- const clean = pick(body, ["path", "body", "parent_id"], ["path", "body"]);
516
- if (!clean || !isSitePath(clean.path) || !isCommentText(clean.body)) return void 0;
517
- if (clean.parent_id === null) delete clean.parent_id;
518
- if (clean.parent_id !== void 0 && !(typeof clean.parent_id === "string" && UUID.test(clean.parent_id))) return void 0;
519
- return { upstream: "/comments", body: clean };
520
- }
521
- };
522
- }
523
- if (a === "comments" && typeof b === "string" && UUID.test(b) && rest.length === 0) {
524
- return {
525
- action: (m) => m === "PATCH" ? "comments.edit" : "comments.delete",
526
- methods: ["PATCH", "DELETE"],
527
- rebuild: (method, body) => {
528
- if (method === "DELETE") return body === void 0 ? { upstream: `/comments/${b}` } : void 0;
529
- const clean = pick(body, ["body"], ["body"]);
530
- return clean && isCommentText(clean.body) ? { upstream: `/comments/${b}`, body: clean } : void 0;
531
- }
532
- };
533
- }
534
- if (a === "reactions" && b === void 0) {
535
- return {
536
- action: (m) => m === "PUT" ? "reactions.add" : "reactions.remove",
537
- methods: ["PUT", "DELETE"],
538
- rebuild: (_method, body) => {
539
- const type = body?.subject_type;
540
- const clean = type === "article" ? pick(body, ["subject_type", "path"], ["subject_type", "path"]) : type === "comment" ? pick(body, ["subject_type", "comment_id"], ["subject_type", "comment_id"]) : void 0;
541
- if (!clean) return void 0;
542
- const valid = type === "article" ? isSitePath(clean.path) : typeof clean.comment_id === "string" && UUID.test(clean.comment_id);
543
- return valid ? { upstream: "/reactions", body: clean } : void 0;
544
- }
545
- };
546
- }
547
- return void 0;
548
- }
549
- function pick(body, allowed, required) {
550
- if (!body || Object.keys(body).some((k) => !allowed.includes(k)) || !required.every((k) => k in body)) return void 0;
551
- return Object.fromEntries(allowed.filter((k) => k in body).map((k) => [k, body[k]]));
552
- }
553
- function isCommentText(value) {
554
- return typeof value === "string" && value.trim().length > 0 && [...value].length <= MAX_COMMENT_CHARACTERS && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value);
555
- }
556
- function sameOriginProblem(req, write, allowedOrigins) {
557
- const site = req.headers.get("sec-fetch-site");
558
- if (site !== null && site !== "same-origin") return true;
559
- if (!write) return false;
560
- const origin = req.headers.get("origin");
561
- if (origin === null) return true;
562
- let parsed;
563
- try {
564
- parsed = new URL(origin);
565
- } catch {
566
- return true;
567
- }
568
- if (req.headers.get(ENGAGE_CSRF_HEADER) !== "1") return true;
569
- if (allowedOrigins) return !allowedOrigins.some((o) => safeOrigin(o) === parsed.origin);
570
- const host = req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || req.headers.get("host") || new URL(req.url).host;
571
- const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
572
- if (proto && proto !== parsed.protocol.slice(0, -1)) return true;
573
- return parsed.host !== host;
574
- }
575
- var safeOrigin = (value) => {
576
- try {
577
- return new URL(value).origin;
578
- } catch {
579
- return void 0;
580
- }
581
- };
582
- async function readBody(req, expected) {
583
- if (!expected) return { kind: "ok", body: void 0 };
584
- if (!/^application\/json(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return { kind: "refused", response: refuse(415, "UNSUPPORTED_MEDIA_TYPE") };
585
- if (Number(req.headers.get("content-length")) > MAX_BODY_BYTES) return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
586
- if (!req.body) return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
587
- const reader = req.body.getReader();
588
- const chunks = [];
589
- let total = 0;
590
- for (; ; ) {
591
- const { done, value } = await reader.read();
592
- if (done) break;
593
- total += value.byteLength;
594
- if (total > MAX_BODY_BYTES) {
595
- await reader.cancel().catch(() => {
596
- });
597
- return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
598
- }
599
- chunks.push(value);
600
- }
601
- try {
602
- const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
603
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return { kind: "ok", body: parsed };
604
- } catch {
605
- }
606
- return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
607
- }
608
- var SUB_CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
609
- function validReader(r) {
610
- if (!r || typeof r.sub !== "string" || typeof r.name !== "string") return null;
611
- if (r.sub.length < 1 || [...r.sub].length > 255 || SUB_CONTROL.test(r.sub)) return null;
612
- const name = cleanDisplayName(r.name);
613
- return name === void 0 ? null : { sub: r.sub, name };
614
- }
615
- function relayFailure(status, retryAfter) {
616
- if (status === 400) return refuse(400, "VALIDATION_ERROR");
617
- if (status === 404) return refuse(404, "NOT_FOUND");
618
- if (status === 409) return refuse(409, "INVALID_TRANSITION");
619
- if (status === 413) return refuse(413, "PAYLOAD_TOO_LARGE");
620
- if (status === 429) {
621
- const seconds = Math.min(3600, Math.max(1, Math.trunc(Number(retryAfter)) || 60));
622
- return refuse(429, "RATE_LIMITED", { "Retry-After": String(seconds) });
623
- }
624
- return refuse(502, "UPSTREAM_ERROR");
625
- }
626
- function createEngagementRoute(options) {
627
- let ready;
628
- const fetchImpl = options.fetch ?? fetch;
629
- const cache = /* @__PURE__ */ new Map();
630
- let cacheBytes = 0;
631
- const clearCache = () => {
632
- cache.clear();
633
- cacheBytes = 0;
885
+ }
886
+ function hyleRootMetadata(options) {
887
+ const route = createRouter(options, hyleMetadata);
888
+ return async function generateMetadata({ params, searchParams }, parent) {
889
+ const hit = await route(await params ?? {});
890
+ return hit ? hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} }, parent) : {};
634
891
  };
635
- async function listing(viewer, call) {
636
- if (!viewer) return call(void 0);
637
- let out = await call(viewer.sign("read"));
638
- if (out.status === 401) out = await call(viewer.sign("read"));
639
- if (out.status !== 401 && out.status !== 404 && !(out.status === 429 && out.throttle === "viewer")) return out;
640
- return { ...await call(void 0), noShare: true };
892
+ }
893
+ async function hyleRootSitemap(options, sitemap) {
894
+ const entries = /* @__PURE__ */ new Map();
895
+ for (const { options: mountOptions, mount, defaultLocale } of await rootMounts(options).all()) {
896
+ for (const locale of mount.locales ?? [defaultLocale]) {
897
+ for (const entry of await hyleSitemap({ ...mountOptions, ...sitemap, locale, defaultLocale })) entries.set(entry.url, entry);
898
+ }
641
899
  }
642
- function shared(key, call) {
643
- const ttl = options.cacheTtlMs ?? DEFAULT_SHARE_MS;
644
- if (ttl <= 0) return call();
645
- const hit = cache.get(key);
646
- if (hit && Date.now() - hit.at < ttl) {
647
- cache.delete(key);
648
- cache.set(key, hit);
649
- return hit.result;
900
+ return [...entries.values()];
901
+ }
902
+
903
+ // src/next/markdown.ts
904
+ var MD_ROUTE_PREFIX = "/api/hyle/md";
905
+ function markdownRewritePath(pathname) {
906
+ if (!pathname.startsWith("/") || !pathname.endsWith(".md") || pathname.endsWith("/.md") || pathname.startsWith("/api/")) return void 0;
907
+ return MD_ROUTE_PREFIX + pathname.slice(0, -3);
908
+ }
909
+ var reply = (body, status, headers = {}) => (
910
+ // noindex on every answer: the .md twin must never compete with the page it mirrors.
911
+ new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers } })
912
+ );
913
+ function createMarkdownRoute(options) {
914
+ const mounts = rootMounts(options);
915
+ return {
916
+ async GET(_req, ctx) {
917
+ const params = await ctx.params ?? {};
918
+ const segments = params.path;
919
+ const path = sitePathFrom("", typeof segments === "string" ? [segments] : segments);
920
+ if (path === void 0 || path === "/") return reply(null, 404);
921
+ try {
922
+ const hit = await mounts.locate(path);
923
+ if (!hit) return reply(null, 404);
924
+ const { locale, toHref } = routeContext({ ...hit.options, basePath: "", param: "path" }, params);
925
+ const result = await resolverFor(hit.options)(path, locale, void 0, void 0, void 0, "md");
926
+ if (result.kind === "article" && result.content.format === "md") {
927
+ const markdown = result.content.markdown.replaceAll("](/assets/", `](${ASSET_ROUTE_PREFIX}/`);
928
+ return reply(markdown, 200, { "Content-Type": "text/markdown; charset=utf-8" });
929
+ }
930
+ if (result.kind === "redirect") {
931
+ const to = safeRedirectTarget(result.to);
932
+ const target = to === void 0 ? void 0 : safeRedirectTarget(toHref(to));
933
+ if (target === void 0) return reply(null, 502);
934
+ return target === toHref(path) ? reply(null, 404) : reply(null, result.status === 301 ? 308 : 307, { Location: `${target}.md` });
935
+ }
936
+ return reply(null, 404);
937
+ } catch (error) {
938
+ if (isRejectedRequest(error)) return reply(null, 404);
939
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
940
+ return reply(null, 502);
941
+ }
650
942
  }
651
- if (hit) forget(key, hit);
652
- const entry = { at: Date.now(), result: call(), bytes: 0 };
653
- cache.set(key, entry);
654
- entry.result.then(
655
- (o) => {
656
- if (cache.get(key) !== entry) return;
657
- if (o.status !== 200 && o.status !== 404 || o.noShare || o.text.length > MAX_SHARED_ENTRY_BYTES) return forget(key, entry);
658
- entry.bytes = o.text.length;
659
- cacheBytes += entry.bytes;
660
- while ((cacheBytes > MAX_SHARED_BYTES || cache.size > MAX_SHARED) && cache.size > 0) {
661
- const oldest = cache.entries().next().value;
662
- forget(oldest[0], oldest[1]);
943
+ };
944
+ }
945
+
946
+ // src/next/llms.ts
947
+ import { unstable_rethrow as unstable_rethrow4 } from "next/navigation";
948
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
949
+ var linkTarget = (url) => url.replace(/[()]/g, (c) => c === "(" ? "%28" : "%29");
950
+ function createLlmsTxtRoute(options, llms) {
951
+ const origin = bareOrigin(llms.origin);
952
+ if (!origin) throw new TypeError("createLlmsTxtRoute: `origin` must be a bare https origin such as https://example.com");
953
+ const mounts = rootMounts(options);
954
+ return {
955
+ async GET() {
956
+ try {
957
+ const lines = [`# ${oneLine(llms.title ?? new URL(origin).host)}`, ...llms.description ? ["", `> ${oneLine(llms.description)}`] : []];
958
+ for (const { options: mountOptions, mount, defaultLocale } of await mounts.all()) {
959
+ if (mount.locales && !mount.locales.includes(defaultLocale)) continue;
960
+ const { basePath, toHref } = routeContext({ ...mountOptions, locale: () => defaultLocale }, {});
961
+ const resolve = resolverFor(mountOptions);
962
+ const client = { resolve: ({ path, locale, limit, cursor }) => resolve(path, locale, limit, cursor) };
963
+ const { paths } = await listPublicationPaths({ client, basePath, locale: defaultLocale });
964
+ lines.push("", `## ${oneLine(mount.name ?? mount.defaultSection)}`, "");
965
+ for (const { path, title, description } of paths) {
966
+ lines.push(`- [${oneLine(title).replace(/[[\]]/g, "")}](${linkTarget(absoluteUrl(origin, toHref(path)))}.md)${description ? `: ${oneLine(description)}` : ""}`);
967
+ }
663
968
  }
664
- },
665
- () => forget(key, entry)
666
- );
667
- return entry.result;
668
- }
669
- function forget(key, entry) {
670
- if (cache.get(key) !== entry) return;
671
- cache.delete(key);
672
- cacheBytes -= entry.bytes;
673
- }
674
- function configured() {
675
- if (ready !== void 0) return ready;
969
+ return new Response(`${lines.join("\n")}
970
+ `, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
971
+ } catch (error) {
972
+ unstable_rethrow4(error);
973
+ console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
974
+ return new Response(null, { status: 503 });
975
+ }
976
+ }
977
+ };
978
+ }
979
+
980
+ // src/next/og.tsx
981
+ import { ImageResponse } from "next/og";
982
+
983
+ // src/next/asset.ts
984
+ var DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
985
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
986
+ var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
987
+ var PARTIAL_CACHE_CONTROL = "no-store";
988
+ var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
989
+ var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
990
+ var isSwitchedOff3 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
991
+ function capped(body, max) {
992
+ let seen = 0;
993
+ return body.pipeThrough(
994
+ new TransformStream({
995
+ transform(chunk, controller) {
996
+ seen += chunk.byteLength;
997
+ if (seen > max) return controller.error(new Error("asset too large"));
998
+ controller.enqueue(chunk);
999
+ }
1000
+ })
1001
+ );
1002
+ }
1003
+ function createAssetRoute(options) {
1004
+ let client;
1005
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
1006
+ async function serve(req, ctx, head) {
1007
+ if (isSwitchedOff3((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
1008
+ const file = (await ctx.params).file;
1009
+ if (typeof file !== "string" || !ASSET_FILE.test(file)) return empty(404);
676
1010
  try {
677
- const baseUrl = options.baseUrl?.trim() ?? "";
678
- checkBaseUrl(baseUrl);
679
- if (!options.token?.trim() || !options.workspaceId?.trim() || !options.signingKey) throw new TypeError("not provisioned");
680
- ready = { base: baseUrl.replace(/\/+$/, ""), key: engagementSigningKey(options.signingKey.trim()) };
1011
+ client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
681
1012
  } catch {
682
- ready = null;
1013
+ return empty(404);
683
1014
  }
684
- return ready;
685
- }
686
- async function reader(req, config) {
1015
+ let upstream;
687
1016
  try {
688
- const found = validReader(await options.getReader(req));
689
- if (!found) return null;
690
- const claims = { sub: found.sub, name: found.name, workspace: options.workspaceId.trim() };
691
- const sign = (scope) => signReaderAssertion(config.key, claims, void 0, scope);
692
- return { reader: found, assertion: sign(), sign };
1017
+ upstream = await client.asset(file, {
1018
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS2,
1019
+ headers: { range: req.headers.get("range"), "if-range": req.headers.get("if-range"), "if-none-match": req.headers.get("if-none-match") }
1020
+ });
693
1021
  } catch {
694
- return null;
1022
+ return empty(502);
695
1023
  }
696
- }
697
- async function handle(req, ctx) {
698
- const env = options.env ?? process.env;
699
- if (isSwitchedOff3(env.HYLE_ENGAGE_ENABLED) || isSwitchedOff3(env.HYLE_CONTENT_ENABLED)) return refuse(404, "NOT_FOUND");
700
- const config = configured();
701
- const route = match((await ctx.params).path ?? []);
702
- if (!config || !route) return refuse(404, "NOT_FOUND");
703
- if (!route.methods.includes(req.method)) return refuse(405, "METHOD_NOT_ALLOWED", { Allow: route.methods.join(", ") });
704
- const write = req.method !== "GET";
705
- if (sameOriginProblem(req, write, options.allowedOrigins)) return refuse(403, "FORBIDDEN");
706
- if (options.onRequest) {
707
- try {
708
- const early = await options.onRequest(req, { action: route.action(req.method) });
709
- if (early instanceof Response) {
710
- const headers = new Headers(early.headers);
711
- headers.set("cache-control", "no-store");
712
- return new Response(early.body, { status: early.status, headers });
713
- }
714
- } catch {
715
- return refuse(502, "UPSTREAM_ERROR");
716
- }
1024
+ const drop = () => void upstream.body?.cancel().catch(() => {
1025
+ });
1026
+ const etag = upstream.headers.get("etag");
1027
+ if (upstream.status === 304) {
1028
+ drop();
1029
+ return new Response(null, { status: 304, headers: { "Cache-Control": CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS, ...etag ? { ETag: etag } : {} } });
717
1030
  }
718
- if (route.local === "session") {
719
- const who = await reader(req, config);
720
- return json(200, { data: { reader: who ? { name: who.reader.name } : null } });
1031
+ if (upstream.status === 404 || upstream.status === 416) {
1032
+ drop();
1033
+ const range = upstream.status === 416 ? upstream.headers.get("content-range") : null;
1034
+ return empty(upstream.status, range ? { "Content-Range": range } : {});
721
1035
  }
722
- let assertion;
723
- let viewer = null;
724
- if (route.action(req.method) === "comments.list") viewer = await reader(req, config);
725
- if (write) {
726
- const who = await reader(req, config);
727
- if (!who) return refuse(401, "UNAUTHENTICATED");
728
- assertion = who.assertion;
1036
+ const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
1037
+ const length = Number(upstream.headers.get("content-length"));
1038
+ const expectedStatus = upstream.status === 200 || upstream.status === 206;
1039
+ if (!expectedStatus || !upstream.body || !type || !ASSET_CONTENT_TYPES.has(type) || Number.isFinite(length) && length > maxBytes) {
1040
+ drop();
1041
+ return empty(502);
729
1042
  }
730
- const url = new URL(req.url);
731
- const hasBody = write && !(req.method === "DELETE" && (await ctx.params).path?.[0] === "comments");
732
- const body = await readBody(req, hasBody);
733
- if (body.kind === "refused") return body.response;
734
- const built = route.rebuild(req.method, body.body, url);
735
- if (!built) return refuse(400, "VALIDATION_ERROR");
736
- const baseHeaders = new Headers({ authorization: `Bearer ${options.token.trim()}`, accept: "application/json" });
737
- if (built.body) baseHeaders.set("content-type", "application/json");
738
- const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
739
- const call = async (withAssertion = assertion) => {
740
- const headers = new Headers(baseHeaders);
741
- if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
742
- const res = await fetchImpl(target, {
743
- method: req.method,
744
- headers,
745
- ...built.body ? { body: JSON.stringify(built.body) } : {},
746
- redirect: "error",
747
- signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS2)
748
- });
749
- return { status: res.status, ok: res.ok, text: await readCapped(res, MAX_RESPONSE_BYTES), retryAfter: res.headers.get("retry-after"), throttle: res.headers.get("hyle-throttle") };
750
- };
751
- try {
752
- const out = route.action(req.method) === "comments.list" ? await shared(`${viewer?.reader.sub ?? ""}
753
- ${built.query.toString()}`, () => listing(viewer, call)) : await call();
754
- if (!out.ok) return relayFailure(out.status, out.retryAfter);
755
- if (write) clearCache();
756
- const data = JSON.parse(out.text).data;
757
- return typeof data === "object" && data !== null ? json(out.status === 201 ? 201 : 200, { data }) : refuse(502, "UPSTREAM_ERROR");
758
- } catch {
759
- return refuse(502, "UPSTREAM_ERROR");
1043
+ const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
1044
+ if (etag) headers.set("ETag", etag);
1045
+ const contentRange = upstream.headers.get("content-range");
1046
+ if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
1047
+ if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
1048
+ if (head) {
1049
+ drop();
1050
+ return new Response(null, { status: upstream.status, headers });
760
1051
  }
1052
+ return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
761
1053
  }
762
- return { GET: handle, POST: handle, PATCH: handle, PUT: handle, DELETE: handle };
1054
+ return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
763
1055
  }
764
1056
 
765
- // src/next/embed.tsx
766
- import { jsx as jsx2 } from "react/jsx-runtime";
767
- async function resolveEmbed(options, run) {
768
- try {
769
- return { result: await run() };
770
- } catch (error) {
771
- if (isRejectedRequest(error)) return {};
772
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
773
- return { failure: options.onError ? options.onError(error) : null };
774
- }
775
- }
776
- async function HyleList({ options, section, limit = 5, locale, layout, title, headingLevel, moreHref }) {
777
- const resolve = resolverFor(options);
778
- const route = routeContext(locale ? { ...options, locale } : options, {});
779
- const path = sitePathFrom(route.basePath, section && section !== "posts" ? [section] : void 0);
780
- if (path === void 0) return null;
781
- const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale, limit));
782
- if (failure !== void 0) return failure;
783
- return /* @__PURE__ */ jsx2(HyleListView, { items: result?.kind === "list" ? result.items : [], layout, title, headingLevel, moreHref, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
784
- }
785
- async function HyleArticle({ options, path, locale, headingLevel }) {
786
- if (!isSitePath(path)) return null;
1057
+ // src/next/og.tsx
1058
+ import { jsx as jsx3, jsxs } from "react/jsx-runtime";
1059
+ var SIZE = { width: 1200, height: 630 };
1060
+ var MAX_TITLE = 140;
1061
+ function createOgImageRoute(options) {
787
1062
  const resolve = resolverFor(options);
788
- const route = routeContext(locale ? { ...options, locale } : options, {});
789
- const { result, failure } = await resolveEmbed(options, () => resolve(path, route.locale));
790
- if (failure !== void 0) return failure;
791
- if (result?.kind !== "article") return null;
792
- return /* @__PURE__ */ jsx2(HyleArticleView, { article: result, headingLevel, components: options.components, slots: options.slots, locale: route.locale, toHref: route.toHref });
793
- }
794
- var MAX_LISTING_BYTES = 4 * 1024 * 1024;
795
- var COMMENTS_TIMEOUT_MS = 1e4;
796
- async function HyleComments({ options, path, revalidate = 60, interactive }) {
797
- checkBaseUrl(options.baseUrl);
798
- if (!options.token) throw new TypeError("token is required");
799
- if (!isSitePath(path)) return null;
800
- const locale = options.locale ?? "en";
801
- let listing;
802
- let fetchedAt;
803
- try {
804
- const init = {
805
- headers: { authorization: `Bearer ${options.token}`, accept: "application/json" },
806
- redirect: "error",
807
- signal: AbortSignal.timeout(COMMENTS_TIMEOUT_MS),
808
- next: { revalidate }
809
- };
810
- const res = await fetch(`${options.baseUrl.replace(/\/+$/, "")}/cp1/engage/comments?${new URLSearchParams({ path })}`, init);
811
- if (!res.ok) {
812
- if (res.status !== 404) console.error(`hyle: comments answered HTTP ${res.status}`);
813
- return null;
1063
+ return {
1064
+ async GET(req, ctx) {
1065
+ if (isSwitchedOff3(process.env.HYLE_CONTENT_ENABLED)) return new Response(null, { status: 404 });
1066
+ const segments = (await ctx.params).path;
1067
+ const route = routeContext({ ...options, basePath: "", param: "path" }, { path: segments });
1068
+ if (!segments?.length || route.path === void 0) return new Response(null, { status: 404 });
1069
+ const path = route.path;
1070
+ const load = async (locale) => {
1071
+ const first = await resolve(path, locale);
1072
+ const target = first.kind === "redirect" ? safeRedirectTarget(first.to) : void 0;
1073
+ return target ? resolve(target, locale) : first;
1074
+ };
1075
+ let title;
1076
+ try {
1077
+ let result = await load();
1078
+ const wanted = new URL(req.url).searchParams.get("locale");
1079
+ if (result.kind === "article" && wanted && wanted !== result.publication.locale && result.alternates.some((a) => a.locale === wanted)) result = await load(wanted);
1080
+ if (result.kind !== "article") return new Response(null, { status: 404 });
1081
+ title = result.publication.title;
1082
+ } catch (error) {
1083
+ return new Response(null, { status: isRejectedRequest(error) ? 404 : 502 });
1084
+ }
1085
+ const chars = [...title];
1086
+ const shown = chars.length > MAX_TITLE ? `${chars.slice(0, MAX_TITLE - 1).join("")}\u2026` : title;
1087
+ return new ImageResponse(
1088
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", flexDirection: "column", justifyContent: "space-between", width: "100%", height: "100%", padding: 80, background: "#111827", color: "#ffffff" }, children: [
1089
+ /* @__PURE__ */ jsx3("div", { style: { fontSize: 64, fontWeight: 700, lineHeight: 1.2 }, children: shown }),
1090
+ options.siteName ? /* @__PURE__ */ jsx3("div", { style: { fontSize: 32, color: "#9ca3af" }, children: options.siteName }) : null
1091
+ ] }),
1092
+ // shortcut: @vercel/og fetches Google Fonts / emoji assets at render time for non-Latin titles and emoji (no switch to disable it), upgrade to a satori render with bundled fonts if a host needs zero egress.
1093
+ { ...SIZE, headers: { "cache-control": "public, max-age=3600, s-maxage=31536000, immutable" } }
1094
+ );
814
1095
  }
815
- listing = parseListing(JSON.parse(await readCapped(res, MAX_LISTING_BYTES)).data);
816
- const date = Date.parse(res.headers.get("date") ?? "");
817
- fetchedAt = Number.isFinite(date) ? date : void 0;
818
- } catch (error) {
819
- unstable_rethrow3(error);
820
- console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
821
- return null;
822
- }
823
- if (!listing) return null;
824
- if (!interactive) return /* @__PURE__ */ jsx2(HyleCommentsView, { listing, locale });
825
- const config = interactive === true ? {} : interactive;
826
- return /* @__PURE__ */ jsx2("div", { className: "hyle hyle-embed", children: /* @__PURE__ */ jsx2(Comments, { path, endpoint: config.endpoint ?? "/api/hyle/engage", signInHref: config.signInHref, locale, labels: stringsFor(locale).comments, initial: listing, initialAt: fetchedAt }) });
1096
+ };
827
1097
  }
828
1098
  export {
829
1099
  ENGAGE_CSRF_HEADER,
@@ -834,14 +1104,19 @@ export {
834
1104
  MOUNTS_MAX_STALE_MS,
835
1105
  createAssetRoute,
836
1106
  createEngagementRoute,
1107
+ createLlmsTxtRoute,
1108
+ createMarkdownRoute,
1109
+ createOgImageRoute,
837
1110
  createRevalidateRoute,
838
1111
  fetchResolver,
839
1112
  hyleFeed,
1113
+ hyleFeedLink,
840
1114
  hyleMetadata,
841
1115
  hylePage,
842
1116
  hyleRootMetadata,
843
1117
  hyleRootPage,
844
1118
  hyleRootSitemap,
845
1119
  hyleSitemap,
1120
+ markdownRewritePath,
846
1121
  workspaceTags
847
1122
  };