@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.js CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  DEFAULT_REVALIDATE,
28
28
  fetchResolver,
29
29
  workspaceTags
30
- } from "./chunk-SY2FMIRZ.js";
30
+ } from "./chunk-O4QWHXVH.js";
31
31
  import {
32
32
  Cp1ClientError,
33
33
  checkBaseUrl,
@@ -40,7 +40,7 @@ import {
40
40
  listPublicationPaths,
41
41
  readCapped,
42
42
  signReaderAssertion
43
- } from "./chunk-4REU4HJI.js";
43
+ } from "./chunk-RCK4NCYC.js";
44
44
  import {
45
45
  ASSET_CONTENT_TYPES,
46
46
  ASSET_FILE,
@@ -383,9 +383,9 @@ function createEngagementRoute(options) {
383
383
  try {
384
384
  const early = await options.onRequest(req, { action: route.action(req.method) });
385
385
  if (early instanceof Response) {
386
- const headers = new Headers(early.headers);
387
- headers.set("cache-control", "no-store");
388
- return new Response(early.body, { status: early.status, headers });
386
+ const headers2 = new Headers(early.headers);
387
+ headers2.set("cache-control", "no-store");
388
+ return new Response(early.body, { status: early.status, headers: headers2 });
389
389
  }
390
390
  } catch {
391
391
  return refuse(502, "UPSTREAM_ERROR");
@@ -413,11 +413,11 @@ function createEngagementRoute(options) {
413
413
  if (built.body) baseHeaders.set("content-type", "application/json");
414
414
  const target = `${config.base}/cp1/engage${built.upstream}${built.query ? `?${built.query}` : ""}`;
415
415
  const call = async (withAssertion = assertion) => {
416
- const headers = new Headers(baseHeaders);
417
- if (withAssertion) headers.set("hyle-reader-assertion", withAssertion);
416
+ const headers2 = new Headers(baseHeaders);
417
+ if (withAssertion) headers2.set("hyle-reader-assertion", withAssertion);
418
418
  const res = await fetchImpl(target, {
419
419
  method: req.method,
420
- headers,
420
+ headers: headers2,
421
421
  ...built.body ? { body: JSON.stringify(built.body) } : {},
422
422
  redirect: "error",
423
423
  signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
@@ -739,7 +739,7 @@ function hyleMetadata(options) {
739
739
  import { unstable_rethrow as unstable_rethrow3 } from "next/navigation";
740
740
  var xml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
741
741
  var tag = (name, value) => `<${name}>${xml(value)}</${name}>`;
742
- var response = (body, status, headers) => new Response(body, { status, ...headers ? { headers } : {} });
742
+ var response = (body, status, headers2) => new Response(body, { status, ...headers2 ? { headers: headers2 } : {} });
743
743
  async function hyleFeed(options) {
744
744
  const origin = options.siteOrigin;
745
745
  if (!origin || !BARE_HTTPS_ORIGIN.test(origin)) {
@@ -898,10 +898,31 @@ function PasswordForm({ slug, failed }) {
898
898
  ] })
899
899
  ] });
900
900
  }
901
- async function drawProtectedShare(options, slug, docSlug) {
901
+ function TooManyAttempts({ seconds }) {
902
+ return /* @__PURE__ */ jsxs2("main", { children: [
903
+ /* @__PURE__ */ jsx4("h1", { children: "Too many attempts, try again later" }),
904
+ /* @__PURE__ */ jsxs2("p", { role: "alert", children: [
905
+ "Try again in ",
906
+ seconds,
907
+ " ",
908
+ seconds === 1 ? "second" : "seconds",
909
+ "."
910
+ ] })
911
+ ] });
912
+ }
913
+ var PRIVATE_META = /* @__PURE__ */ jsxs2(Fragment2, { children: [
914
+ /* @__PURE__ */ jsx4("meta", { name: "robots", content: "noindex, nofollow" }),
915
+ /* @__PURE__ */ jsx4("meta", { name: "referrer", content: "no-referrer" })
916
+ ] });
917
+ async function drawProtectedShare(options, slug, docSlug, clientIp) {
902
918
  const client = createHyleClient({ baseUrl: options.baseUrl, token: options.token });
919
+ const visitor = { clientIp };
903
920
  const password = (await cookies()).get(await protectedCookieName(slug))?.value;
904
- const share = password === void 0 ? void 0 : await client.protected(slug, password, docSlug);
921
+ const share = password === void 0 ? void 0 : await client.protected(slug, password, docSlug, visitor);
922
+ if (share?.kind === "limited") return /* @__PURE__ */ jsxs2(Fragment2, { children: [
923
+ PRIVATE_META,
924
+ /* @__PURE__ */ jsx4(TooManyAttempts, { seconds: share.retryAfterSeconds })
925
+ ] });
905
926
  if (share?.kind === "disabled") notFound3();
906
927
  if (share?.kind === "protected") {
907
928
  if (docSlug !== void 0 && share.doc_slug !== docSlug) notFound3();
@@ -912,16 +933,18 @@ async function drawProtectedShare(options, slug, docSlug) {
912
933
  nav: { truncated: false, items: share.documents.map((d) => ({ slug: d.doc_slug, title: d.title, canonical_path: `/${slug}/${d.doc_slug}`, children: [] })) }
913
934
  };
914
935
  return /* @__PURE__ */ jsxs2(Fragment2, { children: [
915
- /* @__PURE__ */ jsx4("meta", { name: "robots", content: "noindex, nofollow" }),
916
- /* @__PURE__ */ jsx4("meta", { name: "referrer", content: "no-referrer" }),
936
+ PRIVATE_META,
917
937
  drawArticle(article, { ...options, layout: share.documents.length > 1 ? "docs" : "article" })
918
938
  ] });
919
939
  }
920
- const gate = await client.protectedGate(slug);
940
+ const gate = await client.protectedGate(slug, visitor);
941
+ if (gate.kind === "limited") return /* @__PURE__ */ jsxs2(Fragment2, { children: [
942
+ PRIVATE_META,
943
+ /* @__PURE__ */ jsx4(TooManyAttempts, { seconds: gate.retryAfterSeconds })
944
+ ] });
921
945
  if (gate.kind !== "gate") notFound3();
922
946
  return /* @__PURE__ */ jsxs2(Fragment2, { children: [
923
- /* @__PURE__ */ jsx4("meta", { name: "robots", content: "noindex, nofollow" }),
924
- /* @__PURE__ */ jsx4("meta", { name: "referrer", content: "no-referrer" }),
947
+ PRIVATE_META,
925
948
  /* @__PURE__ */ jsx4(PasswordForm, { slug, failed: password !== void 0 })
926
949
  ] });
927
950
  }
@@ -938,12 +961,12 @@ function createProtectedUnlockRoute() {
938
961
  const slug = fields.get("slug") ?? "";
939
962
  if (!PROTECTED_SLUG.test(slug)) return new Response(null, { status: 404, headers: PRIVATE_HEADERS });
940
963
  const password = fields.get("password") ?? "";
941
- const headers = new Headers({ ...PRIVATE_HEADERS, Location: `/${slug}` });
964
+ const headers2 = new Headers({ ...PRIVATE_HEADERS, Location: `/${slug}` });
942
965
  if (PROTECTED_PASSWORD.test(password)) {
943
966
  const name = await protectedCookieName(slug);
944
- 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`);
967
+ 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`);
945
968
  }
946
- return new Response(null, { status: 303, headers });
969
+ return new Response(null, { status: 303, headers: headers2 });
947
970
  }
948
971
  };
949
972
  }
@@ -980,10 +1003,24 @@ function mountsLoader(config, ttlMs) {
980
1003
  }
981
1004
  }
982
1005
  if (ttlMs === void 0) return fetchLoaded;
983
- let memo;
1006
+ let ready;
1007
+ let read;
1008
+ let until = 0;
1009
+ let pending = false;
984
1010
  return function load() {
985
- if (!memo || memo.until <= Date.now()) memo = { read: fetchLoaded(), until: Date.now() + ttlMs };
986
- return memo.read;
1011
+ if (until <= Date.now() && !pending) {
1012
+ pending = true;
1013
+ until = Date.now() + ttlMs;
1014
+ read = fetchLoaded().then(
1015
+ (loaded) => ready = loaded,
1016
+ (error) => {
1017
+ ready = void 0;
1018
+ throw error;
1019
+ }
1020
+ );
1021
+ read.then(() => pending = false, () => pending = false);
1022
+ }
1023
+ return ready ? Promise.resolve(ready) : read;
987
1024
  };
988
1025
  }
