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