@rebilder/agent-readability 0.3.0 → 0.4.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.
@@ -563,33 +563,61 @@ var ACTION_LEXICON = [
563
563
  "book now",
564
564
  "buy",
565
565
  "buy now",
566
+ "call",
566
567
  "call now",
568
+ "check availability",
569
+ "check out",
567
570
  "checkout",
568
571
  "contact",
569
572
  "contact us",
573
+ "create account",
574
+ "create an account",
570
575
  "donate",
571
576
  "download",
572
577
  "email us",
578
+ "enquire",
579
+ "enrol",
573
580
  "enroll",
581
+ "free trial",
582
+ "get a demo",
574
583
  "get a quote",
584
+ "get directions",
585
+ "get in touch",
575
586
  "get quote",
576
587
  "get started",
588
+ "get the app",
589
+ "get tickets",
590
+ "hire",
591
+ "inquire",
592
+ "install",
577
593
  "join",
578
594
  "make an appointment",
595
+ "message us",
579
596
  "order",
580
597
  "order now",
598
+ "order online",
599
+ "pre-order",
600
+ "preorder",
581
601
  "purchase",
582
602
  "register",
603
+ "rent",
583
604
  "request",
584
605
  "request a demo",
585
606
  "request a quote",
586
607
  "reserve",
587
608
  "schedule",
609
+ "shop",
610
+ "shop now",
588
611
  "sign up",
589
612
  "signup",
590
613
  "start",
591
614
  "start free trial",
592
- "subscribe"
615
+ "subscribe",
616
+ "talk to sales",
617
+ "talk to us",
618
+ "text us",
619
+ "try",
620
+ "upgrade"
593
621
  ];
