@rebilder/agent-readability 0.2.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.
@@ -244,33 +244,61 @@ var ACTION_LEXICON = [
244
244
  "book now",
245
245
  "buy",
246
246
  "buy now",
247
+ "call",
247
248
  "call now",
249
+ "check availability",
250
+ "check out",
248
251
  "checkout",
249
252
  "contact",
250
253
  "contact us",
254
+ "create account",
255
+ "create an account",
251
256
  "donate",
252
257
  "download",
253
258
  "email us",
259
+ "enquire",
260
+ "enrol",
254
261
  "enroll",
262
+ "free trial",
263
+ "get a demo",
255
264
  "get a quote",
265
+ "get directions",
266
+ "get in touch",
256
267
  "get quote",
257
268
  "get started",
269
+ "get the app",
270
+ "get tickets",
271
+ "hire",
272
+ "inquire",
273
+ "install",
258
274
  "join",
259
275
  "make an appointment",
276
+ "message us",
260
277
  "order",
261
278
  "order now",
279
+ "order online",
280
+ "pre-order",
281
+ "preorder",
262
282
  "purchase",
263
283
  "register",
284
+ "rent",
264
285
  "request",
265
286
  "request a demo",
266
287
  "request a quote",
267
288
  "reserve",
268
289
  "schedule",
290
+ "shop",
291
+ "shop now",
269
292
  "sign up",
270
293
  "signup",
271
294
  "start",
272
295
  "start free trial",
273
- "subscribe"
296
+ "subscribe",
297
+ "talk to sales",
298
+ "talk to us",
299
+ "text us",
300
+ "try",
301
+ "upgrade"
274
302
  ];
