@tdacorp/hyle-sdk 0.9.0 → 0.12.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 +111 -2
- package/bin/hyle-sdk-engage-keygen.mjs +3 -0
- package/dist/check-routes-bin.js +5 -1
- package/dist/{chunk-54JF4E53.js → chunk-N7ZQUAGM.js} +45 -2
- package/dist/chunk-R5EMI4HQ.js +61 -0
- package/dist/{chunk-XKR74Y5G.js → chunk-S7PCCEHP.js} +1 -1
- package/dist/{chunk-6LW33475.js → chunk-ZQFYH4FX.js} +538 -50
- package/dist/comments.cjs +1048 -0
- package/dist/comments.d.cts +152 -0
- package/dist/comments.d.ts +152 -0
- package/dist/comments.js +1025 -0
- package/dist/{types-BPPZrYOZ.d.cts → embed-DL5QIZRJ.d.ts} +44 -3
- package/dist/{types-C1eCQ2As.d.ts → embed-jCaSI31t.d.cts} +44 -3
- package/dist/engage-keygen-bin.js +67 -0
- package/dist/index.cjs +26 -1
- package/dist/index.d.cts +11 -3
- package/dist/index.d.ts +11 -3
- package/dist/index.js +5 -1
- package/dist/mermaid-diagram.js +9 -54
- package/dist/next.cjs +1010 -78
- package/dist/next.d.cts +163 -6
- package/dist/next.d.ts +163 -6
- package/dist/next.js +442 -14
- package/dist/react.cjs +340 -49
- package/dist/react.d.cts +112 -7
- package/dist/react.d.ts +112 -7
- package/dist/react.js +7 -1
- package/dist/{resolve-Dpb6Orsj.d.ts → resolve-DvmuBlpO.d.ts} +1 -1
- package/dist/{resolve-D2rnnho9.d.cts → resolve-f6IJ6SL9.d.cts} +1 -1
- package/dist/styles.css +117 -0
- package/dist/{types-CHxH5E0S.d.cts → types-5D6ZD0Wi.d.cts} +59 -1
- package/dist/{types-CHxH5E0S.d.ts → types-5D6ZD0Wi.d.ts} +59 -1
- package/dist/use-cache.cjs +5 -1
- package/dist/use-cache.d.cts +2 -2
- package/dist/use-cache.d.ts +2 -2
- package/dist/use-cache.js +2 -2
- package/package.json +4 -3
package/dist/next.js
CHANGED
|
@@ -1,19 +1,32 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ArticlePage,
|
|
3
|
+
BARE_HTTPS_ORIGIN,
|
|
4
|
+
Comments,
|
|
3
5
|
DocsPage,
|
|
4
|
-
|
|
5
|
-
|
|
6
|
+
HyleArticleView,
|
|
7
|
+
HyleCommentsFallback,
|
|
8
|
+
HyleCommentsView,
|
|
9
|
+
HyleListView,
|
|
10
|
+
ListPage,
|
|
11
|
+
parseListing,
|
|
12
|
+
stringsFor
|
|
13
|
+
} from "./chunk-ZQFYH4FX.js";
|
|
6
14
|
import {
|
|
7
15
|
DEFAULT_REVALIDATE,
|
|
8
16
|
fetchResolver,
|
|
9
17
|
workspaceTags
|
|
10
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-S7PCCEHP.js";
|
|
11
19
|
import {
|
|
12
20
|
Cp1ClientError,
|
|
21
|
+
checkBaseUrl,
|
|
22
|
+
cleanDisplayName,
|
|
13
23
|
createHyleClient,
|
|
14
24
|
createRevalidationCallbackRoute,
|
|
15
|
-
|
|
16
|
-
|
|
25
|
+
engagementSigningKey,
|
|
26
|
+
listPublicationPaths,
|
|
27
|
+
readCapped,
|
|
28
|
+
signReaderAssertion
|
|
29
|
+
} from "./chunk-N7ZQUAGM.js";
|
|
17
30
|
import {
|
|
18
31
|
ASSET_CONTENT_TYPES,
|
|
19
32
|
ASSET_FILE
|
|
@@ -91,7 +104,7 @@ function hylePage(options) {
|
|
|
91
104
|
switch (result.kind) {
|
|
92
105
|
case "article": {
|
|
93
106
|
const props = { article: result, components: options.components, slots: options.slots, locale, toHref };
|
|
94
|
-
return options.layout === "docs" ? /* @__PURE__ */ jsx(DocsPage, { ...props }) : /* @__PURE__ */ jsx(ArticlePage, { ...props });
|
|
107
|
+
return options.layout === "docs" ? /* @__PURE__ */ jsx(DocsPage, { ...props }) : /* @__PURE__ */ jsx(ArticlePage, { ...props, origin: options.siteOrigin, ...options.engagement ? { engagement: options.engagement } : {} });
|
|
95
108
|
}
|
|
96
109
|
case "list": {
|
|
97
110
|
const list = options.list?.title ? { ...result, section: { ...result.section, title: options.list.title } } : result;
|
|
@@ -153,26 +166,36 @@ async function hyleSitemap(options) {
|
|
|
153
166
|
// src/next/metadata.ts
|
|
154
167
|
function hyleMetadata(options) {
|
|
155
168
|
const resolve = resolverFor(options);
|
|
156
|
-
return async function generateMetadata({ params }) {
|
|
169
|
+
return async function generateMetadata({ params, searchParams }) {
|
|
157
170
|
const { path, locale, toHref } = routeContext(options, await params ?? {});
|
|
158
171
|
if (path === void 0) return {};
|
|
159
172
|
try {
|
|
160
|
-
const
|
|
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);
|
|
161
175
|
if (result.kind === "list") {
|
|
162
|
-
const title = options.list?.title || result.section.title;
|
|
176
|
+
const title = (options.list?.title || result.section.title) + (cursor ? ` - ${stringsFor(locale).older}` : "");
|
|
163
177
|
const description2 = options.list?.description;
|
|
164
|
-
return {
|
|
178
|
+
return {
|
|
179
|
+
title,
|
|
180
|
+
...description2 ? { description: description2 } : {},
|
|
181
|
+
alternates: { canonical: toHref(path) + (cursor ? `?cursor=${cursor}` : "") },
|
|
182
|
+
openGraph: { title, ...description2 ? { description: description2 } : {} }
|
|
183
|
+
};
|
|
165
184
|
}
|
|
166
185
|
if (result.kind !== "article") return {};
|
|
167
|
-
const { publication: pub, alternates } = result;
|
|
186
|
+
const { publication: pub, alternates, default_locale } = result;
|
|
168
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;
|
|
169
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;
|
|
170
193
|
return {
|
|
171
194
|
title: pub.title,
|
|
172
195
|
...description ? { description } : {},
|
|
173
196
|
alternates: {
|
|
174
197
|
canonical,
|
|
175
|
-
...alternates.length > 1 ? { languages: Object.fromEntries(alternates.map((a) => [a.locale, toHref(a.canonical_path, a.locale)])) } : {}
|
|
198
|
+
...alternates.length > 1 ? { languages: { ...Object.fromEntries(alternates.map((a) => [a.locale, toHref(a.canonical_path, a.locale)])), "x-default": xDefault } } : {}
|
|
176
199
|
},
|
|
177
200
|
openGraph: {
|
|
178
201
|
type: "article",
|
|
@@ -181,7 +204,8 @@ function hyleMetadata(options) {
|
|
|
181
204
|
url: canonical,
|
|
182
205
|
locale: pub.locale,
|
|
183
206
|
publishedTime: pub.published_at,
|
|
184
|
-
modifiedTime:
|
|
207
|
+
...modified ? { modifiedTime: modified } : {},
|
|
208
|
+
...author ? { authors: [author] } : {}
|
|
185
209
|
}
|
|
186
210
|
};
|
|
187
211
|
} catch (error) {
|
|
@@ -191,6 +215,48 @@ function hyleMetadata(options) {
|
|
|
191
215
|
};
|
|
192
216
|
}
|
|
193
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);
|
|
228
|
+
}
|
|
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
|
+
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);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
194
260
|
// src/next/revalidate.ts
|
|
195
261
|
import { revalidateTag } from "next/cache";
|
|
196
262
|
var isSwitchedOff = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
|
|
@@ -205,7 +271,7 @@ function createRevalidateRoute(options) {
|
|
|
205
271
|
if (!workspaceId || secrets.length === 0) return new Response(null, { status: 503 });
|
|
206
272
|
const key = `${workspaceId}\0${secrets.join("\0")}`;
|
|
207
273
|
if (cached?.key !== key) {
|
|
208
|
-
cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (
|
|
274
|
+
cached = { key, route: createRevalidationCallbackRoute({ workspaceId, secrets, revalidateTag: (tag2) => revalidateTag(tag2, { expire: 0 }) }) };
|
|
209
275
|
}
|
|
210
276
|
return cached.route.POST(req);
|
|
211
277
|
}
|
|
@@ -404,11 +470,373 @@ function createAssetRoute(options) {
|
|
|
404
470
|
}
|
|
405
471
|
return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
|
|
406
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;
|
|
634
|
+
};
|
|
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 };
|
|
641
|
+
}
|
|
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;
|
|
650
|
+
}
|
|
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]);
|
|
663
|
+
}
|
|
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;
|
|
676
|
+
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()) };
|
|
681
|
+
} catch {
|
|
682
|
+
ready = null;
|
|
683
|
+
}
|
|
684
|
+
return ready;
|
|
685
|
+
}
|
|
686
|
+
async function reader(req, config) {
|
|
687
|
+
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 };
|
|
693
|
+
} catch {
|
|
694
|
+
return null;
|
|
695
|
+
}
|
|
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
|
+
}
|
|
717
|
+
}
|
|
718
|
+
if (route.local === "session") {
|
|
719
|
+
const who = await reader(req, config);
|
|
720
|
+
return json(200, { data: { reader: who ? { name: who.reader.name } : null } });
|
|
721
|
+
}
|
|
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;
|
|
729
|
+
}
|
|
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");
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
return { GET: handle, POST: handle, PATCH: handle, PUT: handle, DELETE: handle };
|
|
763
|
+
}
|
|
764
|
+
|
|
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;
|
|
787
|
+
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;
|
|
814
|
+
}
|
|
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 }) });
|
|
827
|
+
}
|
|
407
828
|
export {
|
|
829
|
+
ENGAGE_CSRF_HEADER,
|
|
830
|
+
HyleArticle,
|
|
831
|
+
HyleComments,
|
|
832
|
+
HyleCommentsFallback,
|
|
833
|
+
HyleList,
|
|
408
834
|
MOUNTS_MAX_STALE_MS,
|
|
409
835
|
createAssetRoute,
|
|
836
|
+
createEngagementRoute,
|
|
410
837
|
createRevalidateRoute,
|
|
411
838
|
fetchResolver,
|
|
839
|
+
hyleFeed,
|
|
412
840
|
hyleMetadata,
|
|
413
841
|
hylePage,
|
|
414
842
|
hyleRootMetadata,
|