@tdacorp/hyle-sdk 0.14.1 → 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.
- package/README.md +20 -8
- package/dist/check-routes-bin.js +10 -8
- package/dist/{chunk-4V4VKB3O.js → chunk-DMK4XQLU.js} +470 -385
- package/dist/{chunk-R5EMI4HQ.js → chunk-PJMJMP66.js} +3 -1
- package/dist/comments.cjs +6 -4
- package/dist/comments.js +6 -5
- package/dist/{diagram-viewer-DYX6R63Y.js → diagram-viewer-FJPED4SN.js} +46 -26
- package/dist/{embed-B76zRRPa.d.cts → embed-BmdwA2G9.d.cts} +9 -4
- package/dist/{embed-SqOBGI-E.d.ts → embed-DNTZ2UXv.d.ts} +9 -4
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/labels-nmukKYgL.d.cts +37 -0
- package/dist/labels-nmukKYgL.d.ts +37 -0
- package/dist/mermaid-diagram.cjs +59 -30
- package/dist/mermaid-diagram.d.cts +4 -37
- package/dist/mermaid-diagram.d.ts +4 -37
- package/dist/mermaid-diagram.js +7 -5
- package/dist/mermaid-image.cjs +1382 -0
- package/dist/mermaid-image.d.cts +29 -0
- package/dist/mermaid-image.d.ts +29 -0
- package/dist/mermaid-image.js +94 -0
- package/dist/next.cjs +1330 -1118
- package/dist/next.d.cts +61 -11
- package/dist/next.d.ts +61 -11
- package/dist/next.js +922 -793
- package/dist/react.cjs +267 -184
- package/dist/react.d.cts +29 -6
- package/dist/react.d.ts +29 -6
- package/dist/react.js +1 -1
- package/dist/{resolve-DC2ccfwA.d.ts → resolve-Ae7UFjsQ.d.ts} +1 -1
- package/dist/{resolve-DKLVftk_.d.cts → resolve-euZ4-aC9.d.cts} +1 -1
- package/dist/styles.css +11 -22
- package/dist/{types-ByodIyEv.d.cts → types-Czt887Iv.d.cts} +19 -3
- package/dist/{types-ByodIyEv.d.ts → types-Czt887Iv.d.ts} +19 -3
- package/dist/use-cache.d.cts +2 -2
- package/dist/use-cache.d.ts +2 -2
- package/package.json +1 -1
package/dist/next.js
CHANGED
|
@@ -14,9 +14,11 @@ import {
|
|
|
14
14
|
hreflangLanguages,
|
|
15
15
|
modifiedAt,
|
|
16
16
|
parseListing,
|
|
17
|
+
readingMinutes,
|
|
17
18
|
stringsFor,
|
|
18
|
-
validOgImage
|
|
19
|
-
|
|
19
|
+
validOgImage,
|
|
20
|
+
wordCountOf
|
|
21
|
+
} from "./chunk-DMK4XQLU.js";
|
|
20
22
|
import {
|
|
21
23
|
DEFAULT_REVALIDATE,
|
|
22
24
|
fetchResolver,
|
|
@@ -79,6 +81,12 @@ function safeRedirectTarget(to) {
|
|
|
79
81
|
function resolverFor(options) {
|
|
80
82
|
return options.resolver ?? fetchResolver(options);
|
|
81
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
|
+
}
|
|
82
90
|
var CURSOR = /^[A-Za-z0-9_-]{1,256}$/;
|
|
83
91
|
var validCursor = (value) => typeof value === "string" && CURSOR.test(value) ? value : void 0;
|
|
84
92
|
var LOCALE_TAG = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
|
|
@@ -98,875 +106,994 @@ function isRejectedRequest(error) {
|
|
|
98
106
|
return error instanceof Cp1ClientError && error.status >= 400 && error.status < 500 && ![401, 403, 429].includes(error.status);
|
|
99
107
|
}
|
|
100
108
|
|
|
101
|
-
// src/next/
|
|
102
|
-
import {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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;
|
|
130
149
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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 };
|
|
134
155
|
}
|
|
135
|
-
}
|
|
136
|
-
if (isRejectedRequest(error)) notFound();
|
|
137
|
-
if (!options.onError) throw error;
|
|
138
|
-
console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
|
|
139
|
-
return options.onError(error);
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// src/next/sitemap.ts
|
|
145
|
-
var ISO_DATE = /^\d{4}-\d{2}-\d{2}T/;
|
|
146
|
-
var isoTime = (value) => value && ISO_DATE.test(value) ? Date.parse(value) : NaN;
|
|
147
|
-
function httpsOrigin(origin) {
|
|
148
|
-
let url;
|
|
149
|
-
try {
|
|
150
|
-
url = new URL(origin);
|
|
151
|
-
} catch {
|
|
152
|
-
throw new TypeError("hyleSitemap: `origin` must be an https origin such as https://example.com");
|
|
153
|
-
}
|
|
154
|
-
if (url.protocol !== "https:" || url.origin !== origin.replace(/\/$/, "")) {
|
|
155
|
-
throw new TypeError("hyleSitemap: `origin` must be an https origin with no path, query or credentials");
|
|
156
|
+
};
|
|
156
157
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
throw new Error("hyleSitemap: hyle could not be listed completely (see onIncomplete)");
|
|
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
168
|
}
|
|
169
|
-
|
|
170
|
-
return paths.map(({ path, publishedAt, updatedAt, alternates }) => {
|
|
171
|
-
const latest = [publishedAt, updatedAt].filter((v) => !Number.isNaN(isoTime(v))).sort((x, y) => isoTime(y) - isoTime(x))[0];
|
|
172
|
-
const modified = latest && new Date(latest).toISOString();
|
|
173
|
-
const url = origin + encodeURI(toHref(path));
|
|
169
|
+
if (a === "reactions" && b === void 0) {
|
|
174
170
|
return {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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
|
+
}
|
|
179
180
|
};
|
|
180
|
-
}
|
|
181
|
+
}
|
|
182
|
+
return void 0;
|
|
181
183
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
function hyleMetadata(options) {
|
|
186
|
-
const resolve = resolverFor(options);
|
|
187
|
-
const origin = bareOrigin(options.siteOrigin);
|
|
188
|
-
return async function generateMetadata({ params, searchParams }) {
|
|
189
|
-
const { path, locale, toHref } = routeContext(options, await params ?? {});
|
|
190
|
-
if (path === void 0) return {};
|
|
191
|
-
const link = (sitePath, linkLocale) => {
|
|
192
|
-
const href = toHref(sitePath, linkLocale);
|
|
193
|
-
return origin ? absoluteUrl(origin, href) : href;
|
|
194
|
-
};
|
|
195
|
-
try {
|
|
196
|
-
const cursor = options.paginate === "searchParams" ? validCursor((await searchParams)?.cursor) : void 0;
|
|
197
|
-
const result = await resolve(path, locale, options.listLimit, cursor, options.layout === "docs" ? "tree" : void 0);
|
|
198
|
-
if (result.kind === "list") {
|
|
199
|
-
const title = (options.list?.title || result.section.title) + (cursor ? ` - ${stringsFor(locale).older}` : "");
|
|
200
|
-
const description2 = options.list?.description;
|
|
201
|
-
return {
|
|
202
|
-
title: titled(options.titleTemplate, title),
|
|
203
|
-
...description2 ? { description: description2 } : {},
|
|
204
|
-
alternates: { canonical: link(path) + (cursor ? `?cursor=${cursor}` : "") },
|
|
205
|
-
openGraph: { title, ...description2 ? { description: description2 } : {} }
|
|
206
|
-
};
|
|
207
|
-
}
|
|
208
|
-
if (result.kind !== "article") return {};
|
|
209
|
-
const { publication: pub, alternates, default_locale } = result;
|
|
210
|
-
const canonical = link(pub.canonical_path, pub.locale);
|
|
211
|
-
const description = pub.description ?? void 0;
|
|
212
|
-
const author = articleAuthor(result, options.jsonLd)?.name;
|
|
213
|
-
const modified = modifiedAt(pub);
|
|
214
|
-
const image = validOgImage(options.ogImage?.(result), origin);
|
|
215
|
-
const alternateLocale = options.ogLocale ? alternates.filter((a) => a.locale !== pub.locale).flatMap((a) => options.ogLocale?.(a.locale) ?? []) : [];
|
|
216
|
-
const { twitter } = options;
|
|
217
|
-
return {
|
|
218
|
-
title: titled(options.titleTemplate, pub.title),
|
|
219
|
-
...description ? { description } : {},
|
|
220
|
-
alternates: {
|
|
221
|
-
canonical,
|
|
222
|
-
...alternates.length > 1 ? { languages: hreflangLanguages(alternates, default_locale, canonical, (a) => link(a.canonical_path, a.locale)) } : {}
|
|
223
|
-
},
|
|
224
|
-
openGraph: {
|
|
225
|
-
type: "article",
|
|
226
|
-
title: pub.title,
|
|
227
|
-
...description ? { description } : {},
|
|
228
|
-
url: canonical,
|
|
229
|
-
...options.siteName ? { siteName: options.siteName } : {},
|
|
230
|
-
locale: options.ogLocale?.(pub.locale) ?? pub.locale,
|
|
231
|
-
...alternateLocale.length ? { alternateLocale } : {},
|
|
232
|
-
publishedTime: pub.published_at,
|
|
233
|
-
...modified ? { modifiedTime: modified } : {},
|
|
234
|
-
...author ? { authors: [author] } : {},
|
|
235
|
-
...image ? { images: [image] } : {}
|
|
236
|
-
},
|
|
237
|
-
...image ? {
|
|
238
|
-
twitter: {
|
|
239
|
-
card: "summary_large_image",
|
|
240
|
-
...twitter?.site ? { site: twitter.site } : {},
|
|
241
|
-
...twitter?.creator ? { creator: twitter.creator } : {},
|
|
242
|
-
title: pub.title,
|
|
243
|
-
...description ? { description } : {},
|
|
244
|
-
images: [image]
|
|
245
|
-
}
|
|
246
|
-
} : {}
|
|
247
|
-
};
|
|
248
|
-
} catch (error) {
|
|
249
|
-
if (isRejectedRequest(error)) return {};
|
|
250
|
-
throw error;
|
|
251
|
-
}
|
|
252
|
-
};
|
|
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]]));
|
|
253
187
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
const origin =
|
|
262
|
-
if (
|
|
263
|
-
|
|
264
|
-
return response(null, 404);
|
|
265
|
-
}
|
|
266
|
-
const { path, locale, toHref } = routeContext(options, {});
|
|
267
|
-
if (path === void 0) return response(null, 404);
|
|
268
|
-
const url = (sitePath) => origin + encodeURI(toHref(sitePath));
|
|
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;
|
|
269
198
|
try {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
const link = url(item.canonical_path);
|
|
274
|
-
const published = new Date(item.published_at);
|
|
275
|
-
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>`;
|
|
276
|
-
});
|
|
277
|
-
const channel = [
|
|
278
|
-
tag("title", options.list?.title || result.section.title),
|
|
279
|
-
tag("link", url(path)),
|
|
280
|
-
tag("description", options.list?.description ?? ""),
|
|
281
|
-
locale ? tag("language", locale) : "",
|
|
282
|
-
`<atom:link href="${xml(origin + encodeURI(options.feedPath ?? "/feed.xml"))}" rel="self" type="application/rss+xml"/>`,
|
|
283
|
-
...items
|
|
284
|
-
].join("");
|
|
285
|
-
return response(
|
|
286
|
-
`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel>${channel}</channel></rss>`,
|
|
287
|
-
200,
|
|
288
|
-
{ "content-type": "application/rss+xml; charset=utf-8" }
|
|
289
|
-
);
|
|
290
|
-
} catch (error) {
|
|
291
|
-
unstable_rethrow2(error);
|
|
292
|
-
console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
|
|
293
|
-
return response(null, 503);
|
|
199
|
+
parsed = new URL(origin);
|
|
200
|
+
} catch {
|
|
201
|
+
return true;
|
|
294
202
|
}
|
|
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;
|
|
295
209
|
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
210
|
+
var safeOrigin = (value) => {
|
|
211
|
+
try {
|
|
212
|
+
return new URL(value).origin;
|
|
213
|
+
} catch {
|
|
214
|
+
return void 0;
|
|
215
|
+
}
|
|
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") };
|
|
314
233
|
}
|
|
315
|
-
|
|
234
|
+
chunks.push(value);
|
|
235
|
+
}
|
|
236
|
+
try {
|
|
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 {
|
|
240
|
+
}
|
|
241
|
+
return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
|
|
316
242
|
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
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;
|
|
325
311
|
try {
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
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)
|
|
333
383
|
});
|
|
334
|
-
|
|
335
|
-
|
|
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;
|
|
336
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;
|
|
337
458
|
}
|
|
338
|
-
return
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
return reserved.some((entry) => entry.endsWith("/*") ? prefixMatches(entry.slice(0, -2), path) : entry === path);
|
|
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 }) });
|
|
343
463
|
}
|
|
344
464
|
|
|
345
|
-
// src/next/
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
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();
|
|
356
479
|
try {
|
|
357
|
-
const
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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();
|
|
361
506
|
}
|
|
362
|
-
const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale };
|
|
363
|
-
lastKnownGood.set(key, { loaded, at: Date.now() });
|
|
364
|
-
return loaded;
|
|
365
507
|
} catch (error) {
|
|
366
|
-
if (isRejectedRequest(error))
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
if (error instanceof Cp1ClientError && (error.status === 401 || error.status === 403)) {
|
|
371
|
-
lastKnownGood.delete(key);
|
|
372
|
-
throw error;
|
|
373
|
-
}
|
|
374
|
-
const kept = lastKnownGood.get(key);
|
|
375
|
-
if (kept && Date.now() - kept.at <= MOUNTS_MAX_STALE_MS) return kept.loaded;
|
|
376
|
-
throw error;
|
|
377
|
-
}
|
|
378
|
-
};
|
|
379
|
-
}
|
|
380
|
-
var asArray = (options) => Array.isArray(options) ? options : [options];
|
|
381
|
-
function setup(options) {
|
|
382
|
-
const configs = asArray(options);
|
|
383
|
-
if (configs.length === 0) throw new TypeError("hyleRootPage: pass at least one workspace config");
|
|
384
|
-
const param = configs[0].param ?? "hyle";
|
|
385
|
-
if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
|
|
386
|
-
return { configs, param, loaders: configs.map(mountsLoader) };
|
|
387
|
-
}
|
|
388
|
-
var sectionsOf = (config, mount) => [
|
|
389
|
-
...config.sections ?? [],
|
|
390
|
-
...SECTION_SLUG.test(mount.defaultSection) ? [mount.defaultSection] : []
|
|
391
|
-
];
|
|
392
|
-
function mountOptionsOf(config, mount) {
|
|
393
|
-
const { mountOptions, ...rest } = config;
|
|
394
|
-
return { ...rest, ...mountOptions?.[mount.prefix === "" ? "/" : mount.prefix], basePath: mount.prefix, sections: sectionsOf(config, mount) };
|
|
395
|
-
}
|
|
396
|
-
function rootMounts(options) {
|
|
397
|
-
const { configs, param, loaders } = setup(options);
|
|
398
|
-
return {
|
|
399
|
-
param,
|
|
400
|
-
async locate(path) {
|
|
401
|
-
const loaded = await Promise.all(loaders.map((load) => load()));
|
|
402
|
-
let best;
|
|
403
|
-
loaded.forEach(({ mounts, reserved }, index2) => {
|
|
404
|
-
if (isReserved(path, reserved)) return;
|
|
405
|
-
for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
|
|
406
|
-
});
|
|
407
|
-
if (!best) return void 0;
|
|
408
|
-
const { index, mount } = best;
|
|
409
|
-
return { options: mountOptionsOf(configs[index], mount), mount, index };
|
|
410
|
-
},
|
|
411
|
-
async all() {
|
|
412
|
-
const out = [];
|
|
413
|
-
for (const [index, load] of loaders.entries()) {
|
|
414
|
-
const { mounts, defaultLocale } = await load();
|
|
415
|
-
for (const mount of mounts) out.push({ options: mountOptionsOf(configs[index], mount), mount, index, defaultLocale });
|
|
416
|
-
}
|
|
417
|
-
return out;
|
|
418
|
-
}
|
|
419
|
-
};
|
|
420
|
-
}
|
|
421
|
-
function createRouter(options, make) {
|
|
422
|
-
const mounts = rootMounts(options);
|
|
423
|
-
const handlers = /* @__PURE__ */ new Map();
|
|
424
|
-
return async function route(params) {
|
|
425
|
-
const raw = params[mounts.param];
|
|
426
|
-
const segments = typeof raw === "string" ? [raw] : raw;
|
|
427
|
-
const path = sitePathFrom("", segments);
|
|
428
|
-
if (path === void 0 || path === "/" || !segments) return void 0;
|
|
429
|
-
const hit = await mounts.locate(path);
|
|
430
|
-
if (!hit) return void 0;
|
|
431
|
-
const { mount, index } = hit;
|
|
432
|
-
const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
|
|
433
|
-
let handler = handlers.get(id);
|
|
434
|
-
if (!handler) {
|
|
435
|
-
handler = make(hit.options);
|
|
436
|
-
handlers.set(id, handler);
|
|
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);
|
|
437
512
|
}
|
|
438
|
-
return { handler, params: { ...params, [mounts.param]: segments.slice(mount.depth) } };
|
|
439
513
|
};
|
|
440
514
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
}
|
|
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;
|
|
455
530
|
}
|
|
456
|
-
async function
|
|
457
|
-
const
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
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)");
|
|
462
540
|
}
|
|
463
|
-
|
|
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
|
+
});
|
|
464
553
|
}
|
|
465
554
|
|
|
466
|
-
// src/next/
|
|
467
|
-
var
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
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) };
|
|
471
582
|
}
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
);
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
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
|
+
};
|
|
504
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;
|
|
505
688
|
}
|
|
506
689
|
};
|
|
507
690
|
}
|
|
508
691
|
|
|
509
|
-
// src/next/
|
|
692
|
+
// src/next/feed.ts
|
|
510
693
|
import { unstable_rethrow as unstable_rethrow3 } from "next/navigation";
|
|
511
|
-
var
|
|
512
|
-
var
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
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;
|
|
517
739
|
return {
|
|
518
|
-
async
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
lines.push("", `## ${oneLine(mount.name ?? mount.defaultSection)}`, "");
|
|
528
|
-
for (const { path, title, description } of paths) {
|
|
529
|
-
lines.push(`- [${oneLine(title).replace(/[[\]]/g, "")}](${linkTarget(absoluteUrl(origin, toHref(path)))}.md)${description ? `: ${oneLine(description)}` : ""}`);
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
return new Response(`${lines.join("\n")}
|
|
533
|
-
`, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
|
|
534
|
-
} catch (error) {
|
|
535
|
-
unstable_rethrow3(error);
|
|
536
|
-
console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
|
|
537
|
-
return new Response(null, { status: 503 });
|
|
740
|
+
async POST(req) {
|
|
741
|
+
if (isSwitchedOff2((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return new Response(null, { status: 404 });
|
|
742
|
+
const workspaceId = options.workspaceId?.trim();
|
|
743
|
+
const secrets = options.secrets.map((s) => s?.trim()).filter((s) => Boolean(s));
|
|
744
|
+
if (!workspaceId && secrets.length === 0) return new Response(null, { status: 404 });
|
|
745
|
+
if (!workspaceId || secrets.length === 0) return new Response(null, { status: 503 });
|
|
746
|
+
const key = `${workspaceId}\0${secrets.join("\0")}`;
|
|
747
|
+
if (cached?.key !== key) {
|
|
748
|
+
cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (tag2) => revalidateTag(tag2, { expire: 0 }) }) };
|
|
538
749
|
}
|
|
750
|
+
return cached.route.POST(req);
|
|
539
751
|
}
|
|
540
752
|
};
|
|
541
753
|
}
|
|
542
754
|
|
|
543
|
-
// src/next/
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
var isSwitchedOff2 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
|
|
551
|
-
function capped(body, max) {
|
|
552
|
-
let seen = 0;
|
|
553
|
-
return body.pipeThrough(
|
|
554
|
-
new TransformStream({
|
|
555
|
-
transform(chunk, controller) {
|
|
556
|
-
seen += chunk.byteLength;
|
|
557
|
-
if (seen > max) return controller.error(new Error("asset too large"));
|
|
558
|
-
controller.enqueue(chunk);
|
|
559
|
-
}
|
|
560
|
-
})
|
|
561
|
-
);
|
|
562
|
-
}
|
|
563
|
-
function createAssetRoute(options) {
|
|
564
|
-
let client;
|
|
565
|
-
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
566
|
-
async function serve(req, ctx, head) {
|
|
567
|
-
if (isSwitchedOff2((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
|
|
568
|
-
const file = (await ctx.params).file;
|
|
569
|
-
if (typeof file !== "string" || !ASSET_FILE.test(file)) return empty(404);
|
|
570
|
-
try {
|
|
571
|
-
client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
|
|
572
|
-
} catch {
|
|
573
|
-
return empty(404);
|
|
574
|
-
}
|
|
575
|
-
let upstream;
|
|
755
|
+
// src/next/root.ts
|
|
756
|
+
import { notFound as notFound2 } from "next/navigation";
|
|
757
|
+
|
|
758
|
+
// src/next/mount-match.ts
|
|
759
|
+
function activeMounts(mounts) {
|
|
760
|
+
const out = [];
|
|
761
|
+
for (const { prefix, default_section, name, locales } of mounts) {
|
|
576
762
|
try {
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
763
|
+
const normalized = normalizeBasePath(prefix);
|
|
764
|
+
out.push({
|
|
765
|
+
prefix: normalized,
|
|
766
|
+
defaultSection: default_section,
|
|
767
|
+
depth: normalized === "" ? 0 : normalized.split("/").length - 1,
|
|
768
|
+
...name ? { name } : {},
|
|
769
|
+
...locales ? { locales } : {}
|
|
580
770
|
});
|
|
581
|
-
} catch {
|
|
582
|
-
|
|
583
|
-
}
|
|
584
|
-
const drop = () => void upstream.body?.cancel().catch(() => {
|
|
585
|
-
});
|
|
586
|
-
const etag = upstream.headers.get("etag");
|
|
587
|
-
if (upstream.status === 304) {
|
|
588
|
-
drop();
|
|
589
|
-
return new Response(null, { status: 304, headers: { "Cache-Control": CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS, ...etag ? { ETag: etag } : {} } });
|
|
590
|
-
}
|
|
591
|
-
if (upstream.status === 404 || upstream.status === 416) {
|
|
592
|
-
drop();
|
|
593
|
-
const range = upstream.status === 416 ? upstream.headers.get("content-range") : null;
|
|
594
|
-
return empty(upstream.status, range ? { "Content-Range": range } : {});
|
|
595
|
-
}
|
|
596
|
-
const type = upstream.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
597
|
-
const length = Number(upstream.headers.get("content-length"));
|
|
598
|
-
const expectedStatus = upstream.status === 200 || upstream.status === 206;
|
|
599
|
-
if (!expectedStatus || !upstream.body || !type || !ASSET_CONTENT_TYPES.has(type) || Number.isFinite(length) && length > maxBytes) {
|
|
600
|
-
drop();
|
|
601
|
-
return empty(502);
|
|
602
|
-
}
|
|
603
|
-
const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
|
|
604
|
-
if (etag) headers.set("ETag", etag);
|
|
605
|
-
const contentRange = upstream.headers.get("content-range");
|
|
606
|
-
if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
|
|
607
|
-
if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
|
|
608
|
-
if (head) {
|
|
609
|
-
drop();
|
|
610
|
-
return new Response(null, { status: upstream.status, headers });
|
|
771
|
+
} catch (error) {
|
|
772
|
+
console.error(`hyle: ignoring a mount with an invalid prefix (${error instanceof Error ? error.name : "Error"})`);
|
|
611
773
|
}
|
|
612
|
-
return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
|
|
613
774
|
}
|
|
614
|
-
return
|
|
775
|
+
return out;
|
|
615
776
|
}
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
// src/next/engage.ts
|
|
621
|
-
var ENGAGE_CSRF_HEADER = "x-hyle-engage";
|
|
622
|
-
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
623
|
-
var DEFAULT_SHARE_MS = 3e3;
|
|
624
|
-
var MAX_SHARED = 100;
|
|
625
|
-
var MAX_SHARED_BYTES = 8 * 1024 * 1024;
|
|
626
|
-
var MAX_SHARED_ENTRY_BYTES = 256 * 1024;
|
|
627
|
-
var MAX_BODY_BYTES = 20 * 1024;
|
|
628
|
-
var MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
629
|
-
var MAX_COMMENT_CHARACTERS = 4e3;
|
|
630
|
-
var MAX_PATH_LENGTH2 = 1024;
|
|
631
|
-
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
632
|
-
var CONTROL = /[\u0000-\u001f\u007f\\]/;
|
|
633
|
-
var HEADERS = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };
|
|
634
|
-
var isSwitchedOff3 = (value) => {
|
|
635
|
-
const v = value?.trim().toLowerCase() ?? "";
|
|
636
|
-
return v !== "" && v !== "1" && v !== "true";
|
|
637
|
-
};
|
|
638
|
-
var json = (status, body, extra = {}) => new Response(JSON.stringify(body), { status, headers: { ...HEADERS, "Content-Type": "application/json; charset=utf-8", ...extra } });
|
|
639
|
-
var refuse = (status, code, extra = {}) => json(status, { error: { code } }, extra);
|
|
640
|
-
function isSitePath(value) {
|
|
641
|
-
if (typeof value !== "string" || value.length > MAX_PATH_LENGTH2 || !value.startsWith("/") || value.startsWith("//")) return false;
|
|
642
|
-
if (CONTROL.test(value) || /[?#]/.test(value)) return false;
|
|
643
|
-
return !value.split("/").some((segment) => segment === "." || segment === "..");
|
|
777
|
+
var prefixMatches = (prefix, path) => prefix === "" || path === prefix || path.startsWith(`${prefix}/`);
|
|
778
|
+
function isReserved(path, reserved) {
|
|
779
|
+
return reserved.some((entry) => entry.endsWith("/*") ? prefixMatches(entry.slice(0, -2), path) : entry === path);
|
|
644
780
|
}
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
return { upstream: "/comments", body: clean };
|
|
781
|
+
|
|
782
|
+
// src/next/root.ts
|
|
783
|
+
var MOUNTS_MAX_STALE_MS = 15 * 60 * 1e3;
|
|
784
|
+
var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
785
|
+
var NONE = { mounts: [], reserved: [], defaultLocale: "" };
|
|
786
|
+
var lastKnownGood = /* @__PURE__ */ new Map();
|
|
787
|
+
function mountsLoader(config) {
|
|
788
|
+
if (!config.workspaceId) throw new TypeError("hyleRootPage: `workspaceId` is required for the fetch cache");
|
|
789
|
+
const client = createHyleClient({ baseUrl: config.baseUrl, token: config.token });
|
|
790
|
+
const init = { next: { revalidate: config.revalidate ?? DEFAULT_REVALIDATE, tags: workspaceTags(config.workspaceId).slice(0, 1) } };
|
|
791
|
+
const key = `${new URL(config.baseUrl).origin}|${config.workspaceId}`;
|
|
792
|
+
return async function load() {
|
|
793
|
+
try {
|
|
794
|
+
const result = await client.mounts({ init });
|
|
795
|
+
if (result.kind !== "mounts") {
|
|
796
|
+
lastKnownGood.delete(key);
|
|
797
|
+
return NONE;
|
|
663
798
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
if (method === "DELETE") return body === void 0 ? { upstream: `/comments/${b}` } : void 0;
|
|
672
|
-
const clean = pick(body, ["body"], ["body"]);
|
|
673
|
-
return clean && isCommentText(clean.body) ? { upstream: `/comments/${b}`, body: clean } : void 0;
|
|
799
|
+
const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale };
|
|
800
|
+
lastKnownGood.set(key, { loaded, at: Date.now() });
|
|
801
|
+
return loaded;
|
|
802
|
+
} catch (error) {
|
|
803
|
+
if (isRejectedRequest(error)) {
|
|
804
|
+
lastKnownGood.delete(key);
|
|
805
|
+
return NONE;
|
|
674
806
|
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
return {
|
|
679
|
-
action: (m) => m === "PUT" ? "reactions.add" : "reactions.remove",
|
|
680
|
-
methods: ["PUT", "DELETE"],
|
|
681
|
-
rebuild: (_method, body) => {
|
|
682
|
-
const type = body?.subject_type;
|
|
683
|
-
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;
|
|
684
|
-
if (!clean) return void 0;
|
|
685
|
-
const valid = type === "article" ? isSitePath(clean.path) : typeof clean.comment_id === "string" && UUID.test(clean.comment_id);
|
|
686
|
-
return valid ? { upstream: "/reactions", body: clean } : void 0;
|
|
807
|
+
if (error instanceof Cp1ClientError && (error.status === 401 || error.status === 403)) {
|
|
808
|
+
lastKnownGood.delete(key);
|
|
809
|
+
throw error;
|
|
687
810
|
}
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
if (!body || Object.keys(body).some((k) => !allowed.includes(k)) || !required.every((k) => k in body)) return void 0;
|
|
694
|
-
return Object.fromEntries(allowed.filter((k) => k in body).map((k) => [k, body[k]]));
|
|
811
|
+
const kept = lastKnownGood.get(key);
|
|
812
|
+
if (kept && Date.now() - kept.at <= MOUNTS_MAX_STALE_MS) return kept.loaded;
|
|
813
|
+
throw error;
|
|
814
|
+
}
|
|
815
|
+
};
|
|
695
816
|
}
|
|
696
|
-
|
|
697
|
-
|
|
817
|
+
var asArray = (options) => Array.isArray(options) ? options : [options];
|
|
818
|
+
function setup(options) {
|
|
819
|
+
const configs = asArray(options);
|
|
820
|
+
if (configs.length === 0) throw new TypeError("hyleRootPage: pass at least one workspace config");
|
|
821
|
+
const param = configs[0].param ?? "hyle";
|
|
822
|
+
if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
|
|
823
|
+
return { configs, param, loaders: configs.map(mountsLoader) };
|
|
698
824
|
}
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
try {
|
|
707
|
-
parsed = new URL(origin);
|
|
708
|
-
} catch {
|
|
709
|
-
return true;
|
|
710
|
-
}
|
|
711
|
-
if (req.headers.get(ENGAGE_CSRF_HEADER) !== "1") return true;
|
|
712
|
-
if (allowedOrigins) return !allowedOrigins.some((o) => safeOrigin(o) === parsed.origin);
|
|
713
|
-
const host = req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || req.headers.get("host") || new URL(req.url).host;
|
|
714
|
-
const proto = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
|
|
715
|
-
if (proto && proto !== parsed.protocol.slice(0, -1)) return true;
|
|
716
|
-
return parsed.host !== host;
|
|
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) };
|
|
717
832
|
}
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
if (Number(req.headers.get("content-length")) > MAX_BODY_BYTES) return { kind: "refused", response: refuse(413, "PAYLOAD_TOO_LARGE") };
|
|
729
|
-
if (!req.body) return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
|
|
730
|
-
const reader = req.body.getReader();
|
|
731
|
-
const chunks = [];
|
|
732
|
-
let total = 0;
|
|
733
|
-
for (; ; ) {
|
|
734
|
-
const { done, value } = await reader.read();
|
|
735
|
-
if (done) break;
|
|
736
|
-
total += value.byteLength;
|
|
737
|
-
if (total > MAX_BODY_BYTES) {
|
|
738
|
-
await reader.cancel().catch(() => {
|
|
833
|
+
function rootMounts(options) {
|
|
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 };
|
|
739
843
|
});
|
|
740
|
-
|
|
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;
|
|
741
855
|
}
|
|
742
|
-
|
|
743
|
-
}
|
|
744
|
-
try {
|
|
745
|
-
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
746
|
-
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return { kind: "ok", body: parsed };
|
|
747
|
-
} catch {
|
|
748
|
-
}
|
|
749
|
-
return { kind: "refused", response: refuse(400, "VALIDATION_ERROR") };
|
|
856
|
+
};
|
|
750
857
|
}
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
858
|
+
function createRouter(options, make) {
|
|
859
|
+
const mounts = rootMounts(options);
|
|
860
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
861
|
+
return async function route(params) {
|
|
862
|
+
const raw = params[mounts.param];
|
|
863
|
+
const segments = typeof raw === "string" ? [raw] : raw;
|
|
864
|
+
const path = sitePathFrom("", segments);
|
|
865
|
+
if (path === void 0 || path === "/" || !segments) return void 0;
|
|
866
|
+
const hit = await mounts.locate(path);
|
|
867
|
+
if (!hit) return void 0;
|
|
868
|
+
const { mount, index } = hit;
|
|
869
|
+
const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
|
|
870
|
+
let handler = handlers.get(id);
|
|
871
|
+
if (!handler) {
|
|
872
|
+
handler = make(hit.options);
|
|
873
|
+
handlers.set(id, handler);
|
|
874
|
+
}
|
|
875
|
+
return { handler, params: { ...params, [mounts.param]: segments.slice(mount.depth) } };
|
|
876
|
+
};
|
|
757
877
|
}
|
|
758
|
-
function
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
return refuse(429, "RATE_LIMITED", { "Retry-After": String(seconds) });
|
|
766
|
-
}
|
|
767
|
-
return refuse(502, "UPSTREAM_ERROR");
|
|
878
|
+
function hyleRootPage(options) {
|
|
879
|
+
const route = createRouter(options, hylePage);
|
|
880
|
+
return async function HyleRootPage({ params, searchParams }) {
|
|
881
|
+
const hit = await route(await params ?? {});
|
|
882
|
+
if (!hit) notFound2();
|
|
883
|
+
return hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} });
|
|
884
|
+
};
|
|
768
885
|
}
|
|
769
|
-
function
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
const clearCache = () => {
|
|
775
|
-
cache.clear();
|
|
776
|
-
cacheBytes = 0;
|
|
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) : {};
|
|
777
891
|
};
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
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
|
+
}
|
|
784
899
|
}
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
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
|
+
}
|
|
793
942
|
}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
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
|
+
}
|
|
806
968
|
}
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
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);
|
|
819
1010
|
try {
|
|
820
|
-
|
|
821
|
-
checkBaseUrl(baseUrl);
|
|
822
|
-
if (!options.token?.trim() || !options.workspaceId?.trim() || !options.signingKey) throw new TypeError("not provisioned");
|
|
823
|
-
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 } : {} });
|
|
824
1012
|
} catch {
|
|
825
|
-
|
|
1013
|
+
return empty(404);
|
|
826
1014
|
}
|
|
827
|
-
|
|
828
|
-
}
|
|
829
|
-
async function reader(req, config) {
|
|
1015
|
+
let upstream;
|
|
830
1016
|
try {
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
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
|
+
});
|
|
836
1021
|
} catch {
|
|
837
|
-
return
|
|
1022
|
+
return empty(502);
|
|
838
1023
|
}
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
const
|
|
842
|
-
if (
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
if (!config || !route) return refuse(404, "NOT_FOUND");
|
|
846
|
-
if (!route.methods.includes(req.method)) return refuse(405, "METHOD_NOT_ALLOWED", { Allow: route.methods.join(", ") });
|
|
847
|
-
const write = req.method !== "GET";
|
|
848
|
-
if (sameOriginProblem(req, write, options.allowedOrigins)) return refuse(403, "FORBIDDEN");
|
|
849
|
-
if (options.onRequest) {
|
|
850
|
-
try {
|
|
851
|
-
const early = await options.onRequest(req, { action: route.action(req.method) });
|
|
852
|
-
if (early instanceof Response) {
|
|
853
|
-
const headers = new Headers(early.headers);
|
|
854
|
-
headers.set("cache-control", "no-store");
|
|
855
|
-
return new Response(early.body, { status: early.status, headers });
|
|
856
|
-
}
|
|
857
|
-
} catch {
|
|
858
|
-
return refuse(502, "UPSTREAM_ERROR");
|
|
859
|
-
}
|
|
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 } : {} } });
|
|
860
1030
|
}
|
|
861
|
-
if (
|
|
862
|
-
|
|
863
|
-
|
|
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 } : {});
|
|
864
1035
|
}
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
if (
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
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);
|
|
872
1042
|
}
|
|
873
|
-
const
|
|
874
|
-
|
|
875
|
-
const
|
|
876
|
-
if (
|
|
877
|
-
|
|
878
|
-
if (
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
|
|
882
|
-
const call = async (withAssertion = assertion) => {
|
|
883
|
-
const headers = new Headers(baseHeaders);
|
|
884
|
-
if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
|
|
885
|
-
const res = await fetchImpl(target, {
|
|
886
|
-
method: req.method,
|
|
887
|
-
headers,
|
|
888
|
-
...built.body ? { body: JSON.stringify(built.body) } : {},
|
|
889
|
-
redirect: "error",
|
|
890
|
-
signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS2)
|
|
891
|
-
});
|
|
892
|
-
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") };
|
|
893
|
-
};
|
|
894
|
-
try {
|
|
895
|
-
const out = route.action(req.method) === "comments.list" ? await shared(`${viewer?.reader.sub ?? ""}
|
|
896
|
-
${built.query.toString()}`, () => listing(viewer, call)) : await call();
|
|
897
|
-
if (!out.ok) return relayFailure(out.status, out.retryAfter);
|
|
898
|
-
if (write) clearCache();
|
|
899
|
-
const data = JSON.parse(out.text).data;
|
|
900
|
-
return typeof data === "object" && data !== null ? json(out.status === 201 ? 201 : 200, { data }) : refuse(502, "UPSTREAM_ERROR");
|
|
901
|
-
} catch {
|
|
902
|
-
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 });
|
|
903
1051
|
}
|
|
1052
|
+
return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
|
|
904
1053
|
}
|
|
905
|
-
return { GET:
|
|
1054
|
+
return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
|
|
906
1055
|
}
|
|
907
1056
|
|
|
908
|
-
// src/next/
|
|
909
|
-
import { jsx as
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
} catch (error) {
|
|
914
|
-
if (isRejectedRequest(error)) return {};
|
|
915
|
-
console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
|
|
916
|
-
return { failure: options.onError ? options.onError(error) : null };
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
async function HyleList({ options, limit = 5, locale, layout, title, headingLevel, moreHref }) {
|
|
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) {
|
|
920
1062
|
const resolve = resolverFor(options);
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
const res = await fetch(`${options.baseUrl.replace(/\/+$/, "")}/cp1/engage/comments?${new URLSearchParams({ path })}`, init);
|
|
954
|
-
if (!res.ok) {
|
|
955
|
-
if (res.status !== 404) console.error(`hyle: comments answered HTTP ${res.status}`);
|
|
956
|
-
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
|
+
);
|
|
957
1095
|
}
|
|
958
|
-
|
|
959
|
-
const date = Date.parse(res.headers.get("date") ?? "");
|
|
960
|
-
fetchedAt = Number.isFinite(date) ? date : void 0;
|
|
961
|
-
} catch (error) {
|
|
962
|
-
unstable_rethrow4(error);
|
|
963
|
-
console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
|
|
964
|
-
return null;
|
|
965
|
-
}
|
|
966
|
-
if (!listing) return null;
|
|
967
|
-
if (!interactive) return /* @__PURE__ */ jsx2(HyleCommentsView, { listing, locale });
|
|
968
|
-
const config = interactive === true ? {} : interactive;
|
|
969
|
-
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
|
+
};
|
|
970
1097
|
}
|
|
971
1098
|
export {
|
|
972
1099
|
ENGAGE_CSRF_HEADER,
|
|
@@ -979,9 +1106,11 @@ export {
|
|
|
979
1106
|
createEngagementRoute,
|
|
980
1107
|
createLlmsTxtRoute,
|
|
981
1108
|
createMarkdownRoute,
|
|
1109
|
+
createOgImageRoute,
|
|
982
1110
|
createRevalidateRoute,
|
|
983
1111
|
fetchResolver,
|
|
984
1112
|
hyleFeed,
|
|
1113
|
+
hyleFeedLink,
|
|
985
1114
|
hyleMetadata,
|
|
986
1115
|
hylePage,
|
|
987
1116
|
hyleRootMetadata,
|