275
303
  var BANDS = [
276
304
  {
@@ -310,7 +338,7 @@ var BANDS = [
310
338
  }
311
339
  ];
312
340
  var DEFAULT_RULESET = deepFreeze({
313
- version: "0.2.0",
341
+ version: "0.3.0",
314
342
  weights: WEIGHTS,
315
343
  thresholds: THRESHOLDS,
316
344
  audienceTokens: AUDIENCE_TOKENS,
@@ -326,6 +354,494 @@ var DEFAULT_RULESET = deepFreeze({
326
354
  bands: BANDS
327
355
  });
328
356
 
357
+ // src/html.ts
358
+ var Utf8Cursor = class {
359
+ constructor(source) {
360
+ this.source = source;
361
+ }
362
+ source;
363
+ charIndex = 0;
364
+ byteIndex = 0;
365
+ at(target) {
366
+ if (target < this.charIndex) {
367
+ this.charIndex = 0;
368
+ this.byteIndex = 0;
369
+ }
370
+ const limit = Math.min(target, this.source.length);
371
+ while (this.charIndex < limit) {
372
+ const code = this.source.charCodeAt(this.charIndex);
373
+ if (code < 128) {
374
+ this.byteIndex += 1;
375
+ this.charIndex += 1;
376
+ } else if (code < 2048) {
377
+ this.byteIndex += 2;
378
+ this.charIndex += 1;
379
+ } else if (code >= 55296 && code <= 56319) {
380
+ const next = this.charIndex + 1 < this.source.length ? this.source.charCodeAt(this.charIndex + 1) : 0;
381
+ if (next >= 56320 && next <= 57343 && this.charIndex + 1 < limit) {
382
+ this.byteIndex += 4;
383
+ this.charIndex += 2;
384
+ } else {
385
+ this.byteIndex += 3;
386
+ this.charIndex += 1;
387
+ }
388
+ } else {
389
+ this.byteIndex += 3;
390
+ this.charIndex += 1;
391
+ }
392
+ }
393
+ return this.byteIndex;
394
+ }
395
+ };
396
+ var NAMED_ENTITIES = {
397
+ amp: "&",
398
+ lt: "<",
399
+ gt: ">",
400
+ quot: '"',
401
+ apos: "'",
402
+ nbsp: "\xA0",
403
+ ensp: "\u2002",
404
+ emsp: "\u2003",
405
+ thinsp: "\u2009",
406
+ shy: "\xAD",
407
+ zwnj: "\u200C",
408
+ zwj: "\u200D",
409
+ // Currency
410
+ cent: "\xA2",
411
+ pound: "\xA3",
412
+ curren: "\xA4",
413
+ yen: "\xA5",
414
+ euro: "\u20AC",
415
+ dollar: "$",
416
+ // Typography
417
+ ndash: "\u2013",
418
+ mdash: "\u2014",
419
+ hellip: "\u2026",
420
+ lsquo: "\u2018",
421
+ rsquo: "\u2019",
422
+ sbquo: "\u201A",
423
+ ldquo: "\u201C",
424
+ rdquo: "\u201D",
425
+ bdquo: "\u201E",
426
+ laquo: "\xAB",
427
+ raquo: "\xBB",
428
+ lsaquo: "\u2039",
429
+ rsaquo: "\u203A",
430
+ bull: "\u2022",
431
+ middot: "\xB7",
432
+ dagger: "\u2020",
433
+ Dagger: "\u2021",
434
+ prime: "\u2032",
435
+ Prime: "\u2033",
436
+ // Marks and math
437
+ copy: "\xA9",
438
+ reg: "\xAE",
439
+ trade: "\u2122",
440
+ sect: "\xA7",
441
+ para: "\xB6",
442
+ deg: "\xB0",
443
+ plusmn: "\xB1",
444
+ times: "\xD7",
445
+ divide: "\xF7",
446
+ minus: "\u2212",
447
+ permil: "\u2030",
448
+ frac12: "\xBD",
449
+ frac14: "\xBC",
450
+ frac34: "\xBE",
451
+ sup2: "\xB2",
452
+ sup3: "\xB3",
453
+ le: "\u2264",
454
+ ge: "\u2265",
455
+ ne: "\u2260",
456
+ // Directionality (invisible, but they do occupy bytes)
457
+ lrm: "\u200E",
458
+ rlm: "\u200F"
459
+ };
460
+ var C1_REPLACEMENTS = {
461
+ 128: 8364,
462
+ 130: 8218,
463
+ 131: 402,
464
+ 132: 8222,
465
+ 133: 8230,
466
+ 134: 8224,
467
+ 135: 8225,
468
+ 136: 710,
469
+ 137: 8240,
470
+ 138: 352,
471
+ 139: 8249,
472
+ 140: 338,
473
+ 142: 381,
474
+ 145: 8216,
475
+ 146: 8217,
476
+ 147: 8220,
477
+ 148: 8221,
478
+ 149: 8226,
479
+ 150: 8211,
480
+ 151: 8212,
481
+ 152: 732,
482
+ 153: 8482,
483
+ 154: 353,
484
+ 155: 8250,
485
+ 156: 339,
486
+ 158: 382,
487
+ 159: 376
488
+ };
489
+ var ENTITY_RE = /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{0,31});/g;
490
+ function codePointToString(raw) {
491
+ const mapped = C1_REPLACEMENTS[raw];
492
+ const code = mapped ?? raw;
493
+ if (code === 0 || code > 1114111 || code >= 55296 && code <= 57343) return "\uFFFD";
494
+ return String.fromCodePoint(code);
495
+ }
496
+ function decodeEntities(text) {
497
+ if (!text.includes("&")) return text;
498
+ return text.replace(ENTITY_RE, (match, body) => {
499
+ if (body.startsWith("#")) {
500
+ const isHex = body[1] === "x" || body[1] === "X";
501
+ const digits = isHex ? body.slice(2) : body.slice(1);
502
+ const value = Number.parseInt(digits, isHex ? 16 : 10);
503
+ return Number.isNaN(value) ? match : codePointToString(value);
504
+ }
505
+ return NAMED_ENTITIES[body] ?? match;
506
+ });
507
+ }
508
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
509
+ "area",
510
+ "base",
511
+ "br",
512
+ "col",
513
+ "embed",
514
+ "hr",
515
+ "img",
516
+ "input",
517
+ "link",
518
+ "meta",
519
+ "param",
520
+ "source",
521
+ "track",
522
+ "wbr"
523
+ ]);
524
+ var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style"]);
525
+ var RCDATA_ELEMENTS = /* @__PURE__ */ new Set(["textarea", "title"]);
526
+ var IMPLIED_END_TAGS = {
527
+ li: ["li"],
528
+ dt: ["dt", "dd"],
529
+ dd: ["dt", "dd"],
530
+ option: ["option"],
531
+ optgroup: ["option", "optgroup"],
532
+ tr: ["td", "th", "tr"],
533
+ td: ["td", "th"],
534
+ th: ["td", "th"],
535
+ tbody: ["td", "th", "tr", "thead", "tbody"],
536
+ tfoot: ["td", "th", "tr", "thead", "tbody"]
537
+ };
538
+ var CLOSES_OPEN_P = /* @__PURE__ */ new Set([
539
+ "address",
540
+ "article",
541
+ "aside",
542
+ "blockquote",
543
+ "details",
544
+ "div",
545
+ "dl",
546
+ "fieldset",
547
+ "figcaption",
548
+ "figure",
549
+ "footer",
550
+ "form",
551
+ "h1",
552
+ "h2",
553
+ "h3",
554
+ "h4",
555
+ "h5",
556
+ "h6",
557
+ "header",
558
+ "hr",
559
+ "main",
560
+ "nav",
561
+ "ol",
562
+ "p",
563
+ "pre",
564
+ "section",
565
+ "table",
566
+ "ul"
567
+ ]);
568
+ var MAX_DEPTH = 256;
569
+ function isAsciiAlpha(ch) {
570
+ if (ch === void 0) return false;
571
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z";
572
+ }
573
+ function isHtmlSpace(ch) {
574
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f";
575
+ }
576
+ var DISPLAY_NONE_RE = /(^|;)display:none(!important)?(;|$)/;
577
+ function hasInlineDisplayNone(style) {
578
+ if (style === void 0) return false;
579
+ return DISPLAY_NONE_RE.test(style.toLowerCase().replace(/\s+/g, ""));
580
+ }
581
+ function parseStartTag(html, start) {
582
+ let i = start + 1;
583
+ const nameStart = i;
584
+ while (i < html.length) {
585
+ const ch = html[i] ?? "";
586
+ if (isHtmlSpace(ch) || ch === "/" || ch === ">") break;
587
+ i++;
588
+ }
589
+ const tag = html.slice(nameStart, i).toLowerCase();
590
+ const attrs = {};
591
+ let selfClosing = false;
592
+ while (i < html.length) {
593
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
594
+ if (i >= html.length) break;
595
+ const ch = html[i] ?? "";
596
+ if (ch === ">") {
597
+ i++;
598
+ return { tag, attrs, selfClosing, end: i };
599
+ }
600
+ if (ch === "/") {
601
+ selfClosing = true;
602
+ i++;
603
+ continue;
604
+ }
605
+ const attrNameStart = i;
606
+ while (i < html.length) {
607
+ const c = html[i] ?? "";
608
+ if (isHtmlSpace(c) || c === "=" || c === ">" || c === "/") break;
609
+ i++;
610
+ }
611
+ if (i === attrNameStart) {
612
+ i++;
613
+ continue;
614
+ }
615
+ const attrName = html.slice(attrNameStart, i).toLowerCase();
616
+ let value = "";
617
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
618
+ if (html[i] === "=") {
619
+ i++;
620
+ while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
621
+ const quote = html[i];
622
+ if (quote === '"' || quote === "'") {
623
+ i++;
624
+ const valueStart = i;
625
+ const close = html.indexOf(quote, i);
626
+ if (close === -1) {
627
+ value = html.slice(valueStart);
628
+ i = html.length;
629
+ } else {
630
+ value = html.slice(valueStart, close);
631
+ i = close + 1;
632
+ }
633
+ } else {
634
+ const valueStart = i;
635
+ while (i < html.length) {
636
+ const c = html[i] ?? "";
637
+ if (isHtmlSpace(c) || c === ">") break;
638
+ i++;
639
+ }
640
+ value = html.slice(valueStart, i);
641
+ }
642
+ }
643
+ if (!(attrName in attrs)) attrs[attrName] = decodeEntities(value);
644
+ }
645
+ return { tag, attrs, selfClosing, end: i };
646
+ }
647
+ function findRawTextEnd(html, from, tag) {
648
+ const needle = `</${tag}`;
649
+ const lower = html.toLowerCase();
650
+ const at = lower.indexOf(needle, from);
651
+ return at === -1 ? -1 : at;
652
+ }
653
+ function ownExclusion(tag, attrs) {
654
+ if (tag === "script") {
655
+ const type = (attrs["type"] ?? "").toLowerCase().split(";")[0]?.trim() ?? "";
656
+ return type === "application/ld+json" ? "script-ld-json" : "script";
657
+ }
658
+ if (tag === "style") return "style";
659
+ if (tag === "template") return "template";
660
+ if ("hidden" in attrs) return "hidden-attribute";
661
+ if (hasInlineDisplayNone(attrs["style"])) return "inline-display-none";
662
+ return null;
663
+ }
664
+ function tokenizeHtml(html) {
665
+ const elements = [];
666
+ const texts = [];
667
+ const jsonLd = [];
668
+ const metas = [];
669
+ const links = [];
670
+ const stack = [];
671
+ const cursor = new Utf8Cursor(html);
672
+ const topIndex = () => stack[stack.length - 1] ?? -1;
673
+ const exclusionAt = (elementIndex) => elementIndex >= 0 ? elements[elementIndex]?.excludedBy ?? null : null;
674
+ const emitText = (from, to, decode, override) => {
675
+ if (to <= from) return;
676
+ const raw = html.slice(from, to);
677
+ const parent = topIndex();
678
+ const offset = cursor.at(from);
679
+ texts.push({
680
+ text: decode ? decodeEntities(raw) : raw,
681
+ offset,
682
+ bytes: cursor.at(to) - offset,
683
+ parent,
684
+ excludedBy: override ?? exclusionAt(parent)
685
+ });
686
+ };
687
+ const popTo = (tag) => {
688
+ for (let depth = stack.length - 1; depth >= 0; depth--) {
689
+ const candidate = stack[depth];
690
+ if (candidate === void 0) continue;
691
+ if (elements[candidate]?.tag === tag) {
692
+ stack.length = depth;
693
+ return;
694
+ }
695
+ }
696
+ };
697
+ const applyImpliedEndTags = (tag) => {
698
+ const closes = IMPLIED_END_TAGS[tag];
699
+ if (closes !== void 0) {
700
+ while (stack.length > 0) {
701
+ const top = stack[stack.length - 1];
702
+ const openTag = top === void 0 ? void 0 : elements[top]?.tag;
703
+ if (openTag === void 0 || !closes.includes(openTag)) break;
704
+ stack.pop();
705
+ }
706
+ }
707
+ if (CLOSES_OPEN_P.has(tag)) {
708
+ const top = stack[stack.length - 1];
709
+ if (top !== void 0 && elements[top]?.tag === "p") stack.pop();
710
+ }
711
+ };
712
+ let i = 0;
713
+ let textStart = 0;
714
+ while (i < html.length) {
715
+ const lt = html.indexOf("<", i);
716
+ if (lt === -1) break;
717
+ const next = html[lt + 1];
718
+ if (next !== "!" && next !== "/" && !isAsciiAlpha(next)) {
719
+ i = lt + 1;
720
+ continue;
721
+ }
722
+ emitText(textStart, lt, true);
723
+ if (next === "!") {
724
+ if (html.startsWith("<!--", lt)) {
725
+ const close = html.indexOf("-->", lt + 4);
726
+ i = close === -1 ? html.length : close + 3;
727
+ } else {
728
+ const close = html.indexOf(">", lt + 2);
729
+ i = close === -1 ? html.length : close + 1;
730
+ }
731
+ textStart = i;
732
+ continue;
733
+ }
734
+ if (next === "/") {
735
+ const close = html.indexOf(">", lt + 2);
736
+ const end = close === -1 ? html.length : close + 1;
737
+ const rawName = html.slice(lt + 2, close === -1 ? html.length : close).trim();
738
+ const tag = rawName.toLowerCase();
739
+ if (tag.length > 0) popTo(tag);
740
+ i = end;
741
+ textStart = i;
742
+ continue;
743
+ }
744
+ const parsed = parseStartTag(html, lt);
745
+ applyImpliedEndTags(parsed.tag);
746
+ const parent = topIndex();
747
+ const own = ownExclusion(parsed.tag, parsed.attrs);
748
+ const element = {
749
+ index: elements.length,
750
+ tag: parsed.tag,
751
+ attrs: parsed.attrs,
752
+ offset: cursor.at(lt),
753
+ parent,
754
+ depth: stack.length,
755
+ excludedBy: exclusionAt(parent) ?? own
756
+ };
757
+ elements.push(element);
758
+ collectMetaOrLink(element, metas, links);
759
+ i = parsed.end;
760
+ const isVoid = VOID_ELEMENTS.has(parsed.tag);
761
+ const isRawText = RAW_TEXT_ELEMENTS.has(parsed.tag);
762
+ const isRcdata = RCDATA_ELEMENTS.has(parsed.tag);
763
+ if (isRawText || isRcdata) {
764
+ const contentStart = i;
765
+ const close = findRawTextEnd(html, contentStart, parsed.tag);
766
+ const contentEnd = close === -1 ? html.length : close;
767
+ if (contentEnd > contentStart) {
768
+ const wasTop = stack.length;
769
+ stack.push(element.index);
770
+ emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? void 0);
771
+ stack.length = wasTop;
772
+ if (own === "script-ld-json") {
773
+ jsonLd.push({
774
+ text: html.slice(contentStart, contentEnd),
775
+ offset: cursor.at(contentStart),
776
+ element: element.index
777
+ });
778
+ }
779
+ }
780
+ if (close === -1) {
781
+ i = html.length;
782
+ } else {
783
+ const gt = html.indexOf(">", close);
784
+ i = gt === -1 ? html.length : gt + 1;
785
+ }
786
+ textStart = i;
787
+ continue;
788
+ }
789
+ if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index);
790
+ textStart = i;
791
+ }
792
+ emitText(textStart, html.length, true);
793
+ return {
794
+ elements,
795
+ texts,
796
+ jsonLd,
797
+ metas,
798
+ links,
799
+ bytes: cursor.at(html.length)
800
+ };
801
+ }
802
+ function collectMetaOrLink(element, metas, links) {
803
+ const lower = (value) => value === void 0 ? null : value.toLowerCase();
804
+ if (element.tag === "meta") {
805
+ metas.push({
806
+ name: lower(element.attrs["name"]),
807
+ property: lower(element.attrs["property"]),
808
+ httpEquiv: lower(element.attrs["http-equiv"]),
809
+ itemprop: lower(element.attrs["itemprop"]),
810
+ charset: lower(element.attrs["charset"]),
811
+ content: element.attrs["content"] ?? null,
812
+ element: element.index,
813
+ offset: element.offset
814
+ });
815
+ return;
816
+ }
817
+ if (element.tag === "link") {
818
+ const rawRel = element.attrs["rel"] ?? "";
819
+ const rel = [];
820
+ for (const token of rawRel.toLowerCase().split(/\s+/)) {
821
+ if (token.length > 0 && !rel.includes(token)) rel.push(token);
822
+ }
823
+ links.push({
824
+ rel,
825
+ href: element.attrs["href"] ?? null,
826
+ type: lower(element.attrs["type"]),
827
+ hreflang: lower(element.attrs["hreflang"]),
828
+ title: element.attrs["title"] ?? null,
829
+ element: element.index,
830
+ offset: element.offset
831
+ });
832
+ }
833
+ }
834
+ function joinText(parts) {
835
+ return parts.join(" ").replace(/\s+/g, " ").trim();
836
+ }
837
+ function countedText(doc) {
838
+ const parts = [];
839
+ for (const node of doc.texts) {
840
+ if (node.excludedBy === null) parts.push(node.text);
841
+ }
842
+ return joinText(parts);
843
+ }
844
+
329
845
  // src/extract.ts
