@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.
@@ -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,495 @@ 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(lowerHtml, from, tag) {
648
+ const needle = `</${tag}`;
649
+ const at = lowerHtml.indexOf(needle, from);
650
+ return at === -1 ? -1 : at;
651
+ }
652
+ function ownExclusion(tag, attrs) {
653
+ if (tag === "script") {
654
+ const type = (attrs["type"] ?? "").toLowerCase().split(";")[0]?.trim() ?? "";
655
+ return type === "application/ld+json" ? "script-ld-json" : "script";
656
+ }
657
+ if (tag === "style") return "style";
658
+ if (tag === "template") return "template";
659
+ if ("hidden" in attrs) return "hidden-attribute";
660
+ if (hasInlineDisplayNone(attrs["style"])) return "inline-display-none";
661
+ return null;
662
+ }
663
+ function tokenizeHtml(html) {
664
+ const elements = [];
665
+ const texts = [];
666
+ const jsonLd = [];
667
+ const metas = [];
668
+ const links = [];
669
+ const stack = [];
670
+ const cursor = new Utf8Cursor(html);
671
+ const topIndex = () => stack[stack.length - 1] ?? -1;
672
+ const exclusionAt = (elementIndex) => elementIndex >= 0 ? elements[elementIndex]?.excludedBy ?? null : null;
673
+ const emitText = (from, to, decode, override) => {
674
+ if (to <= from) return;
675
+ const raw = html.slice(from, to);
676
+ const parent = topIndex();
677
+ const offset = cursor.at(from);
678
+ texts.push({
679
+ text: decode ? decodeEntities(raw) : raw,
680
+ offset,
681
+ bytes: cursor.at(to) - offset,
682
+ parent,
683
+ excludedBy: override ?? exclusionAt(parent)
684
+ });
685
+ };
686
+ const popTo = (tag) => {
687
+ for (let depth = stack.length - 1; depth >= 0; depth--) {
688
+ const candidate = stack[depth];
689
+ if (candidate === void 0) continue;
690
+ if (elements[candidate]?.tag === tag) {
691
+ stack.length = depth;
692
+ return;
693
+ }
694
+ }
695
+ };
696
+ const applyImpliedEndTags = (tag) => {
697
+ const closes = IMPLIED_END_TAGS[tag];
698
+ if (closes !== void 0) {
699
+ while (stack.length > 0) {
700
+ const top = stack[stack.length - 1];
701
+ const openTag = top === void 0 ? void 0 : elements[top]?.tag;
702
+ if (openTag === void 0 || !closes.includes(openTag)) break;
703
+ stack.pop();
704
+ }
705
+ }
706
+ if (CLOSES_OPEN_P.has(tag)) {
707
+ const top = stack[stack.length - 1];
708
+ if (top !== void 0 && elements[top]?.tag === "p") stack.pop();
709
+ }
710
+ };
711
+ let i = 0;
712
+ let textStart = 0;
713
+ let lowerHtml = null;
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
+ lowerHtml ??= html.toLowerCase();
766
+ const close = findRawTextEnd(lowerHtml, contentStart, parsed.tag);
767
+ const contentEnd = close === -1 ? html.length : close;
768
+ if (contentEnd > contentStart) {
769
+ const wasTop = stack.length;
770
+ stack.push(element.index);
771
+ emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? void 0);
772
+ stack.length = wasTop;
773
+ if (own === "script-ld-json") {
774
+ jsonLd.push({
775
+ text: html.slice(contentStart, contentEnd),
776
+ offset: cursor.at(contentStart),
777
+ element: element.index
778
+ });
779
+ }
780
+ }
781
+ if (close === -1) {
782
+ i = html.length;
783
+ } else {
784
+ const gt = html.indexOf(">", close);
785
+ i = gt === -1 ? html.length : gt + 1;
786
+ }
787
+ textStart = i;
788
+ continue;
789
+ }
790
+ if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index);
791
+ textStart = i;
792
+ }
793
+ emitText(textStart, html.length, true);
794
+ return {
795
+ elements,
796
+ texts,
797
+ jsonLd,
798
+ metas,
799
+ links,
800
+ bytes: cursor.at(html.length)
801
+ };
802
+ }
803
+ function collectMetaOrLink(element, metas, links) {
804
+ const lower = (value) => value === void 0 ? null : value.toLowerCase();
805
+ if (element.tag === "meta") {
806
+ metas.push({
807
+ name: lower(element.attrs["name"]),
808
+ property: lower(element.attrs["property"]),
809
+ httpEquiv: lower(element.attrs["http-equiv"]),
810
+ itemprop: lower(element.attrs["itemprop"]),
811
+ charset: lower(element.attrs["charset"]),
812
+ content: element.attrs["content"] ?? null,
813
+ element: element.index,
814
+ offset: element.offset
815
+ });
816
+ return;
817
+ }
818
+ if (element.tag === "link") {
819
+ const rawRel = element.attrs["rel"] ?? "";
820
+ const rel = [];
821
+ for (const token of rawRel.toLowerCase().split(/\s+/)) {
822
+ if (token.length > 0 && !rel.includes(token)) rel.push(token);
823
+ }
824
+ links.push({
825
+ rel,
826
+ href: element.attrs["href"] ?? null,
827
+ type: lower(element.attrs["type"]),
828
+ hreflang: lower(element.attrs["hreflang"]),
829
+ title: element.attrs["title"] ?? null,
830
+ element: element.index,
831
+ offset: element.offset
832
+ });
833
+ }
834
+ }
835
+ function joinText(parts) {
836
+ return parts.join(" ").replace(/\s+/g, " ").trim();
837
+ }
838
+ function countedText(doc) {
839
+ const parts = [];
840
+ for (const node of doc.texts) {
841
+ if (node.excludedBy === null) parts.push(node.text);
842
+ }
843
+ return joinText(parts);
844
+ }
845
+
329
846
  // src/extract.ts
