@tdacorp/hyle-sdk 0.23.0 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +36 -18
  2. package/dist/check-routes-bin.js +34 -16
  3. package/dist/{chunk-UFMKLCXS.js → chunk-5TKJH2XC.js} +2 -2
  4. package/dist/{chunk-VXARM37R.js → chunk-BDFMNY76.js} +11 -5
  5. package/dist/{chunk-VUML2UPD.js → chunk-O4QWHXVH.js} +1 -1
  6. package/dist/{chunk-YHXE3TGS.js → chunk-RCK4NCYC.js} +33 -16
  7. package/dist/{chunk-JHZJOJDC.js → chunk-Y3BACEWA.js} +1 -1
  8. package/dist/{client-DK-S2580.d.cts → client-CI-3cHtc.d.cts} +13 -5
  9. package/dist/{client--ighAWaj.d.ts → client-DN38IP63.d.ts} +13 -5
  10. package/dist/comments.cjs +3 -2
  11. package/dist/comments.js +3 -2
  12. package/dist/{embed-g7NT1CyB.d.ts → embed-BaLQbE_n.d.ts} +1 -1
  13. package/dist/{embed-XT0x_Jaa.d.cts → embed-BrrGgkgQ.d.cts} +1 -1
  14. package/dist/html.cjs +3 -2
  15. package/dist/html.js +2 -2
  16. package/dist/index.cjs +34 -16
  17. package/dist/index.d.cts +3 -3
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.js +2 -2
  20. package/dist/next.cjs +316 -184
  21. package/dist/next.d.cts +46 -31
  22. package/dist/next.d.ts +46 -31
  23. package/dist/next.js +265 -154
  24. package/dist/react.cjs +3 -2
  25. package/dist/react.d.cts +3 -3
  26. package/dist/react.d.ts +3 -3
  27. package/dist/react.js +3 -3
  28. package/dist/{resolve-CiZCPysX.d.cts → resolve-Ce_yz8gC.d.cts} +1 -1
  29. package/dist/{resolve-BqC9l5RH.d.ts → resolve-DMHbYyTS.d.ts} +1 -1
  30. package/dist/{types-b9QbmEDd.d.cts → types-CxE8kLeo.d.cts} +30 -5
  31. package/dist/{types-b9QbmEDd.d.ts → types-CxE8kLeo.d.ts} +30 -5
  32. package/dist/use-cache.cjs +34 -16
  33. package/dist/use-cache.d.cts +3 -3
  34. package/dist/use-cache.d.ts +3 -3
  35. package/dist/use-cache.js +3 -3
  36. package/package.json +1 -1
