@ecency/render-helper 2.5.38 → 2.5.40

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.
@@ -90,7 +90,7 @@ var INTERNAL_POST_TAG_REGEX = /^(.+?)\/(@[\w.\d-]+)\/(.*)$/i;
90
90
  var INTERNAL_POST_REGEX = /^\/(@[\w.\d-]+)\/(.*)$/i;
91
91
  var CUSTOM_COMMUNITY_REGEX = /^https?:\/\/(.*)\/c\/(hive-\d+)(.*)/i;
92
92
  var YOUTUBE_REGEX = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|shorts\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i;
93
- var YOUTUBE_EMBED_REGEX = /^(https?:)?\/\/www\.youtube\.com\/(embed|shorts)\/.*/i;
93
+ var YOUTUBE_EMBED_REGEX = /^(https?:)?\/\/(?:www\.|m\.)?youtube\.com\/(embed|shorts)\/.*/i;
94
94
  var VIMEO_REGEX = /(https?:\/\/)?(www\.)?(?:vimeo)\.com.*(?:videos|video|channels|)\/([\d]+)/i;
95
95
  var VIMEO_EMBED_REGEX = /https:\/\/player\.vimeo\.com\/video\/([0-9]+)(?:$|[?#])/;
96
96
  var BITCHUTE_REGEX = /^(?:https?:\/\/)?(?:www\.)?bitchute\.com\/(?:video|embed)\/([a-z0-9]+)/i;
@@ -444,8 +444,31 @@ function createDoc(html) {
444
444
  return null;
445
445
  }
446
446
  }
447
+ function hashBody(body) {
448
+ const s = typeof body === "string" ? body : "";
449
+ let h = 2166136261;
450
+ for (let i2 = 0; i2 < s.length; i2++) {
451
+ h ^= s.charCodeAt(i2);
452
+ h = Math.imul(h, 16777619);
453
+ }
454
+ return `${s.length}.${(h >>> 0).toString(36)}`;
455
+ }
456
+ var bodyHashes = /* @__PURE__ */ new WeakMap();
457
+ function entryBodyHash(entry) {
458
+ const body = entry.body;
459
+ if (typeof body !== "string" || typeof entry !== "object" || entry === null) {
460
+ return hashBody(body);
461
+ }
462
+ const stored = bodyHashes.get(entry);
463
+ if (stored && stored.body === body) {
464
+ return stored.hash;
465
+ }
466
+ const hash = hashBody(body);
467
+ bodyHashes.set(entry, { body, hash });
468
+ return hash;
469
+ }
447
470
  function makeEntryCacheKey(entry) {
448
- return `${entry.author}-${entry.permlink}-${entry.last_update}-${entry.updated}`;
471
+ return `${entry.author}-${entry.permlink}-${entry.last_update}-${entry.updated}-${entryBodyHash(entry)}`;
449
472
  }
450
473
  function stripHtmlTags(s) {
451
474
  const n = s.length;
@@ -537,6 +560,10 @@ function extractYtStartTime(url) {
537
560
  return "";
538
561
  }
539
562
  }
563
+ function youtubeVideoLinkClass(matchedUrl) {
564
+ const base = "markdown-video-link markdown-video-link-youtube";
565
+ return /youtube\.com\/shorts\//i.test(matchedUrl) ? `${base} markdown-video-link-youtube-portrait` : base;
566
+ }
540
567
  function sanitizePermlink(permlink) {
541
568
  if (!permlink || typeof permlink !== "string") {
542
569
  return "";
@@ -771,6 +798,27 @@ function buildPictureSources(rawUrl) {
771
798
  return { avif, webp };
772
799
  }
773
800
 
801
+ // src/methods/image-dimensions.ts
802
+ var MAX_IMAGE_DIMENSION_PX = 8192;
803
+ var MAX_IMAGE_DIMENSION_RATIO = 40;
804
+ function parsePixelDimension(value) {
805
+ if (value == null) return null;
806
+ const trimmed = value.trim();
807
+ if (!/^\d{1,4}$/.test(trimmed)) return null;
808
+ const n = Number(trimmed);
809
+ if (n < 1 || n > MAX_IMAGE_DIMENSION_PX) return null;
810
+ return n;
811
+ }
812
+ function authorPixelSize(width, height) {
813
+ const w = parsePixelDimension(width);
814
+ const h = parsePixelDimension(height);
815
+ if (w == null || h == null) return null;
816
+ const larger = Math.max(w, h);
817
+ const smaller = Math.min(w, h);
818
+ if (larger / smaller > MAX_IMAGE_DIMENSION_RATIO) return null;
819
+ return { width: String(w), height: String(h) };
820
+ }
821
+
774
822
  // src/methods/sanitize-html.method.ts
775
823
  var EMBED_SRC_DATA_ATTRS = /* @__PURE__ */ new Set(["data-embed-src", "data-video-href"]);
776
824
  var isSafeNavValue = (value) => {
@@ -785,9 +833,34 @@ var isProxyPSrcset = (srcset) => {
785
833
  const candidates = srcset.split(",").map((c) => c.trim().split(/\s+/)[0]).filter(Boolean);
786
834
  return candidates.length > 0 && candidates.every((url) => url.startsWith(`${base}/p/`));
787
835
  };
788
- function sanitizeHtml(html) {
836
+ var QUOTED_ATTR = /\s([^\s"'>\/=]+)="([^"]*)"/g;
837
+ function enforceImageDimensionPair(html) {
838
+ return html.replace(/<img\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi, (tag) => {
839
+ QUOTED_ATTR.lastIndex = 0;
840
+ const attrs = [];
841
+ let match;
842
+ while (match = QUOTED_ATTR.exec(tag)) {
843
+ attrs.push({ name: match[1].toLowerCase(), value: decodeEntities(match[2]) });
844
+ }
845
+ const width = attrs.find((attr) => attr.name === "width")?.value;
846
+ const height = attrs.find((attr) => attr.name === "height")?.value;
847
+ const src = (attrs.find((attr) => attr.name === "src")?.value ?? "").trim();
848
+ if (src && authorPixelSize(width, height)) return tag;
849
+ QUOTED_ATTR.lastIndex = 0;
850
+ return tag.replace(
851
+ QUOTED_ATTR,
852
+ (full, name) => name.toLowerCase() === "width" || name.toLowerCase() === "height" ? "" : full
853
+ );
854
+ });
855
+ }
856
+ function sanitizeHtml(html, options) {
857
+ const preserveImageDimensions = !!options?.preserveImageDimensions;
858
+ const whiteList = preserveImageDimensions ? {
859
+ ...ALLOWED_ATTRIBUTES,
860
+ img: [...ALLOWED_ATTRIBUTES.img ?? [], "width", "height"]
861
+ } : ALLOWED_ATTRIBUTES;
789
862
  const cleaned = xss__default.default(html, {
790
- whiteList: ALLOWED_ATTRIBUTES,
863
+ whiteList,
791
864
  stripIgnoreTag: true,
792
865
  stripIgnoreTagBody: ["style"],
793
866
  css: false,
@@ -806,6 +879,9 @@ function sanitizeHtml(html) {
806
879
  if ((tag === "video" || tag === "audio") && ["src", "poster"].includes(name) && !/^https?:\/\//.test(decodedLower)) return "";
807
880
  if (tag === "audio" && name === "preload" && decodedLower !== "metadata" && decodedLower !== "none") return "";
808
881
  if (tag === "img" && ["dynsrc", "lowsrc"].includes(name)) return "";
882
+ if (tag === "img" && (name === "width" || name === "height")) {
883
+ if (!preserveImageDimensions || parsePixelDimension(decoded) == null) return "";
884
+ }
809
885
  if (tag === "span" && name === "class" && decoded.toLowerCase().trim() === "wr") return "";
810
886
  if (EMBED_SRC_DATA_ATTRS.has(name) && !isAllowedEmbedSrc(decoded)) return "";
811
887
  if (name === "data-href" && !isSafeNavValue(decoded)) return "";
@@ -815,10 +891,11 @@ function sanitizeHtml(html) {
815
891
  return void 0;
816
892
  }
817
893
  });
818
- return cleaned.replace(
894
+ const withoutBareSource = cleaned.replace(
819
895
  /<source\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi,
820
896
  (t) => /\btype\s*=\s*["'](?:image\/avif|image\/webp)["']/i.test(t) ? t : ""
821
897
  );
898
+ return preserveImageDimensions ? enforceImageDimensionPair(withoutBareSource) : withoutBareSource;
822
899
  }
823
900
 
824
901
  // src/methods/img.method.ts
@@ -846,9 +923,10 @@ function wrapInPicture(el, rawUrl) {
846
923
  picture.appendChild(webp);
847
924
  picture.appendChild(el);
848
925
  }
849
- function img(el, state, forApp = true) {
926
+ function img(el, state, forApp = true, renderOptions) {
850
927
  const src = el.getAttribute("src") || "";
851
928
  const decodedSrc = decodeImageSrc(src);
929
+ const reserved = renderOptions?.preserveImageDimensions ? authorPixelSize(el.getAttribute("width"), el.getAttribute("height")) : null;
852
930
  ["onerror", "dynsrc", "lowsrc", "width", "height"].forEach((attr) => el.removeAttribute(attr));
853
931
  const isInvalid = !src || decodedSrc.startsWith("javascript") || decodedSrc.startsWith("vbscript") || decodedSrc === "x";
854
932
  if (isInvalid) {
@@ -864,6 +942,10 @@ function img(el, state, forApp = true) {
864
942
  el.removeAttribute("sizes");
865
943
  return;
866
944
  }
945
+ if (reserved) {
946
+ el.setAttribute("width", reserved.width);
947
+ el.setAttribute("height", reserved.height);
948
+ }
867
949
  el.setAttribute("itemprop", "image");
868
950
  const avatarRoute = new RegExp(`^${trimTrailingSlash(getProxyBase()).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/u/[^/]+/avatar(?:/[a-z]+)?$`);
869
951
  const classTokens = (el.getAttribute("class") || "").split(/\s+/);
@@ -1338,7 +1420,8 @@ function a(el, forApp, parentDomain = "ecency.com", seoContext, renderOptions) {
1338
1420
  }
1339
1421
  let match = href.match(YOUTUBE_REGEX);
1340
1422
  if (match && match[1] && el.textContent.trim() === href) {
1341
- el.setAttribute("class", "markdown-video-link markdown-video-link-youtube");
1423
+ const videoClass = youtubeVideoLinkClass(match[0]);
1424
+ el.setAttribute("class", videoClass);
1342
1425
  el.removeAttribute("href");
1343
1426
  const vid = match[1];
1344
1427
  const thumbnail = proxifyImageSrc(`https://img.youtube.com/vi/${vid.split("?")[0]}/hqdefault.jpg`, 0, 0, "match");
@@ -1363,7 +1446,7 @@ function a(el, forApp, parentDomain = "ecency.com", seoContext, renderOptions) {
1363
1446
  iframe2.setAttribute("allowfullscreen", "");
1364
1447
  wrapper.appendChild(iframe2);
1365
1448
  el.appendChild(wrapper);
1366
- el.setAttribute("class", "markdown-video-link markdown-video-link-youtube er-youtube");
1449
+ el.setAttribute("class", `${videoClass} er-youtube`);
1367
1450
  } else {
1368
1451
  const thumbImg = el.ownerDocument.createElement("img");
1369
1452
  thumbImg.setAttribute("class", "no-replace video-thumbnail");
@@ -1635,8 +1718,20 @@ function iframe(el, parentDomain = "ecency.com", forApp = false, renderOptions)
1635
1718
  el.parentNode.removeChild(el);
1636
1719
  return;
1637
1720
  }
1638
- if (src.match(YOUTUBE_EMBED_REGEX)) {
1639
- el.setAttribute("src", stripQueryString(src));
1721
+ const ytMatch = src.match(YOUTUBE_EMBED_REGEX);
1722
+ if (ytMatch) {
1723
+ let stripped = stripQueryString(src);
1724
+ if (!/^(https?:)?\/\/www\./i.test(stripped)) {
1725
+ stripped = stripped.replace(/^(https?:)?\/\/(?:m\.)?youtube\.com/i, "https://www.youtube.com");
1726
+ }
1727
+ el.setAttribute("src", stripped);
1728
+ if (ytMatch[2].toLowerCase() === "shorts") {
1729
+ const shortId = stripped.match(/\/shorts\/([A-Za-z0-9_-]{11})\/?(?=[?#]|$)/i);
1730
+ if (shortId) {
1731
+ el.setAttribute("src", `https://www.youtube.com/embed/${shortId[1]}`);
1732
+ el.setAttribute("class", "portrait-embed");
1733
+ }
1734
+ }
1640
1735
  return;
1641
1736
  }
1642
1737
  if (src.match(BITCHUTE_REGEX)) {
@@ -1960,7 +2055,7 @@ function text(node, forApp, renderOptions) {
1960
2055
  const startTime = extractYtStartTime(nodeValue);
1961
2056
  const container = node.ownerDocument.createElement("p");
1962
2057
  const anchor = node.ownerDocument.createElement("a");
1963
- anchor.setAttribute("class", "markdown-video-link markdown-video-link-youtube");
2058
+ anchor.setAttribute("class", youtubeVideoLinkClass(e[0]));
1964
2059
  anchor.setAttribute("data-embed-src", embedSrc);
1965
2060
  anchor.setAttribute("data-youtube", vid);
1966
2061
  if (startTime) {
@@ -2019,7 +2114,7 @@ function traverse(node, forApp, depth = 0, state = { firstImageFound: false }, p
2019
2114
  text(child, forApp, renderOptions);
2020
2115
  }
2021
2116
  if (child.nodeName.toLowerCase() === "img") {
2022
- img(child, state, forApp);
2117
+ img(child, state, forApp, renderOptions);
2023
2118
  }
2024
2119
  if (child.nodeName.toLowerCase() === "p") {
2025
2120
  p(child);
@@ -10198,7 +10293,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
10198
10293
  output = serializer.serializeToString(doc);
10199
10294
  } catch (error) {
10200
10295
  try {
10201
- const preSanitized = sanitizeHtml(output);
10296
+ const preSanitized = sanitizeHtml(output, renderOptions);
10202
10297
  const dom = htmlparser2__namespace.parseDocument(preSanitized, {
10203
10298
  // lenient options - don't throw on malformed HTML
10204
10299
  lowerCaseTags: false,
@@ -10209,7 +10304,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
10209
10304
  traverse(doc, forApp, 0, { firstImageFound: false }, parentDomain, seoContext, renderOptions);
10210
10305
  output = serializer.serializeToString(doc);
10211
10306
  } catch (fallbackError) {
10212
- output = sanitizeHtml(output || md.render(input));
10307
+ output = sanitizeHtml(output || md.render(input), renderOptions);
10213
10308
  }
10214
10309
  }
10215
10310
  if (forApp && output && entityPlaceholders.length > 0) {
@@ -10219,7 +10314,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
10219
10314
  });
10220
10315
  }
10221
10316
  output = output.replace(/ xmlns="http:\/\/www.w3.org\/1999\/xhtml"/g, "").replace(/^<\?xml[^?]*\?>/, "").replace(/^<!DOCTYPE[^>]*>/i, "").replace(/<\/?html[^>]*>/g, "").replace(/<head[^>]*>[\s\S]*?<\/head>/g, "").replace('<body id="root">', "").replace("</body>", "").trim();
10222
- return sanitizeHtml(output);
10317
+ return sanitizeHtml(output, renderOptions);
10223
10318
  }
10224
10319
 
10225
10320
  // src/methods/simple-markdown-to-html.method.ts
@@ -10243,11 +10338,16 @@ var cache = new lruCache.LRUCache({ max: 500 });
10243
10338
  function setCacheSize(size) {
10244
10339
  cache = new lruCache.LRUCache({ max: size });
10245
10340
  }
10246
- function cacheGet(key) {
10247
- return cache.get(key);
10341
+ var MEMO_MISS = /* @__PURE__ */ Symbol("memo-miss");
10342
+ function entryMemoGet(key, body, meta) {
10343
+ const slot = cache.get(key);
10344
+ if (slot === void 0 || slot.body !== body || slot.meta !== meta) {
10345
+ return MEMO_MISS;
10346
+ }
10347
+ return slot.value;
10248
10348
  }
10249
- function cacheSet(key, value) {
10250
- cache.set(key, value);
10349
+ function entryMemoSet(key, body, meta, value) {
10350
+ cache.set(key, { body, meta, value });
10251
10351
  }
10252
10352
 
10253
10353
  // src/markdown-2-html.ts
@@ -10271,9 +10371,9 @@ function markdown2Html(obj, forApp = true, _webp = false, parentDomain = "ecency
10271
10371
  logIfSlow(performance.now() - t02, `body_len=${obj.length}`);
10272
10372
  return res2;
10273
10373
  }
10274
- const key = `${makeEntryCacheKey(obj)}-md-${forApp ? "app" : "site"}-${parentDomain}${seoContext ? `-seo${seoContext.authorReputation ?? ""}-${seoContext.postPayout ?? ""}` : ""}${renderOptions?.embedVideosDirectly ? "-embed" : ""}${renderOptions?.inertAuthorAndTagChips ? "-inert" : ""}${renderOptions?.externalProfileBase ? "-ext" + renderOptions.externalProfileBase : ""}`;
10275
- const item = cacheGet(key);
10276
- if (item) {
10374
+ const key = `${makeEntryCacheKey(obj)}-md-${forApp ? "app" : "site"}-${parentDomain}${seoContext ? `-seo${seoContext.authorReputation ?? ""}-${seoContext.postPayout ?? ""}` : ""}${renderOptions?.embedVideosDirectly ? "-embed" : ""}${renderOptions?.inertAuthorAndTagChips ? "-inert" : ""}${renderOptions?.externalProfileBase ? "-ext" + renderOptions.externalProfileBase : ""}${renderOptions?.preserveImageDimensions ? "-imgdim" : ""}`;
10375
+ const item = entryMemoGet(key, obj.body);
10376
+ if (item !== MEMO_MISS) {
10277
10377
  return item;
10278
10378
  }
10279
10379
  const cleanBody = cleanReply(obj.body);
@@ -10283,7 +10383,7 @@ function markdown2Html(obj, forApp = true, _webp = false, parentDomain = "ecency
10283
10383
  performance.now() - t0,
10284
10384
  `author=@${obj.author} permlink=${obj.permlink} body_len=${obj.body?.length ?? 0}`
10285
10385
  );
10286
- cacheSet(key, res);
10386
+ entryMemoSet(key, obj.body, void 0, res);
10287
10387
  return res;
10288
10388
  }
10289
10389
 
@@ -10791,6 +10891,23 @@ function firstMetaUrl(value) {
10791
10891
  }
10792
10892
  return void 0;
10793
10893
  }
10894
+ function metaFingerprint(jsonMetadata) {
10895
+ let meta;
10896
+ if (typeof jsonMetadata === "object") {
10897
+ meta = jsonMetadata;
10898
+ } else {
10899
+ try {
10900
+ meta = JSON.parse(jsonMetadata);
10901
+ } catch {
10902
+ meta = null;
10903
+ }
10904
+ }
10905
+ try {
10906
+ return JSON.stringify([meta?.thumbnails, meta?.image]);
10907
+ } catch {
10908
+ return {};
10909
+ }
10910
+ }
10794
10911
  function proxifyFound(src, width, height, format) {
10795
10912
  return proxifyImageSrc(decodeEntities(src), width, height, format);
10796
10913
  }
@@ -10913,12 +11030,13 @@ function catchPostImage(obj, width = 0, height = 0, format = "match", options =
10913
11030
  return null;
10914
11031
  }
10915
11032
  const key = `${makeEntryCacheKey(obj)}-${width}x${height}-${format}${fastMode ? "-fast" : ""}`;
10916
- const item = cacheGet(key);
10917
- if (item !== void 0) {
11033
+ const meta = metaFingerprint(obj.json_metadata);
11034
+ const item = entryMemoGet(key, obj.body, meta);
11035
+ if (item !== MEMO_MISS) {
10918
11036
  return item;
10919
11037
  }
10920
11038
  const res = getImage(obj, width, height, format, fastMode);
10921
- cacheSet(key, res);
11039
+ entryMemoSet(key, obj.body, meta, res);
10922
11040
  return res;
10923
11041
  }
10924
11042
 
@@ -11005,12 +11123,12 @@ function getPostBodySummary(obj, length, platform) {
11005
11123
  return postBodySummary(obj, normalizedLength, normalizedPlatform);
11006
11124
  }
11007
11125
  const key = `${makeEntryCacheKey(obj)}-sum-${normalizedLength}-${normalizedPlatform}`;
11008
- const item = cacheGet(key);
11009
- if (item) {
11126
+ const item = entryMemoGet(key, obj.body);
11127
+ if (item !== MEMO_MISS) {
11010
11128
  return item;
11011
11129
  }
11012
11130
  const res = postBodySummary(obj.body, normalizedLength, normalizedPlatform);
11013
- cacheSet(key, res);
11131
+ entryMemoSet(key, obj.body, void 0, res);
11014
11132
  return res;
11015
11133
  }
11016
11134