330
846
  function utf8Length(text) {
331
847
  let bytes = 0;
@@ -343,6 +859,100 @@ function utf8Length(text) {
343
859
  }
344
860
  return bytes;
345
861
  }
862
+ var SCHEMA_PREFIX = /^https?:\/\/schema\.org\//;
863
+ function stripSchemaPrefix(type) {
864
+ return type.replace(SCHEMA_PREFIX, "");
865
+ }
866
+ function typesOf(value) {
867
+ const raw = value["@type"];
868
+ if (typeof raw === "string") return [stripSchemaPrefix(raw)];
869
+ if (Array.isArray(raw)) {
870
+ const out = [];
871
+ for (const entry of raw) if (typeof entry === "string") out.push(stripSchemaPrefix(entry));
872
+ return out;
873
+ }
874
+ return [];
875
+ }
876
+ var JSON_LD_MAX_DEPTH = 12;
877
+ function collectNodes(value, offset, depth, out, seen) {
878
+ if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== "object") return;
879
+ if (seen.has(value)) return;
880
+ seen.add(value);
881
+ if (Array.isArray(value)) {
882
+ for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen);
883
+ return;
884
+ }
885
+ const record = value;
886
+ const types = typesOf(record);
887
+ if (types.length > 0) out.push({ types, value: record, offset });
888
+ for (const [key, child] of Object.entries(record)) {
889
+ if (key === "@context") continue;
890
+ collectNodes(child, offset, depth + 1, out, seen);
891
+ }
892
+ }
893
+ function parseJsonLd(blocks) {
894
+ const nodes = [];
895
+ let parsed = 0;
896
+ for (const block of blocks) {
897
+ let value;
898
+ try {
899
+ value = JSON.parse(block.text);
900
+ } catch {
901
+ continue;
902
+ }
903
+ parsed++;
904
+ collectNodes(value, block.offset, 0, nodes, /* @__PURE__ */ new Set());
905
+ }
906
+ return { nodes, blocks: blocks.length, parsed };
907
+ }
908
+ function header(headers, name) {
909
+ const values = headers[name];
910
+ return values !== void 0 && values.length > 0 ? values[0] ?? null : null;
911
+ }
912
+ function headerAll(headers, name) {
913
+ return headers[name] ?? [];
914
+ }
915
+ function mediaType(contentType) {
916
+ if (contentType === null) return null;
917
+ const semi = contentType.indexOf(";");
918
+ const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
919
+ return value.length > 0 ? value : null;
920
+ }
921
+ function classifyMediaType(type) {
922
+ if (type === null) return "other";
923
+ if (type === "text/html" || type === "application/xhtml+xml") return "html";
924
+ if (type === "text/markdown" || type === "text/x-markdown") return "markdown";
925
+ if (type === "text/plain") return "text";
926
+ if (type === "application/json" || type === "application/ld+json" || type.endsWith("+json")) {
927
+ return "json";
928
+ }
929
+ return "other";
930
+ }
931
+ function bodyLooksLikeHtml(body) {
932
+ const head = body.slice(0, 1024).trimStart().toLowerCase();
933
+ return head.startsWith("<!doctype html") || head.startsWith("<html") || head.startsWith("<?xml") ? true : head.includes("<html") || head.includes("<head>") || head.includes("<body");
934
+ }
935
+ function buildRepresentation(capture) {
936
+ if (typeof capture.body !== "string") return null;
937
+ const contentType = mediaType(header(capture.headers, "content-type"));
938
+ const declared = classifyMediaType(contentType);
939
+ const looksLikeHtml = bodyLooksLikeHtml(capture.body);
940
+ const doc = declared === "html" || looksLikeHtml ? tokenizeHtml(capture.body) : null;
941
+ 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 };
942
+ return {
943
+ kind: declared,
944
+ contentType,
945
+ body: capture.body,
946
+ bytes: capture.bytes,
947
+ doc,
948
+ jsonLd,
949
+ text: doc !== null ? countedText(doc) : capture.body,
950
+ looksLikeHtml,
951
+ truncated: capture.truncated,
952
+ finalUrl: capture.finalUrl,
953
+ headers: capture.headers
954
+ };
955
+ }
346
956
  function parseRobots(text) {
347
957
  const groups = [];
348
958
  const sitemaps = [];
@@ -466,8 +1076,14 @@ deepFreeze2({
466
1076
  band: [100, 7, 75, 5, 50, 3, 25, 1],
467
1077
  noscriptFloor: 1
468
1078
  },
469
- /** D2.1, 9. All-or-nothing: a machine media type AND a body that is not HTML. */
470
- negotiatedResponse: { full: 9 },
1079
+ /**
1080
+ * D2.1, 9 for a machine copy served at the page's own address on `Accept`
1081
+ * negotiation: a machine media type AND a body that is not HTML. ARS 0.3: 6
1082
+ * when the page does not negotiate but the Markdown copy it declares as an
1083
+ * alternate was fetched and is real. Less than full because only agents that
1084
+ * look for the link reach it, and they pay a second request to do so.
1085
+ */
1086
+ negotiatedResponse: { full: 9, linkedCopy: 6 },
471
1087
  /** D2.2, 3. All-or-nothing. */
472
1088
  declaredAlternates: { full: 3 },
473
1089
  /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */
@@ -619,7 +1235,107 @@ function sha256Hex(message) {
619
1235
  for (const word of h) hex += word.toString(16).padStart(8, "0");
620
1236
  return hex;
621
1237
  }
622
- sha256Hex("ars-0.2-corpus-unfrozen");
1238
+ sha256Hex("ars-0.3-corpus-unfrozen");
1239
+ function parseLinkHeaders(values) {
1240
+ const out = [];
1241
+ for (const value of values) {
1242
+ for (const entry of splitLinkEntries(value)) {
1243
+ const open = entry.indexOf("<");
1244
+ const close = entry.indexOf(">", open + 1);
1245
+ if (open === -1 || close === -1) continue;
1246
+ const url = entry.slice(open + 1, close).trim();
1247
+ if (url.length === 0) continue;
1248
+ let rel = [];
1249
+ let type = null;
1250
+ for (const param of entry.slice(close + 1).split(";")) {
1251
+ const equals = param.indexOf("=");
1252
+ if (equals === -1) continue;
1253
+ const name = param.slice(0, equals).trim().toLowerCase();
1254
+ const raw = param.slice(equals + 1).trim();
1255
+ const unquoted = raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1) : raw;
1256
+ if (name === "rel")
1257
+ rel = unquoted.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
1258
+ else if (name === "type") type = unquoted.trim().toLowerCase();
1259
+ }
1260
+ out.push({ url, rel, type });
1261
+ }
1262
+ }
1263
+ return out;
1264
+ }
1265
+ function splitLinkEntries(value) {
1266
+ const entries = [];
1267
+ let depth = 0;
1268
+ let quoted = false;
1269
+ let start = 0;
1270
+ for (let i = 0; i < value.length; i++) {
1271
+ const char = value.charAt(i);
1272
+ if (quoted) {
1273
+ if (char === '"') quoted = false;
1274
+ continue;
1275
+ }
1276
+ if (char === '"') quoted = true;
1277
+ else if (char === "<") depth++;
1278
+ else if (char === ">") depth = depth > 0 ? depth - 1 : 0;
1279
+ else if (char === "," && depth === 0) {
1280
+ entries.push(value.slice(start, i));
1281
+ start = i + 1;
1282
+ }
1283
+ }
1284
+ entries.push(value.slice(start));
1285
+ return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0);
1286
+ }
1287
+ var MACHINE_KINDS = /* @__PURE__ */ new Set(["markdown", "text", "json"]);
1288
+ function isMachineCopy(capture) {
1289
+ const representation = buildRepresentation(capture);
1290
+ return representation !== null && MACHINE_KINDS.has(representation.kind) && !representation.looksLikeHtml;
1291
+ }
1292
+ var MARKDOWN_MEDIA = /* @__PURE__ */ new Set(["text/markdown", "text/x-markdown"]);
1293
+ function isMarkdownType(type) {
1294
+ return type !== null && MARKDOWN_MEDIA.has((type.split(";")[0] ?? "").trim().toLowerCase());
1295
+ }
1296
+ function declaredMarkdownAlternates(captures) {
1297
+ const out = [];
1298
+ const add = (raw, base) => {
1299
+ try {
1300
+ const url = new URL(raw, base);
1301
+ url.hash = "";
1302
+ const href = url.toString();
1303
+ if (!out.includes(href)) out.push(href);
1304
+ } catch {
1305
+ }
1306
+ };
1307
+ for (const capture of captures) {
1308
+ if (capture === null) continue;
1309
+ for (const link of parseLinkHeaders(headerAll(capture.headers, "link"))) {
1310
+ if (link.rel.includes("alternate") && isMarkdownType(link.type)) add(link.url, capture.finalUrl);
1311
+ }
1312
+ }
1313
+ for (const capture of captures) {
1314
+ if (capture === null) continue;
1315
+ const representation = buildRepresentation(capture);
1316
+ if (representation === null || representation.doc === null) continue;
1317
+ for (const link of representation.doc.links) {
1318
+ if (!link.rel.includes("alternate") || link.href === null) continue;
1319
+ if (isMarkdownType(link.type)) add(link.href, capture.finalUrl);
1320
+ }
1321
+ }
1322
+ return out;
1323
+ }
1324
+ function markdownAlternateTarget(agent, browser, origin) {
1325
+ if (agent === null || agent.status < 200 || agent.status >= 300) return null;
1326
+ if (isMachineCopy(agent)) return null;
1327
+ const own = /* @__PURE__ */ new Set([agent.finalUrl, agent.requestedUrl]);
1328
+ for (const href of declaredMarkdownAlternates([browser, agent])) {
1329
+ let sameOrigin = false;
1330
+ try {
1331
+ sameOrigin = new URL(href).origin === origin;
1332
+ } catch {
1333
+ sameOrigin = false;
1334
+ }
1335
+ if (sameOrigin && !own.has(href)) return href;
1336
+ }
1337
+ return null;
1338
+ }
623
1339
  var ALLOW_PRIVATE_HOSTS = /* @__PURE__ */ Symbol("rebilder.ars.probe.allow-private-hosts");