989
1026
  var asArray = (options) => Array.isArray(options) ? options : [options];
@@ -1062,7 +1099,7 @@ function createRouter(options, make, share) {
1062
1099
  };
1063
1100
  }
1064
1101
  function hyleRootPage(options) {
1065
- const route = createRouter(options, hylePage, (s) => () => drawProtectedShare(s.config, s.slug, s.docSlug));
1102
+ const route = createRouter(options, hylePage, () => async () => notFound4());
1066
1103
  return async function HyleRootPage({ params, searchParams }) {
1067
1104
  const hit = await route(await params ?? {});
1068
1105
  if (!hit) notFound4();
@@ -1092,9 +1129,9 @@ function markdownRewritePath(pathname) {
1092
1129
  if (!pathname.startsWith("/") || !pathname.endsWith(".md") || pathname.endsWith("/.md") || pathname.startsWith("/api/")) return void 0;
1093
1130
  return MD_ROUTE_PREFIX + pathname.slice(0, -3);
1094
1131
  }
1095
- var reply = (body, status, headers = {}) => (
1132
+ var reply = (body, status, headers2 = {}) => (
1096
1133
  // noindex on every answer: the .md twin must never compete with the page it mirrors.
1097
- new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers } })
1134
+ new Response(body, { status, headers: { "X-Robots-Tag": "noindex", ...headers2 } })
1098
1135
  );