package/dist/next.cjs CHANGED
@@ -42,6 +42,7 @@ __export(next_exports, {
42
42
  hylePreviewPage: () => hylePreviewPage,
43
43
  hyleProtectedMetadata: () => hyleProtectedMetadata,
44
44
  hyleProtectedPage: () => hyleProtectedPage,
45
+ hyleProtectedProxy: () => hyleProtectedProxy,
45
46
  hyleRootMetadata: () => hyleRootMetadata,
46
47
  hyleRootPage: () => hyleRootPage,
47
48
  hyleRootSitemap: () => hyleRootSitemap,
@@ -75,10 +76,15 @@ var PREVIEW_PARAM = "hyle_preview";
75
76
  var PREVIEW_QUERY_SOURCE = `\\?${PREVIEW_PARAM}=${PREVIEW_TOKEN_SOURCE}`;
76
77
  var PROTECTED_PARAM = "hyle_protected";
77
78
  var PROTECTED_HEADER = "cp-protected";
78
- var PROTECTED_ID = new RegExp(`^${UUID}$`);
79
- var PROTECTED_PASSWORD = /^[A-Za-z0-9]{16}$/;
80
- var protectedCookieName = (pageId) => `hyle_p_${pageId}`;
81
- var PROTECTED_QUERY_SOURCE = `\\?${PROTECTED_PARAM}=${UUID}`;
79
+ var SHARE_SLUG = "[a-z0-9-]+(?:/[a-z0-9-]+){0,3}";
80
+ var PROTECTED_SLUG = new RegExp(`^${SHARE_SLUG}$`);
81
+ var PROTECTED_DOC_SLUG = /^[a-z0-9-]+$/;
82
+ var PROTECTED_PASSWORD = /^[\x21\x23-\x24\x26-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]{12,128}$/;
83
+ async function protectedCookieName(slug) {
84
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(slug));
85
+ return `hyle_p_${Buffer.from(digest).toString("base64url").slice(0, 16)}`;
86
+ }
87
+ var PROTECTED_QUERY_SOURCE = `\\?${PROTECTED_PARAM}=${SHARE_SLUG}`;
82
88
  var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)(${PREVIEW_QUERY_SOURCE}|${PROTECTED_QUERY_SOURCE})?$`, "i");
83
89
  function hostAssetSrc(src) {
84
90
  const [, file, query = ""] = HYLE_ASSET_URL.exec(src) ?? [];
@@ -143,17 +149,19 @@ function withAssetQuery(article, query) {
143
149
 
144
150
  // src/client.ts
145
151
  var RENDERER_VERSION = "4";
146
- function applyCredential(headers, credential, method, url) {
152
+ function applyCredential(headers2, credential, method, url) {
147
153
  if (!credential.auth) {
148
- headers.set("authorization", `Bearer ${credential.token}`);
154
+ headers2.set("authorization", `Bearer ${credential.token}`);
149
155
  return void 0;
150
156
  }
151
157
  const { workspaceId } = credential;
152
158
  return credential.auth({ method, url }).then((extra) => {
153
- for (const [name, value] of Object.entries(extra)) headers.set(name, value);
154
- headers.set("cp-workspace", workspaceId);
159
+ for (const [name, value] of Object.entries(extra)) headers2.set(name, value);
160
+ headers2.set("cp-workspace", workspaceId);
155
161
  });
156
162
  }
163
+ var IP_LITERAL = /^[0-9a-fA-F:.]{2,45}$/;
164
+ var visitorHeaders = ({ clientIp }) => clientIp !== void 0 && IP_LITERAL.test(clientIp) ? { "x-forwarded-for": clientIp } : {};
157
165
  var DEFAULT_TIMEOUT_MS = 1e4;
158
166
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
159
167
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -191,7 +199,7 @@ var KINDS = /* @__PURE__ */ new Set(["article", "list", "redirect", "notfound",
191
199
  var isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
192
200
  function isMounts(data) {
193
201
  const mounts = data.mounts;
194
- return typeof data.workspace_id === "string" && isStrings(data.reserved) && isStrings(data.supported_locales) && Array.isArray(mounts) && mounts.every((m) => typeof m?.prefix === "string" && typeof m.default_section === "string");
202
+ return typeof data.workspace_id === "string" && isStrings(data.reserved) && isStrings(data.supported_locales) && Array.isArray(mounts) && mounts.every((m) => typeof m?.prefix === "string" && typeof m.default_section === "string") && (data.protected === void 0 || isStrings(data.protected));
195
203
  }
196
204
  function checkBaseUrl(baseUrl, allowInsecureHttp) {
197
205
  let origin;
@@ -212,13 +220,13 @@ function createHyleClient(options) {
212
220
  async function get(pathname, query, init) {
213
221
  const url = new URL(`${base}${pathname}`);
214
222
  url.search = query.toString();
215
- const headers = new Headers(init?.headers);
216
- headers.set("cp-renderer-version", RENDERER_VERSION);
217
- const applied = applyCredential(headers, options, "GET", url.toString());
223
+ const headers2 = new Headers(init?.headers);
224
+ headers2.set("cp-renderer-version", RENDERER_VERSION);
225
+ const applied = applyCredential(headers2, options, "GET", url.toString());
218
226
  if (applied) await applied;
219
227
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
220
228
  const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
221
- const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
229
+ const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers: headers2, redirect: "error", signal });
222
230
  const text = await readCapped(res, options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES);
223
231
  let parsed;
224
232
  try {
@@ -226,7 +234,7 @@ function createHyleClient(options) {
226
234
  } catch {
227
235
  parsed = void 0;
228
236
  }
229
- return { parsed, status: res.status };
237
+ return { parsed, status: res.status, retryAfter: res.headers.get("retry-after") };
230
238
  }
231
239
  const failure = ({ parsed, status }) => {
232
240
  const err = parsed?.error;
@@ -274,44 +282,58 @@ function createHyleClient(options) {
274
282
  if (data?.cp !== 1 || data.kind !== "preview" || typeof data.expires_at !== "string" || article?.kind !== "article" || article.content?.format !== "hast" || !article.publication) throw failure(reply2);
275
283
  return { kind: "preview", expires_at: data.expires_at, article: withAssetQuery(article, `${PREVIEW_PARAM}=${token}`) };
276
284
  }
277
- async function protectedPage(pageId, password) {
278
- if (!PROTECTED_ID.test(pageId) || !PROTECTED_PASSWORD.test(password)) return { kind: "notfound" };
279
- const reply2 = await get("/cp1/read/_protected", new URLSearchParams(), { headers: { [PROTECTED_HEADER]: `${pageId}.${password}` }, cache: "no-store" });
285
+ const limited = ({ retryAfter }) => ({ kind: "limited", retryAfterSeconds: Math.min(3600, Math.max(1, Math.trunc(Number(retryAfter)) || 60)) });
286
+ async function protectedGate(slug, opts = {}) {
287
+ if (!PROTECTED_SLUG.test(slug)) return { kind: "notfound" };
288
+ const reply2 = await get("/cp1/read/_protected/gate", new URLSearchParams({ path: slug }), { headers: visitorHeaders(opts), cache: "no-store" });
289
+ if (reply2.status === 429) return limited(reply2);
290
+ if (reply2.status === 404 && reply2.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
291
+ const data = reply2.parsed?.data;
292
+ if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
293
+ if (data?.cp === 1 && data.kind === "gate") return { kind: "gate" };
294
+ throw failure(reply2);
295
+ }
296
+ async function protectedShare(slug, password, docSlug, opts = {}) {
297
+ if (!PROTECTED_SLUG.test(slug) || docSlug !== void 0 && !PROTECTED_DOC_SLUG.test(docSlug) || !PROTECTED_PASSWORD.test(password)) return { kind: "notfound" };
298
+ const path = docSlug === void 0 ? slug : `${slug}/${docSlug}`;
299
+ const reply2 = await get("/cp1/read/_protected", new URLSearchParams({ path }), { headers: { ...visitorHeaders(opts), [PROTECTED_HEADER]: password }, cache: "no-store" });
300
+ if (reply2.status === 429) return limited(reply2);
280
301
  if (reply2.status === 404 && reply2.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
281
302
  const data = reply2.parsed?.data;
282
303
  if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
283
304
  const article = data?.article;
284
- const expires = data?.expires_at;
285
- if (data?.cp !== 1 || data.kind !== "protected" || typeof expires !== "string" && expires !== null || article?.kind !== "article" || article.content?.format !== "hast" || !article.publication) throw failure(reply2);
286
- return { kind: "protected", expires_at: expires, article: withAssetQuery(article, `${PROTECTED_PARAM}=${pageId}`) };
305
+ const { name, expires_at: expires, documents, doc_slug: current } = data ?? {};
306
+ if (data?.cp !== 1 || data.kind !== "protected" || typeof name !== "string" || typeof expires !== "string" && expires !== null || !Array.isArray(documents) || typeof current !== "string" || article?.kind !== "article" || article.content?.format !== "hast" || !article.publication) throw failure(reply2);
307
+ return { cp: 1, kind: "protected", name, expires_at: expires, documents, doc_slug: current, article: withAssetQuery(article, `${PROTECTED_PARAM}=${slug}`) };
287
308
  }
288
309
  async function asset(file, opts = {}) {
289
310
  if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
290
311
  const { previewToken } = opts;
291
312
  if (previewToken !== void 0 && !PREVIEW_TOKEN.test(previewToken)) throw new TypeError("previewToken is not a preview token");
292
- const url = `${base}/cp1/read/assets/${file}`;
293
- const headers = new Headers();
294
- const applied = applyCredential(headers, options, "GET", url);
313
+ const { protectedAccess } = opts;
314
+ if (protectedAccess !== void 0 && !(PROTECTED_SLUG.test(protectedAccess.slug) && PROTECTED_PASSWORD.test(protectedAccess.password))) throw new TypeError("protectedAccess is not a share slug and password");
315
+ const query = protectedAccess === void 0 ? "" : `?protected=${encodeURIComponent(protectedAccess.slug)}`;
316
+ const url = `${base}/cp1/read/assets/${file}${query}`;
317
+ const headers2 = new Headers();
318
+ const applied = applyCredential(headers2, options, "GET", url);
295
319
  if (applied) await applied;
296
320
  for (const name of ["range", "if-range", "if-none-match"]) {
297
321
  const value = opts.headers?.[name];
298
- if (value) headers.set(name, value);
322
+ if (value) headers2.set(name, value);
299
323
  }
300
- const { protectedAccess } = opts;
301
- if (protectedAccess !== void 0 && !(PROTECTED_ID.test(protectedAccess.pageId) && PROTECTED_PASSWORD.test(protectedAccess.password))) throw new TypeError("protectedAccess is not a page id and password");
302
- if (previewToken !== void 0) headers.set(PREVIEW_HEADER, previewToken);
303
- if (protectedAccess !== void 0) headers.set(PROTECTED_HEADER, `${protectedAccess.pageId}.${protectedAccess.password}`);
324
+ if (previewToken !== void 0) headers2.set(PREVIEW_HEADER, previewToken);
325
+ if (protectedAccess !== void 0) headers2.set(PROTECTED_HEADER, protectedAccess.password);
304
326
  const uncached = previewToken !== void 0 || protectedAccess !== void 0;
305
- return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS), ...uncached ? { cache: "no-store" } : {} });
327
+ return fetchImpl(url, { method: "GET", headers: headers2, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS), ...uncached ? { cache: "no-store" } : {} });
306
328
  }
307
329
  async function theme(opts = {}) {
308
330
  const url = `${base}/cp1/read/theme.css`;
309
- const headers = new Headers();
310
- const applied = applyCredential(headers, options, "GET", url);
331
+ const headers2 = new Headers();
332
+ const applied = applyCredential(headers2, options, "GET", url);
311
333
  if (applied) await applied;
312
- return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
334
+ return fetchImpl(url, { method: "GET", headers: headers2, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
313
335
  }
314
- return { resolve, mounts, pushPosts, preview, protected: protectedPage, asset, theme };
336
+ return { resolve, mounts, pushPosts, preview, protectedGate, protected: protectedShare, asset, theme };
315
337
  }
316
338
 
317
339
  // src/delivery-dedupe.ts
@@ -2700,9 +2722,9 @@ function createEngagementRoute(options) {
2700
2722
  try {
2701
2723
  const early = await options.onRequest(req, { action: route.action(req.method) });
2702
2724
  if (early instanceof Response) {
2703
- const headers = new Headers(early.headers);
2704
- headers.set("cache-control", "no-store");
2705
- return new Response(early.body, { status: early.status, headers });
2725
+ const headers2 = new Headers(early.headers);
2726
+ headers2.set("cache-control", "no-store");
2727
+ return new Response(early.body, { status: early.status, headers: headers2 });
2706
2728
  }
2707
2729
  } catch {
2708
2730
  return refuse(502, "UPSTREAM_ERROR");
@@ -2730,11 +2752,11 @@ function createEngagementRoute(options) {
2730
2752
  if (built.body) baseHeaders.set("content-type", "application/json");
2731
2753
  const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
2732
2754
  const call = async (withAssertion = assertion) => {
2733
- const headers = new Headers(baseHeaders);
2734
- if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
2755
+ const headers2 = new Headers(baseHeaders);
2756
+ if (withAssertion) headers2.set("hyle-reader-assertion", withAssertion);
2735
2757
  const res = await fetchImpl(target, {
2736
2758
  method: req.method,
2737
- headers,
2759
+ headers: headers2,
2738
2760
  ...built.body ? { body: JSON.stringify(built.body) } : {},
2739
2761
  redirect: "error",
2740
2762
  signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS2)
@@ -3056,7 +3078,7 @@ function hyleMetadata(options) {
3056
3078
  var import_navigation4 = require("next/navigation");
3057
3079
  var xml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
3058
3080
  var tag = (name, value) => `<${name}>${xml(value)}</${name}>`;
3059
- var response = (body, status, headers) => new Response(body, { status, ...headers ? { headers } : {} });
3081
+ var response = (body, status, headers2) => new Response(body, { status, ...headers2 ? { headers: headers2 } : {} });
3060
3082
  async function hyleFeed(options) {
3061
3083
  const origin = options.siteOrigin;
3062
3084
  if (!origin || !BARE_HTTPS_ORIGIN.test(origin)) {
@@ -3116,7 +3138,7 @@ function createRevalidateRoute(options) {
3116
3138
  }
3117
3139
 
3118
3140
  // src/next/root.ts
3119
- var import_navigation5 = require("next/navigation");
3141
+ var import_navigation7 = require("next/navigation");
3120
3142
 
3121
3143
  // src/next/mount-match.ts
3122
3144
  function activeMounts(mounts) {
@@ -3142,28 +3164,174 @@ function isReserved(path, reserved) {
3142
3164
  return reserved.some((entry) => entry.endsWith("/*") ? prefixMatches(entry.slice(0, -2), path) : entry === path);
3143
3165
  }
3144
3166
 
3167
+ // src/next/protected.tsx
3168
+ var import_headers = require("next/headers");
3169
+ var import_navigation6 = require("next/navigation");
3170
+
3171
+ // src/next/preview.tsx
3172
+ var import_navigation5 = require("next/navigation");
3173
+ var import_jsx_runtime13 = require("react/jsx-runtime");
3174
+ function drawArticle(article, options) {
3175
+ const { locale } = article.publication;
3176
+ const toHref = (sitePath, linkLocale = locale) => (options.localePrefix?.(linkLocale) ?? "") + sitePath;
3177
+ const props = { article, components: options.components, slots: options.slots, locale, toHref };
3178
+ return options.layout === "docs" ? /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(DocsPage, { ...props }) : /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(ArticlePage, { ...props });
3179
+ }
3180
+ var hylePreviewMetadata = { robots: { index: false, follow: false }, referrer: "no-referrer" };
3181
+ var BANNER = {
3182
+ position: "sticky",
3183
+ top: 0,
3184
+ zIndex: 2147483647,
3185
+ padding: "8px 16px",
3186
+ background: "#fde047",
3187
+ color: "#1a1a1a",
3188
+ font: "600 14px/1.4 system-ui, sans-serif",
3189
+ textAlign: "center"
3190
+ };
3191
+ function hylePreviewPage(options) {
3192
+ return async function HylePreviewPage({ searchParams }) {
3193
+ const { token } = await searchParams ?? {};
3194
+ const result = await createHyleClient(options).preview(typeof token === "string" ? token : void 0);
3195
+ if (result.kind !== "preview") (0, import_navigation5.notFound)();
3196
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(import_jsx_runtime13.Fragment, { children: [
3197
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("meta", { name: "robots", content: "noindex, nofollow" }),
3198
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("meta", { name: "referrer", content: "no-referrer" }),
3199
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { role: "status", style: BANNER, children: "Unpublished draft preview" }),
3200
+ drawArticle(result.article, options)
3201
+ ] });
3202
+ };
3203
+ }
3204
+
3205
+ // src/next/protected.tsx
3206
+ var import_jsx_runtime14 = require("react/jsx-runtime");
3207
+ var hyleProtectedMetadata = { robots: { index: false, follow: false }, referrer: "no-referrer" };
3208
+ var COOKIE_MAX_AGE_SECONDS = 12 * 60 * 60;
3209
+ var UNLOCK_MAX_BYTES = 1024;
3210
+ var PRIVATE_HEADERS = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
3211
+ var UNLOCK_PATH = "/hyle-protected/unlock";
3212
+ var PASSWORD_FIELD = "hyle-protected-password";
3213
+ var ERROR_ID = "hyle-protected-error";
3214
+ function PasswordForm({ slug, failed }) {
3215
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("main", { children: [
3216
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("h1", { children: "Password required" }),
3217
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("form", { method: "post", action: UNLOCK_PATH, autoComplete: "off", children: [
3218
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("input", { type: "hidden", name: "slug", value: slug }),
3219
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("label", { htmlFor: PASSWORD_FIELD, children: "Password" }),
3220
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
3221
+ "input",
3222
+ {
3223
+ id: PASSWORD_FIELD,
3224
+ name: "password",
3225
+ type: "password",
3226
+ autoComplete: "off",
3227
+ spellCheck: false,
3228
+ required: true,
3229
+ minLength: 12,
3230
+ maxLength: 128,
3231
+ "aria-invalid": failed || void 0,
3232
+ "aria-describedby": failed ? ERROR_ID : void 0
3233
+ }
3234
+ ),
3235
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("button", { type: "submit", children: "Open" }),
3236
+ failed ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("p", { id: ERROR_ID, role: "alert", children: "Wrong or expired password." }) : null
3237
+ ] })
3238
+ ] });
3239
+ }
3240
+ function TooManyAttempts({ seconds }) {
3241
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("main", { children: [
3242
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("h1", { children: "Too many attempts, try again later" }),
3243
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("p", { role: "alert", children: [
3244
+ "Try again in ",
3245
+ seconds,
3246
+ " ",
3247
+ seconds === 1 ? "second" : "seconds",
3248
+ "."
3249
+ ] })
3250
+ ] });
3251
+ }
3252
+ var PRIVATE_META = /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
3253
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("meta", { name: "robots", content: "noindex, nofollow" }),
3254
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("meta", { name: "referrer", content: "no-referrer" })
3255
+ ] });
3256
+ async function drawProtectedShare(options, slug, docSlug, clientIp) {
3257
+ const client = createHyleClient({ baseUrl: options.baseUrl, token: options.token });
3258
+ const visitor = { clientIp };
3259
+ const password = (await (0, import_headers.cookies)()).get(await protectedCookieName(slug))?.value;
3260
+ const share = password === void 0 ? void 0 : await client.protected(slug, password, docSlug, visitor);
3261
+ if (share?.kind === "limited") return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
3262
+ PRIVATE_META,
3263
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(TooManyAttempts, { seconds: share.retryAfterSeconds })
3264
+ ] });
3265
+ if (share?.kind === "disabled") (0, import_navigation6.notFound)();
3266
+ if (share?.kind === "protected") {
3267
+ if (docSlug !== void 0 && share.doc_slug !== docSlug) (0, import_navigation6.notFound)();
3268
+ const here = `/${slug}/${share.doc_slug}`;
3269
+ const article = {
3270
+ ...share.article,
3271
+ publication: { ...share.article.publication, canonical_path: here },
3272
+ nav: { truncated: false, items: share.documents.map((d) => ({ slug: d.doc_slug, title: d.title, canonical_path: `/${slug}/${d.doc_slug}`, children: [] })) }
3273
+ };
3274
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
3275
+ PRIVATE_META,
3276
+ drawArticle(article, { ...options, layout: share.documents.length > 1 ? "docs" : "article" })
3277
+ ] });
3278
+ }
3279
+ const gate = await client.protectedGate(slug, visitor);
3280
+ if (gate.kind === "limited") return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
3281
+ PRIVATE_META,
3282
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(TooManyAttempts, { seconds: gate.retryAfterSeconds })
3283
+ ] });
3284
+ if (gate.kind !== "gate") (0, import_navigation6.notFound)();
3285
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
3286
+ PRIVATE_META,
3287
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(PasswordForm, { slug, failed: password !== void 0 })
3288
+ ] });
3289
+ }
3290
+ function createProtectedUnlockRoute() {
3291
+ return {
3292
+ async POST(req) {
3293
+ const site = req.headers.get("sec-fetch-site");
3294
+ if (site === null ? originMismatch(req) : site !== "same-origin") return new Response(null, { status: 403, headers: PRIVATE_HEADERS });
3295
+ if (!/^application\/x-www-form-urlencoded(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return new Response(null, { status: 415, headers: PRIVATE_HEADERS });
3296
+ if (Number(req.headers.get("content-length")) > UNLOCK_MAX_BYTES) return new Response(null, { status: 413, headers: PRIVATE_HEADERS });
3297
+ const form = await readCapped(new Response(req.body), UNLOCK_MAX_BYTES).catch(() => void 0);
3298
+ if (form === void 0) return new Response(null, { status: 413, headers: PRIVATE_HEADERS });
3299
+ const fields = new URLSearchParams(form);
3300
+ const slug = fields.get("slug") ?? "";
3301
+ if (!PROTECTED_SLUG.test(slug)) return new Response(null, { status: 404, headers: PRIVATE_HEADERS });
3302
+ const password = fields.get("password") ?? "";
3303
+ const headers2 = new Headers({ ...PRIVATE_HEADERS, Location: `/${slug}` });
3304
+ if (PROTECTED_PASSWORD.test(password)) {
3305
+ const name = await protectedCookieName(slug);
3306
+ for (const path of [`/${slug}`, ASSET_ROUTE_PREFIX]) headers2.append("Set-Cookie", `${name}=${password}; Max-Age=${COOKIE_MAX_AGE_SECONDS}; Path=${path}; HttpOnly; Secure; SameSite=Lax`);
3307
+ }
3308
+ return new Response(null, { status: 303, headers: headers2 });
3309
+ }
3310
+ };
3311
+ }
3312
+
3145
3313
  // src/next/root.ts
3146
3314
  var MOUNTS_MAX_STALE_MS = 15 * 60 * 1e3;
3147
3315
  var SECTION_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
3148
- var NONE = { mounts: [], reserved: [], defaultLocale: "" };
3316
+ var NONE = { mounts: [], reserved: [], defaultLocale: "", protected: [] };
3149
3317
  var lastKnownGood = /* @__PURE__ */ new Map();
3150
- function mountsLoader(config) {
3318
+ function mountsLoader(config, ttlMs) {
3151
3319
  if (!config.workspaceId) throw new TypeError("hyleRootPage: `workspaceId` is required for the fetch cache");
3152
3320
  const client = createHyleClient({ baseUrl: config.baseUrl, token: config.token });
3153
3321
  const init = { next: { revalidate: config.revalidate ?? DEFAULT_REVALIDATE, tags: workspaceTags(config.workspaceId).slice(0, 1) } };
3154
3322
  const key = `${new URL(config.baseUrl).origin}|${config.workspaceId}`;
3155
- return async function load() {
3323
+ async function fetchLoaded() {
3156
3324
  try {
3157
3325
  const result = await client.mounts({ init });
3158
3326
  if (result.kind !== "mounts") {
3159
3327
  lastKnownGood.delete(key);
3160
3328
  return NONE;
3161
3329
  }
3162
- const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale };
3330
+ const loaded = { mounts: activeMounts(result.mounts), reserved: result.reserved, defaultLocale: result.default_locale, protected: result.protected ?? [] };
3163
3331
  lastKnownGood.set(key, { loaded, at: Date.now() });
3164
3332
  return loaded;
3165
3333
  } catch (error) {
3166
- (0, import_navigation5.unstable_rethrow)(error);
3334
+ (0, import_navigation7.unstable_rethrow)(error);
3167
3335
  if (error instanceof Cp1ClientError && (error.status === 401 || error.status === 403)) {
3168
3336
  lastKnownGood.delete(key);
3169
3337
  throw error;
@@ -3172,15 +3340,35 @@ function mountsLoader(config) {
3172
3340
  if (kept && Date.now() - kept.at <= MOUNTS_MAX_STALE_MS) return kept.loaded;
3173
3341
  throw error;
3174
3342
  }
3343
+ }
3344
+ if (ttlMs === void 0) return fetchLoaded;
3345
+ let ready;
3346
+ let read;
3347
+ let until = 0;
3348
+ let pending = false;
3349
+ return function load() {
3350
+ if (until <= Date.now() && !pending) {
3351
+ pending = true;
3352
+ until = Date.now() + ttlMs;
3353
+ read = fetchLoaded().then(
3354
+ (loaded) => ready = loaded,
3355
+ (error) => {
3356
+ ready = void 0;
3357
+ throw error;
3358
+ }
3359
+ );
3360
+ read.then(() => pending = false, () => pending = false);
3361
+ }
3362
+ return ready ? Promise.resolve(ready) : read;
3175
3363
  };
3176
3364
  }
3177
3365
  var asArray = (options) => Array.isArray(options) ? options : [options];
3178
- function setup(options) {
3366
+ function setup(options, ttlMs) {
3179
3367
  const configs = asArray(options);
3180
3368
  if (configs.length === 0) throw new TypeError("hyleRootPage: pass at least one workspace config");
3181
3369
  const param = configs[0].param ?? "hyle";
3182
3370
  if (configs.some((c) => (c.param ?? "hyle") !== param)) throw new TypeError("hyleRootPage: every config must use the same `param`");
3183
- return { configs, param, loaders: configs.map(mountsLoader) };
3371
+ return { configs, param, loaders: configs.map((config) => mountsLoader(config, ttlMs)) };
3184
3372
  }
3185
3373
  var sectionsOf = (config, mount) => [
3186
3374
  ...config.sections ?? [],
@@ -3190,20 +3378,33 @@ function mountOptionsOf(config, mount) {
3190
3378
  const { mountOptions, ...rest } = config;
3191
3379
  return { ...rest, ...mountOptions?.[mount.prefix === "" ? "/" : mount.prefix], basePath: mount.prefix, sections: sectionsOf(config, mount) };
3192
3380
  }
3193
- function rootMounts(options) {
3194
- const { configs, param, loaders } = setup(options);
3381
+ function rootMounts(options, ttlMs) {
3382
+ const { configs, param, loaders } = setup(options, ttlMs);
3195
3383
  return {
3196
3384
  param,
3197
3385
  async locate(path) {
3198
3386
  const loaded = await Promise.all(loaders.map((load) => load()));
3387
+ let share;
3388
+ loaded.forEach(({ protected: slugs }, index) => {
3389
+ for (const slug of slugs) {
3390
+ const depth = slug.split("/").length;
3391
+ if (!prefixMatches(`/${slug}`, path) || share && depth <= share.depth) continue;
3392
+ const docSlug = path === `/${slug}` ? void 0 : path.slice(slug.length + 2);
3393
+ if (docSlug === void 0 || PROTECTED_DOC_SLUG.test(docSlug)) share = { index, slug, depth, docSlug };
3394
+ }
3395
+ });
3199
3396
  let best;
3200
- loaded.forEach(({ mounts, reserved }, index2) => {
3397
+ loaded.forEach(({ mounts, reserved }, index) => {
3201
3398
  if (isReserved(path, reserved)) return;
3202
- for (const mount2 of mounts) if (prefixMatches(mount2.prefix, path) && (!best || mount2.depth > best.mount.depth)) best = { index: index2, mount: mount2 };
3399
+ for (const mount of mounts) if (prefixMatches(mount.prefix, path) && (!best || mount.depth > best.mount.depth)) best = { index, mount };
3203
3400
  });
3204
- if (!best) return void 0;
3205
- const { index, mount } = best;
3206
- return { options: mountOptionsOf(configs[index], mount), mount, index };
3401
+ const won = share;
3402
+ const mounted = best;
3403
+ if (won && (!mounted || won.depth > mounted.mount.depth || won.depth === mounted.mount.depth && won.index === mounted.index)) {
3404
+ return { share: { config: configs[won.index], slug: won.slug, docSlug: won.docSlug } };
3405
+ }
3406
+ if (!mounted) return void 0;
3407
+ return { options: mountOptionsOf(configs[mounted.index], mounted.mount), mount: mounted.mount, index: mounted.index };
3207
3408
  },
3208
3409
  async all() {
3209
3410
  const out = [];
@@ -3215,7 +3416,7 @@ function rootMounts(options) {
3215
3416
  }
3216
3417
  };
3217
3418
  }
3218
- function createRouter(options, make) {
3419
+ function createRouter(options, make, share) {
3219
3420
  const mounts = rootMounts(options);
3220
3421
  const handlers = /* @__PURE__ */ new Map();
3221
3422
  return async function route(params) {
@@ -3225,6 +3426,7 @@ function createRouter(options, make) {
3225
3426
  if (path === void 0 || path === "/" || !segments) return void 0;
3226
3427
  const hit = await mounts.locate(path);
3227
3428
  if (!hit) return void 0;
3429
+ if ("share" in hit) return { handler: share(hit.share), params };
3228
3430
  const { mount, index } = hit;
3229
3431
  const id = `${index}|${mount.prefix}|${mount.defaultSection}`;
3230
3432
  let handler = handlers.get(id);
@@ -3236,15 +3438,15 @@ function createRouter(options, make) {
3236
3438
  };
3237
3439
  }
3238
3440
  function hyleRootPage(options) {
3239
- const route = createRouter(options, hylePage);
3441
+ const route = createRouter(options, hylePage, () => async () => (0, import_navigation7.notFound)());
3240
3442
  return async function HyleRootPage({ params, searchParams }) {
3241
3443
  const hit = await route(await params ?? {});
3242
- if (!hit) (0, import_navigation5.notFound)();
3444
+ if (!hit) (0, import_navigation7.notFound)();
3243
3445
  return hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} });
3244
3446
  };
3245
3447
  }
3246
3448
  function hyleRootMetadata(options) {
3247
- const route = createRouter(options, hyleMetadata);
3449
+ const route = createRouter(options, hyleMetadata, () => async () => hyleProtectedMetadata);
3248
3450
  return async function generateMetadata({ params, searchParams }, parent) {
3249
3451
  const hit = await route(await params ?? {});
3250
3452
  return hit ? hit.handler({ params: Promise.resolve(hit.params), ...searchParams ? { searchParams } : {} }, parent) : {};
@@ -3266,9 +3468,9 @@ function markdownRewritePath(pathname) {
3266
3468
  if (!pathname.startsWith("/") || !pathname.endsWith(".md") || pathname.endsWith("/.md") || pathname.startsWith("/api/")) return void 0;
3267
3469
  return MD_ROUTE_PREFIX + pathname.slice(0, -3);
3268
3470
  }
3269
- var reply = (body, status, headers = {}) => (
3471
+ var reply = (body, status, headers2 = {}) => (
3270
3472
  // noindex on every answer: the .md twin must never compete with the page it mirrors.
3271
- new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers } })
3473
+ new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers2 } })
3272
3474
  );
3273
3475
  function createMarkdownRoute(options) {
3274
3476
  const mounts = rootMounts(options);
@@ -3280,7 +3482,7 @@ function createMarkdownRoute(options) {
3280
3482
  if (path === void 0 || path === "/") return reply(null, 404);
3281
3483
  try {
3282
3484
  const hit = await mounts.locate(path);
3283
- if (!hit) return reply(null, 404);
3485
+ if (!hit || "share" in hit) return reply(null, 404);
3284
3486
  const { locale, toHref } = routeContext({ ...hit.options, basePath: "", param: "path" }, params);
3285
3487
  const result = await resolverFor(hit.options)(path, locale, void 0, void 0, void 0, "md");
3286
3488
  if (result.kind === "article" && result.content.format === "md") {
@@ -3304,7 +3506,7 @@ function createMarkdownRoute(options) {
3304
3506
  }
3305
3507
 
3306
3508
  // src/next/llms.ts
3307
- var import_navigation6 = require("next/navigation");
3509
+ var import_navigation8 = require("next/navigation");
3308
3510
  var oneLine = (text) => text.replace(/\s+/g, " ").trim();
3309
3511
  var linkTarget = (url) => url.replace(/[()]/g, (c) => c === "(" ? "%28" : "%29");
3310
3512
  function createLlmsTxtRoute(options, llms) {
@@ -3329,7 +3531,7 @@ function createLlmsTxtRoute(options, llms) {
3329
3531
  return new Response(`${lines.join("\n")}
