@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.
@@ -63,7 +63,7 @@ var INTERNAL_POST_TAG_REGEX = /^(.+?)\/(@[\w.\d-]+)\/(.*)$/i;
63
63
  var INTERNAL_POST_REGEX = /^\/(@[\w.\d-]+)\/(.*)$/i;
64
64
  var CUSTOM_COMMUNITY_REGEX = /^https?:\/\/(.*)\/c\/(hive-\d+)(.*)/i;
65
65
  var YOUTUBE_REGEX = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|shorts\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i;
66
- var YOUTUBE_EMBED_REGEX = /^(https?:)?\/\/www\.youtube\.com\/(embed|shorts)\/.*/i;
66
+ var YOUTUBE_EMBED_REGEX = /^(https?:)?\/\/(?:www\.|m\.)?youtube\.com\/(embed|shorts)\/.*/i;
67
67
  var VIMEO_REGEX = /(https?:\/\/)?(www\.)?(?:vimeo)\.com.*(?:videos|video|channels|)\/([\d]+)/i;
68
68
  var VIMEO_EMBED_REGEX = /https:\/\/player\.vimeo\.com\/video\/([0-9]+)(?:$|[?#])/;
69
69
  var BITCHUTE_REGEX = /^(?:https?:\/\/)?(?:www\.)?bitchute\.com\/(?:video|embed)\/([a-z0-9]+)/i;
@@ -417,8 +417,31 @@ function createDoc(html) {
417
417
  return null;
418
418
  }
419
419
  }
420
+ function hashBody(body) {
421
+ const s = typeof body === "string" ? body : "";
422
+ let h = 2166136261;
423
+ for (let i2 = 0; i2 < s.length; i2++) {
424
+ h ^= s.charCodeAt(i2);
425
+ h = Math.imul(h, 16777619);
426
+ }
427
+ return `${s.length}.${(h >>> 0).toString(36)}`;
428
+ }
429
+ var bodyHashes = /* @__PURE__ */ new WeakMap();
430
+ function entryBodyHash(entry) {
431
+ const body = entry.body;
432
+ if (typeof body !== "string" || typeof entry !== "object" || entry === null) {
433
+ return hashBody(body);
434
+ }
435
+ const stored = bodyHashes.get(entry);
436
+ if (stored && stored.body === body) {
437
+ return stored.hash;
438
+ }
439
+ const hash = hashBody(body);
440
+ bodyHashes.set(entry, { body, hash });
441
+ return hash;
442
+ }
420
443
  function makeEntryCacheKey(entry) {
421
- return `${entry.author}-${entry.permlink}-${entry.last_update}-${entry.updated}`;
444
+ return `${entry.author}-${entry.permlink}-${entry.last_update}-${entry.updated}-${entryBodyHash(entry)}`;
422
445
  }
423
446
  function stripHtmlTags(s) {
424
447
  const n = s.length;
@@ -510,6 +533,10 @@ function extractYtStartTime(url) {
510
533
  return "";
511
534
  }
512
535
  }
536
+ function youtubeVideoLinkClass(matchedUrl) {
537
+ const base = "markdown-video-link markdown-video-link-youtube";
538
+ return /youtube\.com\/shorts\//i.test(matchedUrl) ? `${base} markdown-video-link-youtube-portrait` : base;
539
+ }
513
540
  function sanitizePermlink(permlink) {
514
541
  if (!permlink || typeof permlink !== "string") {
515
542
  return "";
@@ -744,6 +771,27 @@ function buildPictureSources(rawUrl) {
744
771
  return { avif, webp };
745
772
  }
746
773
 
774
+ // src/methods/image-dimensions.ts
775
+ var MAX_IMAGE_DIMENSION_PX = 8192;
776
+ var MAX_IMAGE_DIMENSION_RATIO = 40;
777
+ function parsePixelDimension(value) {
778
+ if (value == null) return null;
779
+ const trimmed = value.trim();
780
+ if (!/^\d{1,4}$/.test(trimmed)) return null;
781
+ const n = Number(trimmed);
782
+ if (n < 1 || n > MAX_IMAGE_DIMENSION_PX) return null;
783
+ return n;
784
+ }
785
+ function authorPixelSize(width, height) {
786
+ const w = parsePixelDimension(width);
787
+ const h = parsePixelDimension(height);
788
+ if (w == null || h == null) return null;
789
+ const larger = Math.max(w, h);
790
+ const smaller = Math.min(w, h);
791
+ if (larger / smaller > MAX_IMAGE_DIMENSION_RATIO) return null;
792
+ return { width: String(w), height: String(h) };
793
+ }
794
+
747
795
  // src/methods/sanitize-html.method.ts
748
796
  var EMBED_SRC_DATA_ATTRS = /* @__PURE__ */ new Set(["data-embed-src", "data-video-href"]);
749
797
  var isSafeNavValue = (value) => {
@@ -758,9 +806,34 @@ var isProxyPSrcset = (srcset) => {
758
806
  const candidates = srcset.split(",").map((c) => c.trim().split(/\s+/)[0]).filter(Boolean);
759
807
  return candidates.length > 0 && candidates.every((url) => url.startsWith(`${base}/p/`));
760
808
  };
761
- function sanitizeHtml(html) {
809
+ var QUOTED_ATTR = /\s([^\s"'>\/=]+)="([^"]*)"/g;
810
+ function enforceImageDimensionPair(html) {
811
+ return html.replace(/<img\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi, (tag) => {
812
+ QUOTED_ATTR.lastIndex = 0;
813
+ const attrs = [];
814
+ let match;
815
+ while (match = QUOTED_ATTR.exec(tag)) {
816
+ attrs.push({ name: match[1].toLowerCase(), value: decodeEntities(match[2]) });
817
+ }
818
+ const width = attrs.find((attr) => attr.name === "width")?.value;
819
+ const height = attrs.find((attr) => attr.name === "height")?.value;
820
+ const src = (attrs.find((attr) => attr.name === "src")?.value ?? "").trim();
821
+ if (src && authorPixelSize(width, height)) return tag;
822
+ QUOTED_ATTR.lastIndex = 0;
823
+ return tag.replace(
824
+ QUOTED_ATTR,
825
+ (full, name) => name.toLowerCase() === "width" || name.toLowerCase() === "height" ? "" : full
826
+ );
827
+ });
828
+ }
829
+ function sanitizeHtml(html, options) {
830
+ const preserveImageDimensions = !!options?.preserveImageDimensions;
831
+ const whiteList = preserveImageDimensions ? {
832
+ ...ALLOWED_ATTRIBUTES,
833
+ img: [...ALLOWED_ATTRIBUTES.img ?? [], "width", "height"]
834
+ } : ALLOWED_ATTRIBUTES;
762
835
  const cleaned = xss(html, {
763
- whiteList: ALLOWED_ATTRIBUTES,
836
+ whiteList,
764
837
  stripIgnoreTag: true,
765
838
  stripIgnoreTagBody: ["style"],
766
839
  css: false,
@@ -779,6 +852,9 @@ function sanitizeHtml(html) {
779
852
  if ((tag === "video" || tag === "audio") && ["src", "poster"].includes(name) && !/^https?:\/\//.test(decodedLower)) return "";
780
853
  if (tag === "audio" && name === "preload" && decodedLower !== "metadata" && decodedLower !== "none") return "";
781
854
  if (tag === "img" && ["dynsrc", "lowsrc"].includes(name)) return "";
855
+ if (tag === "img" && (name === "width" || name === "height")) {
856
+ if (!preserveImageDimensions || parsePixelDimension(decoded) == null) return "";
857
+ }
782
858
  if (tag === "span" && name === "class" && decoded.toLowerCase().trim() === "wr") return "";
783
859
  if (EMBED_SRC_DATA_ATTRS.has(name) && !isAllowedEmbedSrc(decoded)) return "";
784
860
  if (name === "data-href" && !isSafeNavValue(decoded)) return "";
@@ -788,10 +864,11 @@ function sanitizeHtml(html) {
788
864
  return void 0;
789
865
  }
790
866
  });
791
- return cleaned.replace(
867
+ const withoutBareSource = cleaned.replace(
792
868
  /<source\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi,
793
869
  (t) => /\btype\s*=\s*["'](?:image\/avif|image\/webp)["']/i.test(t) ? t : ""
794
870
  );
871
+ return preserveImageDimensions ? enforceImageDimensionPair(withoutBareSource) : withoutBareSource;
795
872
  }
796
873
 
797
874
  // src/methods/img.method.ts
@@ -819,9 +896,10 @@ function wrapInPicture(el, rawUrl) {
819
896
  picture.appendChild(webp);
820
897
  picture.appendChild(el);
821
898
  }
822
- function img(el, state, forApp = true) {
899
+ function img(el, state, forApp = true, renderOptions) {
823
900
  const src = el.getAttribute("src") || "";
824
901
  const decodedSrc = decodeImageSrc(src);
902
+ const reserved = renderOptions?.preserveImageDimensions ? authorPixelSize(el.getAttribute("width"), el.getAttribute("height")) : null;
825
903
  ["onerror", "dynsrc", "lowsrc", "width", "height"].forEach((attr) => el.removeAttribute(attr));
826
904
  const isInvalid = !src || decodedSrc.startsWith("javascript") || decodedSrc.startsWith("vbscript") || decodedSrc === "x";
827
905
  if (isInvalid) {
@@ -837,6 +915,10 @@ function img(el, state, forApp = true) {
837
915
  el.removeAttribute("sizes");
838
916
  return;
839
917
  }
918
+ if (reserved) {
919
+ el.setAttribute("width", reserved.width);
920
+ el.setAttribute("height", reserved.height);
921
+ }
840
922
  el.setAttribute("itemprop", "image");
841
923
  const avatarRoute = new RegExp(`^${trimTrailingSlash(getProxyBase()).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/u/[^/]+/avatar(?:/[a-z]+)?$`);
842
924
  const classTokens = (el.getAttribute("class") || "").split(/\s+/);
@@ -1311,7 +1393,8 @@ function a(el, forApp, parentDomain = "ecency.com", seoContext, renderOptions) {
1311
1393
  }
1312
1394
  let match = href.match(YOUTUBE_REGEX);
1313
1395
  if (match && match[1] && el.textContent.trim() === href) {
1314
- el.setAttribute("class", "markdown-video-link markdown-video-link-youtube");
1396
+ const videoClass = youtubeVideoLinkClass(match[0]);
1397
+ el.setAttribute("class", videoClass);
1315
1398
  el.removeAttribute("href");
1316
1399
  const vid = match[1];
1317
1400
  const thumbnail = proxifyImageSrc(`https://img.youtube.com/vi/${vid.split("?")[0]}/hqdefault.jpg`, 0, 0, "match");
@@ -1336,7 +1419,7 @@ function a(el, forApp, parentDomain = "ecency.com", seoContext, renderOptions) {
1336
1419
  iframe2.setAttribute("allowfullscreen", "");
1337
1420
  wrapper.appendChild(iframe2);
1338
1421
  el.appendChild(wrapper);
1339
- el.setAttribute("class", "markdown-video-link markdown-video-link-youtube er-youtube");
1422
+ el.setAttribute("class", `${videoClass} er-youtube`);
1340
1423
  } else {
1341
1424
  const thumbImg = el.ownerDocument.createElement("img");
1342
1425
  thumbImg.setAttribute("class", "no-replace video-thumbnail");
@@ -1608,8 +1691,20 @@ function iframe(el, parentDomain = "ecency.com", forApp = false, renderOptions)
1608
1691
  el.parentNode.removeChild(el);
1609
1692
  return;
1610
1693
  }
1611
- if (src.match(YOUTUBE_EMBED_REGEX)) {
1612
- el.setAttribute("src", stripQueryString(src));
1694
+ const ytMatch = src.match(YOUTUBE_EMBED_REGEX);
1695
+ if (ytMatch) {
1696
+ let stripped = stripQueryString(src);
1697
+ if (!/^(https?:)?\/\/www\./i.test(stripped)) {
1698
+ stripped = stripped.replace(/^(https?:)?\/\/(?:m\.)?youtube\.com/i, "https://www.youtube.com");
1699
+ }
1700
+ el.setAttribute("src", stripped);
1701
+ if (ytMatch[2].toLowerCase() === "shorts") {
1702
+ const shortId = stripped.match(/\/shorts\/([A-Za-z0-9_-]{11})\/?(?=[?#]|$)/i);
1703
+ if (shortId) {
1704
+ el.setAttribute("src", `https://www.youtube.com/embed/${shortId[1]}`);
1705
+ el.setAttribute("class", "portrait-embed");
1706
+ }
1707
+ }
1613
1708
  return;
1614
1709
  }
1615
1710
  if (src.match(BITCHUTE_REGEX)) {
@@ -1933,7 +2028,7 @@ function text(node, forApp, renderOptions) {
1933
2028
  const startTime = extractYtStartTime(nodeValue);
1934
2029
  const container = node.ownerDocument.createElement("p");
1935
2030
  const anchor = node.ownerDocument.createElement("a");
1936
- anchor.setAttribute("class", "markdown-video-link markdown-video-link-youtube");
2031
+ anchor.setAttribute("class", youtubeVideoLinkClass(e[0]));
1937
2032
  anchor.setAttribute("data-embed-src", embedSrc);
1938
2033
  anchor.setAttribute("data-youtube", vid);
1939
2034
  if (startTime) {
@@ -1992,7 +2087,7 @@ function traverse(node, forApp, depth = 0, state = { firstImageFound: false }, p
1992
2087
  text(child, forApp, renderOptions);
1993
2088
  }
1994
2089
  if (child.nodeName.toLowerCase() === "img") {
1995
- img(child, state, forApp);
2090
+ img(child, state, forApp, renderOptions);
1996
2091
  }
1997
2092
  if (child.nodeName.toLowerCase() === "p") {
1998
2093
  p(child);
@@ -10171,7 +10266,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
10171
10266
  output = serializer.serializeToString(doc);
10172
10267
  } catch (error) {
10173
10268
  try {
10174
- const preSanitized = sanitizeHtml(output);
10269
+ const preSanitized = sanitizeHtml(output, renderOptions);
10175
10270
  const dom = htmlparser2.parseDocument(preSanitized, {
10176
10271
  // lenient options - don't throw on malformed HTML
10177
10272
  lowerCaseTags: false,
@@ -10182,7 +10277,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
10182
10277
  traverse(doc, forApp, 0, { firstImageFound: false }, parentDomain, seoContext, renderOptions);
10183
10278
  output = serializer.serializeToString(doc);
10184
10279
  } catch (fallbackError) {
10185
- output = sanitizeHtml(output || md.render(input));
10280
+ output = sanitizeHtml(output || md.render(input), renderOptions);
10186
10281
  }
10187
10282
  }
10188
10283
  if (forApp && output && entityPlaceholders.length > 0) {
@@ -10192,7 +10287,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
10192
10287
  });
10193
10288
  }
10194
10289
  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();
10195
- return sanitizeHtml(output);
10290
+ return sanitizeHtml(output, renderOptions);
10196
10291
  }
10197
10292
 
10198
10293
  // src/methods/simple-markdown-to-html.method.ts
@@ -10216,11 +10311,16 @@ var cache = new LRUCache({ max: 500 });
10216
10311
  function setCacheSize(size) {
10217
10312
  cache = new LRUCache({ max: size });
10218
10313
  }
10219
- function cacheGet(key) {
10220
- return cache.get(key);
10314
+ var MEMO_MISS = /* @__PURE__ */ Symbol("memo-miss");
10315
+ function entryMemoGet(key, body, meta) {
10316
+ const slot = cache.get(key);
10317
+ if (slot === void 0 || slot.body !== body || slot.meta !== meta) {
10318
+ return MEMO_MISS;
10319
+ }
10320
+ return slot.value;
10221
10321
  }
10222
- function cacheSet(key, value) {
10223
- cache.set(key, value);
10322
+ function entryMemoSet(key, body, meta, value) {
10323
+ cache.set(key, { body, meta, value });
10224
10324
  }
10225
10325
 
10226
10326
  // src/markdown-2-html.ts
@@ -10244,9 +10344,9 @@ function markdown2Html(obj, forApp = true, _webp = false, parentDomain = "ecency
10244
10344
  logIfSlow(performance.now() - t02, `body_len=${obj.length}`);
10245
10345
  return res2;
10246
10346
  }
10247
- 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 : ""}`;
10248
- const item = cacheGet(key);
10249
- if (item) {
10347
+ 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" : ""}`;
10348
+ const item = entryMemoGet(key, obj.body);
10349
+ if (item !== MEMO_MISS) {
10250
10350
  return item;
10251
10351
  }
10252
10352
  const cleanBody = cleanReply(obj.body);
@@ -10256,7 +10356,7 @@ function markdown2Html(obj, forApp = true, _webp = false, parentDomain = "ecency
10256
10356
  performance.now() - t0,
10257
10357
  `author=@${obj.author} permlink=${obj.permlink} body_len=${obj.body?.length ?? 0}`
10258
10358
  );
10259
- cacheSet(key, res);
10359
+ entryMemoSet(key, obj.body, void 0, res);
10260
10360
  return res;
10261
10361
  }
10262
10362
 
@@ -10764,6 +10864,23 @@ function firstMetaUrl(value) {
10764
10864
  }
10765
10865
  return void 0;
10766
10866
  }
10867
+ function metaFingerprint(jsonMetadata) {
10868
+ let meta;
10869
+ if (typeof jsonMetadata === "object") {
10870
+ meta = jsonMetadata;
10871
+ } else {
10872
+ try {
10873
+ meta = JSON.parse(jsonMetadata);
10874
+ } catch {
10875
+ meta = null;
10876
+ }
10877
+ }
10878
+ try {
10879
+ return JSON.stringify([meta?.thumbnails, meta?.image]);
10880
+ } catch {
10881
+ return {};
10882
+ }
10883
+ }
10767
10884
  function proxifyFound(src, width, height, format) {
10768
10885
  return proxifyImageSrc(decodeEntities(src), width, height, format);
10769
10886
  }
@@ -10886,12 +11003,13 @@ function catchPostImage(obj, width = 0, height = 0, format = "match", options =
10886
11003
  return null;
10887
11004
  }
10888
11005
  const key = `${makeEntryCacheKey(obj)}-${width}x${height}-${format}${fastMode ? "-fast" : ""}`;
10889
- const item = cacheGet(key);
10890
- if (item !== void 0) {
11006
+ const meta = metaFingerprint(obj.json_metadata);
11007
+ const item = entryMemoGet(key, obj.body, meta);
11008
+ if (item !== MEMO_MISS) {
10891
11009
  return item;
10892
11010
  }
10893
11011
  const res = getImage(obj, width, height, format, fastMode);
10894
- cacheSet(key, res);
11012
+ entryMemoSet(key, obj.body, meta, res);
10895
11013
  return res;
10896
11014
  }
10897
11015
 
@@ -10978,12 +11096,12 @@ function getPostBodySummary(obj, length, platform) {
10978
11096
  return postBodySummary(obj, normalizedLength, normalizedPlatform);
10979
11097
  }
10980
11098
  const key = `${makeEntryCacheKey(obj)}-sum-${normalizedLength}-${normalizedPlatform}`;
10981
- const item = cacheGet(key);
10982
- if (item) {
11099
+ const item = entryMemoGet(key, obj.body);
11100
+ if (item !== MEMO_MISS) {
10983
11101
  return item;
10984
11102
  }
10985
11103
  const res = postBodySummary(obj.body, normalizedLength, normalizedPlatform);
10986
- cacheSet(key, res);
11104
+ entryMemoSet(key, obj.body, void 0, res);
10987
11105
  return res;
10988
11106
  }
10989
11107