330
847
  function utf8Length(text) {
331
848
  let bytes = 0;
@@ -343,6 +860,100 @@ function utf8Length(text) {
343
860
  }
344
861
  return bytes;
345
862
  }
863
+ var SCHEMA_PREFIX = /^https?:\/\/schema\.org\//;
864
+ function stripSchemaPrefix(type) {
865
+ return type.replace(SCHEMA_PREFIX, "");
866
+ }
867
+ function typesOf(value) {
868
+ const raw = value["@type"];
869
+ if (typeof raw === "string") return [stripSchemaPrefix(raw)];
870
+ if (Array.isArray(raw)) {
871
+ const out = [];
872
+ for (const entry of raw) if (typeof entry === "string") out.push(stripSchemaPrefix(entry));
873
+ return out;
874
+ }
875
+ return [];
876
+ }
877
+ var JSON_LD_MAX_DEPTH = 12;
878
+ function collectNodes(value, offset, depth, out, seen) {
879
+ if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== "object") return;
880
+ if (seen.has(value)) return;
881
+ seen.add(value);
882
+ if (Array.isArray(value)) {
883
+ for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen);
884
+ return;
885
+ }
886
+ const record = value;
887
+ const types = typesOf(record);
888
+ if (types.length > 0) out.push({ types, value: record, offset });
889
+ for (const [key, child] of Object.entries(record)) {
890
+ if (key === "@context") continue;
891
+ collectNodes(child, offset, depth + 1, out, seen);
892
+ }
893
+ }
894
+ function parseJsonLd(blocks) {
895
+ const nodes = [];
896
+ let parsed = 0;
897
+ for (const block of blocks) {
898
+ let value;
899
+ try {
900
+ value = JSON.parse(block.text);
901
+ } catch {
902
+ continue;
903
+ }
904
+ parsed++;
905
+ collectNodes(value, block.offset, 0, nodes, /* @__PURE__ */ new Set());
906
+ }
907
+ return { nodes, blocks: blocks.length, parsed };
908
+ }
909
+ function header(headers, name) {
910
+ const values = headers[name];
911
+ return values !== void 0 && values.length > 0 ? values[0] ?? null : null;
912
+ }
913
+ function headerAll(headers, name) {
914
+ return headers[name] ?? [];
915
+ }
916
+ function mediaType(contentType) {
917
+ if (contentType === null) return null;
918
+ const semi = contentType.indexOf(";");
919
+ const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
920
+ return value.length > 0 ? value : null;
921
+ }
922
+ function classifyMediaType(type) {
923
+ if (type === null) return "other";
924
+ if (type === "text/html" || type === "application/xhtml+xml") return "html";
925
+ if (type === "text/markdown" || type === "text/x-markdown") return "markdown";
926
+ if (type === "text/plain") return "text";
927
+ if (type === "application/json" || type === "application/ld+json" || type.endsWith("+json")) {
928
+ return "json";
929
+ }
930
+ return "other";
931
+ }
932
+ function bodyLooksLikeHtml(body) {
933
+ const head = body.slice(0, 1024).trimStart().toLowerCase();
934
+ return head.startsWith("<!doctype html") || head.startsWith("<html") || head.startsWith("<?xml") ? true : head.includes("<html") || head.includes("<head>") || head.includes("<body");
935
+ }
936
+ function buildRepresentation(capture) {
937
+ if (typeof capture.body !== "string") return null;
938
+ const contentType = mediaType(header(capture.headers, "content-type"));
939
+ const declared = classifyMediaType(contentType);
940
+ const looksLikeHtml = bodyLooksLikeHtml(capture.body);
941
+ const doc = declared === "html" || looksLikeHtml ? tokenizeHtml(capture.body) : null;
942
+ 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 };
943
+ return {
944
+ kind: declared,
945
+ contentType,
946
+ body: capture.body,
947
+ bytes: capture.bytes,
948
+ doc,
949
+ jsonLd,
950
+ text: doc !== null ? countedText(doc) : capture.body,
951
+ looksLikeHtml,
952
+ truncated: capture.truncated,
953
+ finalUrl: capture.finalUrl,
954
+ headers: capture.headers
955
+ };
956
+ }
346
957
  function parseRobots(text) {
347
958
  const groups = [];
348
959
  const sitemaps = [];
@@ -384,7 +995,10 @@ function parseRobots(text) {
384
995
  else current.disallow.push(value);
385
996
  continue;
386
997
  }
387
- if (field === "crawl-delay" || field === "host" || field === "clean-param") continue;
998
+ if (field === "crawl-delay" || field === "host" || field === "clean-param" || field === "content-signal") {
999
+ if (field === "content-signal" && current !== null) openingGroup = false;
1000
+ continue;
1001
+ }
388
1002
  malformedLines++;
389
1003
  }