1099
1136
  function createMarkdownRoute(options) {
1100
1137
  const mounts = rootMounts(options);
@@ -1173,7 +1210,7 @@ var CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidat
1173
1210
  var PARTIAL_CACHE_CONTROL = "no-store";
1174
1211
  var SAFE_HEADERS = { "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" };
1175
1212
  var PRIVATE_HEADERS2 = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Robots-Tag": "noindex, nofollow" };
1176
- var empty = (status, headers = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers } });
1213
+ var empty = (status, headers2 = {}) => new Response(null, { status, headers: { "Cache-Control": "no-store", ...headers2 } });
1177
1214
  var isSwitchedOff3 = (value) => ["0", "false"].includes(value?.trim().toLowerCase() ?? "");
1178
1215
  var THEME_CACHE_CONTROL = "public, max-age=31536000, immutable";
1179
1216
  var OUTDATED_THEME_CACHE_CONTROL = "public, max-age=60";
@@ -1194,8 +1231,8 @@ async function serveTheme(client, scope, hash, timeoutMs, head) {
1194
1231
  const current = await sha256Hex(css);
1195
1232
  if (current !== hash && upstream.headers.get(THEME_SCOPE_HEADER) !== scope) return empty(404);
1196
1233
  const cache = current === hash ? THEME_CACHE_CONTROL : OUTDATED_THEME_CACHE_CONTROL;
1197
- const headers = { "Content-Type": "text/css; charset=utf-8", "Cache-Control": cache, ETag: `"${current}"`, ...SAFE_HEADERS };
1198
- return new Response(head ? null : css, { status: 200, headers });
1234
+ const headers2 = { "Content-Type": "text/css; charset=utf-8", "Cache-Control": cache, ETag: `"${current}"`, ...SAFE_HEADERS };
1235
+ return new Response(head ? null : css, { status: 200, headers: headers2 });
1199
1236
  } catch {
1200
1237
  return empty(502);
1201
1238
  }
