@tdacorp/hyle-sdk 0.24.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.
package/dist/next.cjs CHANGED
@@ -149,17 +149,19 @@ function withAssetQuery(article, query) {
149
149
 
150
150
  // src/client.ts
151
151
  var RENDERER_VERSION = "4";
152
- function applyCredential(headers, credential, method, url) {
152
+ function applyCredential(headers2, credential, method, url) {
153
153
  if (!credential.auth) {
154
- headers.set("authorization", `Bearer ${credential.token}`);
154
+ headers2.set("authorization", `Bearer ${credential.token}`);
155
155
  return void 0;
156
156
  }
157
157
  const { workspaceId } = credential;
158
158
  return credential.auth({ method, url }).then((extra) => {
159
- for (const [name, value] of Object.entries(extra)) headers.set(name, value);
160
- headers.set("cp-workspace", workspaceId);
159
+ for (const [name, value] of Object.entries(extra)) headers2.set(name, value);
160
+ headers2.set("cp-workspace", workspaceId);
161
161
  });
162
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 } : {};
163
165
  var DEFAULT_TIMEOUT_MS = 1e4;
164
166
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
165
167
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -218,13 +220,13 @@ function createHyleClient(options) {
218
220
  async function get(pathname, query, init) {
219
221
  const url = new URL(`${base}${pathname}`);
220
222
  url.search = query.toString();
221
- const headers = new Headers(init?.headers);
222
- headers.set("cp-renderer-version", RENDERER_VERSION);
223
- 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());
224
226
  if (applied) await applied;
225
227
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
226
228
  const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
227
- 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 });
228
230
  const text = await readCapped(res, options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES);
229
231
  let parsed;
230
232
  try {
@@ -232,7 +234,7 @@ function createHyleClient(options) {
232
234
  } catch {
233
235
  parsed = void 0;
234
236
  }
235
- return { parsed, status: res.status };
237
+ return { parsed, status: res.status, retryAfter: res.headers.get("retry-after") };
236
238
  }
237
239
  const failure = ({ parsed, status }) => {
238
240
  const err = parsed?.error;
@@ -280,19 +282,22 @@ function createHyleClient(options) {
280
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);
281
283
  return { kind: "preview", expires_at: data.expires_at, article: withAssetQuery(article, `${PREVIEW_PARAM}=${token}`) };
282
284
  }
283
- async function protectedGate(slug) {
285
+ const limited = ({ retryAfter }) => ({ kind: "limited", retryAfterSeconds: Math.min(3600, Math.max(1, Math.trunc(Number(retryAfter)) || 60)) });
286
+ async function protectedGate(slug, opts = {}) {
284
287
  if (!PROTECTED_SLUG.test(slug)) return { kind: "notfound" };
285
- const reply2 = await get("/cp1/read/_protected/gate", new URLSearchParams({ path: slug }), { cache: "no-store" });
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);
286
290
  if (reply2.status === 404 && reply2.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
287
291
  const data = reply2.parsed?.data;
288
292
  if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
289
293
  if (data?.cp === 1 && data.kind === "gate") return { kind: "gate" };
290
294
  throw failure(reply2);
291
295
  }
292
- async function protectedShare(slug, password, docSlug) {
296
+ async function protectedShare(slug, password, docSlug, opts = {}) {
293
297
  if (!PROTECTED_SLUG.test(slug) || docSlug !== void 0 && !PROTECTED_DOC_SLUG.test(docSlug) || !PROTECTED_PASSWORD.test(password)) return { kind: "notfound" };
294
298
  const path = docSlug === void 0 ? slug : `${slug}/${docSlug}`;
295
- const reply2 = await get("/cp1/read/_protected", new URLSearchParams({ path }), { headers: { [PROTECTED_HEADER]: password }, cache: "no-store" });
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);
296
301
  if (reply2.status === 404 && reply2.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
297
302
  const data = reply2.parsed?.data;
298
303
  if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
@@ -309,24 +314,24 @@ function createHyleClient(options) {
309
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");
310
315
  const query = protectedAccess === void 0 ? "" : `?protected=${encodeURIComponent(protectedAccess.slug)}`;
311
316
  const url = `${base}/cp1/read/assets/${file}${query}`;
312
- const headers = new Headers();
313
- const applied = applyCredential(headers, options, "GET", url);
317
+ const headers2 = new Headers();
318
+ const applied = applyCredential(headers2, options, "GET", url);
314
319
  if (applied) await applied;
315
320
  for (const name of ["range", "if-range", "if-none-match"]) {
316
321
  const value = opts.headers?.[name];
317
- if (value) headers.set(name, value);
322
+ if (value) headers2.set(name, value);
318
323
  }
319
- if (previewToken !== void 0) headers.set(PREVIEW_HEADER, previewToken);
320
- if (protectedAccess !== void 0) headers.set(PROTECTED_HEADER, protectedAccess.password);
324
+ if (previewToken !== void 0) headers2.set(PREVIEW_HEADER, previewToken);
325
+ if (protectedAccess !== void 0) headers2.set(PROTECTED_HEADER, protectedAccess.password);
321
326
  const uncached = previewToken !== void 0 || protectedAccess !== void 0;
322
- 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" } : {} });
323
328
  }
324
329
  async function theme(opts = {}) {
325
330
  const url = `${base}/cp1/read/theme.css`;
326
- const headers = new Headers();
327
- const applied = applyCredential(headers, options, "GET", url);
331
+ const headers2 = new Headers();
332
+ const applied = applyCredential(headers2, options, "GET", url);
328
333
  if (applied) await applied;
329
- 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) });
330
335
  }
331
336
  return { resolve, mounts, pushPosts, preview, protectedGate, protected: protectedShare, asset, theme };
332
337
  }