3330
3532
  `, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
3331
3533
  } catch (error) {
3332
- (0, import_navigation6.unstable_rethrow)(error);
3534
+ (0, import_navigation8.unstable_rethrow)(error);
3333
3535
  console.error(`hyle: ${error instanceof Error ? error.name : "UnknownError"}`);
3334
3536
  return new Response(null, { status: 503 });
3335
3537
  }
@@ -3346,8 +3548,8 @@ var DEFAULT_TIMEOUT_MS3 = 3e4;
3346
3548
  var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400";
3347
3549
  var PARTIAL_CACHE_CONTROL = "no-store";
3348
3550
  var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
3349
- var PRIVATE_HEADERS = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
3350
- var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
3551
+ var PRIVATE_HEADERS2 = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
3552
+ var empty = (status, headers2 = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers2 } });
3351
3553
  var isSwitchedOff3 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
3352
3554
  var THEME_CACHE_CONTROL = "public, max-age=31536000, immutable";
3353
3555
  var OUTDATED_THEME_CACHE_CONTROL = "public, max-age=60";
@@ -3368,17 +3570,17 @@ async function serveTheme(client, scope, hash, timeoutMs, head) {
3368
3570
  const current = await sha256Hex(css);
3369
3571
  if (current !== hash && upstream.headers.get(THEME_SCOPE_HEADER) !== scope) return empty(404);
3370
3572
  const cache = current === hash ? THEME_CACHE_CONTROL : OUTDATED_THEME_CACHE_CONTROL;
3371
- const headers = { "Content-Type": "text/css; charset=utf-8", "Cache-Control": cache, ETag: `"${current}"`, ...SAFE_HEADERS };
3372
- return new Response(head ? null : css, { status: 200, headers });
3573
+ const headers2 = { "Content-Type": "text/css; charset=utf-8", "Cache-Control": cache, ETag: `"${current}"`, ...SAFE_HEADERS };
3574
+ return new Response(head ? null : css, { status: 200, headers: headers2 });
3373
3575
  } catch {
3374
3576
  return empty(502);
3375
3577
  }
3376
3578
  }
3377
- function protectedAccessFor(req, pageId) {
3378
- if (!PROTECTED_ID.test(pageId)) return void 0;
3379
- const name = protectedCookieName(pageId);
3579
+ async function protectedAccessFor(req, slug) {
3580
+ if (!PROTECTED_SLUG.test(slug)) return void 0;
3581
+ const name = await protectedCookieName(slug);
3380
3582
  const password = req.headers.get("cookie")?.split(";").map((c) => c.trim()).find((c) => c.startsWith(`${name}=`))?.slice(name.length + 1);
3381
- return password !== void 0 && PROTECTED_PASSWORD.test(password) ? { pageId, password } : void 0;
3583
+ return password !== void 0 && PROTECTED_PASSWORD.test(password) ? { slug, password } : void 0;
3382
3584
  }
3383
3585
  function capped(body, max) {
3384
3586
  let seen = 0;
@@ -3398,19 +3600,19 @@ function createAssetRoute(options) {
3398
3600
  async function serve(req, ctx2, head) {
3399
3601
  const query = new URL(req.url).searchParams;
3400
3602
  const previewToken = query.get(PREVIEW_PARAM);
3401
- const pageId = query.get(PROTECTED_PARAM);
3402
- const res = await relay(req, ctx2, head, previewToken, pageId);
3403
- if (previewToken !== null || pageId !== null) for (const [name, value] of Object.entries(PRIVATE_HEADERS)) res.headers.set(name, value);
3603
+ const slug = query.get(PROTECTED_PARAM);
3604
+ const res = await relay(req, ctx2, head, previewToken, slug);
3605
+ if (previewToken !== null || slug !== null) for (const [name, value] of Object.entries(PRIVATE_HEADERS2)) res.headers.set(name, value);
3404
3606
  return res;
3405
3607
  }
3406
- async function relay(req, ctx2, head, previewToken, pageId) {
3608
+ async function relay(req, ctx2, head, previewToken, slug) {
3407
3609
  if (isSwitchedOff3((options.env ?? process.env).HYLE_CONTENT_ENABLED)) return empty(404);
3408
3610
  const file = (await ctx2.params).file;
3409
3611
  const [, themeScope, themeHash] = typeof file === "string" ? THEME_FILE.exec(file) ?? [] : [];
3410
3612
  if (typeof file !== "string" || !themeHash && !ASSET_FILE.test(file)) return empty(404);
3411
3613
  if (previewToken !== null && !PREVIEW_TOKEN.test(previewToken)) return empty(404);
3412
- const protectedAccess = pageId === null ? void 0 : protectedAccessFor(req, pageId);
3413
- if (pageId !== null && protectedAccess === void 0) return empty(404);
3614
+ const protectedAccess = slug === null ? void 0 : await protectedAccessFor(req, slug);
3615
+ if (slug !== null && protectedAccess === void 0) return empty(404);
3414
3616
  try {
3415
3617
  client ??= createHyleClient({ baseUrl: options.baseUrl?.trim() ?? "", token: options.token?.trim() ?? "", ...options.fetch ? { fetch: options.fetch } : {} });
3416
3618
  } catch {
@@ -3441,7 +3643,7 @@ function createAssetRoute(options) {
3441
3643
  const range = upstream.headers.get("content-range");
3442
3644
  return empty(416, range ? { "Content-Range": range } : {});
3443
3645
  }
3444
- if (upstream.status === 429 && (previewToken !== null || pageId !== null)) {
3646
+ if (upstream.status === 429 && (previewToken !== null || slug !== null)) {
3445
3647
  drop();
3446
3648
  const wait = upstream.headers.get("retry-after");
3447
3649
  return empty(429, wait ? { "Retry-After": wait } : {});
@@ -3453,22 +3655,22 @@ function createAssetRoute(options) {
3453
3655
  drop();
3454
3656
  return empty(502);
3455
3657
  }
3456
- const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
3457
- if (etag) headers.set("ETag", etag);
3658
+ const headers2 = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
3659
+ if (etag) headers2.set("ETag", etag);
3458
3660
  const contentRange = upstream.headers.get("content-range");
3459
- if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
3460
- if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
3661
+ if (upstream.status === 206 && contentRange) headers2.set("Content-Range", contentRange);
3662
+ if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers2.set("Content-Length", String(length));
3461
3663
  if (head) {
3462
3664
  drop();
3463
- return new Response(null, { status: upstream.status, headers });
3665
+ return new Response(null, { status: upstream.status, headers: headers2 });
3464
3666
  }
3465
- return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
3667
+ return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers: headers2 });
3466
3668
  }
3467
3669
  return { GET: (req, ctx2) => serve(req, ctx2, false), HEAD: (req, ctx2) => serve(req, ctx2, true) };
3468
3670
  }
3469
3671
 
3470
3672
  // src/next/og.tsx
3471
- var import_jsx_runtime13 = require("react/jsx-runtime");
3673
+ var import_jsx_runtime15 = require("react/jsx-runtime");
3472
3674
  var SIZE = { width: 1200, height: 630 };
3473
3675
  var MAX_TITLE = 140;
3474
3676
  function createOgImageRoute(options) {
@@ -3498,9 +3700,9 @@ function createOgImageRoute(options) {
3498
3700
  const chars = [...title];
3499
3701
  const shown = chars.length > MAX_TITLE ? `${chars.slice(0, MAX_TITLE - 1).join("")}\u2026` : title;
3500
3702
  return new import_og.ImageResponse(
3501
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { style: { display: "flex", flexDirection: "column", justifyContent: "space-between", width: "100%", height: "100%", padding: 80, background: "#111827", color: "#ffffff" }, children: [
3502
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { style: { fontSize: 64, fontWeight: 700, lineHeight: 1.2 }, children: shown }),
3503
- options.siteName ? /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { style: { fontSize: 32, color: "#9ca3af" }, children: options.siteName }) : null
3703
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", flexDirection: "column", justifyContent: "space-between", width: "100%", height: "100%", padding: 80, background: "#111827", color: "#ffffff" }, children: [
3704
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { fontSize: 64, fontWeight: 700, lineHeight: 1.2 }, children: shown }),
3705
+ options.siteName ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { fontSize: 32, color: "#9ca3af" }, children: options.siteName }) : null
3504
3706
  ] }),
3505
3707
  // 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.
3506
3708
  { ...SIZE, headers: { "cache-control": "public, max-age=3600, s-maxage=31536000, immutable" } }
@@ -3509,104 +3711,33 @@ function createOgImageRoute(options) {
3509
3711
  };
3510
3712
  }
3511
3713
 
3512
- // src/next/preview.tsx
3513
- var import_navigation7 = require("next/navigation");
3514
- var import_jsx_runtime14 = require("react/jsx-runtime");
3515
- function drawArticle(article, options) {
3516
- const { locale } = article.publication;
3517
- const toHref = (sitePath, linkLocale = locale) => (options.localePrefix?.(linkLocale) ?? "") + sitePath;
3518
- const props = { article, components: options.components, slots: options.slots, locale, toHref };
3519
- return options.layout === "docs" ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(DocsPage, { ...props }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(ArticlePage, { ...props });
3520
- }
3521
- var hylePreviewMetadata = { robots: { index: false, follow: false }, referrer: "no-referrer" };
3522
- var BANNER = {
3523
- position: "sticky",
3524
- top: 0,
3525
- zIndex: 2147483647,
3526
- padding: "8px 16px",
3527
- background: "#fde047",
3528
- color: "#1a1a1a",
3529
- font: "600 14px/1.4 system-ui, sans-serif",
3530
- textAlign: "center"
3531
- };
3532
- function hylePreviewPage(options) {
3533
- return async function HylePreviewPage({ searchParams }) {
3534
- const { token } = await searchParams ?? {};
3535
- const result = await createHyleClient(options).preview(typeof token === "string" ? token : void 0);
3536
- if (result.kind !== "preview") (0, import_navigation7.notFound)();
3537
- return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
3538
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("meta", { name: "robots", content: "noindex, nofollow" }),
3539
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("meta", { name: "referrer", content: "no-referrer" }),
3540
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", { role: "status", style: BANNER, children: "Unpublished draft preview" }),
3541
- drawArticle(result.article, options)
3542
- ] });
3714
+ // src/next/protected-view.ts
3715
+ var import_headers2 = require("next/headers");
3716
+ var import_navigation9 = require("next/navigation");
3717
+ var import_server = require("next/server");
3718
+ var VIEW_PATH = "/hyle-protected/view";
3719
+ var MOUNTS_SNAPSHOT_MS = 3e4;
3720
+ var DEFAULT_LOOKUP_TIMEOUT_MS = 1500;
3721
+ var SHARE_PATH = /^\/[a-z0-9-]+(?:\/[a-z0-9-]+){0,4}$/;
3722
+ function hyleProtectedProxy(options, { lookupTimeoutMs = DEFAULT_LOOKUP_TIMEOUT_MS } = {}) {
3723
+ const mounts = rootMounts(options, MOUNTS_SNAPSHOT_MS);
3724
+ return async function protectedProxy(req) {
3725
+ const path = req.nextUrl.pathname;
3726
+ if (!SHARE_PATH.test(path)) return void 0;
3727
+ let timer;
3728
+ const deadline = new Promise((resolve) => timer = setTimeout(resolve, lookupTimeoutMs));
3729
+ const hit = await Promise.race([mounts.locate(path).catch(() => void 0), deadline]).finally(() => clearTimeout(timer));
3730
+ return hit && "share" in hit ? import_server.NextResponse.rewrite(new URL(`${VIEW_PATH}${path}`, req.url)) : void 0;
3543
3731
  };
3544
3732
  }
3545
-
3546
- // src/next/protected.tsx
3547
- var import_headers = require("next/headers");
3548
- var import_navigation8 = require("next/navigation");
3549
- var import_jsx_runtime15 = require("react/jsx-runtime");
3550
- var hyleProtectedMetadata = { robots: { index: false, follow: false }, referrer: "same-origin" };
3551
- var COOKIE_MAX_AGE_SECONDS = 12 * 60 * 60;
3552
- var UNLOCK_MAX_BYTES = 1024;
3553
- var PRIVATE_HEADERS2 = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
3554
- var PASSWORD_FIELD = "hyle-protected-password";
3555
- var ERROR_ID = "hyle-protected-error";
3556
- function PasswordForm({ pageId, failed }) {
3557
- return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("main", { children: [
3558
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("h1", { children: "Protected page" }),
3559
- /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("form", { method: "post", action: `/p/${pageId}/unlock`, autoComplete: "off", children: [
3560
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("label", { htmlFor: PASSWORD_FIELD, children: "Password" }),
3561
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
3562
- "input",
3563
- {
3564
- id: PASSWORD_FIELD,
3565
- name: "password",
3566
- type: "password",
3567
- autoComplete: "off",
3568
- spellCheck: false,
3569
- required: true,
3570
- pattern: "[A-Za-z0-9]{16}",
3571
- title: "16 letters or digits",
3572
- "aria-invalid": failed || void 0,
3573
- "aria-describedby": failed ? ERROR_ID : void 0
3574
- }
3575
- ),
3576
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("button", { type: "submit", children: "Open" }),
3577
- failed ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("p", { id: ERROR_ID, role: "alert", children: "Wrong or expired password." }) : null
3578
- ] })
3579
- ] });
3580
- }
3581
- function hyleProtectedPage(options) {
3733
+ var forwardedClientIp = (h) => h.get("x-forwarded-for")?.split(",")[0]?.trim() || h.get("x-real-ip")?.trim() || void 0;
3734
+ function hyleProtectedPage(options, { clientIp = forwardedClientIp } = {}) {
3735
+ const mounts = rootMounts(options);
3582
3736
  return async function HyleProtectedPage({ params }) {
3583
- const { id } = await params;
3584
- if (typeof id !== "string" || !PROTECTED_ID.test(id)) (0, import_navigation8.notFound)();
3585
- const password = (await (0, import_headers.cookies)()).get(protectedCookieName(id))?.value;
3586
- const result = password === void 0 ? void 0 : await createHyleClient(options).protected(id, password);
3587
- if (result?.kind === "disabled") (0, import_navigation8.notFound)();
3588
- return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_jsx_runtime15.Fragment, { children: [
3589
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("meta", { name: "robots", content: "noindex, nofollow" }),
3590
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("meta", { name: "referrer", content: "same-origin" }),
3591
- result?.kind === "protected" ? drawArticle(result.article, options) : /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(PasswordForm, { pageId: id, failed: result !== void 0 })
3592
- ] });
3593
- };
3594
- }
3595
- function createProtectedUnlockRoute() {
3596
- return {
3597
- async POST(req, ctx2) {
3598
- const { id } = await ctx2.params;
3599
- if (typeof id !== "string" || !PROTECTED_ID.test(id)) return new Response(null, { status: 404, headers: PRIVATE_HEADERS2 });
3600
- const site = req.headers.get("sec-fetch-site");
3601
- if (site === null ? originMismatch(req) : site !== "same-origin") return new Response(null, { status: 403, headers: PRIVATE_HEADERS2 });
3602
- if (!/^application\/x-www-form-urlencoded(\s*;|$)/i.test(req.headers.get("content-type") ?? "")) return new Response(null, { status: 415, headers: PRIVATE_HEADERS2 });
3603
- if (Number(req.headers.get("content-length")) > UNLOCK_MAX_BYTES) return new Response(null, { status: 413, headers: PRIVATE_HEADERS2 });
3604
- const form = await readCapped(new Response(req.body), UNLOCK_MAX_BYTES).catch(() => void 0);
3605
- if (form === void 0) return new Response(null, { status: 413, headers: PRIVATE_HEADERS2 });
3606
- const password = new URLSearchParams(form).get("password") ?? "";
3607
- const cookie = PROTECTED_PASSWORD.test(password) ? { "Set-Cookie": `${protectedCookieName(id)}=${password}; Max-Age=${COOKIE_MAX_AGE_SECONDS}; Path=/; HttpOnly; Secure; SameSite=Lax` } : {};
3608
- return new Response(null, { status: 303, headers: { ...PRIVATE_HEADERS2, Location: `/p/${id}`, ...cookie } });
3609
- }
3737
+ const path = `/${((await params).path ?? []).join("/")}`;
3738
+ const hit = SHARE_PATH.test(path) ? await mounts.locate(path) : void 0;
3739
+ if (!hit || !("share" in hit)) (0, import_navigation9.notFound)();
3740
+ return drawProtectedShare(hit.share.config, hit.share.slug, hit.share.docSlug, clientIp(await (0, import_headers2.headers)()));
3610
3741
  };
3611
3742
  }
3612
3743
  // Annotate the CommonJS export names for ESM import in node:
@@ -3633,6 +3764,7 @@ function createProtectedUnlockRoute() {
3633
3764
  hylePreviewPage,
3634
3765
  hyleProtectedMetadata,
3635
3766
  hyleProtectedPage,
3767
+ hyleProtectedProxy,
3636
3768
  hyleRootMetadata,
3637
3769
  hyleRootPage,
3638
3770
  hyleRootSitemap,