@@ -1279,16 +1316,16 @@ function createAssetRoute(options) {
1279
1316
  drop();
1280
1317
  return empty(502);
1281
1318
  }
1282
- const headers = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
1283
- if (etag) headers.set("ETag", etag);
1319
+ const headers2 = new Headers({ "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": upstream.status === 206 ? PARTIAL_CACHE_CONTROL : CACHE_CONTROL, Vary: "Range", ...SAFE_HEADERS });
1320
+ if (etag) headers2.set("ETag", etag);
1284
1321
  const contentRange = upstream.headers.get("content-range");
1285
- if (upstream.status === 206 && contentRange) headers.set("Content-Range", contentRange);
1286
- if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers.set("Content-Length", String(length));
1322
+ if (upstream.status === 206 && contentRange) headers2.set("Content-Range", contentRange);
1323
+ if (!upstream.headers.get("content-encoding") && upstream.headers.get("content-length")) headers2.set("Content-Length", String(length));
1287
1324
  if (head) {
1288
1325
  drop();
1289
- return new Response(null, { status: upstream.status, headers });
1326
+ return new Response(null, { status: upstream.status, headers: headers2 });
1290
1327
  }
1291
- return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers });
1328
+ return new Response(capped(upstream.body, maxBytes), { status: upstream.status, headers: headers2 });
1292
1329
  }
1293
1330
  return { GET: (req, ctx) => serve(req, ctx, false), HEAD: (req, ctx) => serve(req, ctx, true) };
1294
1331
  }
@@ -1336,27 +1373,32 @@ function createOgImageRoute(options) {
1336
1373
  }
1337
1374
 
1338
1375
  // src/next/protected-view.ts
1376
+ import { headers } from "next/headers";
1339
1377
  import { notFound as notFound5 } from "next/navigation";
1340
1378
  import { NextResponse } from "next/server";
1341
1379
  var VIEW_PATH = "/hyle-protected/view";
1342
1380
  var MOUNTS_SNAPSHOT_MS = 3e4;
1381
+ var DEFAULT_LOOKUP_TIMEOUT_MS = 1500;
1343
1382
  var SHARE_PATH = /^\/[a-z0-9-]+(?:\/[a-z0-9-]+){0,4}$/;