@@ -2717,9 +2722,9 @@ function createEngagementRoute(options) {
2717
2722
  try {
2718
2723
  const early = await options.onRequest(req, { action: route.action(req.method) });
2719
2724
  if (early instanceof Response) {
2720
- const headers = new Headers(early.headers);
2721
- headers.set("cache-control", "no-store");
2722
- 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 });
2723
2728
  }
2724
2729
  } catch {
2725
2730
  return refuse(502, "UPSTREAM_ERROR");
@@ -2747,11 +2752,11 @@ function createEngagementRoute(options) {
2747
2752
  if (built.body) baseHeaders.set("content-type", "application/json");
2748
2753
  const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
2749
2754
  const call = async (withAssertion = assertion) => {
2750
- const headers = new Headers(baseHeaders);
2751
- if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
2755
+ const headers2 = new Headers(baseHeaders);
2756
+ if (withAssertion) headers2.set("hyle-reader-assertion", withAssertion);
2752
2757
  const res = await fetchImpl(target, {
2753
2758
  method: req.method,
2754
- headers,
2759
+ headers: headers2,
2755
2760
  ...built.body ? { body: JSON.stringify(built.body) } : {},
2756
2761
  redirect: "error",
2757
2762
  signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS2)
@@ -3073,7 +3078,7 @@ function hyleMetadata(options) {
3073
3078
  var import_navigation4 = require("next/navigation");
3074
3079
  var xml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
3075
3080
  var tag = (name, value) => `<${name}>${xml(value)}</${name}>`;
3076
- var response = (body, status, headers) => new Response(body, { status, ...headers ? { headers } : {} });
3081
+ var response = (body, status, headers2) => new Response(body, { status, ...headers2 ? { headers: headers2 } : {} });
3077
3082
  async function hyleFeed(options) {
3078
3083
  const origin = options.siteOrigin;
3079
3084
  if (!origin || !BARE_HTTPS_ORIGIN.test(origin)) {
@@ -3232,10 +3237,31 @@ function PasswordForm({ slug, failed }) {
3232
3237
  ] })
3233
3238
  ] });
3234
3239
  }
3235
- async function drawProtectedShare(options, slug, docSlug) {
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) {
3236
3257
  const client = createHyleClient({ baseUrl: options.baseUrl, token: options.token });
3258
+ const visitor = { clientIp };
3237
3259
  const password = (await (0, import_headers.cookies)()).get(await protectedCookieName(slug))?.value;
3238
- const share = password === void 0 ? void 0 : await client.protected(slug, password, docSlug);
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
+ ] });
3239
3265
  if (share?.kind === "disabled") (0, import_navigation6.notFound)();
3240
3266
  if (share?.kind === "protected") {
3241
3267
  if (docSlug !== void 0 && share.doc_slug !== docSlug) (0, import_navigation6.notFound)();
@@ -3246,16 +3272,18 @@ async function drawProtectedShare(options, slug, docSlug) {
3246
3272
  nav: { truncated: false, items: share.documents.map((d) => ({ slug: d.doc_slug, title: d.title, canonical_path: `/${slug}/${d.doc_slug}`, children: [] })) }
3247
3273
  };
3248
3274
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
3249
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("meta", { name: "robots", content: "noindex, nofollow" }),
3250
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("meta", { name: "referrer", content: "no-referrer" }),
3275
+ PRIVATE_META,
3251
3276
  drawArticle(article, { ...options, layout: share.documents.length > 1 ? "docs" : "article" })
3252
3277
  ] });