594
622
  var BANDS = [
595
623
  {
@@ -629,7 +657,7 @@ var BANDS = [
629
657
  }
630
658
  ];
631
659
  var DEFAULT_RULESET = deepFreeze({
632
- version: "0.2.0",
660
+ version: "0.3.0",
633
661
  weights: WEIGHTS,
634
662
  thresholds: THRESHOLDS,
635
663
  audienceTokens: AUDIENCE_TOKENS,
@@ -645,6 +673,494 @@ var DEFAULT_RULESET = deepFreeze({
645
673
  bands: BANDS
646
674
  });
647
675
 
676
+ // src/html.ts
677
+ var Utf8Cursor = class {
678
+ constructor(source) {
679
+ this.source = source;
680
+ }
681
+ source;
682
+ charIndex = 0;
683
+ byteIndex = 0;
684
+ at(target) {
685
+ if (target < this.charIndex) {
686
+ this.charIndex = 0;
687
+ this.byteIndex = 0;
688
+ }
689
+ const limit = Math.min(target, this.source.length);
690
+ while (this.charIndex < limit) {
691
+ const code = this.source.charCodeAt(this.charIndex);
692
+ if (code < 128) {
693
+ this.byteIndex += 1;
694
+ this.charIndex += 1;
695
+ } else if (code < 2048) {
696
+ this.byteIndex += 2;
697
+ this.charIndex += 1;
698
+ } else if (code >= 55296 && code <= 56319) {
699
+ const next = this.charIndex + 1 < this.source.length ? this.source.charCodeAt(this.charIndex + 1) : 0;
700
+ if (next >= 56320 && next <= 57343 && this.charIndex + 1 < limit) {
701
+ this.byteIndex += 4;
702
+ this.charIndex += 2;
703
+ } else {
704
+ this.byteIndex += 3;
705
+ this.charIndex += 1;
706
+ }
707
+ } else {
708
+ this.byteIndex += 3;
709
+ this.charIndex += 1;
710
+ }
711
+ }
712
+ return this.byteIndex;
713
+ }
714
+ };
715
+ var NAMED_ENTITIES = {
716
+ amp: "&",
717
+ lt: "<",
718
+ gt: ">",
719
+ quot: '"',
720
+ apos: "'",
721
+ nbsp: "\xA0",
722
+ ensp: "\u2002",
723
+ emsp: "\u2003",
724
+ thinsp: "\u2009",
725
+ shy: "\xAD",
726
+ zwnj: "\u200C",
727
+ zwj: "\u200D",
728
+ // Currency
729
+ cent: "\xA2",
730
+ pound: "\xA3",
731
+ curren: "\xA4",
732
+ yen: "\xA5",
733
+ euro: "\u20AC",
734
+ dollar: "$",
735
+ // Typography
736
+ ndash: "\u2013",
737
+ mdash: "\u2014",
738
+ hellip: "\u2026",
739
+ lsquo: "\u2018",
740
+ rsquo: "\u2019",
741
+ sbquo: "\u201A",
742
+ ldquo: "\u201C",
743
+ rdquo: "\u201D",
744
+ bdquo: "\u201E",
745
+ laquo: "\xAB",
746
+ raquo: "\xBB",
747
+ lsaquo: "\u2039",
748
+ rsaquo: "\u203A",
749
+ bull: "\u2022",
750
+ middot: "\xB7",
751
+ dagger: "\u2020",
752
+ Dagger: "\u2021",
753
+ prime: "\u2032",
754
+ Prime: "\u2033",
755
+ // Marks and math
756
+ copy: "\xA9",
757
+ reg: "\xAE",
758
+ trade: "\u2122",
759
+ sect: "\xA7",
760
+ para: "\xB6",
761
+ deg: "\xB0",
762
+ plusmn: "\xB1",
763
+ times: "\xD7",
764
+ divide: "\xF7",
765
+ minus: "\u2212",
766
+ permil: "\u2030",
767
+ frac12: "\xBD",
768
+ frac14: "\xBC",
769
+ frac34: "\xBE",
770
+ sup2: "\xB2",
771
+ sup3: "\xB3",
772
+ le: "\u2264",
773
+ ge: "\u2265",
774
+ ne: "\u2260",
775
+ // Directionality (invisible, but they do occupy bytes)
776
+ lrm: "\u200E",
777
+ rlm: "\u200F"
778
+ };
779
+ var C1_REPLACEMENTS = {
780
+ 128: 8364,
781
+ 130: 8218,
782
+ 131: 402,
783
+ 132: 8222,
784
+ 133: 8230,
785
+ 134: 8224,
786
+ 135: 8225,
787
+ 136: 710,
788
+ 137: 8240,
789
+ 138: 352,
790
+ 139: 8249,
791
+ 140: 338,
792
+ 142: 381,
793
+ 145: 8216,
794
+ 146: 8217,
795
+ 147: 8220,
796
+ 148: 8221,
797
+ 149: 8226,
798
+ 150: 8211,
799
+ 151: 8212,
800
+ 152: 732,
801
+ 153: 8482,
802
+ 154: 353,
803
+ 155: 8250,
804
+ 156: 339,
805
+ 158: 382,
806
+ 159: 376
807
+ };
808
+ var ENTITY_RE = /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{0,31});/g;
809
+ function codePointToString(raw) {
810
+ const mapped = C1_REPLACEMENTS[raw];
811
+ const code = mapped ?? raw;
812
+ if (code === 0 || code > 1114111 || code >= 55296 && code <= 57343) return "\uFFFD";
813
+ return String.fromCodePoint(code);
814
+ }
815
+ function decodeEntities(text) {
816
+ if (!text.includes("&")) return text;
817
+ return text.replace(ENTITY_RE, (match, body) => {
818
+ if (body.startsWith("#")) {
819
+ const isHex = body[1] === "x" || body[1] === "X";
820
+ const digits = isHex ? body.slice(2) : body.slice(1);
821
+ const value = Number.parseInt(digits, isHex ? 16 : 10);
822
+ return Number.isNaN(value) ? match : codePointToString(value);
823
+ }
824
+ return NAMED_ENTITIES[body] ?? match;
825
+ });
826
+ }
827
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
828
+ "area",
829
+ "base",
830
+ "br",
831
+ "col",
832
+ "embed",
833
+ "hr",
834
+ "img",
835
+ "input",
836
+ "link",
837
+ "meta",
838
+ "param",
839
+ "source",
840
+ "track",
841
+ "wbr"
842
+ ]);
843
+ var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style"]);
844
+ var RCDATA_ELEMENTS = /* @__PURE__ */ new Set(["textarea", "title"]);
845
+ var IMPLIED_END_TAGS = {
846
+ li: ["li"],
847
+ dt: ["dt", "dd"],
848
+ dd: ["dt", "dd"],
849
+ option: ["option"],
850
+ optgroup: ["option", "optgroup"],
851
+ tr: ["td", "th", "tr"],
852
+ td: ["td", "th"],
853
+ th: ["td", "th"],
854
+ tbody: ["td", "th", "tr", "thead", "tbody"],
855
+ tfoot: ["td", "th", "tr", "thead", "tbody"]
856
+ };
857
+ var CLOSES_OPEN_P = /* @__PURE__ */ new Set([
858
+ "address",
859
+ "article",
860
+ "aside",
861
+ "blockquote",
862
+ "details",
863
+ "div",
864
+ "dl",
865
+ "fieldset",
866
+ "figcaption",
867
+ "figure",
868
+ "footer",
869
+ "form",
870
+ "h1",
871
+ "h2",
872
+ "h3",
873
+ "h4",
874
+ "h5",
875
+ "h6",
876
+ "header",
877
+ "hr",
878
+ "main",
879
+ "nav",
880
+ "ol",
881
+ "p",
882
+ "pre",
883
+ "section",
884
+ "table",
885
+ "ul"
886
+ ]);
887
+ var MAX_DEPTH = 256;
888
+ function isAsciiAlpha(ch) {
889
+ if (ch === void 0) return false;
890
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z";
891
+ }
892
+ function isHtmlSpace(ch) {
893
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f";
894
+ }
895
+ var DISPLAY_NONE_RE = /(^|;)display:none(!important)?(;|$)/;
896
+ function hasInlineDisplayNone(style) {
897
+ if (style === void 0) return false;
898
+ return DISPLAY_NONE_RE.test(style.toLowerCase().replace(/\s+/g, ""));
899
+ }
900
+ function parseStartTag(html, start) {
901
+ let i = start + 1;
902
+ const nameStart = i;
903
+ while (i < html.length) {
904
+ const ch = html[i] ?? "";
905
+ if (isHtmlSpace(ch) || ch === "/" || ch === ">") break;
906
+ i++;
907
+ }
908
+ const tag = html.slice(nameStart, i).toLowerCase();
909
+ const attrs = {};
910
+ let selfClosing = false;
911
+ while (i < html.length) {
912
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
913
+ if (i >= html.length) break;
914
+ const ch = html[i] ?? "";
915
+ if (ch === ">") {
916
+ i++;
917
+ return { tag, attrs, selfClosing, end: i };
918
+ }
919
+ if (ch === "/") {
920
+ selfClosing = true;
921
+ i++;
922
+ continue;
923
+ }
924
+ const attrNameStart = i;
925
+ while (i < html.length) {
926
+ const c = html[i] ?? "";
927
+ if (isHtmlSpace(c) || c === "=" || c === ">" || c === "/") break;
928
+ i++;
929
+ }
930
+ if (i === attrNameStart) {
931
+ i++;
932
+ continue;
933
+ }
934
+ const attrName = html.slice(attrNameStart, i).toLowerCase();
935
+ let value = "";
936
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
937
+ if (html[i] === "=") {
938
+ i++;
939
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
940
+ const quote = html[i];
941
+ if (quote === '"' || quote === "'") {
942
+ i++;
943
+ const valueStart = i;
944
+ const close = html.indexOf(quote, i);
945
+ if (close === -1) {
946
+ value = html.slice(valueStart);
947
+ i = html.length;
948
+ } else {
949
+ value = html.slice(valueStart, close);
950
+ i = close + 1;
951
+ }
952
+ } else {
953
+ const valueStart = i;
954
+ while (i < html.length) {
955
+ const c = html[i] ?? "";
956
+ if (isHtmlSpace(c) || c === ">") break;
957
+ i++;
958
+ }
959
+ value = html.slice(valueStart, i);
960
+ }
961
+ }
962
+ if (!(attrName in attrs)) attrs[attrName] = decodeEntities(value);
963
+ }
964
+ return { tag, attrs, selfClosing, end: i };
965
+ }
966
+ function findRawTextEnd(html, from, tag) {
967
+ const needle = `</${tag}`;
968
+ const lower = html.toLowerCase();
969
+ const at = lower.indexOf(needle, from);
970
+ return at === -1 ? -1 : at;
971
+ }
972
+ function ownExclusion(tag, attrs) {
973
+ if (tag === "script") {
974
+ const type = (attrs["type"] ?? "").toLowerCase().split(";")[0]?.trim() ?? "";
975
+ return type === "application/ld+json" ? "script-ld-json" : "script";
976
+ }
977
+ if (tag === "style") return "style";
978
+ if (tag === "template") return "template";
979
+ if ("hidden" in attrs) return "hidden-attribute";
980
+ if (hasInlineDisplayNone(attrs["style"])) return "inline-display-none";
981
+ return null;
982
+ }
983
+ function tokenizeHtml(html) {
984
+ const elements = [];
985
+ const texts = [];
986
+ const jsonLd = [];
987
+ const metas = [];
988
+ const links = [];
989
+ const stack = [];
990
+ const cursor = new Utf8Cursor(html);
991
+ const topIndex = () => stack[stack.length - 1] ?? -1;
992
+ const exclusionAt = (elementIndex) => elementIndex >= 0 ? elements[elementIndex]?.excludedBy ?? null : null;
993
+ const emitText = (from, to, decode, override) => {
994
+ if (to <= from) return;
995
+ const raw = html.slice(from, to);
996
+ const parent = topIndex();
997
+ const offset = cursor.at(from);
998
+ texts.push({
999
+ text: decode ? decodeEntities(raw) : raw,
1000
+ offset,
1001
+ bytes: cursor.at(to) - offset,
1002
+ parent,
1003
+ excludedBy: override ?? exclusionAt(parent)
1004
+ });
1005
+ };
1006
+ const popTo = (tag) => {
1007
+ for (let depth = stack.length - 1; depth >= 0; depth--) {
1008
+ const candidate = stack[depth];
1009
+ if (candidate === void 0) continue;
1010
+ if (elements[candidate]?.tag === tag) {
1011
+ stack.length = depth;
1012
+ return;
1013
+ }
1014
+ }
1015
+ };
1016
+ const applyImpliedEndTags = (tag) => {
1017
+ const closes = IMPLIED_END_TAGS[tag];
1018
+ if (closes !== void 0) {
1019
+ while (stack.length > 0) {
1020
+ const top = stack[stack.length - 1];
1021
+ const openTag = top === void 0 ? void 0 : elements[top]?.tag;
1022
+ if (openTag === void 0 || !closes.includes(openTag)) break;
1023
+ stack.pop();
1024
+ }
1025
+ }
1026
+ if (CLOSES_OPEN_P.has(tag)) {
1027
+ const top = stack[stack.length - 1];
1028
+ if (top !== void 0 && elements[top]?.tag === "p") stack.pop();
1029
+ }
1030
+ };
1031
+ let i = 0;
1032
+ let textStart = 0;
1033
+ while (i < html.length) {
1034
+ const lt = html.indexOf("<", i);
1035
+ if (lt === -1) break;
1036
+ const next = html[lt + 1];
1037
+ if (next !== "!" && next !== "/" && !isAsciiAlpha(next)) {
1038
+ i = lt + 1;
1039
+ continue;
1040
+ }
1041
+ emitText(textStart, lt, true);
1042
+ if (next === "!") {
1043
+ if (html.startsWith("<!--", lt)) {
1044
+ const close = html.indexOf("-->", lt + 4);
1045
+ i = close === -1 ? html.length : close + 3;
1046
+ } else {
1047
+ const close = html.indexOf(">", lt + 2);
1048
+ i = close === -1 ? html.length : close + 1;
1049
+ }
1050
+ textStart = i;
1051
+ continue;
1052
+ }
1053
+ if (next === "/") {
1054
+ const close = html.indexOf(">", lt + 2);
1055
+ const end = close === -1 ? html.length : close + 1;
1056
+ const rawName = html.slice(lt + 2, close === -1 ? html.length : close).trim();
1057
+ const tag = rawName.toLowerCase();
1058
+ if (tag.length > 0) popTo(tag);
1059
+ i = end;
1060
+ textStart = i;
1061
+ continue;
1062
+ }
1063
+ const parsed = parseStartTag(html, lt);
1064
+ applyImpliedEndTags(parsed.tag);
1065
+ const parent = topIndex();
1066
+ const own = ownExclusion(parsed.tag, parsed.attrs);
1067
+ const element = {
1068
+ index: elements.length,
1069
+ tag: parsed.tag,
1070
+ attrs: parsed.attrs,
1071
+ offset: cursor.at(lt),
1072
+ parent,
1073
+ depth: stack.length,
1074
+ excludedBy: exclusionAt(parent) ?? own
1075
+ };
1076
+ elements.push(element);
1077
+ collectMetaOrLink(element, metas, links);
1078
+ i = parsed.end;
1079
+ const isVoid = VOID_ELEMENTS.has(parsed.tag);
1080
+ const isRawText = RAW_TEXT_ELEMENTS.has(parsed.tag);
1081
+ const isRcdata = RCDATA_ELEMENTS.has(parsed.tag);
1082
+ if (isRawText || isRcdata) {
1083
+ const contentStart = i;
1084
+ const close = findRawTextEnd(html, contentStart, parsed.tag);
1085
+ const contentEnd = close === -1 ? html.length : close;
1086
+ if (contentEnd > contentStart) {
1087
+ const wasTop = stack.length;
1088
+ stack.push(element.index);
1089
+ emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? void 0);
1090
+ stack.length = wasTop;
1091
+ if (own === "script-ld-json") {
1092
+ jsonLd.push({
1093
+ text: html.slice(contentStart, contentEnd),
1094
+ offset: cursor.at(contentStart),
1095
+ element: element.index
1096
+ });
1097
+ }
1098
+ }
1099
+ if (close === -1) {
1100
+ i = html.length;
1101
+ } else {
1102
+ const gt = html.indexOf(">", close);
1103
+ i = gt === -1 ? html.length : gt + 1;
1104
+ }
1105
+ textStart = i;
1106
+ continue;
1107
+ }
1108
+ if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index);
1109
+ textStart = i;
1110
+ }
1111
+ emitText(textStart, html.length, true);
1112
+ return {
1113
+ elements,
1114
+ texts,
1115
+ jsonLd,
1116
+ metas,
1117
+ links,
1118
+ bytes: cursor.at(html.length)
1119
+ };
1120
+ }
1121
+ function collectMetaOrLink(element, metas, links) {
1122
+ const lower = (value) => value === void 0 ? null : value.toLowerCase();
1123
+ if (element.tag === "meta") {
1124
+ metas.push({
1125
+ name: lower(element.attrs["name"]),
1126
+ property: lower(element.attrs["property"]),
1127
+ httpEquiv: lower(element.attrs["http-equiv"]),
1128
+ itemprop: lower(element.attrs["itemprop"]),
1129
+ charset: lower(element.attrs["charset"]),
1130
+ content: element.attrs["content"] ?? null,
1131
+ element: element.index,
1132
+ offset: element.offset
1133
+ });
1134
+ return;
1135
+ }
1136
+ if (element.tag === "link") {
1137
+ const rawRel = element.attrs["rel"] ?? "";
1138
+ const rel = [];
1139
+ for (const token of rawRel.toLowerCase().split(/\s+/)) {
1140
+ if (token.length > 0 && !rel.includes(token)) rel.push(token);
1141
+ }
1142
+ links.push({
1143
+ rel,
1144
+ href: element.attrs["href"] ?? null,
1145
+ type: lower(element.attrs["type"]),
1146
+ hreflang: lower(element.attrs["hreflang"]),
1147
+ title: element.attrs["title"] ?? null,
1148
+ element: element.index,
1149
+ offset: element.offset
1150
+ });
1151
+ }
1152
+ }
1153
+ function joinText(parts) {
1154
+ return parts.join(" ").replace(/\s+/g, " ").trim();
1155
+ }
1156
+ function countedText(doc) {
1157
+ const parts = [];
1158
+ for (const node of doc.texts) {
1159
+ if (node.excludedBy === null) parts.push(node.text);
1160
+ }
1161
+ return joinText(parts);
1162
+ }
1163
+
648
1164
  // src/extract.ts