1344
- function hyleProtectedProxy(options) {
1383
+ function hyleProtectedProxy(options, { lookupTimeoutMs = DEFAULT_LOOKUP_TIMEOUT_MS } = {}) {
1345
1384
  const mounts = rootMounts(options, MOUNTS_SNAPSHOT_MS);
1346
1385
  return async function protectedProxy(req) {
1347
1386
  const path = req.nextUrl.pathname;
1348
1387
  if (!SHARE_PATH.test(path)) return void 0;
1349
- const hit = await mounts.locate(path).catch(() => void 0);
1388
+ let timer;
1389
+ const deadline = new Promise((resolve) => timer = setTimeout(resolve, lookupTimeoutMs));
1390
+ const hit = await Promise.race([mounts.locate(path).catch(() => void 0), deadline]).finally(() => clearTimeout(timer));
1350
1391
  return hit && "share" in hit ? NextResponse.rewrite(new URL(`${VIEW_PATH}${path}`, req.url)) : void 0;
1351
1392
  };
1352
1393
  }
1353
- function hyleProtectedPage(options) {
1394
+ var forwardedClientIp = (h) => h.get("x-forwarded-for")?.split(",")[0]?.trim() || h.get("x-real-ip")?.trim() || void 0;
1395
+ function hyleProtectedPage(options, { clientIp = forwardedClientIp } = {}) {
1354
1396
  const mounts = rootMounts(options);
1355
1397
  return async function HyleProtectedPage({ params }) {
1356
1398
  const path = `/${((await params).path ?? []).join("/")}`;
1357
1399
  const hit = SHARE_PATH.test(path) ? await mounts.locate(path) : void 0;
1358
1400
  if (!hit || !("share" in hit)) notFound5();
1359
- return drawProtectedShare(hit.share.config, hit.share.slug, hit.share.docSlug);
1401
+ return drawProtectedShare(hit.share.config, hit.share.slug, hit.share.docSlug, clientIp(await headers()));
1360
1402
  };
1361
1403
  }
1362
1404
  export {
package/dist/react.d.cts CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as react from 'react';
2
2
  import { ReactElement, ReactNode } from 'react';
3
- import { H as HyleComponents, P as PageBaseProps, E as EngagementConfig, J as JsonLdConfig } from './embed-B7T--kTT.cjs';
4
- export { A as ArticleRef, C as CalloutKind, d as CalloutProps, e as CodeBlockProps, b as EmbedHeading, f as HyleArticleView, g as HyleArticleViewProps, h as HyleListView, i as HyleListViewProps, a as HyleSlots, I as ImageProps, L as LinkProps, j as ListItemProps, M as MermaidProps, O as OgImage } from './embed-B7T--kTT.cjs';
3
+ import { H as HyleComponents, P as PageBaseProps, E as EngagementConfig, J as JsonLdConfig } from './embed-BrrGgkgQ.cjs';
4
+ export { A as ArticleRef, C as CalloutKind, d as CalloutProps, e as CodeBlockProps, b as EmbedHeading, f as HyleArticleView, g as HyleArticleViewProps, h as HyleListView, i as HyleListViewProps, a as HyleSlots, I as ImageProps, L as LinkProps, j as ListItemProps, M as MermaidProps, O as OgImage } from './embed-BrrGgkgQ.cjs';
5
5
  export { H as HastLimitError, i as isSafeUrl, s as sanitizeHast, a as scopeId } from './sanitize-BpY_AdZh.cjs';
6
- import { m as ResolvedArticle, L as ListItem, r as TocEntry, o as ResolvedList, c as EngageListing, T as ThemeRef } from './types-Dx-fEiZd.cjs';
6
+ import { n as ResolvedArticle, L as ListItem, s as TocEntry, p as ResolvedList, c as EngageListing, T as ThemeRef } from './types-CxE8kLeo.cjs';
7
7
  import 'hast';
8
8
 
9
9
  interface HastContentProps {
package/dist/react.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as react from 'react';
2
2
  import { ReactElement, ReactNode } from 'react';
3
- import { H as HyleComponents, P as PageBaseProps, E as EngagementConfig, J as JsonLdConfig } from './embed-DavTgSU4.js';
4
- export { A as ArticleRef, C as CalloutKind, d as CalloutProps, e as CodeBlockProps, b as EmbedHeading, f as HyleArticleView, g as HyleArticleViewProps, h as HyleListView, i as HyleListViewProps, a as HyleSlots, I as ImageProps, L as LinkProps, j as ListItemProps, M as MermaidProps, O as OgImage } from './embed-DavTgSU4.js';
3
+ import { H as HyleComponents, P as PageBaseProps, E as EngagementConfig, J as JsonLdConfig } from './embed-BaLQbE_n.js';
4
+ export { A as ArticleRef, C as CalloutKind, d as CalloutProps, e as CodeBlockProps, b as EmbedHeading, f as HyleArticleView, g as HyleArticleViewProps, h as HyleListView, i as HyleListViewProps, a as HyleSlots, I as ImageProps, L as LinkProps, j as ListItemProps, M as MermaidProps, O as OgImage } from './embed-BaLQbE_n.js';
5
5
  export { H as HastLimitError, i as isSafeUrl, s as sanitizeHast, a as scopeId } from './sanitize-BpY_AdZh.js';
6
- import { m as ResolvedArticle, L as ListItem, r as TocEntry, o as ResolvedList, c as EngageListing, T as ThemeRef } from './types-Dx-fEiZd.js';
6
+ import { n as ResolvedArticle, L as ListItem, s as TocEntry, p as ResolvedList, c as EngageListing, T as ThemeRef } from './types-CxE8kLeo.js';
7
7
  import 'hast';
8
8
 
9
9
  interface HastContentProps {
@@ -1,4 +1,4 @@
1
- import { l as Resolved } from './types-Dx-fEiZd.cjs';
1
+ import { m as Resolved } from './types-CxE8kLeo.cjs';
2
2
 
3
3
  /** Resolves a site path to a result. The two built-in strategies are `fetchResolver` (default) and `cachedResolver` (`@tdacorp/hyle-sdk/next/use-cache`). */
4
4
  type HyleResolver = (path: string, locale: string | undefined, limit?: number, cursor?: string, nav?: "tree", format?: "md") => Promise<Resolved>;
@@ -1,4 +1,4 @@
1
- import { l as Resolved } from './types-Dx-fEiZd.js';
1
+ import { m as Resolved } from './types-CxE8kLeo.js';
2
2
 
3
3
  /** Resolves a site path to a result. The two built-in strategies are `fetchResolver` (default) and `cachedResolver` (`@tdacorp/hyle-sdk/next/use-cache`). */
4
4
  type HyleResolver = (path: string, locale: string | undefined, limit?: number, cursor?: string, nav?: "tree", format?: "md") => Promise<Resolved>;
@@ -295,7 +295,12 @@ interface HyleProtectedShare {
295
295
  /** The article's asset addresses carry the share slug. */
296
296
  readonly article: ResolvedArticle;
297
297
  }
298
- type HyleProtected = HyleProtectedShare | {
298
+ /** hyle refused the read for now (HTTP 429): try again after `retryAfterSeconds`. */
299
+ interface HyleProtectedLimited {
300
+ readonly kind: "limited";
301
+ readonly retryAfterSeconds: number;
302
+ }
303
+ type HyleProtected = HyleProtectedShare | HyleProtectedLimited | {
299
304
  readonly kind: "notfound";
300
305
  } | {
301
306
  readonly kind: "disabled";
@@ -303,10 +308,10 @@ type HyleProtected = HyleProtectedShare | {
303
308
  /** The `data` of GET /cp1/read/_protected/gate: a live share exists at the slug (no name, it is behind the password), or why none does. */
304
309
  type HyleProtectedGate = {
305
310
  readonly kind: "gate";
306
- } | {
311
+ } | HyleProtectedLimited | {
307
312
  readonly kind: "notfound";
308
313
  } | {
309
314
  readonly kind: "disabled";
310
315
  };
311
316
 
312
- export type { Alternate as A, Breadcrumb as B, CacheInfo as C, DocumentMetaFields as D, EngageComment as E, Fallback as F, HylePreview as H, ListItem as L, Mount as M, NavItem as N, ReactionCounts as R, ThemeRef as T, VoteValue as V, ArticleContent as a, EngageHeldComment as b, EngageListing as c, HyleProtected as d, HyleProtectedGate as e, HyleProtectedShare as f, Mounts as g, MountsResult as h, NavNode as i, NavTree as j, ReactionKind as k, Resolved as l, ResolvedArticle as m, ResolvedDisabled as n, ResolvedList as o, ResolvedNotFound as p, ResolvedRedirect as q, TocEntry as r };
317
+ export type { Alternate as A, Breadcrumb as B, CacheInfo as C, DocumentMetaFields as D, EngageComment as E, Fallback as F, HylePreview as H, ListItem as L, Mount as M, NavItem as N, ReactionCounts as R, ThemeRef as T, VoteValue as V, ArticleContent as a, EngageHeldComment as b, EngageListing as c, HyleProtected as d, HyleProtectedGate as e, HyleProtectedLimited as f, HyleProtectedShare as g, Mounts as h, MountsResult as i, NavNode as j, NavTree as k, ReactionKind as l, Resolved as m, ResolvedArticle as n, ResolvedDisabled as o, ResolvedList as p, ResolvedNotFound as q, ResolvedRedirect as r, TocEntry as s };
@@ -295,7 +295,12 @@ interface HyleProtectedShare {
295
295
  /** The article's asset addresses carry the share slug. */
296
296
  readonly article: ResolvedArticle;
297
297
  }
298
- type HyleProtected = HyleProtectedShare | {
298
+ /** hyle refused the read for now (HTTP 429): try again after `retryAfterSeconds`. */
299
+ interface HyleProtectedLimited {
300
+ readonly kind: "limited";
301
+ readonly retryAfterSeconds: number;
302
+ }
303
+ type HyleProtected = HyleProtectedShare | HyleProtectedLimited | {
299
304
  readonly kind: "notfound";
300
305
  } | {
301
306
  readonly kind: "disabled";
@@ -303,10 +308,10 @@ type HyleProtected = HyleProtectedShare | {
303
308
  /** The `data` of GET /cp1/read/_protected/gate: a live share exists at the slug (no name, it is behind the password), or why none does. */
304
309
  type HyleProtectedGate = {
305
310
  readonly kind: "gate";
306
- } | {
311
+ } | HyleProtectedLimited | {
307
312
  readonly kind: "notfound";
308
313
  } | {
309
314
  readonly kind: "disabled";
310
315
  };
311
316
 
312
- export type { Alternate as A, Breadcrumb as B, CacheInfo as C, DocumentMetaFields as D, EngageComment as E, Fallback as F, HylePreview as H, ListItem as L, Mount as M, NavItem as N, ReactionCounts as R, ThemeRef as T, VoteValue as V, ArticleContent as a, EngageHeldComment as b, EngageListing as c, HyleProtected as d, HyleProtectedGate as e, HyleProtectedShare as f, Mounts as g, MountsResult as h, NavNode as i, NavTree as j, ReactionKind as k, Resolved as l, ResolvedArticle as m, ResolvedDisabled as n, ResolvedList as o, ResolvedNotFound as p, ResolvedRedirect as q, TocEntry as r };
317
+ export type { Alternate as A, Breadcrumb as B, CacheInfo as C, DocumentMetaFields as D, EngageComment as E, Fallback as F, HylePreview as H, ListItem as L, Mount as M, NavItem as N, ReactionCounts as R, ThemeRef as T, VoteValue as V, ArticleContent as a, EngageHeldComment as b, EngageListing as c, HyleProtected as d, HyleProtectedGate as e, HyleProtectedLimited as f, HyleProtectedShare as g, Mounts as h, MountsResult as i, NavNode as j, NavTree as k, ReactionKind as l, Resolved as m, ResolvedArticle as n, ResolvedDisabled as o, ResolvedList as p, ResolvedNotFound as q, ResolvedRedirect as r, TocEntry as s };
@@ -97,6 +97,8 @@ function applyCredential(headers, credential, method, url) {
97
97
  headers.set("cp-workspace", workspaceId);
98
98
  });
99
99
  }
100
+ var IP_LITERAL = /^[0-9a-fA-F:.]{2,45}$/;
101
+ var visitorHeaders = ({ clientIp }) => clientIp !== void 0 && IP_LITERAL.test(clientIp) ? { "x-forwarded-for": clientIp } : {};
100
102
  var DEFAULT_TIMEOUT_MS = 1e4;
101
103
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
102
104
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -158,7 +160,7 @@ function createHyleClient(options) {
158
160
  } catch {
159
161
  parsed = void 0;
160
162
  }
161
- return { parsed, status: res.status };
163
+ return { parsed, status: res.status, retryAfter: res.headers.get("retry-after") };
162
164
  }
163
165
  const failure = ({ parsed, status }) => {
164
166
  const err = parsed?.error;
@@ -206,19 +208,22 @@ function createHyleClient(options) {
206
208
  if (data?.cp !== 1 || data.kind !== "preview" || typeof data.expires_at !== "string" || article?.kind !== "article" || article.content?.format !== "hast" || !article.publication) throw failure(reply);
207
209
  return { kind: "preview", expires_at: data.expires_at, article: withAssetQuery(article, `${PREVIEW_PARAM}=${token}`) };
208
210
  }
209
- async function protectedGate(slug) {
211
+ const limited = ({ retryAfter }) => ({ kind: "limited", retryAfterSeconds: Math.min(3600, Math.max(1, Math.trunc(Number(retryAfter)) || 60)) });
212
+ async function protectedGate(slug, opts = {}) {
210
213
  if (!PROTECTED_SLUG.test(slug)) return { kind: "notfound" };
211
- const reply = await get("/cp1/read/_protected/gate", new URLSearchParams({ path: slug }), { cache: "no-store" });
214
+ const reply = await get("/cp1/read/_protected/gate", new URLSearchParams({ path: slug }), { headers: visitorHeaders(opts), cache: "no-store" });
215
+ if (reply.status === 429) return limited(reply);
212
216
  if (reply.status === 404 && reply.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
213
217
  const data = reply.parsed?.data;
214
218
  if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
215
219
  if (data?.cp === 1 && data.kind === "gate") return { kind: "gate" };
216
220
  throw failure(reply);
217
221
  }
218
- async function protectedShare(slug, password, docSlug) {
222
+ async function protectedShare(slug, password, docSlug, opts = {}) {
219
223
  if (!PROTECTED_SLUG.test(slug) || docSlug !== void 0 && !PROTECTED_DOC_SLUG.test(docSlug) || !PROTECTED_PASSWORD.test(password)) return { kind: "notfound" };
220
224
  const path = docSlug === void 0 ? slug : `${slug}/${docSlug}`;
221
- const reply = await get("/cp1/read/_protected", new URLSearchParams({ path }), { headers: { [PROTECTED_HEADER]: password }, cache: "no-store" });
225
+ const reply = await get("/cp1/read/_protected", new URLSearchParams({ path }), { headers: { ...visitorHeaders(opts), [PROTECTED_HEADER]: password }, cache: "no-store" });
226
+ if (reply.status === 429) return limited(reply);
222
227
  if (reply.status === 404 && reply.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
223
228
  const data = reply.parsed?.data;
224
229
  if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
@@ -1,6 +1,6 @@
1
- import { H as HyleAuth } from './client-DrB2vcTi.cjs';
2
- import { H as HyleResolver } from './resolve-03IVloXU.cjs';
3
- import './types-Dx-fEiZd.cjs';
1
+ import { H as HyleAuth } from './client-CI-3cHtc.cjs';
2
+ import { H as HyleResolver } from './resolve-Ce_yz8gC.cjs';
3
+ import './types-CxE8kLeo.cjs';
4
4
 
5
5
  /**
6
6
  * The exact caching strategy: a `'use cache'` function that fetches, then tags its own entry with the tags the response
@@ -1,6 +1,6 @@
1
- import { H as HyleAuth } from './client-BErei7cE.js';
2
- import { H as HyleResolver } from './resolve-BseM68oy.js';
3
- import './types-Dx-fEiZd.js';
1
+ import { H as HyleAuth } from './client-DN38IP63.js';
2
+ import { H as HyleResolver } from './resolve-DMHbYyTS.js';
3
+ import './types-CxE8kLeo.js';
4
4
 
5
5
  /**
6
6
  * The exact caching strategy: a `'use cache'` function that fetches, then tags its own entry with the tags the response
package/dist/use-cache.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  DEFAULT_REVALIDATE
3
- } from "./chunk-SY2FMIRZ.js";
3
+ } from "./chunk-O4QWHXVH.js";
4
4
  import {
5
5
  createHyleClient,
6
6
  isValidCacheTag
7
- } from "./chunk-4REU4HJI.js";
7
+ } from "./chunk-RCK4NCYC.js";
8
8
  import "./chunk-BDFMNY76.js";
9
9
 
10
10
  // src/next/use-cache.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tdacorp/hyle-sdk",
3
- "version": "0.24.0",
3
+ "version": "0.24.1",
4
4
  "description": "hyle SDK: a typed client for hyle's resolve endpoint, a hast renderer for React, and a Next.js catch-all page with tag-based revalidation.",
5
5
  "license": "MIT",
6
6
  "repository": {