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