649
1165
  function utf8Length(text) {
650
1166
  let bytes = 0;
@@ -662,6 +1178,100 @@ function utf8Length(text) {
662
1178
  }
663
1179
  return bytes;
664
1180
  }
1181
+ var SCHEMA_PREFIX = /^https?:\/\/schema\.org\//;
1182
+ function stripSchemaPrefix(type) {
1183
+ return type.replace(SCHEMA_PREFIX, "");
1184
+ }
1185
+ function typesOf(value) {
1186
+ const raw = value["@type"];
1187
+ if (typeof raw === "string") return [stripSchemaPrefix(raw)];
1188
+ if (Array.isArray(raw)) {
1189
+ const out = [];
1190
+ for (const entry of raw) if (typeof entry === "string") out.push(stripSchemaPrefix(entry));
1191
+ return out;
1192
+ }
1193
+ return [];
1194
+ }
1195
+ var JSON_LD_MAX_DEPTH = 12;
1196
+ function collectNodes(value, offset, depth, out, seen) {
1197
+ if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== "object") return;
1198
+ if (seen.has(value)) return;
1199
+ seen.add(value);
1200
+ if (Array.isArray(value)) {
1201
+ for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen);
1202
+ return;
1203
+ }
1204
+ const record = value;
1205
+ const types = typesOf(record);
1206
+ if (types.length > 0) out.push({ types, value: record, offset });
1207
+ for (const [key, child] of Object.entries(record)) {
1208
+ if (key === "@context") continue;
1209
+ collectNodes(child, offset, depth + 1, out, seen);
1210
+ }
1211
+ }
1212
+ function parseJsonLd(blocks) {
1213
+ const nodes = [];
1214
+ let parsed = 0;
1215
+ for (const block of blocks) {
1216
+ let value;
1217
+ try {
1218
+ value = JSON.parse(block.text);
1219
+ } catch {
1220
+ continue;
1221
+ }
1222
+ parsed++;
1223
+ collectNodes(value, block.offset, 0, nodes, /* @__PURE__ */ new Set());
1224
+ }
1225
+ return { nodes, blocks: blocks.length, parsed };
1226
+ }
1227
+ function header(headers, name) {
1228
+ const values = headers[name];
1229
+ return values !== void 0 && values.length > 0 ? values[0] ?? null : null;
1230
+ }
1231
+ function headerAll(headers, name) {
1232
+ return headers[name] ?? [];
1233
+ }
1234
+ function mediaType(contentType) {
1235
+ if (contentType === null) return null;
1236
+ const semi = contentType.indexOf(";");
1237
+ const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
1238
+ return value.length > 0 ? value : null;
1239
+ }
1240
+ function classifyMediaType(type) {
1241
+ if (type === null) return "other";
1242
+ if (type === "text/html" || type === "application/xhtml+xml") return "html";
1243
+ if (type === "text/markdown" || type === "text/x-markdown") return "markdown";
1244
+ if (type === "text/plain") return "text";
1245
+ if (type === "application/json" || type === "application/ld+json" || type.endsWith("+json")) {
1246
+ return "json";
1247
+ }
1248
+ return "other";
1249
+ }
1250
+ function bodyLooksLikeHtml(body) {
1251
+ const head = body.slice(0, 1024).trimStart().toLowerCase();
1252
+ return head.startsWith("<!doctype html") || head.startsWith("<html") || head.startsWith("<?xml") ? true : head.includes("<html") || head.includes("<head>") || head.includes("<body");
1253
+ }
1254
+ function buildRepresentation(capture) {
1255
+ if (typeof capture.body !== "string") return null;
1256
+ const contentType = mediaType(header(capture.headers, "content-type"));
1257
+ const declared = classifyMediaType(contentType);
1258
+ const looksLikeHtml = bodyLooksLikeHtml(capture.body);
1259
+ const doc = declared === "html" || looksLikeHtml ? tokenizeHtml(capture.body) : null;
1260
+ 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 };
1261
+ return {
1262
+ kind: declared,
1263
+ contentType,
1264
+ body: capture.body,
1265
+ bytes: capture.bytes,
1266
+ doc,
1267
+ jsonLd,
1268
+ text: doc !== null ? countedText(doc) : capture.body,
1269
+ looksLikeHtml,
1270
+ truncated: capture.truncated,
1271
+ finalUrl: capture.finalUrl,
1272
+ headers: capture.headers
1273
+ };
1274
+ }
665
1275
  function parseRobots(text) {
666
1276
  const groups = [];
667
1277
  const sitemaps = [];
@@ -785,8 +1395,14 @@ deepFreeze2({
785
1395
  band: [100, 7, 75, 5, 50, 3, 25, 1],
786
1396
  noscriptFloor: 1
787
1397
  },
788
- /** D2.1, 9. All-or-nothing: a machine media type AND a body that is not HTML. */
789
- negotiatedResponse: { full: 9 },
1398
+ /**
1399
+ * D2.1, 9 for a machine copy served at the page's own address on `Accept`
1400
+ * negotiation: a machine media type AND a body that is not HTML. ARS 0.3: 6
1401
+ * when the page does not negotiate but the Markdown copy it declares as an
1402
+ * alternate was fetched and is real. Less than full because only agents that
1403
+ * look for the link reach it, and they pay a second request to do so.
1404
+ */
1405
+ negotiatedResponse: { full: 9, linkedCopy: 6 },
790
1406
  /** D2.2, 3. All-or-nothing. */
791
1407
  declaredAlternates: { full: 3 },
792
1408
  /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */
@@ -938,7 +1554,107 @@ function sha256Hex(message) {
938
1554
  for (const word of h) hex += word.toString(16).padStart(8, "0");
939
1555
  return hex;
940
1556
  }
941
- sha256Hex("ars-0.2-corpus-unfrozen");
1557
+ sha256Hex("ars-0.3-corpus-unfrozen");
1558
+ function parseLinkHeaders(values) {
1559
+ const out = [];
1560
+ for (const value of values) {
1561
+ for (const entry of splitLinkEntries(value)) {
1562
+ const open = entry.indexOf("<");
1563
+ const close = entry.indexOf(">", open + 1);
1564
+ if (open === -1 || close === -1) continue;
1565
+ const url = entry.slice(open + 1, close).trim();
1566
+ if (url.length === 0) continue;
1567
+ let rel = [];
1568
+ let type = null;
1569
+ for (const param of entry.slice(close + 1).split(";")) {
1570
+ const equals = param.indexOf("=");
1571
+ if (equals === -1) continue;
1572
+ const name = param.slice(0, equals).trim().toLowerCase();
1573
+ const raw = param.slice(equals + 1).trim();
1574
+ const unquoted = raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1) : raw;
1575
+ if (name === "rel")
1576
+ rel = unquoted.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
1577
+ else if (name === "type") type = unquoted.trim().toLowerCase();
1578
+ }
1579
+ out.push({ url, rel, type });
1580
+ }
1581
+ }
1582
+ return out;
1583
+ }
1584
+ function splitLinkEntries(value) {
1585
+ const entries = [];
1586
+ let depth = 0;
1587
+ let quoted = false;
1588
+ let start = 0;
1589
+ for (let i = 0; i < value.length; i++) {
1590
+ const char = value.charAt(i);
1591
+ if (quoted) {
1592
+ if (char === '"') quoted = false;
1593
+ continue;
1594
+ }
1595
+ if (char === '"') quoted = true;
1596
+ else if (char === "<") depth++;
1597
+ else if (char === ">") depth = depth > 0 ? depth - 1 : 0;
1598
+ else if (char === "," && depth === 0) {
1599
+ entries.push(value.slice(start, i));
1600
+ start = i + 1;
1601
+ }
1602
+ }
1603
+ entries.push(value.slice(start));
1604
+ return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0);
1605
+ }
1606
+ var MACHINE_KINDS = /* @__PURE__ */ new Set(["markdown", "text", "json"]);
1607
+ function isMachineCopy(capture) {
1608
+ const representation = buildRepresentation(capture);
1609
+ return representation !== null && MACHINE_KINDS.has(representation.kind) && !representation.looksLikeHtml;
1610
+ }
1611
+ var MARKDOWN_MEDIA = /* @__PURE__ */ new Set(["text/markdown", "text/x-markdown"]);
1612
+ function isMarkdownType(type) {
1613
+ return type !== null && MARKDOWN_MEDIA.has((type.split(";")[0] ?? "").trim().toLowerCase());
1614
+ }
1615
+ function declaredMarkdownAlternates(captures) {
1616
+ const out = [];
1617
+ const add = (raw, base) => {
1618
+ try {
1619
+ const url = new URL(raw, base);
1620
+ url.hash = "";
1621
+ const href = url.toString();
1622
+ if (!out.includes(href)) out.push(href);
1623
+ } catch {
1624
+ }
1625
+ };
1626
+ for (const capture of captures) {
1627
+ if (capture === null) continue;
1628
+ for (const link of parseLinkHeaders(headerAll(capture.headers, "link"))) {
1629
+ if (link.rel.includes("alternate") && isMarkdownType(link.type)) add(link.url, capture.finalUrl);
1630
+ }
1631
+ }
1632
+ for (const capture of captures) {
1633
+ if (capture === null) continue;
1634
+ const representation = buildRepresentation(capture);
1635
+ if (representation === null || representation.doc === null) continue;
1636
+ for (const link of representation.doc.links) {
1637
+ if (!link.rel.includes("alternate") || link.href === null) continue;
1638
+ if (isMarkdownType(link.type)) add(link.href, capture.finalUrl);
1639
+ }
1640
+ }
1641
+ return out;
1642
+ }
1643
+ function markdownAlternateTarget(agent, browser, origin) {
1644
+ if (agent === null || agent.status < 200 || agent.status >= 300) return null;
1645
+ if (isMachineCopy(agent)) return null;
1646
+ const own = /* @__PURE__ */ new Set([agent.finalUrl, agent.requestedUrl]);
1647
+ for (const href of declaredMarkdownAlternates([browser, agent])) {
1648
+ let sameOrigin = false;
1649
+ try {
1650
+ sameOrigin = new URL(href).origin === origin;
1651
+ } catch {
1652
+ sameOrigin = false;
1653
+ }
1654
+ if (sameOrigin && !own.has(href)) return href;
1655
+ }
1656
+ return null;
1657
+ }
942
1658
 