624
1340
  var allowsPrivateHosts = (policy) => policy === ALLOW_PRIVATE_HOSTS;
625
1341
  var NOT_AN_IP = { family: null, reserved: false, label: "hostname" };
@@ -1067,7 +1783,7 @@ function createLimiter(options = {}) {
1067
1783
  }
1068
1784
 
1069
1785
  // src/probe/index.ts
1070
- var ARS_USER_AGENT = "rebilder-ars/0.2 (+https://rebilder.com/bots)";
1786
+ var ARS_USER_AGENT = "rebilder-ars/0.3 (+https://rebilder.com/bots)";
1071
1787
  var AGENT_IDENTITY = {
1072
1788
  role: "agent",
1073
1789
  userAgent: ARS_USER_AGENT,
@@ -1407,6 +2123,16 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1407
2123
  }
1408
2124
  const agent = await run(url.toString(), agentHeaders);
1409
2125
  const browser = await run(url.toString(), browserHeaders);
2126
+ const linked = markdownAlternateTarget(
2127
+ agent.result.ok ? agent.result.capture : null,
2128
+ browser.result.ok ? browser.result.capture : null,
2129
+ origin
2130
+ );
2131
+ let markdownAlternate = null;
2132
+ if (linked !== null) {
2133
+ const rule = disallowedFor(new URL(linked).pathname);
2134
+ markdownAlternate = rule !== null ? skipped(agentHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${linked}`) : await run(linked, agentHeaders);
2135
+ }
1410
2136
  const fetchAsset = async (path) => {
1411
2137
  const rule = disallowedFor(path);
1412
2138
  if (rule !== null)
@@ -1415,7 +2141,17 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1415
2141
  };
1416
2142
  const llmsTxt = await fetchAsset("/llms.txt");
1417
2143
  const wellKnownUcp = await fetchAsset("/.well-known/ucp");
1418
- return evidenceOf({ agent, browser, parityConfirm: null, robotsTxt, llmsTxt, wellKnownUcp });
2144
+ return evidenceOf({
2145
+ agent,
2146
+ browser,
2147
+ parityConfirm: null,
2148
+ // Omitted when not taken, so a page with no linked copy produces exactly
2149
+ // the bundle (and the evidence hash) it produced under 0.2.
2150
+ ...markdownAlternate === null ? {} : { markdownAlternate },
2151
+ robotsTxt,
2152
+ llmsTxt,
2153
+ wellKnownUcp
2154
+ });
1419
2155
  } catch (error) {
1420
2156
  if (error instanceof ProbeBudgetExceededError) {
1421
2157
  return { ok: false, rejection: "budget-exceeded", detail: error.message };
@@ -1451,5 +2187,3 @@ exports.probeWithHostPolicy = probeWithHostPolicy;
1451
2187
  exports.resolveAndValidate = resolveAndValidate;
1452
2188
  exports.strictPolicy = strictPolicy;
1453
2189
  exports.strictPolicyForRun = strictPolicyForRun;
1454
- //# sourceMappingURL=index.cjs.map
1455
- //# sourceMappingURL=index.cjs.map