Repository navigation
Expand file tree
/
Copy pathfetch-docs.sh
More file actions
executable file
·844 lines (799 loc) · 34.8 KB
/
Copy pathfetch-docs.sh
File metadata and controls
executable file
·844 lines (799 loc) · 34.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
#!/usr/bin/env bash
# Upstream docs fetcher, shared by the plugins that read vendor docs pages.
#
# Skills that rest on official docs pages grep them for cited spans and read
# them for the criteria their checks apply. This script is the one place those
# pages are fetched. It reads each page verbatim to a file and writes a
# manifest of what it did. It never reads, searches or summarizes a page: it
# guarantees complete bytes on disk plus the manifest, and the caller reads.
#
# A publisher is a profile (--profile, default anthropic). An indexed profile
# (anthropic, platform) has an index URL (llms.txt), the path prefix pages live
# under on the index's origin, the raw channel (the suffix that turns a page
# slug into its raw-markdown file name) and the content types the index and the
# channel answer with. A page whose channel does not answer as declared is
# unread with a reason, never read from another channel.
#
# Identity in an indexed profile comes from the index. A slug the index does not
# list is not fetched: a retired slug can answer 200 with another page's body, so
# a body that arrived is no proof the page exists. A page is read only when the
# whole body arrived over HTTPS from the profile's origin with the profile's
# content type and a 2xx status. Anything else is unread and leaves no file, so a
# partial or foreign body is never counted as read. A body over max_page_bytes
# (--max-page-bytes, else docs-cache.sh's configuration) is unread too-large:
# nothing of it is converted or stored.
#
# The generic profile takes any https URL and needs no index. It prefers
# markdown, in this order: the URL with Accept: text/markdown; the URL with a
# .md suffix; a same-origin link in the origin's llms.txt whose path, without a
# .md or .txt suffix or a trailing /index, is the page's path. The two later
# channels accept text/plain as markdown. The URL's own request does too when
# its path ends in .md, so a host that serves .md files as text/plain is read;
# for any other path a text/plain answer is not markdown and the read moves
# on. When none
# answers with markdown, the page's HTML is converted by html2md.py beside this
# script, run by the first of python3 and python whose probe prints 3, with
# PYTHONUTF8=1. Identity: the page's own request must end on the requested
# origin and path, or the page is unread. With --cache the page's title (its
# first heading, else the HTML <title>) is stored, and an entry whose title
# differs from the one it replaces quarantines the cache key (docs-cache.sh).
# A 2xx with an accepted type is still no proof of content: X serves a
# logged-out shell for a status page. An x.com or twitter.com page whose body
# links to redirect_after_login and holds fewer than 200 words outside its
# links is unread login-wall and is never stored, whether it was fetched or
# served from the cache or the fixture directory; /x:read reads X posts.
# With --expect <marker>, a generic page whose body lacks the literal marker is
# unread no-content. With --render-fallback and docs-cache.sh's renderer set to
# firecrawl, a generic page left unread for fetch-failed, http-403, http-429,
# unexpected-content-type or no-content is rendered through the Firecrawl CLI
# (never 404, 410 or an off-site landing), checked against --public-only and
# landed, and stored under format rendered with content type text/markdown; if
# rendering also fails on 403 or 429, a cached copy is served stale.
#
# curl runs with -q, so no ~/.curlrc option reaches a request. With
# --public-only, for a caller whose URLs come from untrusted text, every
# address a host resolves to must be global (Python's ipaddress is_global), or
# the page is unread private-address; the request then connects to the first
# checked address through --connect-to with no proxy, so a redirect hop to any
# host and a second DNS answer reach that address and no other. Without a
# Python 3 the page is unread address-unchecked. OWASP's SSRF prevention cheat
# sheet, case 2, prescribes this check over an allowlist when the destination
# is open: https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html
#
# The page file is the raw bytes as fetched, or the converter's output. The
# manifest hash is taken over those bytes, so a caller that strips control
# characters from a working copy does not change it.
#
# With --cache the index and every page go through docs-cache.sh beside this
# script, keyed by URL and format (markdown, html-converted or rendered), so one URL that
# negotiates to either is two keys. An entry validated within --max-age seconds
# is copied to the page file with no request. Any other read is fetched; when
# the cached entry was stored with an ETag or Last-Modified, the request carries
# If-None-Match or If-Modified-Since, and a 304 serves the entry and moves only
# its validated time. A Last-Modified equal to the response's Date is treated as
# absent. --max-age 0 always asks the server, and a failed fetch is unread. With
# --max-age above 0, a fetch that failed (a transport error or a 5xx) serves the
# cached bytes flagged stale: true, its reason and age_seconds since validated.
# A 404, a 410, a landing off the origin or path, or a slug the index no longer
# lists is unread and quarantines the URL's cache keys, so their notes are never
# served; while that quarantine stands, the URL is fetched again whatever its
# age, and a read under the recorded title lifts it. The server's Date is
# recorded as server_date, never used for age.
#
# Manifest (JSON, written to --manifest):
# claude_version installed `claude --version` number, or "" when unreadable
# index record for the index itself (null for the generic profile)
# pages[] one record per requested page, in request order
# cache_disabled null, or the layer (env or file) whose cache_enabled false
# made this --cache run read and write no cache
# Each record: slug, url, mode, source (fetch|fixture|cache), retrieved (UTC
# ISO, when these bytes were first fetched), validated (UTC ISO, when they were
# last confirmed current), age_seconds (since validated), cache_key (the
# docs-cache.sh key, null when nothing was stored), sha256 (raw bytes), status
# (HTTP code; 304 when the server confirmed a cached entry), content_type,
# bytes, lines, file (path on disk), format (markdown|html-converted|rendered), title
# (from the cache), quarantined (the cache key's quarantine flag), stale (true
# when cached bytes stood in for a failed fetch), server_date (the Date header of
# the response that last validated the bytes), cache_error (why --cache stored
# nothing for a read page, else null), state, reason. state is read or unread; unparsed is set by a caller whose parse of a
# read page failed. mode (full|search) is the caller's declaration of how it
# will use the page; the fetcher only records it. Fields with no value are null
# (a page never requested, or served fresh from the cache, has no status; one
# served stale carries the failed fetch's status, if it had one; a run
# without --cache has no title or quarantined).
#
# Exit codes:
# 0 the manifest was written (pages may be unread; read the manifest)
# 2 fatal (bad arguments, unknown profile, jq missing, manifest not writable)
#
# Env overrides (the test seam):
# FETCH_DOCS_FIXTURE_DIR directory of llms.txt and <slug>.md
# files. Set, even to an empty or missing directory, means no network: a
# file the directory lacks is unread (fixture-missing), never fetched.
# FETCH_DOCS_INDEX_URL index URL when --index-url is absent (default: the profile's)
# FETCH_DOCS_CLAUDE_BIN claude binary for claude_version
# FETCH_DOCS_HTML2MD HTML converter (default: html2md.py beside this script)
# FETCH_DOCS_ADDRESSES with --public-only, the DNS answers to use instead of
# a lookup: host=addr[,addr] entries separated by spaces; a host it does not
# name does not resolve
# DOCS_CACHE_DIR cache directory when --cache-dir is absent; in
# fixture mode --cache needs one of the two, so fixture bytes never reach
# the default or the machine file's cache. The other DOCS_CACHE_*
# settings and the machine file are docs-cache.sh's (its header).
# DOCS_CACHE_NOW epoch seconds docs-cache.sh uses as the current time
set -uo pipefail
PROFILES="anthropic, platform, generic"
usage() {
cat <<EOF
fetch-docs.sh: fetch a publisher's docs pages verbatim and write a manifest.
Usage:
fetch-docs.sh --out <dir> [--manifest <file>] [--profile <name>] [--index-url <url>] [--follow <depth>]
[--max-page-bytes <n>] [--cache [--max-age <seconds>] [--cache-dir <dir>]] [--public-only]
[--expect <marker>] [--render-fallback]
(--discover | [--mode full|search] <slug|url>...)
--out <dir> directory for the page files (<slug>.md) and the index (llms.txt)
--manifest <file> manifest path (default: <dir>/manifest.json)
--profile <name> publisher profile (default: anthropic; known: $PROFILES)
--index-url <url> docs index (default: the profile's; its origin is the allowed origin)
--discover request every page the index links under the profile's path prefix
--mode <m> how the caller will use the pages that follow: full (default) or search
--follow <depth> reserved for link-following; accepted, default 0, acted on by no caller
--max-page-bytes <n> a body over <n> bytes is unread too-large (default: the docs cache's
max_page_bytes, 10485760 unless configured)
--cache read through the docs cache and store what is fetched
--max-age <s> serve a cached entry validated at most <s> seconds ago (default: the
docs cache's ttl_seconds, 86400 unless configured); 0 always asks the server
--cache-dir <dir> cache directory (default: the docs cache's cache_dir)
These defaults, and cache_enabled, resolve from DOCS_CACHE_* and the machine
file; docs-cache.sh config prints them with their layer.
--public-only connect only to a global address the host was checked to resolve to
--expect <marker> generic profile only: a read page lacking <marker> is unread no-content
--render-fallback generic profile only: when docs-cache renderer is firecrawl, render
fetch-failed, http-403, http-429, unexpected-content-type or no-content
pages via firecrawl scrape and cache as format rendered
<slug|url> a page slug (settings-reference) or an origin URL the index lists
(its raw suffix optional, a #fragment ignored);
for --profile generic, any https URL (its slug is host/path); X's
logged-out shell for an x.com or twitter.com page is unread login-wall,
not a read page
Exit: 0 manifest written; 2 fatal (including an unknown profile).
EOF
}
die() {
echo "ERROR: $1" >&2
exit 2
}
PROFILE=anthropic
INDEX_URL=""
OUT=""
MANIFEST=""
DISCOVER=0
MODE=full
CACHE=0
MAX_AGE=""
MAX_PAGE=""
CACHE_DIR=""
PUBLIC_ONLY=0
EXPECT=""
RENDER_FALLBACK=0
RENDER_SEQ=0
TARGETS=()
TARGET_MODES=()
while [[ $# -gt 0 ]]; do
case "$1" in
-h | --help)
usage
exit 0
;;
--out | --manifest | --profile | --index-url | --follow | --mode | --max-age | --max-page-bytes | --cache-dir | --expect)
[[ $# -ge 2 ]] || die "$1 needs a value"
case "$1" in
--out) OUT="$2" ;;
--manifest) MANIFEST="$2" ;;
--profile) PROFILE="$2" ;;
--index-url) INDEX_URL="$2" ;;
--follow) [[ "$2" =~ ^[0-9]+$ ]] || die "--follow needs a non-negative integer" ;; # depth is validated and dropped: no caller follows links
--mode)
[[ "$2" == full || "$2" == search ]] || die "--mode is full or search"
MODE="$2"
;;
--max-age)
[[ "$2" =~ ^(0|[1-9][0-9]{0,17})$ ]] || die "--max-age needs a non-negative integer"
MAX_AGE="$2"
;;
--max-page-bytes)
[[ "$2" =~ ^[1-9][0-9]{0,17}$ ]] || die "--max-page-bytes needs a positive integer"
MAX_PAGE="$2"
;;
--cache-dir)
[[ -n "$2" ]] || die "--cache-dir needs a value"
CACHE_DIR="$2"
;;
--expect)
[[ -n "$2" ]] || die "--expect needs a value"
EXPECT="$2"
;;
*) die "unreachable" ;;
esac
shift 2
;;
--discover)
DISCOVER=1
shift
;;
--cache)
CACHE=1
shift
;;
--public-only)
PUBLIC_ONLY=1
shift
;;
--render-fallback)
RENDER_FALLBACK=1
shift
;;
-*) die "unknown argument: $1" ;;
*)
TARGETS+=("$1")
TARGET_MODES+=("$MODE")
shift
;;
esac
done
MD_CTYPE='^text/(markdown|x-markdown)'
MD_OR_TEXT_CTYPE='^text/(markdown|x-markdown|plain)'
HTML_CTYPE='^(text/html|application/xhtml\+xml)'
# profile <name>: set the publisher's record. P_KIND is index or url. For an
# index profile P_DOCS_PATH is the path prefix a page URL has under the index's
# origin, P_SUFFIX the raw channel's file suffix, P_INDEX_CTYPE and
# P_PAGE_CTYPE the content-type patterns the index and the raw channel answer
# with, P_FORMAT the format the cache keys their bytes by.
profile() {
P_KIND=index P_DOCS_PATH="/docs/" P_SUFFIX=".md" P_FORMAT=markdown
P_INDEX_CTYPE='^text/(plain|markdown)' P_PAGE_CTYPE="$MD_CTYPE"
case "$1" in
anthropic) P_INDEX_URL="https://code.claude.com/docs/llms.txt" ;;
platform) P_INDEX_URL="https://platform.claude.com/llms.txt" ;;
generic) P_KIND=url P_INDEX_URL="" ;;
*) return 1 ;;
esac
}
profile "$PROFILE" || die "unknown profile: $PROFILE (known: $PROFILES)"
[[ -n "$OUT" ]] || die "--out is required"
[[ $DISCOVER -eq 1 || ${#TARGETS[@]} -gt 0 ]] || die "name a page or pass --discover"
command -v jq >/dev/null 2>&1 || die "jq required"
ORIGIN=""
if [[ "$P_KIND" == index ]]; then
INDEX_URL="${INDEX_URL:-${FETCH_DOCS_INDEX_URL:-$P_INDEX_URL}}"
[[ "$INDEX_URL" =~ ^(https://[^/]+) ]] && ORIGIN="${BASH_REMATCH[1]}"
[[ -n "$ORIGIN" ]] || die "--index-url must be an https URL"
[[ -z "$EXPECT" ]] || die "--expect needs the generic profile"
[[ $RENDER_FALLBACK -eq 0 ]] || die "--render-fallback needs the generic profile"
else
[[ $DISCOVER -eq 0 ]] || die "--discover needs an indexed profile"
[[ -z "$INDEX_URL" ]] || die "--index-url needs an indexed profile"
fi
FIXTURE_SET=0
[[ -n "${FETCH_DOCS_FIXTURE_DIR+x}" ]] && FIXTURE_SET=1
FIXTURE="${FETCH_DOCS_FIXTURE_DIR:-}"
CURL_MISSING=0
if [[ $FIXTURE_SET -eq 0 ]] && ! command -v curl >/dev/null 2>&1; then CURL_MISSING=1; fi
CACHE_DISABLED=""
# The docs cache's configuration holds max_page_bytes, so it resolves with or without --cache.
HERE="$(dirname "${BASH_SOURCE[0]}")"
DOCS_CACHE="$HERE/docs-cache.sh"
[[ -f "$DOCS_CACHE" ]] || die "docs-cache.sh not found beside fetch-docs.sh"
# shellcheck source=docs-cache.sh
. "$DOCS_CACHE"
FETCH_DOCS_GENERIC="$HERE/fetch-docs-generic.sh"
[[ -f "$FETCH_DOCS_GENERIC" ]] || die "fetch-docs-generic.sh not found beside fetch-docs.sh"
# shellcheck source=fetch-docs-generic.sh
. "$FETCH_DOCS_GENERIC"
dc_config cache_dir="$CACHE_DIR" ttl_seconds="$MAX_AGE" max_page_bytes="$MAX_PAGE"
dc_config_warn
MAX_PAGE="$DC_CFG_max_page_bytes"
if [[ $CACHE -eq 1 ]]; then
if [[ "$DC_CFG_cache_enabled" == false ]]; then
CACHE=0 CACHE_DISABLED="$DC_LAYER_cache_enabled"
else
# Fixture bytes reach only a cache this invocation named, never the machine file's.
[[ $FIXTURE_SET -eq 0 || "$DC_LAYER_cache_dir" == flag || "$DC_LAYER_cache_dir" == env ]] ||
die "--cache with FETCH_DOCS_FIXTURE_DIR needs --cache-dir or DOCS_CACHE_DIR"
MAX_AGE="$DC_CFG_ttl_seconds"
fi
fi
MAX_AGE="${MAX_AGE:-0}"
CONVERTER="${FETCH_DOCS_HTML2MD:-$HERE/html2md.py}"
mkdir -p "$OUT" || die "cannot create $OUT"
MANIFEST="${MANIFEST:-$OUT/manifest.json}"
mkdir -p "$(dirname "$MANIFEST")" || die "cannot create the manifest directory"
WORK="$(mktemp -d)" || die "could not create a temp directory"
INDEX_REC="$WORK/index.json"
PAGE_RECS="$WORK/pages.jsonl"
: >"$PAGE_RECS"
trap 'rm -rf "$WORK"' EXIT
sha256_of() {
if command -v sha256sum >/dev/null 2>&1; then sha256sum <"$1" | cut -d' ' -f1; else shasum -a 256 <"$1" | cut -d' ' -f1; fi
}
# with_timeout <seconds> <command...>: run under timeout when it exists.
with_timeout() {
local s="$1"
shift
if command -v timeout >/dev/null 2>&1; then timeout "$s" "$@"; else "$@"; fi
}
reset_g() {
G_SOURCE="" G_STATE=unread G_REASON="" G_STATUS="" G_CTYPE="" G_AT="" G_VALIDATED="" G_AGE="" G_KEY=""
G_FORMAT="" G_TITLE="" G_QUAR="" G_VALIDATORS="" G_TITLE_HINT="" G_STALE="" G_DATE="" G_CACHE_ERR=""
}
# Prints the host's addresses, IPv6 in brackets, comma-separated; exit 3 when
# any is not global (an IPv4-mapped IPv6 address is judged as its IPv4), 4
# when the host does not resolve.
# shellcheck disable=SC2016 # Python source, not shell
PIN_PY='
import ipaddress, os, socket, sys
host = sys.argv[1]
stub = os.environ.get("FETCH_DOCS_ADDRESSES")
try:
if stub is not None:
found = [a for e in stub.split() if e.partition("=")[0] == host for a in e.partition("=")[2].split(",")]
else:
found = [i[4][0] for i in socket.getaddrinfo(host, 443, proto=socket.IPPROTO_TCP)]
ips = [ipaddress.ip_address(a.split("%")[0]) for a in found]
except (OSError, ValueError, UnicodeError):
sys.exit(4)
if not ips:
sys.exit(4)
out = []
for ip in ips:
if ip.version == 6 and ip.ipv4_mapped:
ip = ip.ipv4_mapped
if not ip.is_global or ip.is_multicast:
sys.exit(3)
a = str(ip) if ip.version == 4 else "[" + str(ip) + "]"
if a not in out:
out.append(a)
print(",".join(out))
'
# shellcheck disable=SC2034 # read and written by name in map_get and map_put
PINS_K=() PINS_V=()
# pin <host>: set PIN to the first global address the host resolves to, checked
# once per run. Returns 97 when an address is not global, 96 when no Python 3
# can check, 6 (curl's code for a name that does not resolve) otherwise.
pin() {
local rc=0 v
[[ -n "$1" ]] || return 6
if ! map_get PINS "$1" v; then
v=96
if resolve_python; then
v="$(with_timeout 30 "$PY" -I -c "$PIN_PY" "$1" 2>/dev/null </dev/null)" || rc=$?
case "$rc" in
0) v="${v%%,*}" v="${v%$'\r'}" ;;
3) v=97 ;;
*) v=6 ;;
esac
fi
map_put PINS "$1" "$v"
fi
PIN="$v"
[[ "$PIN" =~ ^[0-9]+$ ]] || return 0
return "$PIN"
}
# http_get <url> <dest> <accept> <if-none-match> <if-modified-since>: one GET
# with the body at <dest>. Sets H_RC H_STATUS H_EFF H_CTYPE and the final
# response's H_DATE, H_ETAG and H_LM (empty when absent, or Last-Modified equal
# to Date). A body over max_page_bytes is deleted and H_RC is 63, curl's own
# code for it: curl stops at a declared Content-Length over the limit, and the
# size check catches a body sent without one, which an older curl lets through.
http_get() {
local hdr="$2.hdr" meta args=() line low date=""
[[ -z "$3" ]] || args+=(-H "Accept: $3")
[[ -z "$4" ]] || args+=(-H "If-None-Match: $4")
[[ -z "$5" ]] || args+=(-H "If-Modified-Since: $5")
rm -f "$2" "$hdr"
H_STATUS="" H_EFF="" H_CTYPE="" H_CTYPE_LC="" H_ETAG="" H_LM="" H_DATE=""
if [[ $PUBLIC_ONLY -eq 1 ]]; then
url_parts "$1" || {
H_RC=1
return
}
[[ "${U_ORIGIN#https://}" =~ ^([^:]+)(:[0-9]+)?$ ]]
pin "${BASH_REMATCH[1]:-}" || {
H_RC=$?
return
}
args+=(--noproxy '*' --connect-to "::$PIN:")
fi
# No -f: an HTTP error still prints its status and content type through -w.
meta="$(curl -q -sSL --proto =https --proto-redir =https --max-redirs 5 --connect-timeout 15 --max-time 120 \
--max-filesize "$MAX_PAGE" ${args[@]+"${args[@]}"} -D "$hdr" -w '%{http_code} %{url_effective} %{content_type}' \
-o "$2" "$1" 2>/dev/null)"
H_RC=$?
if [[ -f "$2" && $(wc -c <"$2") -gt $MAX_PAGE ]]; then H_RC=63; fi
[[ $H_RC -ne 63 ]] || rm -f "$2"
read -r H_STATUS H_EFF H_CTYPE <<<"$meta"
[[ "$H_STATUS" =~ ^[0-9]+$ ]] || H_STATUS=""
dc_lower H_CTYPE_LC "$H_CTYPE"
if [[ -f "$hdr" ]]; then
# A redirect writes one header block per response; the last one counts.
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%$'\r'}"
dc_lower low "$line"
case "$low" in
http/*) H_ETAG="" H_LM="" date="" ;;
etag:*) H_ETAG="$(trim "${line#*:}")" ;;
last-modified:*) H_LM="$(trim "${line#*:}")" ;;
date:*) date="$(trim "${line#*:}")" ;;
*) ;;
esac
done <"$hdr"
rm -f "$hdr"
fi
[[ "$H_LM" != "$date" ]] || H_LM=""
H_DATE="$date"
}
# failure_reason: the unread reason for a nonzero H_RC.
failure_reason() {
case "$H_RC" in
63) printf too-large ;;
97) printf private-address ;;
96) printf address-unchecked ;;
*) printf fetch-failed ;;
esac
}
trim() {
local s="$1"
s="${s#"${s%%[![:space:]]*}"}"
printf '%s' "${s%"${s##*[![:space:]]}"}"
}
# cache_candidate <url> <format>...: the freshest stored entry for the URL in
# any of the formats. Sets C_REF (<key>-<sha256>, empty when none), the
# validated time its pointer held when it was chosen (C_EPOCH C_ISO) and the
# server Date (C_DATE), C_CTYPE C_FORMAT and its validators C_ACCEPT C_REQ_URL
# C_ETAG C_LM.
cache_candidate() {
local url="$1" f
C_REF="" C_EPOCH="" C_ISO="" C_DATE="" C_CTYPE="" C_CTYPE_LC="" C_FORMAT="" C_ACCEPT="" C_REQ_URL="" C_ETAG="" C_LM=""
[[ $CACHE -eq 1 ]] || return 0
shift
for f in "$@"; do
dc_lookup "$(dc_key "$url" "$f")" || continue
[[ -n "$DC_VALIDATED_EPOCH" ]] || continue
[[ -z "$C_REF" || $DC_VALIDATED_EPOCH -gt $C_EPOCH ]] || continue
C_REF="$DC_REF" C_EPOCH="$DC_VALIDATED_EPOCH" C_ISO="$DC_VALIDATED" C_DATE="$DC_SERVER_DATE" C_CTYPE="$DC_CTYPE" C_FORMAT="$f"
dc_lower C_CTYPE_LC "$C_CTYPE"
C_ACCEPT="$DC_ACCEPT" C_REQ_URL="$DC_REQ_URL" C_ETAG="$DC_ETAG" C_LM="$DC_LM"
done
}
# serve_cached <dest> <status>: copy the candidate's body to <dest> and set the
# G_ fields from its immutable entry and the pointer snapshot taken when it was
# chosen, so a pointer switched since then cannot blank its validated time.
serve_cached() {
if ! { [[ -n "$C_EPOCH" ]] && dc_lookup "$C_REF" && cp "$DC_ENTRY/body" "$1"; }; then
rm -f "$1"
return 1
fi
G_SOURCE=cache G_STATE=read G_REASON="" G_STATUS="$2" G_CTYPE="$DC_CTYPE" G_AT="$DC_RETRIEVED"
G_VALIDATED="$C_ISO" G_AGE=$((DC_NOW - C_EPOCH)) G_KEY="$DC_KEY"
G_FORMAT="$DC_FORMAT" G_TITLE="$DC_TITLE" G_QUAR="$DC_QUARANTINED" G_DATE="$C_DATE"
}
settle_unread() {
local url="$1" dest="$2" reason="$G_REASON" status="$G_STATUS" f
shift 2
[[ $CACHE -eq 1 && "$G_STATE" != read ]] || return 0
case "$reason" in
fetch-failed | http-5[0-9][0-9] | http-403 | http-429)
if [[ "$reason" == http-403 || "$reason" == http-429 ]]; then
[[ $RENDER_FALLBACK -eq 1 && "$DC_CFG_renderer" == firecrawl ]] || return 0
fi
[[ $MAX_AGE -gt 0 && -n "$C_REF" ]] || return 0
! removal_quarantined "${C_REF%-*}" || return 0
serve_cached "$dest" "$status" || return 0
G_STALE=1 G_REASON="$reason"
;;
http-404 | http-410 | redirected-off-origin | redirected-off-path | not-in-index)
for f in "$@"; do dc_quarantine_reason "$(dc_key "$url" "$f")" "$reason"; done
;;
*) ;;
esac
}
# removal_quarantined <key>: the key carries a removal quarantine (any reason
# but retitled).
removal_quarantined() {
local q="$DC_DIR/keys/${1:0:16}.quarantine"
[[ -f "$q" ]] && jq -e '(.reason // "retitled") != "retitled"' "$q" >/dev/null 2>&1
}
# serve_fresh <dest> <format>...: serve the candidate when it was validated
# within --max-age and its key has no removal quarantine, so a page found
# removed is asked for again. Outside fixture mode its stored content type must
# fit its format, so a fixture read (stored with none) never reaches a real read.
serve_fresh() {
local dest="$1" age re
[[ $CACHE -eq 1 && $MAX_AGE -gt 0 && -n "$C_REF" ]] || return 1
! removal_quarantined "${C_REF%-*}" || return 1
age=$((DC_NOW - C_EPOCH))
[[ $age -ge 0 && $age -le $MAX_AGE ]] || return 1
re="$MD_OR_TEXT_CTYPE"
[[ "$C_FORMAT" != html-converted ]] || re="$HTML_CTYPE"
[[ $FIXTURE_SET -eq 1 || "$C_CTYPE_LC" =~ $re ]] || return 1
serve_cached "$dest" ""
}
# request <accept> <url> <dest>: http_get, conditional when the candidate was
# last confirmed over this same request. A 304 to a conditional request serves
# the candidate and returns 0; anything else returns 1 with the H_ fields set.
request() {
local inm="" ims=""
if [[ -n "$C_REF" && "$C_ACCEPT" == "$1" && "$C_REQ_URL" == "$2" ]]; then inm="$C_ETAG" ims="$C_LM"; fi
http_get "$2" "$3" "$1" "$inm" "$ims"
[[ $H_RC -eq 0 && "$H_STATUS" == 304 && -n "$inm$ims" ]] || return 1
rm -f "$3"
dc_confirm "$C_REF" "$(dc_validators "$1" "$2" "${H_ETAG:-$C_ETAG}" "${H_LM:-$C_LM}")" "$H_DATE" || return 1
C_EPOCH="$DC_VALIDATED_EPOCH" C_ISO="$DC_VALIDATED" C_DATE="$DC_SERVER_DATE"
[[ -n "$4" ]] || return 0
serve_cached "$4" 304
}
# store <url> <dest>: put a read page in the cache and take its record.
store() {
G_VALIDATED="$G_AT" G_AGE=0
[[ $CACHE -eq 1 ]] || return 0
if dc_put "$1" "$G_FORMAT" "$2" "$G_CTYPE" "$G_TITLE_HINT" "$G_VALIDATORS" "$G_DATE"; then
G_AT="$DC_RETRIEVED" G_VALIDATED="$DC_VALIDATED" G_KEY="$DC_KEY" G_TITLE="$DC_TITLE" G_QUAR="$DC_QUARANTINED"
else
G_CACHE_ERR="${DC_ERR:-the store refused the write}"
echo "WARNING: $1 was read but not cached in $DC_DIR: $G_CACHE_ERR" >&2
fi
}
# fixture_read <dest> <fixture file> <format>: a read from the fixture directory.
fixture_read() {
G_SOURCE=fixture
if [[ -s "$FIXTURE/$2" ]] && cp "$FIXTURE/$2" "$1"; then
G_STATE=read G_FORMAT="$3"
G_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
else
G_REASON="fixture-missing"
fi
}
# get_doc <url> <dest> <fixture file> <content-type regex>: an indexed
# profile's read, the whole body or nothing. Sets the G_ fields; on read the raw
# bytes are at <dest>, otherwise no file is left there.
get_doc() {
local url="$1" dest="$2" ctype_re="$4"
reset_g
rm -f "$dest" "$dest.part"
mkdir -p "$(dirname "$dest")"
cache_candidate "$url" "$P_FORMAT"
if [[ -n "$C_REF" && $FIXTURE_SET -eq 0 && ! "$C_CTYPE_LC" =~ $ctype_re ]]; then C_REF=""; fi
serve_fresh "$dest" && return 0
if [[ $FIXTURE_SET -eq 1 ]]; then
fixture_read "$dest" "$3" "$P_FORMAT"
else
G_SOURCE=fetch
if [[ $CURL_MISSING -eq 1 ]]; then
G_REASON="curl-missing"
return 0
fi
G_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
request "" "$url" "$dest.part" "$dest" && return 0
G_STATUS="$H_STATUS" G_CTYPE="$H_CTYPE"
if [[ $H_RC -ne 0 ]]; then
G_REASON="$(failure_reason)"
elif [[ "$H_EFF" != "$ORIGIN$P_DOCS_PATH"* && ("$url" != "$INDEX_URL" || "$H_EFF" != "$INDEX_URL") ]]; then
# A page lands under the docs path; the index, at its own URL.
G_REASON="redirected-off-origin"
elif [[ ! "$H_STATUS" =~ ^2[0-9][0-9]$ ]]; then
G_REASON="http-${H_STATUS:-unknown}"
elif [[ ! "$H_CTYPE_LC" =~ $ctype_re ]]; then
G_REASON="unexpected-content-type"
elif [[ ! -s "$dest.part" ]]; then
G_REASON="empty-body"
elif mv "$dest.part" "$dest"; then
G_STATE=read G_FORMAT="$P_FORMAT" G_VALIDATORS="$(dc_validators_or_none "" "$url")" G_DATE="$H_DATE"
fi
rm -f "$dest.part"
fi
if [[ "$G_STATE" != read ]]; then
settle_unread "$url" "$dest" "$P_FORMAT"
return 0
fi
store "$url" "$dest"
}
# dc_validators_or_none <accept> <url>: the validators record of the last
# response, or nothing without --cache.
dc_validators_or_none() {
[[ $CACHE -eq 1 ]] || return 0
dc_validators "$1" "$2" "$H_ETAG" "$H_LM"
}
# url_parts <url>: set U_ORIGIN (scheme and host lower-cased) and U_PATH (the
# rest, fragment dropped, one trailing slash dropped); return 1 unless https.
url_parts() {
local u="${1%%#*}"
[[ "$u" =~ ^([Hh][Tt][Tt][Pp][Ss]://[^/?]+)(.*)$ ]] || return 1
U_PATH="${BASH_REMATCH[2]}" U_ORIGIN=""
dc_lower U_ORIGIN "${BASH_REMATCH[1]}"
[[ "$U_PATH" == "/" || "$U_PATH" != */ ]] || U_PATH="${U_PATH%/}"
[[ -n "$U_PATH" ]] || U_PATH="/"
}
# landed <requested> <effective>: same, off-origin or off-path.
landed() {
local o p
url_parts "$1" || return 1
o="$U_ORIGIN" p="$U_PATH"
url_parts "$2" || {
printf off-origin
return 0
}
if [[ "$U_ORIGIN" != "$o" ]]; then
printf off-origin
elif [[ "$U_PATH" != "$p" ]]; then
printf off-path
else
printf same
fi
}
# emit <slug> <url> <mode> <file>: print one manifest record from the G_ result.
emit() {
local sha="" bytes=0 lines=0 file=""
if [[ "$G_STATE" == read ]]; then
file="$4"
sha="$(sha256_of "$file")"
bytes="$(wc -c <"$file" | tr -d ' ')"
lines="$(awk 'END { print NR }' "$file")"
else
G_FORMAT="" G_TITLE="" G_QUAR="" G_DATE=""
fi
jq -cn --arg slug "$1" --arg url "$2" --arg mode "$3" --arg source "$G_SOURCE" --arg at "$G_AT" --arg sha "$sha" \
--arg status "$G_STATUS" --arg ctype "$G_CTYPE" --argjson bytes "$bytes" --argjson lines "$lines" --arg file "$file" \
--arg state "$G_STATE" --arg reason "$G_REASON" --arg validated "$G_VALIDATED" --arg age "$G_AGE" --arg key "$G_KEY" \
--arg format "$G_FORMAT" --arg title "$G_TITLE" --arg quar "$G_QUAR" --arg stale "$G_STALE" --arg sdate "$G_DATE" \
--arg cerr "$G_CACHE_ERR" \
'def n: if . == "" then null else . end;
{slug: $slug, url: ($url | n), mode: $mode, source: ($source | n), retrieved: ($at | n),
validated: ($validated | n), age_seconds: ($age | n | if . == null then null else tonumber end),
cache_key: ($key | n), sha256: ($sha | n),
status: ($status | if . == "" then null else tonumber end), content_type: ($ctype | n), bytes: $bytes,
lines: $lines, file: ($file | n), format: ($format | n), title: ($title | n),
quarantined: (if $quar == "" then null else $quar == "1" end), stale: ($stale == "1"),
server_date: ($sdate | n), cache_error: ($cerr | n), state: $state, reason: ($reason | n)}'
}
# link_urls <file>: every link URL in the file, one per line.
link_urls() {
awk '{
while (match($0, /\]\([^) \t]+\)/)) {
print substr($0, RSTART + 2, RLENGTH - 3)
$0 = substr($0, RSTART + RLENGTH)
}
}' "$1"
}
# index_link <slug>: the first link URL in the index whose path is exactly
# <docs-path>en/<slug><suffix> or <docs-path><slug><suffix>, on any scheme (or none) and host (an
# off-origin link is reported by the caller). A page nested under another path (plugins/x.md) is
# a different slug and never matches x.
index_link() {
link_urls "$OUT/llms.txt" | awk -v a="${P_DOCS_PATH}en/$1${P_SUFFIX}" -v b="${P_DOCS_PATH}$1${P_SUFFIX}" '{ p = $0; sub(/^([A-Za-z][A-Za-z0-9+.-]*:)?\/\/[^\/]+/, "", p) } p == a || p == b { print; exit }'
}
# slug_of <url>: the slug an index link names: its path under the profile path, without a
# leading en/ and the raw-channel suffix.
slug_of() {
local s="${1#"$ORIGIN$P_DOCS_PATH"}"
s="${s#en/}"
printf '%s' "${s%"$P_SUFFIX"}"
}
# A slug becomes a path under --out: lower-case segments joined by `/`, never
# `.`, `..` or a leading `/`. The C locale keeps `a-z` an ASCII range.
slug_ok() {
local LC_ALL=C re='^[a-z0-9_-]+(/[a-z0-9_-]+)*$'
[[ "$1" =~ $re ]]
}
# Bash 3.2 has no associative arrays: a map is two indexed arrays, <name>_K and
# <name>_V, searched in order. map_get <name> <key> [<var>]: set var to the
# value, 1 when absent; the caller names a local, so no call in between can
# overwrite it. map_put <name> <key> <value>: add a key the map does not hold.
map_get() {
local _mg_i _mg_n _mg_k
eval "_mg_n=\${#$1_K[@]}"
for ((_mg_i = 0; _mg_i < _mg_n; _mg_i++)); do
_mg_k="$1_K[$_mg_i]"
[[ "${!_mg_k}" == "$2" ]] || continue
_mg_k="$1_V[$_mg_i]"
[[ -z "${3:-}" ]] || printf -v "$3" '%s' "${!_mg_k}"
return 0
done
return 1
}
map_put() { eval "$1_K+=(\"\$2\") $1_V+=(\"\$3\")"; }
# shellcheck disable=SC2034 # read and written by name in map_get and map_put
SEEN_K=() SEEN_V=() BUNDLES_K=() BUNDLES_V=()
if [[ "$P_KIND" == url ]]; then
printf 'null\n' >"$INDEX_REC"
for ((i = 0; i < ${#TARGETS[@]}; i++)); do
t="${TARGETS[$i]}"
m="${TARGET_MODES[$i]}"
reset_g
if ! slug="$(generic_slug "$t")"; then
G_REASON="invalid-url"
emit "$t" "" "$m" "" >>"$PAGE_RECS"
continue
fi
if ! slug_ok "$slug"; then
G_REASON="invalid-slug"
emit "$t" "$t" "$m" "" >>"$PAGE_RECS"
continue
fi
if map_get SEEN "$slug" seen; then
[[ "$seen" != "${t%%#*}" ]] || continue
G_REASON="slug-collision"
emit "$slug" "$t" "$m" "" >>"$PAGE_RECS"
continue
fi
map_put SEEN "$slug" "${t%%#*}"
get_generic "$t" "$OUT/$slug.md" "$slug.md"
emit "$slug" "$t" "$m" "$OUT/$slug.md" >>"$PAGE_RECS"
done
else
# The index first: every page resolves through it.
get_doc "$INDEX_URL" "$OUT/llms.txt" llms.txt "$P_INDEX_CTYPE"
INDEX_STATE="$G_STATE"
emit index "$INDEX_URL" "" "$OUT/llms.txt" >"$INDEX_REC"
if [[ $DISCOVER -eq 1 && "$INDEX_STATE" == read ]]; then
while IFS= read -r u; do
[[ "$u" == "$ORIGIN$P_DOCS_PATH"*"$P_SUFFIX" ]] || continue
TARGETS+=("$u")
TARGET_MODES+=("$MODE")
done < <(link_urls "$OUT/llms.txt")
fi
for ((i = 0; i < ${#TARGETS[@]}; i++)); do
t="${TARGETS[$i]}"
m="${TARGET_MODES[$i]}"
want=""
slug="${t%"$P_SUFFIX"}"
if [[ "$t" == *://* ]]; then
# A browser-form URL, with no raw-channel suffix, a fragment, a query or a trailing
# slash, names the same page.
want="${t%%#*}"
want="${want%%\?*}"
want="${want%/}"
[[ "$want" == *"$P_SUFFIX" ]] || want="$want$P_SUFFIX"
slug="$(slug_of "$want")"
fi
! map_get SEEN "$slug" || continue
map_put SEEN "$slug" 1
reset_g
url=""
if ! slug_ok "$slug"; then
G_REASON="invalid-slug"
emit "$t" "$want" "$m" "" >>"$PAGE_RECS"
continue
fi
rm -f "$OUT/$slug.md"
if [[ "$INDEX_STATE" != read ]]; then
G_REASON="index-unread"
else
url="$(index_link "$slug")"
if [[ -z "$url" || (-n "$want" && "$url" != "$want") ]]; then
G_REASON="not-in-index"
# Only a slug the index has no link for is quarantined, never a URL it lists.
if [[ $CACHE -eq 1 && -z "$url" ]]; then
for u in "$want" "$ORIGIN${P_DOCS_PATH}en/$slug$P_SUFFIX" "$ORIGIN$P_DOCS_PATH$slug$P_SUFFIX"; do
[[ -z "$u" ]] || dc_quarantine_reason "$(dc_key "$u" "$P_FORMAT")" not-in-index
done
fi
url=""
elif [[ "$url" != "$ORIGIN$P_DOCS_PATH"* ]]; then
G_REASON="off-origin"
else
get_doc "$url" "$OUT/$slug.md" "$slug.md" "$P_PAGE_CTYPE"
fi
fi
emit "$slug" "$url" "$m" "$OUT/$slug.md" >>"$PAGE_RECS"
done
fi
claude_bin="${FETCH_DOCS_CLAUDE_BIN-$(command -v claude 2>/dev/null || true)}"
claude_version=""
if [[ -n "$claude_bin" && -f "$claude_bin" ]]; then
raw="$(with_timeout 30 "$claude_bin" --version 2>/dev/null </dev/null | head -n 1)"
[[ "$raw" =~ ([0-9]+\.[0-9]+\.[0-9]+) ]] && claude_version="${BASH_REMATCH[1]}"
fi
jq -n --arg v "$claude_version" --slurpfile idx "$INDEX_REC" --slurpfile pages "$PAGE_RECS" --arg cd "$CACHE_DISABLED" \
'{claude_version: $v, index: $idx[0], pages: $pages, cache_disabled: (if $cd == "" then null else $cd end)}' >"$MANIFEST.tmp" ||
die "could not write $MANIFEST"
mv "$MANIFEST.tmp" "$MANIFEST" || die "could not write $MANIFEST"