943
1659
  // src/probe/limiter.ts
944
1660
  var ProbeBudgetExceededError = class extends Error {
@@ -953,7 +1669,7 @@ var ProbeBudgetExceededError = class extends Error {
953
1669
  };
954
1670
 
955
1671
  // src/probe/index.ts
956
- var ARS_USER_AGENT = "rebilder-ars/0.2 (+https://rebilder.com/bots)";
1672
+ var ARS_USER_AGENT = "rebilder-ars/0.3 (+https://rebilder.com/bots)";
957
1673
  var AGENT_IDENTITY = {
958
1674
  role: "agent",
959
1675
  userAgent: ARS_USER_AGENT,
@@ -1293,6 +2009,16 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1293
2009
  }
1294
2010
  const agent = await run(url.toString(), agentHeaders);
1295
2011
  const browser = await run(url.toString(), browserHeaders);
2012
+ const linked = markdownAlternateTarget(
2013
+ agent.result.ok ? agent.result.capture : null,
2014
+ browser.result.ok ? browser.result.capture : null,
2015
+ origin
2016
+ );
2017
+ let markdownAlternate = null;
2018
+ if (linked !== null) {
2019
+ const rule = disallowedFor(new URL(linked).pathname);
2020
+ markdownAlternate = rule !== null ? skipped(agentHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${linked}`) : await run(linked, agentHeaders);
2021
+ }
1296
2022
  const fetchAsset = async (path) => {
1297
2023
  const rule = disallowedFor(path);
1298
2024
  if (rule !== null)
@@ -1301,7 +2027,17 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1301
2027
  };
1302
2028
  const llmsTxt = await fetchAsset("/llms.txt");
1303
2029
  const wellKnownUcp = await fetchAsset("/.well-known/ucp");
1304
- return evidenceOf({ agent, browser, parityConfirm: null, robotsTxt, llmsTxt, wellKnownUcp });
2030
+ return evidenceOf({
2031
+ agent,
2032
+ browser,
2033
+ parityConfirm: null,
2034
+ // Omitted when not taken, so a page with no linked copy produces exactly
2035
+ // the bundle (and the evidence hash) it produced under 0.2.
2036
+ ...markdownAlternate === null ? {} : { markdownAlternate },
2037
+ robotsTxt,
2038
+ llmsTxt,
2039
+ wellKnownUcp
2040
+ });
1305
2041
  } catch (error) {
1306
2042
  if (error instanceof ProbeBudgetExceededError) {
1307
2043
  return { ok: false, rejection: "budget-exceeded", detail: error.message };