3253
3278
  }
3254
- const gate = await client.protectedGate(slug);
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
+ ] });
3255
3284
  if (gate.kind !== "gate") (0, import_navigation6.notFound)();
3256
3285
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
3257
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("meta", { name: "robots", content: "noindex, nofollow" }),
3258
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("meta", { name: "referrer", content: "no-referrer" }),
3286
+ PRIVATE_META,
3259
3287
  /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(PasswordForm, { slug, failed: password !== void 0 })
3260
3288
  ] });
3261
3289
  }
@@ -3272,12 +3300,12 @@ function createProtectedUnlockRoute() {
3272
3300
  const slug = fields.get("slug") ?? "";
3273
3301
  if (!PROTECTED_SLUG.test(slug)) return new Response(null, { status: 404, headers: PRIVATE_HEADERS });
3274
3302
  const password = fields.get("password") ?? "";
3275
- const headers = new Headers({ ...PRIVATE_HEADERS, Location: `/${slug}` });
3303
+ const headers2 = new Headers({ ...PRIVATE_HEADERS, Location: `/${slug}` });
3276
3304
  if (PROTECTED_PASSWORD.test(password)) {
3277
3305
  const name = await protectedCookieName(slug);
3278
- for (const path of [`/${slug}`, ASSET_ROUTE_PREFIX]) headers.append("Set-Cookie", `${name}=${password}; Max-Age=${COOKIE_MAX_AGE_SECONDS}; Path=${path}; HttpOnly; Secure; SameSite=Lax`);
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`);
3279
3307
  }
3280
- return new Response(null, { status: 303, headers });
3308
+ return new Response(null, { status: 303, headers: headers2 });
3281
3309
  }
3282
3310
  };
3283
3311
  }
@@ -3314,10 +3342,24 @@ function mountsLoader(config, ttlMs) {
3314
3342
  }
3315
3343
  }
3316
3344
  if (ttlMs === void 0) return fetchLoaded;
3317
- let memo;
3345
+ let ready;
3346
+ let read;
3347
+ let until = 0;
3348
+ let pending = false;
3318
3349
  return function load() {
3319
- if (!memo || memo.until <= Date.now()) memo = { read: fetchLoaded(), until: Date.now() + ttlMs };
3320
- return memo.read;
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;
3321
3363
  };
3322
3364
  }
3323
3365
  var asArray = (options) => Array.isArray(options) ? options : [options];
@@ -3396,7 +3438,7 @@ function createRouter(options, make, share) {
3396
3438
  };
3397
3439
  }
3398
3440
  function hyleRootPage(options) {
3399
- const route = createRouter(options, hylePage, (s) => () => drawProtectedShare(s.config, s.slug, s.docSlug));
3441
+ const route = createRouter(options, hylePage, () => async () => (0, import_navigation7.notFound)());
3400
3442
  return async function HyleRootPage({ params, searchParams }) {
3401
3443
  const hit = await route(await params ?? {});
3402
3444
  if (!hit) (0, import_navigation7.notFound)();
@@ -3426,9 +3468,9 @@ function markdownRewritePath(pathname) {
3426
3468
  if (!pathname.startsWith("/") || !pathname.endsWith(".md") || pathname.endsWith("/.md") || pathname.startsWith("/api/")) return void 0;
3427
3469
  return MD_ROUTE_PREFIX + pathname.slice(0, -3);
3428
3470
  }
3429
- var reply = (body, status, headers = {}) => (
3471
+ var reply = (body, status, headers2 = {}) => (
3430
3472
  // noindex on every answer: the .md twin must never compete with the page it mirrors.
3431
- new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers } })
3473
+ new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers2 } })
3432
3474
  );
3433
3475
  function createMarkdownRoute(options) {
3434
3476
  const mounts = rootMounts(options);
@@ -3507,7 +3549,7 @@ var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidat
3507
3549
  var PARTIAL_CACHE_CONTROL = "no-store";
3508
3550
  var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
3509
3551
  var PRIVATE_HEADERS2 = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
3510
- var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
3552
+ var empty = (status, headers2 = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers2 } });
3511
3553
  var isSwitchedOff3 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
3512
3554
  var THEME_CACHE_CONTROL = "public, max-age=31536000, immutable";
3513
3555
  var OUTDATED_THEME_CACHE_CONTROL = "public, max-age=60";
@@ -3528,8 +3570,8 @@ async function serveTheme(client, scope, hash, timeoutMs, head) {
3528
3570
  const current = await sha256Hex(css);
3529
3571
  if (current !== hash && upstream.headers.get(THEME_SCOPE_HEADER) !== scope) return empty(404);
3530
3572
  const cache = current === hash ? THEME_CACHE_CONTROL : OUTDATED_THEME_CACHE_CONTROL;
3531
- const headers = { "Content-Type": "text/css; charset=utf-8", "Cache-Control": cache, ETag: `"${current}"`, ...SAFE_HEADERS };
3532
- 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 });
3533
3575
  } catch {
3534
3576
  return empty(502);
3535
3577
  }
@@ -3613,16 +3655,16 @@ function createAssetRoute(options) {
3613
3655
  drop();
3614
3656
  return empty(502);
3615
3657
  }
3616
- const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
3617
- 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);
3618
3660
  const contentRange = upstream.headers.get("content-range");
3619
- if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
3620
- 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));
3621
3663
  if (head) {
3622
3664
  drop();
3623
- return new Response(null, { status: upstream.status, headers });
3665
+ return new Response(null, { status: upstream.status, headers: headers2 });
3624
3666
  }
3625
- return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
3667
+ return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers: headers2 });
3626
3668
  }
3627
3669
  return { GET: (req, ctx2) => serve(req, ctx2, false), HEAD: (req, ctx2) => serve(req, ctx2, true) };
3628
3670
  }
@@ -3670,27 +3712,32 @@ function createOgImageRoute(options) {
3670
3712
  }
3671
3713
 
3672
3714
  // src/next/protected-view.ts
3715
+ var import_headers2 = require("next/headers");
3673
3716
  var import_navigation9 = require("next/navigation");
3674
3717
  var import_server = require("next/server");
3675
3718
  var VIEW_PATH = "/hyle-protected/view";
3676
3719
  var MOUNTS_SNAPSHOT_MS = 3e4;
3720
+ var DEFAULT_LOOKUP_TIMEOUT_MS = 1500;
3677
3721
  var SHARE_PATH = /^\/[a-z0-9-]+(?:\/[a-z0-9-]+){0,4}$/;
3678
- function hyleProtectedProxy(options) {
3722
+ function hyleProtectedProxy(options, { lookupTimeoutMs = DEFAULT_LOOKUP_TIMEOUT_MS } = {}) {
3679
3723
  const mounts = rootMounts(options, MOUNTS_SNAPSHOT_MS);
3680
3724
  return async function protectedProxy(req) {
3681
3725
  const path = req.nextUrl.pathname;
3682
3726
  if (!SHARE_PATH.test(path)) return void 0;
3683
- const hit = await mounts.locate(path).catch(() => 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));
3684
3730
  return hit && "share" in hit ? import_server.NextResponse.rewrite(new URL(`${VIEW_PATH}${path}`, req.url)) : void 0;
3685
3731
  };
3686
3732
  }
3687
- 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 } = {}) {
3688
3735
  const mounts = rootMounts(options);
3689
3736
  return async function HyleProtectedPage({ params }) {
3690
3737
  const path = `/${((await params).path ?? []).join("/")}`;
3691
3738
  const hit = SHARE_PATH.test(path) ? await mounts.locate(path) : void 0;
3692
3739
  if (!hit || !("share" in hit)) (0, import_navigation9.notFound)();
3693
- return drawProtectedShare(hit.share.config, hit.share.slug, hit.share.docSlug);
3740
+ return drawProtectedShare(hit.share.config, hit.share.slug, hit.share.docSlug, clientIp(await (0, import_headers2.headers)()));
3694
3741
  };
3695
3742
  }
3696
3743
  // Annotate the CommonJS export names for ESM import in node:
package/dist/next.d.cts CHANGED
@@ -1,13 +1,13 @@
1
1
  import { ReactElement } from 'react';
2
- import { A as ArticleRef, O as OgImage, J as JsonLdConfig, H as HyleComponents, a as HyleSlots, E as EngagementConfig, b as EmbedHeading } from './embed-B7T--kTT.cjs';
3
- export { c as HyleCommentsFallback } from './embed-B7T--kTT.cjs';
4
- import { F as FetchResolverOptions, H as HyleResolver } from './resolve-03IVloXU.cjs';
5
- export { f as fetchResolver, w as workspaceTags } from './resolve-03IVloXU.cjs';
2
+ import { A as ArticleRef, O as OgImage, J as JsonLdConfig, H as HyleComponents, a as HyleSlots, E as EngagementConfig, b as EmbedHeading } from './embed-BrrGgkgQ.cjs';
3
+ export { c as HyleCommentsFallback } from './embed-BrrGgkgQ.cjs';
4
+ import { F as FetchResolverOptions, H as HyleResolver } from './resolve-Ce_yz8gC.cjs';
5
+ export { f as fetchResolver, w as workspaceTags } from './resolve-Ce_yz8gC.cjs';
6
6
  import { MetadataRoute, ResolvingMetadata, Metadata } from 'next';
7
7
  import { R as RevalidationCallbackOptions, b as RevalidationCallbackRoute } from './revalidation-callback-BQl77tQR.cjs';
8
- import { c as HyleCredential } from './client-DrB2vcTi.cjs';
8
+ import { c as HyleCredential } from './client-CI-3cHtc.cjs';
9
9
  import { NextRequest, NextResponse } from 'next/server';
10
- import './types-Dx-fEiZd.cjs';
10
+ import './types-CxE8kLeo.cjs';
11
11
 
12
12
  type RouteParams = Record<string, string | string[] | undefined>;
13
13
  interface CommonOptions {
@@ -561,14 +561,24 @@ declare function createProtectedUnlockRoute(): {
561
561
  * `const share = hyleProtectedProxy(configs); export async function proxy(req) { return (await share(req)) ?? NextResponse.next(); }`.
562
562
  * A path under a live share slug is REWRITTEN to `/hyle-protected/view/<path>` (the visitor's URL does not change); every other
563
563
  * request returns undefined, so the host's ordinary pages stay cached. A proxy has no fetch cache, so it keeps ONE read of hyle's
564
- * mounts per config in memory for 30 seconds (shared by concurrent requests, the last good copy used when a refresh fails) and
565
- * matches every path against it locally: random paths never cost a call to hyle. The page behind the rewrite checks again through
566
- * the usual mounts cache. A mounts read that fails with no copy counts as "not a share" for those 30 seconds rather than erroring
567
- * every request of the host.
564
+ * mounts per config in memory and matches every path against it locally: random paths never cost a call to hyle. It is
565
+ * stale-while-revalidate: after 30 seconds the copy it has is still used at once and ONE refresh runs in the background (a failed
566
+ * refresh keeps the copy, within the 15 minutes `hyleRootPage` also allows), so a slow hyle delays no request. Only with no copy
567
+ * at all (a cold start) does a request wait, for `lookupTimeoutMs` (default 1500) at most, then it passes through as not a share;
568
+ * the read goes on and the next request finds its result. The page behind the rewrite checks again through the usual mounts cache.
569
+ * A mounts read that fails with no copy counts as "not a share" for those 30 seconds rather than erroring every request of the host.
568
570
  */
569
- declare function hyleProtectedProxy(options: Configs): (req: NextRequest) => Promise<NextResponse | undefined>;
570
- /** The page of `app/hyle-protected/view/[[...path]]/page.tsx` (see `hyleProtectedProxy`): the share under the path, else `notFound()`. */
571
- declare function hyleProtectedPage(options: Configs): (props: {
571
+ declare function hyleProtectedProxy(options: Configs, { lookupTimeoutMs }?: {
572
+ readonly lookupTimeoutMs?: number;
573
+ }): (req: NextRequest) => Promise<NextResponse | undefined>;
574
+ /**
575
+ * The page of `app/hyle-protected/view/[[...path]]/page.tsx` (see `hyleProtectedProxy`): the share under the path, else `notFound()`.
576
+ * The visitor's address goes to hyle with every read: by default the first `x-forwarded-for` hop, else `x-real-ip`; pass `clientIp`
577
+ * to read it from where your platform puts it (the first hop is only the visitor's when your edge overwrites that header).
578
+ */
579
+ declare function hyleProtectedPage(options: Configs, { clientIp }?: {
580
+ readonly clientIp?: (headers: Headers) => string | undefined;
581
+ }): (props: {
572
582
  readonly params: Promise<{
573
583
  readonly path?: string[];
574
584
  }>;
package/dist/next.d.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  import { ReactElement } from 'react';
2
- import { A as ArticleRef, O as OgImage, J as JsonLdConfig, H as HyleComponents, a as HyleSlots, E as EngagementConfig, b as EmbedHeading } from './embed-DavTgSU4.js';
3
- export { c as HyleCommentsFallback } from './embed-DavTgSU4.js';
4
- import { F as FetchResolverOptions, H as HyleResolver } from './resolve-BseM68oy.js';
5
- export { f as fetchResolver, w as workspaceTags } from './resolve-BseM68oy.js';
2
+ import { A as ArticleRef, O as OgImage, J as JsonLdConfig, H as HyleComponents, a as HyleSlots, E as EngagementConfig, b as EmbedHeading } from './embed-BaLQbE_n.js';
3
+ export { c as HyleCommentsFallback } from './embed-BaLQbE_n.js';
4
+ import { F as FetchResolverOptions, H as HyleResolver } from './resolve-DMHbYyTS.js';
5
+ export { f as fetchResolver, w as workspaceTags } from './resolve-DMHbYyTS.js';
6
6
  import { MetadataRoute, ResolvingMetadata, Metadata } from 'next';
7
7
  import { R as RevalidationCallbackOptions, b as RevalidationCallbackRoute } from './revalidation-callback-BQl77tQR.js';
8
- import { c as HyleCredential } from './client-BErei7cE.js';
8
+ import { c as HyleCredential } from './client-DN38IP63.js';
9
9
  import { NextRequest, NextResponse } from 'next/server';
10
- import './types-Dx-fEiZd.js';
10
+ import './types-CxE8kLeo.js';
11
11
 
12
12
  type RouteParams = Record<string, string | string[] | undefined>;
13
13
  interface CommonOptions {
@@ -561,14 +561,24 @@ declare function createProtectedUnlockRoute(): {
561
561
  * `const share = hyleProtectedProxy(configs); export async function proxy(req) { return (await share(req)) ?? NextResponse.next(); }`.
562
562
  * A path under a live share slug is REWRITTEN to `/hyle-protected/view/<path>` (the visitor's URL does not change); every other
563
563
  * request returns undefined, so the host's ordinary pages stay cached. A proxy has no fetch cache, so it keeps ONE read of hyle's
564
- * mounts per config in memory for 30 seconds (shared by concurrent requests, the last good copy used when a refresh fails) and
565
- * matches every path against it locally: random paths never cost a call to hyle. The page behind the rewrite checks again through
566
- * the usual mounts cache. A mounts read that fails with no copy counts as "not a share" for those 30 seconds rather than erroring
567
- * every request of the host.
564
+ * mounts per config in memory and matches every path against it locally: random paths never cost a call to hyle. It is
565
+ * stale-while-revalidate: after 30 seconds the copy it has is still used at once and ONE refresh runs in the background (a failed
566
+ * refresh keeps the copy, within the 15 minutes `hyleRootPage` also allows), so a slow hyle delays no request. Only with no copy
567
+ * at all (a cold start) does a request wait, for `lookupTimeoutMs` (default 1500) at most, then it passes through as not a share;
568
+ * the read goes on and the next request finds its result. The page behind the rewrite checks again through the usual mounts cache.
569
+ * A mounts read that fails with no copy counts as "not a share" for those 30 seconds rather than erroring every request of the host.
568
570
  */
569
- declare function hyleProtectedProxy(options: Configs): (req: NextRequest) => Promise<NextResponse | undefined>;
570
- /** The page of `app/hyle-protected/view/[[...path]]/page.tsx` (see `hyleProtectedProxy`): the share under the path, else `notFound()`. */
571
- declare function hyleProtectedPage(options: Configs): (props: {
571
+ declare function hyleProtectedProxy(options: Configs, { lookupTimeoutMs }?: {
572
+ readonly lookupTimeoutMs?: number;
573
+ }): (req: NextRequest) => Promise<NextResponse | undefined>;
574
+ /**
575
+ * The page of `app/hyle-protected/view/[[...path]]/page.tsx` (see `hyleProtectedProxy`): the share under the path, else `notFound()`.
576
+ * The visitor's address goes to hyle with every read: by default the first `x-forwarded-for` hop, else `x-real-ip`; pass `clientIp`
577
+ * to read it from where your platform puts it (the first hop is only the visitor's when your edge overwrites that header).
578
+ */
579
+ declare function hyleProtectedPage(options: Configs, { clientIp }?: {
580
+ readonly clientIp?: (headers: Headers) => string | undefined;
581
+ }): (props: {
572
582
  readonly params: Promise<{
573
583
  readonly path?: string[];
574
584
  }>;