@rebilder/agent-readability 0.3.0 → 0.5.0

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.
@@ -96,6 +96,9 @@ function classifyIpv6Groups(groups) {
96
96
  const allZeroThrough = (upTo) => groups.slice(0, upTo).every((x) => x === 0);
97
97
  if (groups.every((x) => x === 0)) return v6("unspecified (::)", true);
98
98
  if (allZeroThrough(7) && g(7) === 1) return v6("loopback (::1)", true);
99
+ if (allZeroThrough(4) && g(4) === 65535 && g(5) === 0) {
100
+ return v6("IPv4-translated (::ffff:0:0:0/96)", true);
101
+ }
99
102
  if (allZeroThrough(5) && g(5) === 65535) {
100
103
  const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
101
104
  return v6(`IPv4-mapped \u2192 ${inner.label}`, inner.reserved);
@@ -104,10 +107,16 @@ function classifyIpv6Groups(groups) {
104
107
  const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
105
108
  return v6(`IPv4-compatible \u2192 ${inner.label}`, true);
106
109
  }
110
+ if (g(0) === 100 && g(1) === 65435 && g(2) === 1) {
111
+ return v6("NAT64 local-use (64:ff9b:1::/48)", true);
112
+ }
107
113
  if (g(0) === 100 && g(1) === 65435 && g(2) === 0 && g(3) === 0 && g(4) === 0 && g(5) === 0) {
108
114
  const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
109
115
  return v6(`NAT64 64:ff9b::/96 \u2192 ${inner.label}`, inner.reserved);
110
116
  }
117
+ if (g(0) === 8193 && g(1) === 0) {
118
+ return v6("Teredo (2001::/32)", true);
119
+ }
111
120
  if (g(0) === 8194) {
112
121
  const inner = classifyIpv4Octets(embeddedV4(g(1), g(2)));
113
122
  return v6(`6to4 2002::/16 \u2192 ${inner.label}`, inner.reserved);
@@ -117,6 +126,7 @@ function classifyIpv6Groups(groups) {
117
126
  if (g(0) === 8193 && g(1) === 3512) return v6("documentation (2001:db8::/32)", true);
118
127
  if ((g(0) & 65024) === 64512) return v6("unique local (fc00::/7)", true);
119
128
  if ((g(0) & 65472) === 65152) return v6("link-local (fe80::/10)", true);
129
+ if ((g(0) & 65472) === 65216) return v6("site-local (fec0::/10)", true);
120
130
  if ((g(0) & 65280) === 65280) return v6("multicast (ff00::/8)", true);
121
131
  return v6("public", false);
122
132
  }
@@ -159,8 +169,10 @@ function guardUrl(input, policy) {
159
169
  if (url.username !== "" || url.password !== "") {
160
170
  return { ok: false, reason: "URLs with embedded credentials cannot be fetched." };
161
171
  }
162
- let hostname = url.hostname.toLowerCase();
163
- if (hostname.endsWith(".") && hostname.length > 1) hostname = hostname.slice(0, -1);
172
+ const hostname = url.hostname.toLowerCase().replace(/\.+$/, "");
173
+ if (hostname === "") {
174
+ return { ok: false, reason: "That URL has no hostname." };
175
+ }
164
176
  const permissive = allowsPrivateHosts(policy.hostPolicy);
165
177
  if (!permissive && (hostname === "localhost" || hostname.endsWith(".localhost"))) {
166
178
  return { ok: false, reason: "localhost cannot be fetched." };
@@ -563,33 +575,61 @@ var ACTION_LEXICON = [
563
575
  "book now",
564
576
  "buy",
565
577
  "buy now",
578
+ "call",
566
579
  "call now",
580
+ "check availability",
581
+ "check out",
567
582
  "checkout",
568
583
  "contact",
569
584
  "contact us",
585
+ "create account",
586
+ "create an account",
570
587
  "donate",
571
588
  "download",
572
589
  "email us",
590
+ "enquire",
591
+ "enrol",
573
592
  "enroll",
593
+ "free trial",
594
+ "get a demo",
574
595
  "get a quote",
596
+ "get directions",
597
+ "get in touch",
575
598
  "get quote",
576
599
  "get started",
600
+ "get the app",
601
+ "get tickets",
602
+ "hire",
603
+ "inquire",
604
+ "install",
577
605
  "join",
578
606
  "make an appointment",
607
+ "message us",
579
608
  "order",
580
609
  "order now",
610
+ "order online",
611
+ "pre-order",
612
+ "preorder",
581
613
  "purchase",
582
614
  "register",
615
+ "rent",
583
616
  "request",
584
617
  "request a demo",
585
618
  "request a quote",
586
619
  "reserve",
587
620
  "schedule",
621
+ "shop",
622
+ "shop now",
588
623
  "sign up",
589
624
  "signup",
590
625
  "start",
591
626
  "start free trial",
592
- "subscribe"
627
+ "subscribe",
628
+ "talk to sales",
629
+ "talk to us",
630
+ "text us",
631
+ "try",
632
+ "upgrade"
593
633
  ];
594
634
  var BANDS = [
595
635
  {
@@ -629,7 +669,7 @@ var BANDS = [
629
669
  }
630
670
  ];
631
671
  var DEFAULT_RULESET = deepFreeze({
632
- version: "0.2.0",
672
+ version: "0.3.0",
633
673
  weights: WEIGHTS,
634
674
  thresholds: THRESHOLDS,
635
675
  audienceTokens: AUDIENCE_TOKENS,
@@ -645,6 +685,495 @@ var DEFAULT_RULESET = deepFreeze({
645
685
  bands: BANDS
646
686
  });
647
687
 
688
+ // src/html.ts
689
+ var Utf8Cursor = class {
690
+ constructor(source) {
691
+ this.source = source;
692
+ }
693
+ source;
694
+ charIndex = 0;
695
+ byteIndex = 0;
696
+ at(target) {
697
+ if (target < this.charIndex) {
698
+ this.charIndex = 0;
699
+ this.byteIndex = 0;
700
+ }
701
+ const limit = Math.min(target, this.source.length);
702
+ while (this.charIndex < limit) {
703
+ const code = this.source.charCodeAt(this.charIndex);
704
+ if (code < 128) {
705
+ this.byteIndex += 1;
706
+ this.charIndex += 1;
707
+ } else if (code < 2048) {
708
+ this.byteIndex += 2;
709
+ this.charIndex += 1;
710
+ } else if (code >= 55296 && code <= 56319) {
711
+ const next = this.charIndex + 1 < this.source.length ? this.source.charCodeAt(this.charIndex + 1) : 0;
712
+ if (next >= 56320 && next <= 57343 && this.charIndex + 1 < limit) {
713
+ this.byteIndex += 4;
714
+ this.charIndex += 2;
715
+ } else {
716
+ this.byteIndex += 3;
717
+ this.charIndex += 1;
718
+ }
719
+ } else {
720
+ this.byteIndex += 3;
721
+ this.charIndex += 1;
722
+ }
723
+ }
724
+ return this.byteIndex;
725
+ }
726
+ };
727
+ var NAMED_ENTITIES = {
728
+ amp: "&",
729
+ lt: "<",
730
+ gt: ">",
731
+ quot: '"',
732
+ apos: "'",
733
+ nbsp: "\xA0",
734
+ ensp: "\u2002",
735
+ emsp: "\u2003",
736
+ thinsp: "\u2009",
737
+ shy: "\xAD",
738
+ zwnj: "\u200C",
739
+ zwj: "\u200D",
740
+ // Currency
741
+ cent: "\xA2",
742
+ pound: "\xA3",
743
+ curren: "\xA4",
744
+ yen: "\xA5",
745
+ euro: "\u20AC",
746
+ dollar: "$",
747
+ // Typography
748
+ ndash: "\u2013",
749
+ mdash: "\u2014",
750
+ hellip: "\u2026",
751
+ lsquo: "\u2018",
752
+ rsquo: "\u2019",
753
+ sbquo: "\u201A",
754
+ ldquo: "\u201C",
755
+ rdquo: "\u201D",
756
+ bdquo: "\u201E",
757
+ laquo: "\xAB",
758
+ raquo: "\xBB",
759
+ lsaquo: "\u2039",
760
+ rsaquo: "\u203A",
761
+ bull: "\u2022",
762
+ middot: "\xB7",
763
+ dagger: "\u2020",
764
+ Dagger: "\u2021",
765
+ prime: "\u2032",
766
+ Prime: "\u2033",
767
+ // Marks and math
768
+ copy: "\xA9",
769
+ reg: "\xAE",
770
+ trade: "\u2122",
771
+ sect: "\xA7",
772
+ para: "\xB6",
773
+ deg: "\xB0",
774
+ plusmn: "\xB1",
775
+ times: "\xD7",
776
+ divide: "\xF7",
777
+ minus: "\u2212",
778
+ permil: "\u2030",
779
+ frac12: "\xBD",
780
+ frac14: "\xBC",
781
+ frac34: "\xBE",
782
+ sup2: "\xB2",
783
+ sup3: "\xB3",
784
+ le: "\u2264",
785
+ ge: "\u2265",
786
+ ne: "\u2260",
787
+ // Directionality (invisible, but they do occupy bytes)
788
+ lrm: "\u200E",
789
+ rlm: "\u200F"
790
+ };
791
+ var C1_REPLACEMENTS = {
792
+ 128: 8364,
793
+ 130: 8218,
794
+ 131: 402,
795
+ 132: 8222,
796
+ 133: 8230,
797
+ 134: 8224,
798
+ 135: 8225,
799
+ 136: 710,
800
+ 137: 8240,
801
+ 138: 352,
802
+ 139: 8249,
803
+ 140: 338,
804
+ 142: 381,
805
+ 145: 8216,
806
+ 146: 8217,
807
+ 147: 8220,
808
+ 148: 8221,
809
+ 149: 8226,
810
+ 150: 8211,
811
+ 151: 8212,
812
+ 152: 732,
813
+ 153: 8482,
814
+ 154: 353,
815
+ 155: 8250,
816
+ 156: 339,
817
+ 158: 382,
818
+ 159: 376
819
+ };
820
+ var ENTITY_RE = /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{0,31});/g;
821
+ function codePointToString(raw) {
822
+ const mapped = C1_REPLACEMENTS[raw];
823
+ const code = mapped ?? raw;
824
+ if (code === 0 || code > 1114111 || code >= 55296 && code <= 57343) return "\uFFFD";
825
+ return String.fromCodePoint(code);
826
+ }
827
+ function decodeEntities(text) {
828
+ if (!text.includes("&")) return text;
829
+ return text.replace(ENTITY_RE, (match, body) => {
830
+ if (body.startsWith("#")) {
831
+ const isHex = body[1] === "x" || body[1] === "X";
832
+ const digits = isHex ? body.slice(2) : body.slice(1);
833
+ const value = Number.parseInt(digits, isHex ? 16 : 10);
834
+ return Number.isNaN(value) ? match : codePointToString(value);
835
+ }
836
+ return NAMED_ENTITIES[body] ?? match;
837
+ });
838
+ }
839
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
840
+ "area",
841
+ "base",
842
+ "br",
843
+ "col",
844
+ "embed",
845
+ "hr",
846
+ "img",
847
+ "input",
848
+ "link",
849
+ "meta",
850
+ "param",
851
+ "source",
852
+ "track",
853
+ "wbr"
854
+ ]);
855
+ var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style"]);
856
+ var RCDATA_ELEMENTS = /* @__PURE__ */ new Set(["textarea", "title"]);
857
+ var IMPLIED_END_TAGS = {
858
+ li: ["li"],
859
+ dt: ["dt", "dd"],
860
+ dd: ["dt", "dd"],
861
+ option: ["option"],
862
+ optgroup: ["option", "optgroup"],
863
+ tr: ["td", "th", "tr"],
864
+ td: ["td", "th"],
865
+ th: ["td", "th"],
866
+ tbody: ["td", "th", "tr", "thead", "tbody"],
867
+ tfoot: ["td", "th", "tr", "thead", "tbody"]
868
+ };
869
+ var CLOSES_OPEN_P = /* @__PURE__ */ new Set([
870
+ "address",
871
+ "article",
872
+ "aside",
873
+ "blockquote",
874
+ "details",
875
+ "div",
876
+ "dl",
877
+ "fieldset",
878
+ "figcaption",
879
+ "figure",
880
+ "footer",
881
+ "form",
882
+ "h1",
883
+ "h2",
884
+ "h3",
885
+ "h4",
886
+ "h5",
887
+ "h6",
888
+ "header",
889
+ "hr",
890
+ "main",
891
+ "nav",
892
+ "ol",
893
+ "p",
894
+ "pre",
895
+ "section",
896
+ "table",
897
+ "ul"
898
+ ]);
899
+ var MAX_DEPTH = 256;
900
+ function isAsciiAlpha(ch) {
901
+ if (ch === void 0) return false;
902
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z";
903
+ }
904
+ function isHtmlSpace(ch) {
905
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f";
906
+ }
907
+ var DISPLAY_NONE_RE = /(^|;)display:none(!important)?(;|$)/;
908
+ function hasInlineDisplayNone(style) {
909
+ if (style === void 0) return false;
910
+ return DISPLAY_NONE_RE.test(style.toLowerCase().replace(/\s+/g, ""));
911
+ }
912
+ function parseStartTag(html, start) {
913
+ let i = start + 1;
914
+ const nameStart = i;
915
+ while (i < html.length) {
916
+ const ch = html[i] ?? "";
917
+ if (isHtmlSpace(ch) || ch === "/" || ch === ">") break;
918
+ i++;
919
+ }
920
+ const tag = html.slice(nameStart, i).toLowerCase();
921
+ const attrs = {};
922
+ let selfClosing = false;
923
+ while (i < html.length) {
924
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
925
+ if (i >= html.length) break;
926
+ const ch = html[i] ?? "";
927
+ if (ch === ">") {
928
+ i++;
929
+ return { tag, attrs, selfClosing, end: i };
930
+ }
931
+ if (ch === "/") {
932
+ selfClosing = true;
933
+ i++;
934
+ continue;
935
+ }
936
+ const attrNameStart = i;
937
+ while (i < html.length) {
938
+ const c = html[i] ?? "";
939
+ if (isHtmlSpace(c) || c === "=" || c === ">" || c === "/") break;
940
+ i++;
941
+ }
942
+ if (i === attrNameStart) {
943
+ i++;
944
+ continue;
945
+ }
946
+ const attrName = html.slice(attrNameStart, i).toLowerCase();
947
+ let value = "";
948
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
949
+ if (html[i] === "=") {
950
+ i++;
951
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
952
+ const quote = html[i];
953
+ if (quote === '"' || quote === "'") {
954
+ i++;
955
+ const valueStart = i;
956
+ const close = html.indexOf(quote, i);
957
+ if (close === -1) {
958
+ value = html.slice(valueStart);
959
+ i = html.length;
960
+ } else {
961
+ value = html.slice(valueStart, close);
962
+ i = close + 1;
963
+ }
964
+ } else {
965
+ const valueStart = i;
966
+ while (i < html.length) {
967
+ const c = html[i] ?? "";
968
+ if (isHtmlSpace(c) || c === ">") break;
969
+ i++;
970
+ }
971
+ value = html.slice(valueStart, i);
972
+ }
973
+ }
974
+ if (!(attrName in attrs)) attrs[attrName] = decodeEntities(value);
975
+ }
976
+ return { tag, attrs, selfClosing, end: i };
977
+ }
978
+ function findRawTextEnd(lowerHtml, from, tag) {
979
+ const needle = `</${tag}`;
980
+ const at = lowerHtml.indexOf(needle, from);
981
+ return at === -1 ? -1 : at;
982
+ }
983
+ function ownExclusion(tag, attrs) {
984
+ if (tag === "script") {
985
+ const type = (attrs["type"] ?? "").toLowerCase().split(";")[0]?.trim() ?? "";
986
+ return type === "application/ld+json" ? "script-ld-json" : "script";
987
+ }
988
+ if (tag === "style") return "style";
989
+ if (tag === "template") return "template";
990
+ if ("hidden" in attrs) return "hidden-attribute";
991
+ if (hasInlineDisplayNone(attrs["style"])) return "inline-display-none";
992
+ return null;
993
+ }
994
+ function tokenizeHtml(html) {
995
+ const elements = [];
996
+ const texts = [];
997
+ const jsonLd = [];
998
+ const metas = [];
999
+ const links = [];
1000
+ const stack = [];
1001
+ const cursor = new Utf8Cursor(html);
1002
+ const topIndex = () => stack[stack.length - 1] ?? -1;
1003
+ const exclusionAt = (elementIndex) => elementIndex >= 0 ? elements[elementIndex]?.excludedBy ?? null : null;
1004
+ const emitText = (from, to, decode, override) => {
1005
+ if (to <= from) return;
1006
+ const raw = html.slice(from, to);
1007
+ const parent = topIndex();
1008
+ const offset = cursor.at(from);
1009
+ texts.push({
1010
+ text: decode ? decodeEntities(raw) : raw,
1011
+ offset,
1012
+ bytes: cursor.at(to) - offset,
1013
+ parent,
1014
+ excludedBy: override ?? exclusionAt(parent)
1015
+ });
1016
+ };
1017
+ const popTo = (tag) => {
1018
+ for (let depth = stack.length - 1; depth >= 0; depth--) {
1019
+ const candidate = stack[depth];
1020
+ if (candidate === void 0) continue;
1021
+ if (elements[candidate]?.tag === tag) {
1022
+ stack.length = depth;
1023
+ return;
1024
+ }
1025
+ }
1026
+ };
1027
+ const applyImpliedEndTags = (tag) => {
1028
+ const closes = IMPLIED_END_TAGS[tag];
1029
+ if (closes !== void 0) {
1030
+ while (stack.length > 0) {
1031
+ const top = stack[stack.length - 1];
1032
+ const openTag = top === void 0 ? void 0 : elements[top]?.tag;
1033
+ if (openTag === void 0 || !closes.includes(openTag)) break;
1034
+ stack.pop();
1035
+ }
1036
+ }
1037
+ if (CLOSES_OPEN_P.has(tag)) {
1038
+ const top = stack[stack.length - 1];
1039
+ if (top !== void 0 && elements[top]?.tag === "p") stack.pop();
1040
+ }
1041
+ };
1042
+ let i = 0;
1043
+ let textStart = 0;
1044
+ let lowerHtml = null;
1045
+ while (i < html.length) {
1046
+ const lt = html.indexOf("<", i);
1047
+ if (lt === -1) break;
1048
+ const next = html[lt + 1];
1049
+ if (next !== "!" && next !== "/" && !isAsciiAlpha(next)) {
1050
+ i = lt + 1;
1051
+ continue;
1052
+ }
1053
+ emitText(textStart, lt, true);
1054
+ if (next === "!") {
1055
+ if (html.startsWith("<!--", lt)) {
1056
+ const close = html.indexOf("-->", lt + 4);
1057
+ i = close === -1 ? html.length : close + 3;
1058
+ } else {
1059
+ const close = html.indexOf(">", lt + 2);
1060
+ i = close === -1 ? html.length : close + 1;
1061
+ }
1062
+ textStart = i;
1063
+ continue;
1064
+ }
1065
+ if (next === "/") {
1066
+ const close = html.indexOf(">", lt + 2);
1067
+ const end = close === -1 ? html.length : close + 1;
1068
+ const rawName = html.slice(lt + 2, close === -1 ? html.length : close).trim();
1069
+ const tag = rawName.toLowerCase();
1070
+ if (tag.length > 0) popTo(tag);
1071
+ i = end;
1072
+ textStart = i;
1073
+ continue;
1074
+ }
1075
+ const parsed = parseStartTag(html, lt);
1076
+ applyImpliedEndTags(parsed.tag);
1077
+ const parent = topIndex();
1078
+ const own = ownExclusion(parsed.tag, parsed.attrs);
1079
+ const element = {
1080
+ index: elements.length,
1081
+ tag: parsed.tag,
1082
+ attrs: parsed.attrs,
1083
+ offset: cursor.at(lt),
1084
+ parent,
1085
+ depth: stack.length,
1086
+ excludedBy: exclusionAt(parent) ?? own
1087
+ };
1088
+ elements.push(element);
1089
+ collectMetaOrLink(element, metas, links);
1090
+ i = parsed.end;
1091
+ const isVoid = VOID_ELEMENTS.has(parsed.tag);
1092
+ const isRawText = RAW_TEXT_ELEMENTS.has(parsed.tag);
1093
+ const isRcdata = RCDATA_ELEMENTS.has(parsed.tag);
1094
+ if (isRawText || isRcdata) {
1095
+ const contentStart = i;
1096
+ lowerHtml ??= html.toLowerCase();
1097
+ const close = findRawTextEnd(lowerHtml, contentStart, parsed.tag);
1098
+ const contentEnd = close === -1 ? html.length : close;
1099
+ if (contentEnd > contentStart) {
1100
+ const wasTop = stack.length;
1101
+ stack.push(element.index);
1102
+ emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? void 0);
1103
+ stack.length = wasTop;
1104
+ if (own === "script-ld-json") {
1105
+ jsonLd.push({
1106
+ text: html.slice(contentStart, contentEnd),
1107
+ offset: cursor.at(contentStart),
1108
+ element: element.index
1109
+ });
1110
+ }
1111
+ }
1112
+ if (close === -1) {
1113
+ i = html.length;
1114
+ } else {
1115
+ const gt = html.indexOf(">", close);
1116
+ i = gt === -1 ? html.length : gt + 1;
1117
+ }
1118
+ textStart = i;
1119
+ continue;
1120
+ }
1121
+ if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index);
1122
+ textStart = i;
1123
+ }
1124
+ emitText(textStart, html.length, true);
1125
+ return {
1126
+ elements,
1127
+ texts,
1128
+ jsonLd,
1129
+ metas,
1130
+ links,
1131
+ bytes: cursor.at(html.length)
1132
+ };
1133
+ }
1134
+ function collectMetaOrLink(element, metas, links) {
1135
+ const lower = (value) => value === void 0 ? null : value.toLowerCase();
1136
+ if (element.tag === "meta") {
1137
+ metas.push({
1138
+ name: lower(element.attrs["name"]),
1139
+ property: lower(element.attrs["property"]),
1140
+ httpEquiv: lower(element.attrs["http-equiv"]),
1141
+ itemprop: lower(element.attrs["itemprop"]),
1142
+ charset: lower(element.attrs["charset"]),
1143
+ content: element.attrs["content"] ?? null,
1144
+ element: element.index,
1145
+ offset: element.offset
1146
+ });
1147
+ return;
1148
+ }
1149
+ if (element.tag === "link") {
1150
+ const rawRel = element.attrs["rel"] ?? "";
1151
+ const rel = [];
1152
+ for (const token of rawRel.toLowerCase().split(/\s+/)) {
1153
+ if (token.length > 0 && !rel.includes(token)) rel.push(token);
1154
+ }
1155
+ links.push({
1156
+ rel,
1157
+ href: element.attrs["href"] ?? null,
1158
+ type: lower(element.attrs["type"]),
1159
+ hreflang: lower(element.attrs["hreflang"]),
1160
+ title: element.attrs["title"] ?? null,
1161
+ element: element.index,
1162
+ offset: element.offset
1163
+ });
1164
+ }
1165
+ }
1166
+ function joinText(parts) {
1167
+ return parts.join(" ").replace(/\s+/g, " ").trim();
1168
+ }
1169
+ function countedText(doc) {
1170
+ const parts = [];
1171
+ for (const node of doc.texts) {
1172
+ if (node.excludedBy === null) parts.push(node.text);
1173
+ }
1174
+ return joinText(parts);
1175
+ }
1176
+
648
1177
  // src/extract.ts
649
1178
  function utf8Length(text) {
650
1179
  let bytes = 0;
@@ -662,6 +1191,100 @@ function utf8Length(text) {
662
1191
  }
663
1192
  return bytes;
664
1193
  }
1194
+ var SCHEMA_PREFIX = /^https?:\/\/schema\.org\//;
1195
+ function stripSchemaPrefix(type) {
1196
+ return type.replace(SCHEMA_PREFIX, "");
1197
+ }
1198
+ function typesOf(value) {
1199
+ const raw = value["@type"];
1200
+ if (typeof raw === "string") return [stripSchemaPrefix(raw)];
1201
+ if (Array.isArray(raw)) {
1202
+ const out = [];
1203
+ for (const entry of raw) if (typeof entry === "string") out.push(stripSchemaPrefix(entry));
1204
+ return out;
1205
+ }
1206
+ return [];
1207
+ }
1208
+ var JSON_LD_MAX_DEPTH = 12;
1209
+ function collectNodes(value, offset, depth, out, seen) {
1210
+ if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== "object") return;
1211
+ if (seen.has(value)) return;
1212
+ seen.add(value);
1213
+ if (Array.isArray(value)) {
1214
+ for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen);
1215
+ return;
1216
+ }
1217
+ const record = value;
1218
+ const types = typesOf(record);
1219
+ if (types.length > 0) out.push({ types, value: record, offset });
1220
+ for (const [key, child] of Object.entries(record)) {
1221
+ if (key === "@context") continue;
1222
+ collectNodes(child, offset, depth + 1, out, seen);
1223
+ }
1224
+ }
1225
+ function parseJsonLd(blocks) {
1226
+ const nodes = [];
1227
+ let parsed = 0;
1228
+ for (const block of blocks) {
1229
+ let value;
1230
+ try {
1231
+ value = JSON.parse(block.text);
1232
+ } catch {
1233
+ continue;
1234
+ }
1235
+ parsed++;
1236
+ collectNodes(value, block.offset, 0, nodes, /* @__PURE__ */ new Set());
1237
+ }
1238
+ return { nodes, blocks: blocks.length, parsed };
1239
+ }
1240
+ function header(headers, name) {
1241
+ const values = headers[name];
1242
+ return values !== void 0 && values.length > 0 ? values[0] ?? null : null;
1243
+ }
1244
+ function headerAll(headers, name) {
1245
+ return headers[name] ?? [];
1246
+ }
1247
+ function mediaType(contentType) {
1248
+ if (contentType === null) return null;
1249
+ const semi = contentType.indexOf(";");
1250
+ const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
1251
+ return value.length > 0 ? value : null;
1252
+ }
1253
+ function classifyMediaType(type) {
1254
+ if (type === null) return "other";
1255
+ if (type === "text/html" || type === "application/xhtml+xml") return "html";
1256
+ if (type === "text/markdown" || type === "text/x-markdown") return "markdown";
1257
+ if (type === "text/plain") return "text";
1258
+ if (type === "application/json" || type === "application/ld+json" || type.endsWith("+json")) {
1259
+ return "json";
1260
+ }
1261
+ return "other";
1262
+ }
1263
+ function bodyLooksLikeHtml(body) {
1264
+ const head = body.slice(0, 1024).trimStart().toLowerCase();
1265
+ return head.startsWith("<!doctype html") || head.startsWith("<html") || head.startsWith("<?xml") ? true : head.includes("<html") || head.includes("<head>") || head.includes("<body");
1266
+ }
1267
+ function buildRepresentation(capture) {
1268
+ if (typeof capture.body !== "string") return null;
1269
+ const contentType = mediaType(header(capture.headers, "content-type"));
1270
+ const declared = classifyMediaType(contentType);
1271
+ const looksLikeHtml = bodyLooksLikeHtml(capture.body);
1272
+ const doc = declared === "html" || looksLikeHtml ? tokenizeHtml(capture.body) : null;
1273
+ const jsonLd = doc !== null ? parseJsonLd(doc.jsonLd.map((block) => ({ text: block.text, offset: block.offset }))) : declared === "json" ? parseJsonLd([{ text: capture.body, offset: 0 }]) : { nodes: [], blocks: 0, parsed: 0 };
1274
+ return {
1275
+ kind: declared,
1276
+ contentType,
1277
+ body: capture.body,
1278
+ bytes: capture.bytes,
1279
+ doc,
1280
+ jsonLd,
1281
+ text: doc !== null ? countedText(doc) : capture.body,
1282
+ looksLikeHtml,
1283
+ truncated: capture.truncated,
1284
+ finalUrl: capture.finalUrl,
1285
+ headers: capture.headers
1286
+ };
1287
+ }
665
1288
  function parseRobots(text) {
666
1289
  const groups = [];
667
1290
  const sitemaps = [];
@@ -703,7 +1326,10 @@ function parseRobots(text) {
703
1326
  else current.disallow.push(value);
704
1327
  continue;
705
1328
  }
706
- if (field === "crawl-delay" || field === "host" || field === "clean-param") continue;
1329
+ if (field === "crawl-delay" || field === "host" || field === "clean-param" || field === "content-signal") {
1330
+ if (field === "content-signal" && current !== null) openingGroup = false;
1331
+ continue;
1332
+ }
707
1333
  malformedLines++;
708
1334
  }
709
1335
  return { groups, sitemaps, malformedLines, orphanRules };
@@ -785,8 +1411,14 @@ deepFreeze2({
785
1411
  band: [100, 7, 75, 5, 50, 3, 25, 1],
786
1412
  noscriptFloor: 1
787
1413
  },
788
- /** D2.1, 9. All-or-nothing: a machine media type AND a body that is not HTML. */
789
- negotiatedResponse: { full: 9 },
1414
+ /**
1415
+ * D2.1, 9 for a machine copy served at the page's own address on `Accept`
1416
+ * negotiation: a machine media type AND a body that is not HTML. ARS 0.3: 6
1417
+ * when the page does not negotiate but the Markdown copy it declares as an
1418
+ * alternate was fetched and is real. Less than full because only agents that
1419
+ * look for the link reach it, and they pay a second request to do so.
1420
+ */
1421
+ negotiatedResponse: { full: 9, linkedCopy: 6 },
790
1422
  /** D2.2, 3. All-or-nothing. */
791
1423
  declaredAlternates: { full: 3 },
792
1424
  /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */
@@ -938,7 +1570,183 @@ function sha256Hex(message) {
938
1570
  for (const word of h) hex += word.toString(16).padStart(8, "0");
939
1571
  return hex;
940
1572
  }
941
- sha256Hex("ars-0.2-corpus-unfrozen");
1573
+ sha256Hex("ars-0.3-corpus-unfrozen");
1574
+ function parseLinkHeaders(values) {
1575
+ const out = [];
1576
+ for (const value of values) {
1577
+ for (const entry of splitLinkEntries(value)) {
1578
+ const open = entry.indexOf("<");
1579
+ const close = entry.indexOf(">", open + 1);
1580
+ if (open === -1 || close === -1) continue;
1581
+ const url = entry.slice(open + 1, close).trim();
1582
+ if (url.length === 0) continue;
1583
+ let rel = [];
1584
+ let type = null;
1585
+ for (const param of entry.slice(close + 1).split(";")) {
1586
+ const equals = param.indexOf("=");
1587
+ if (equals === -1) continue;
1588
+ const name = param.slice(0, equals).trim().toLowerCase();
1589
+ const raw = param.slice(equals + 1).trim();
1590
+ const unquoted = raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1) : raw;
1591
+ if (name === "rel")
1592
+ rel = unquoted.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
1593
+ else if (name === "type") type = unquoted.trim().toLowerCase();
1594
+ }
1595
+ out.push({ url, rel, type });
1596
+ }
1597
+ }
1598
+ return out;
1599
+ }
1600
+ function splitLinkEntries(value) {
1601
+ const entries = [];
1602
+ let depth = 0;
1603
+ let quoted = false;
1604
+ let start = 0;
1605
+ for (let i = 0; i < value.length; i++) {
1606
+ const char = value.charAt(i);
1607
+ if (quoted) {
1608
+ if (char === '"') quoted = false;
1609
+ continue;
1610
+ }
1611
+ if (char === '"') quoted = true;
1612
+ else if (char === "<") depth++;
1613
+ else if (char === ">") depth = depth > 0 ? depth - 1 : 0;
1614
+ else if (char === "," && depth === 0) {
1615
+ entries.push(value.slice(start, i));
1616
+ start = i + 1;
1617
+ }
1618
+ }
1619
+ entries.push(value.slice(start));
1620
+ return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0);
1621
+ }
1622
+ var MACHINE_KINDS = /* @__PURE__ */ new Set(["markdown", "text", "json"]);
1623
+ function isMachineCopy(capture) {
1624
+ const representation = buildRepresentation(capture);
1625
+ return representation !== null && MACHINE_KINDS.has(representation.kind) && !representation.looksLikeHtml;
1626
+ }
1627
+ var MARKDOWN_MEDIA = /* @__PURE__ */ new Set(["text/markdown", "text/x-markdown"]);
1628
+ function isMarkdownType(type) {
1629
+ return type !== null && MARKDOWN_MEDIA.has((type.split(";")[0] ?? "").trim().toLowerCase());
1630
+ }
1631
+ function declaredMarkdownAlternates(captures) {
1632
+ const out = [];
1633
+ const add = (raw, base) => {
1634
+ try {
1635
+ const url = new URL(raw, base);
1636
+ url.hash = "";
1637
+ const href = url.toString();
1638
+ if (!out.includes(href)) out.push(href);
1639
+ } catch {
1640
+ }
1641
+ };
1642
+ for (const capture of captures) {
1643
+ if (capture === null) continue;
1644
+ for (const link of parseLinkHeaders(headerAll(capture.headers, "link"))) {
1645
+ if (link.rel.includes("alternate") && isMarkdownType(link.type)) add(link.url, capture.finalUrl);
1646
+ }
1647
+ }
1648
+ for (const capture of captures) {
1649
+ if (capture === null) continue;
1650
+ const representation = buildRepresentation(capture);
1651
+ if (representation === null || representation.doc === null) continue;
1652
+ for (const link of representation.doc.links) {
1653
+ if (!link.rel.includes("alternate") || link.href === null) continue;
1654
+ if (isMarkdownType(link.type)) add(link.href, capture.finalUrl);
1655
+ }
1656
+ }
1657
+ return out;
1658
+ }
1659
+ function markdownAlternateTarget(agent, browser, origin) {
1660
+ if (agent === null || agent.status < 200 || agent.status >= 300) return null;
1661
+ if (isMachineCopy(agent)) return null;
1662
+ const own = /* @__PURE__ */ new Set([agent.finalUrl, agent.requestedUrl]);
1663
+ for (const href of declaredMarkdownAlternates([browser, agent])) {
1664
+ let sameOrigin = false;
1665
+ try {
1666
+ sameOrigin = new URL(href).origin === origin;
1667
+ } catch {
1668
+ sameOrigin = false;
1669
+ }
1670
+ if (sameOrigin && !own.has(href)) return href;
1671
+ }
1672
+ return null;
1673
+ }
1674
+
1675
+ // src/site-signals.ts
1676
+ var BODY_SCAN_CHARS = 256 * 1024;
1677
+ function headerValues(input, name) {
1678
+ const direct = input.headers[name];
1679
+ if (direct !== void 0) return direct.map((value) => value.toLowerCase());
1680
+ const target = name.toLowerCase();
1681
+ const out = [];
1682
+ for (const [key, values] of Object.entries(input.headers)) {
1683
+ if (key.toLowerCase() === target) {
1684
+ for (const value of values) out.push(value.toLowerCase());
1685
+ }
1686
+ }
1687
+ return out;
1688
+ }
1689
+ function hasToken(values, token) {
1690
+ return values.some(
1691
+ (value) => value.split(",").map((part) => part.trim()).includes(token)
1692
+ );
1693
+ }
1694
+ function isRobotsTxtTarget(input) {
1695
+ for (const raw of [input.requestedUrl, input.finalUrl]) {
1696
+ if (typeof raw !== "string" || raw.length === 0) continue;
1697
+ try {
1698
+ if (new URL(raw).pathname.toLowerCase() === "/robots.txt") return true;
1699
+ } catch {
1700
+ const path = (raw.split("#")[0]?.split("?")[0] ?? "").toLowerCase();
1701
+ if (path === "/robots.txt" || path.endsWith("/robots.txt")) return true;
1702
+ }
1703
+ }
1704
+ return false;
1705
+ }
1706
+ function detectEdgeChallenge(input) {
1707
+ const status = input.status;
1708
+ const body = typeof input.body === "string" ? input.body.slice(0, BODY_SCAN_CHARS) : "";
1709
+ const server = headerValues(input, "server");
1710
+ const contentTypes = headerValues(input, "content-type");
1711
+ const isHtmlContent = contentTypes.some(
1712
+ (value) => value.includes("text/html") || value.includes("application/xhtml+xml")
1713
+ );
1714
+ const lowerBodyHead = body.slice(0, 4096).toLowerCase();
1715
+ const isPlainTextWithoutMarkup = contentTypes.some((value) => value.includes("text/plain")) && !lowerBodyHead.includes("<html") && !lowerBodyHead.includes("<script") && !lowerBodyHead.includes("<!doctype html");
1716
+ const isRobotsHtmlChallenge = isRobotsTxtTarget(input) && isHtmlContent;
1717
+ if (hasToken(headerValues(input, "cf-mitigated"), "challenge")) {
1718
+ return { vendor: "cloudflare", signal: "cf-mitigated: challenge", status };
1719
+ }
1720
+ if ((status === 403 || status === 429 || status === 503 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && server.some((value) => value.includes("cloudflare")) && body.includes("/cdn-cgi/challenge-platform/")) {
1721
+ return { vendor: "cloudflare", signal: "Cloudflare challenge page", status };
1722
+ }
1723
+ if (hasToken(headerValues(input, "x-vercel-mitigated"), "challenge")) {
1724
+ return { vendor: "vercel", signal: "x-vercel-mitigated: challenge", status };
1725
+ }
1726
+ if ((status < 200 || status >= 300 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && server.some((value) => value.includes("vercel")) && body.includes("Vercel Security Checkpoint")) {
1727
+ return { vendor: "vercel", signal: "Vercel Security Checkpoint page", status };
1728
+ }
1729
+ if ((status === 401 || status === 403) && headerValues(input, "x-datadome").length > 0) {
1730
+ return { vendor: "datadome", signal: `x-datadome with HTTP ${status}`, status };
1731
+ }
1732
+ if ((status === 403 || status === 429 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && body.includes("px-captcha") && body.includes("_pxAppId")) {
1733
+ return { vendor: "human", signal: "HUMAN block page", status };
1734
+ }
1735
+ return null;
1736
+ }
1737
+ var DETAIL_PREFIX = "edge-challenge";
1738
+ function challengeDetail(challenge) {
1739
+ return `${DETAIL_PREFIX}; vendor=${challenge.vendor}; status=${challenge.status}; signal=${challenge.signal.slice(0, 120)}`;
1740
+ }
1741
+ new Set(
1742
+ [
1743
+ ...DEFAULT_RULESET.audienceTokens.assistant,
1744
+ ...DEFAULT_RULESET.audienceTokens.training,
1745
+ ...DEFAULT_RULESET.audienceTokens.search,
1746
+ "googlebot",
1747
+ "bingbot"
1748
+ ].map((token) => token.toLowerCase())
1749
+ );
942
1750
 
943
1751
  // src/probe/limiter.ts
944
1752
  var ProbeBudgetExceededError = class extends Error {
@@ -953,7 +1761,7 @@ var ProbeBudgetExceededError = class extends Error {
953
1761
  };
954
1762
 
955
1763
  // src/probe/index.ts
956
- var ARS_USER_AGENT = "rebilder-ars/0.2 (+https://rebilder.com/bots)";
1764
+ var ARS_USER_AGENT = "rebilder-ars/0.3 (+https://rebilder.com/bots)";
957
1765
  var AGENT_IDENTITY = {
958
1766
  role: "agent",
959
1767
  userAgent: ARS_USER_AGENT,
@@ -1247,6 +2055,16 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1247
2055
  };
1248
2056
  }
1249
2057
  };
2058
+ const runPage = async (href, headers) => {
2059
+ const record = await run(href, headers);
2060
+ if (!record.result.ok) return record;
2061
+ const challenge = detectEdgeChallenge(record.result.capture);
2062
+ if (challenge === null) return record;
2063
+ return {
2064
+ requestHeaders: headers,
2065
+ result: { ok: false, error: "challenge", detail: challengeDetail(challenge) }
2066
+ };
2067
+ };
1250
2068
  const evidenceOf = (probes) => ({
1251
2069
  ok: true,
1252
2070
  evidence: {
@@ -1291,8 +2109,18 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1291
2109
  wellKnownUcp: null
1292
2110
  });
1293
2111
  }
1294
- const agent = await run(url.toString(), agentHeaders);
1295
- const browser = await run(url.toString(), browserHeaders);
2112
+ const agent = await runPage(url.toString(), agentHeaders);
2113
+ const browser = await runPage(url.toString(), browserHeaders);
2114
+ const linked = markdownAlternateTarget(
2115
+ agent.result.ok ? agent.result.capture : null,
2116
+ browser.result.ok ? browser.result.capture : null,
2117
+ origin
2118
+ );
2119
+ let markdownAlternate = null;
2120
+ if (linked !== null) {
2121
+ const rule = disallowedFor(new URL(linked).pathname);
2122
+ markdownAlternate = rule !== null ? skipped(agentHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${linked}`) : await runPage(linked, agentHeaders);
2123
+ }
1296
2124
  const fetchAsset = async (path) => {
1297
2125
  const rule = disallowedFor(path);
1298
2126
  if (rule !== null)
@@ -1301,7 +2129,17 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1301
2129
  };
1302
2130
  const llmsTxt = await fetchAsset("/llms.txt");
1303
2131
  const wellKnownUcp = await fetchAsset("/.well-known/ucp");
1304
- return evidenceOf({ agent, browser, parityConfirm: null, robotsTxt, llmsTxt, wellKnownUcp });
2132
+ return evidenceOf({
2133
+ agent,
2134
+ browser,
2135
+ parityConfirm: null,
2136
+ // Omitted when not taken, so a page with no linked copy produces exactly
2137
+ // the bundle (and the evidence hash) it produced under 0.2.
2138
+ ...markdownAlternate === null ? {} : { markdownAlternate },
2139
+ robotsTxt,
2140
+ llmsTxt,
2141
+ wellKnownUcp
2142
+ });
1305
2143
  } catch (error) {
1306
2144
  if (error instanceof ProbeBudgetExceededError) {
1307
2145
  return { ok: false, rejection: "budget-exceeded", detail: error.message };