390
1004
  return { groups, sitemaps, malformedLines, orphanRules };
@@ -466,8 +1080,14 @@ deepFreeze2({
466
1080
  band: [100, 7, 75, 5, 50, 3, 25, 1],
467
1081
  noscriptFloor: 1
468
1082
  },
469
- /** D2.1, 9. All-or-nothing: a machine media type AND a body that is not HTML. */
470
- negotiatedResponse: { full: 9 },
1083
+ /**
1084
+ * D2.1, 9 for a machine copy served at the page's own address on `Accept`
1085
+ * negotiation: a machine media type AND a body that is not HTML. ARS 0.3: 6
1086
+ * when the page does not negotiate but the Markdown copy it declares as an
1087
+ * alternate was fetched and is real. Less than full because only agents that
1088
+ * look for the link reach it, and they pay a second request to do so.
1089
+ */
1090
+ negotiatedResponse: { full: 9, linkedCopy: 6 },
471
1091
  /** D2.2, 3. All-or-nothing. */
472
1092
  declaredAlternates: { full: 3 },
473
1093
  /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */
@@ -619,7 +1239,183 @@ function sha256Hex(message) {
619
1239
  for (const word of h) hex += word.toString(16).padStart(8, "0");
620
1240
  return hex;
621
1241
  }
622
- sha256Hex("ars-0.2-corpus-unfrozen");
1242
+ sha256Hex("ars-0.3-corpus-unfrozen");
1243
+ function parseLinkHeaders(values) {
1244
+ const out = [];
1245
+ for (const value of values) {
1246
+ for (const entry of splitLinkEntries(value)) {
1247
+ const open = entry.indexOf("<");
1248
+ const close = entry.indexOf(">", open + 1);
1249
+ if (open === -1 || close === -1) continue;
1250
+ const url = entry.slice(open + 1, close).trim();
1251
+ if (url.length === 0) continue;
1252
+ let rel = [];
1253
+ let type = null;
1254
+ for (const param of entry.slice(close + 1).split(";")) {
1255
+ const equals = param.indexOf("=");
1256
+ if (equals === -1) continue;
1257
+ const name = param.slice(0, equals).trim().toLowerCase();
1258
+ const raw = param.slice(equals + 1).trim();
1259
+ const unquoted = raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1) : raw;
1260
+ if (name === "rel")
1261
+ rel = unquoted.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
1262
+ else if (name === "type") type = unquoted.trim().toLowerCase();
1263
+ }
1264
+ out.push({ url, rel, type });
1265
+ }
1266
+ }
1267
+ return out;
1268
+ }
1269
+ function splitLinkEntries(value) {
1270
+ const entries = [];
1271
+ let depth = 0;
1272
+ let quoted = false;
1273
+ let start = 0;
1274
+ for (let i = 0; i < value.length; i++) {
1275
+ const char = value.charAt(i);
1276
+ if (quoted) {
1277
+ if (char === '"') quoted = false;
1278
+ continue;
1279
+ }
1280
+ if (char === '"') quoted = true;
1281
+ else if (char === "<") depth++;
1282
+ else if (char === ">") depth = depth > 0 ? depth - 1 : 0;
1283
+ else if (char === "," && depth === 0) {
1284
+ entries.push(value.slice(start, i));
1285
+ start = i + 1;
1286
+ }
1287
+ }
1288
+ entries.push(value.slice(start));
1289
+ return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0);
1290
+ }
1291
+ var MACHINE_KINDS = /* @__PURE__ */ new Set(["markdown", "text", "json"]);
1292
+ function isMachineCopy(capture) {
1293
+ const representation = buildRepresentation(capture);
1294
+ return representation !== null && MACHINE_KINDS.has(representation.kind) && !representation.looksLikeHtml;
1295
+ }
1296
+ var MARKDOWN_MEDIA = /* @__PURE__ */ new Set(["text/markdown", "text/x-markdown"]);
1297
+ function isMarkdownType(type) {
1298
+ return type !== null && MARKDOWN_MEDIA.has((type.split(";")[0] ?? "").trim().toLowerCase());
1299
+ }
1300
+ function declaredMarkdownAlternates(captures) {
1301
+ const out = [];
1302
+ const add = (raw, base) => {
1303
+ try {
1304
+ const url = new URL(raw, base);
1305
+ url.hash = "";
1306
+ const href = url.toString();
1307
+ if (!out.includes(href)) out.push(href);
1308
+ } catch {
1309
+ }
1310
+ };
1311
+ for (const capture of captures) {
1312
+ if (capture === null) continue;
1313
+ for (const link of parseLinkHeaders(headerAll(capture.headers, "link"))) {
1314
+ if (link.rel.includes("alternate") && isMarkdownType(link.type)) add(link.url, capture.finalUrl);
1315
+ }
1316
+ }
1317
+ for (const capture of captures) {
1318
+ if (capture === null) continue;
1319
+ const representation = buildRepresentation(capture);
1320
+ if (representation === null || representation.doc === null) continue;
1321
+ for (const link of representation.doc.links) {
1322
+ if (!link.rel.includes("alternate") || link.href === null) continue;
1323
+ if (isMarkdownType(link.type)) add(link.href, capture.finalUrl);
1324
+ }
1325
+ }
1326
+ return out;
1327
+ }
1328
+ function markdownAlternateTarget(agent, browser, origin) {
1329
+ if (agent === null || agent.status < 200 || agent.status >= 300) return null;
1330
+ if (isMachineCopy(agent)) return null;
1331
+ const own = /* @__PURE__ */ new Set([agent.finalUrl, agent.requestedUrl]);
1332
+ for (const href of declaredMarkdownAlternates([browser, agent])) {
1333
+ let sameOrigin = false;
1334
+ try {
1335
+ sameOrigin = new URL(href).origin === origin;
1336
+ } catch {
1337
+ sameOrigin = false;
1338
+ }
1339
+ if (sameOrigin && !own.has(href)) return href;
1340
+ }
1341
+ return null;
1342
+ }
1343
+
1344
+ // src/site-signals.ts
1345
+ var BODY_SCAN_CHARS = 256 * 1024;
1346
+ function headerValues(input, name) {
1347
+ const direct = input.headers[name];
1348
+ if (direct !== void 0) return direct.map((value) => value.toLowerCase());
1349
+ const target = name.toLowerCase();
1350
+ const out = [];
1351
+ for (const [key, values] of Object.entries(input.headers)) {
1352
+ if (key.toLowerCase() === target) {
1353
+ for (const value of values) out.push(value.toLowerCase());
1354
+ }
1355
+ }
1356
+ return out;
1357
+ }
1358
+ function hasToken(values, token) {
1359
+ return values.some(
1360
+ (value) => value.split(",").map((part) => part.trim()).includes(token)
1361
+ );
1362
+ }
1363
+ function isRobotsTxtTarget(input) {
1364
+ for (const raw of [input.requestedUrl, input.finalUrl]) {
1365
+ if (typeof raw !== "string" || raw.length === 0) continue;
1366
+ try {
1367
+ if (new URL(raw).pathname.toLowerCase() === "/robots.txt") return true;
1368
+ } catch {
1369
+ const path = (raw.split("#")[0]?.split("?")[0] ?? "").toLowerCase();
1370
+ if (path === "/robots.txt" || path.endsWith("/robots.txt")) return true;
1371
+ }
1372
+ }
1373
+ return false;
1374
+ }
1375
+ function detectEdgeChallenge(input) {
1376
+ const status = input.status;
1377
+ const body = typeof input.body === "string" ? input.body.slice(0, BODY_SCAN_CHARS) : "";
1378
+ const server = headerValues(input, "server");
1379
+ const contentTypes = headerValues(input, "content-type");
1380
+ const isHtmlContent = contentTypes.some(
1381
+ (value) => value.includes("text/html") || value.includes("application/xhtml+xml")
1382
+ );
1383
+ const lowerBodyHead = body.slice(0, 4096).toLowerCase();
1384
+ const isPlainTextWithoutMarkup = contentTypes.some((value) => value.includes("text/plain")) && !lowerBodyHead.includes("<html") && !lowerBodyHead.includes("<script") && !lowerBodyHead.includes("<!doctype html");
1385
+ const isRobotsHtmlChallenge = isRobotsTxtTarget(input) && isHtmlContent;
1386
+ if (hasToken(headerValues(input, "cf-mitigated"), "challenge")) {
1387
+ return { vendor: "cloudflare", signal: "cf-mitigated: challenge", status };
1388
+ }
1389
+ if ((status === 403 || status === 429 || status === 503 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && server.some((value) => value.includes("cloudflare")) && body.includes("/cdn-cgi/challenge-platform/")) {
1390
+ return { vendor: "cloudflare", signal: "Cloudflare challenge page", status };
1391
+ }
1392
+ if (hasToken(headerValues(input, "x-vercel-mitigated"), "challenge")) {
1393
+ return { vendor: "vercel", signal: "x-vercel-mitigated: challenge", status };
1394
+ }
1395
+ if ((status < 200 || status >= 300 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && server.some((value) => value.includes("vercel")) && body.includes("Vercel Security Checkpoint")) {
1396
+ return { vendor: "vercel", signal: "Vercel Security Checkpoint page", status };
1397
+ }
1398
+ if ((status === 401 || status === 403) && headerValues(input, "x-datadome").length > 0) {
1399
+ return { vendor: "datadome", signal: `x-datadome with HTTP ${status}`, status };
1400
+ }
1401
+ if ((status === 403 || status === 429 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && body.includes("px-captcha") && body.includes("_pxAppId")) {
1402
+ return { vendor: "human", signal: "HUMAN block page", status };
1403
+ }
1404
+ return null;
1405
+ }
1406
+ var DETAIL_PREFIX = "edge-challenge";
1407
+ function challengeDetail(challenge) {
1408
+ return `${DETAIL_PREFIX}; vendor=${challenge.vendor}; status=${challenge.status}; signal=${challenge.signal.slice(0, 120)}`;
1409
+ }
1410
+ new Set(
1411
+ [
1412
+ ...DEFAULT_RULESET.audienceTokens.assistant,
1413
+ ...DEFAULT_RULESET.audienceTokens.training,
1414
+ ...DEFAULT_RULESET.audienceTokens.search,
1415
+ "googlebot",
1416
+ "bingbot"
1417
+ ].map((token) => token.toLowerCase())
1418
+ );
623
1419
  var ALLOW_PRIVATE_HOSTS = /* @__PURE__ */ Symbol("rebilder.ars.probe.allow-private-hosts");
624
1420
  var allowsPrivateHosts = (policy) => policy === ALLOW_PRIVATE_HOSTS;
625
1421
  var NOT_AN_IP = { family: null, reserved: false, label: "hostname" };
@@ -713,6 +1509,9 @@ function classifyIpv6Groups(groups) {
713
1509
  const allZeroThrough = (upTo) => groups.slice(0, upTo).every((x) => x === 0);
714
1510
  if (groups.every((x) => x === 0)) return v6("unspecified (::)", true);
715
1511
  if (allZeroThrough(7) && g(7) === 1) return v6("loopback (::1)", true);
1512
+ if (allZeroThrough(4) && g(4) === 65535 && g(5) === 0) {
1513
+ return v6("IPv4-translated (::ffff:0:0:0/96)", true);
1514
+ }
716
1515
  if (allZeroThrough(5) && g(5) === 65535) {
717
1516
  const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
718
1517
  return v6(`IPv4-mapped \u2192 ${inner.label}`, inner.reserved);
@@ -721,10 +1520,16 @@ function classifyIpv6Groups(groups) {
721
1520
  const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
722
1521
  return v6(`IPv4-compatible \u2192 ${inner.label}`, true);
723
1522
  }
1523
+ if (g(0) === 100 && g(1) === 65435 && g(2) === 1) {
1524
+ return v6("NAT64 local-use (64:ff9b:1::/48)", true);
1525
+ }
724
1526
  if (g(0) === 100 && g(1) === 65435 && g(2) === 0 && g(3) === 0 && g(4) === 0 && g(5) === 0) {
725
1527
  const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
726
1528
  return v6(`NAT64 64:ff9b::/96 \u2192 ${inner.label}`, inner.reserved);
727
1529
  }
1530
+ if (g(0) === 8193 && g(1) === 0) {
1531
+ return v6("Teredo (2001::/32)", true);
1532
+ }
728
1533
  if (g(0) === 8194) {
729
1534
  const inner = classifyIpv4Octets(embeddedV4(g(1), g(2)));
730
1535
  return v6(`6to4 2002::/16 \u2192 ${inner.label}`, inner.reserved);
@@ -734,6 +1539,7 @@ function classifyIpv6Groups(groups) {
734
1539
  if (g(0) === 8193 && g(1) === 3512) return v6("documentation (2001:db8::/32)", true);
735
1540
  if ((g(0) & 65024) === 64512) return v6("unique local (fc00::/7)", true);
736
1541
  if ((g(0) & 65472) === 65152) return v6("link-local (fe80::/10)", true);
1542
+ if ((g(0) & 65472) === 65216) return v6("site-local (fec0::/10)", true);
737
1543
  if ((g(0) & 65280) === 65280) return v6("multicast (ff00::/8)", true);
738
1544
  return v6("public", false);
739
1545
  }
@@ -776,8 +1582,10 @@ function guardUrl(input, policy) {
776
1582
  if (url.username !== "" || url.password !== "") {
777
1583
  return { ok: false, reason: "URLs with embedded credentials cannot be fetched." };
778
1584
  }
779
- let hostname = url.hostname.toLowerCase();
780
- if (hostname.endsWith(".") && hostname.length > 1) hostname = hostname.slice(0, -1);
1585
+ const hostname = url.hostname.toLowerCase().replace(/\.+$/, "");
1586
+ if (hostname === "") {
1587
+ return { ok: false, reason: "That URL has no hostname." };
1588
+ }
781
1589
  const permissive = allowsPrivateHosts(policy.hostPolicy);
782
1590
  if (!permissive && (hostname === "localhost" || hostname.endsWith(".localhost"))) {
783
1591
  return { ok: false, reason: "localhost cannot be fetched." };
@@ -1067,7 +1875,7 @@ function createLimiter(options = {}) {
1067
1875
  }
1068
1876
 
1069
1877
  // src/probe/index.ts
1070
- var ARS_USER_AGENT = "rebilder-ars/0.2 (+https://rebilder.com/bots)";
1878
+ var ARS_USER_AGENT = "rebilder-ars/0.3 (+https://rebilder.com/bots)";
1071
1879
  var AGENT_IDENTITY = {
1072
1880
  role: "agent",
1073
1881
  userAgent: ARS_USER_AGENT,
@@ -1361,6 +2169,16 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1361
2169
  };
1362
2170
  }
1363
2171
  };
2172
+ const runPage = async (href, headers) => {
2173
+ const record = await run(href, headers);
2174
+ if (!record.result.ok) return record;
2175
+ const challenge = detectEdgeChallenge(record.result.capture);
2176
+ if (challenge === null) return record;
2177
+ return {
2178
+ requestHeaders: headers,
2179
+ result: { ok: false, error: "challenge", detail: challengeDetail(challenge) }
2180
+ };
2181
+ };
1364
2182
  const evidenceOf = (probes) => ({
1365
2183
  ok: true,
1366
2184
  evidence: {
@@ -1405,8 +2223,18 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1405
2223
  wellKnownUcp: null
1406
2224
  });
1407
2225
  }
1408
- const agent = await run(url.toString(), agentHeaders);
1409
- const browser = await run(url.toString(), browserHeaders);
2226
+ const agent = await runPage(url.toString(), agentHeaders);
2227
+ const browser = await runPage(url.toString(), browserHeaders);
2228
+ const linked = markdownAlternateTarget(
2229
+ agent.result.ok ? agent.result.capture : null,
2230
+ browser.result.ok ? browser.result.capture : null,
2231
+ origin
2232
+ );
2233
+ let markdownAlternate = null;
2234
+ if (linked !== null) {
2235
+ const rule = disallowedFor(new URL(linked).pathname);
2236
+ markdownAlternate = rule !== null ? skipped(agentHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${linked}`) : await runPage(linked, agentHeaders);
2237
+ }
1410
2238
  const fetchAsset = async (path) => {
1411
2239
  const rule = disallowedFor(path);
1412
2240
  if (rule !== null)
@@ -1415,7 +2243,17 @@ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1415
2243
  };
1416
2244
  const llmsTxt = await fetchAsset("/llms.txt");
1417
2245
  const wellKnownUcp = await fetchAsset("/.well-known/ucp");
1418
- return evidenceOf({ agent, browser, parityConfirm: null, robotsTxt, llmsTxt, wellKnownUcp });
2246
+ return evidenceOf({
2247
+ agent,
2248
+ browser,
2249
+ parityConfirm: null,
2250
+ // Omitted when not taken, so a page with no linked copy produces exactly
2251
+ // the bundle (and the evidence hash) it produced under 0.2.
2252
+ ...markdownAlternate === null ? {} : { markdownAlternate },
2253
+ robotsTxt,
2254
+ llmsTxt,
2255
+ wellKnownUcp
2256
+ });
1419
2257
  } catch (error) {
1420
2258
  if (error instanceof ProbeBudgetExceededError) {
1421
2259
  return { ok: false, rejection: "budget-exceeded", detail: error.message };