@kinloom/cli 0.1.1 → 0.3.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.
- package/dist/assets/cached-ocr.py +786 -0
- package/dist/assets/ocr.md +76 -0
- package/dist/assets/prep-scan.md +97 -0
- package/dist/assets/prep-scan.py +1313 -0
- package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
- package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
- package/dist/bundled-skills/archive-org/SKILL.md +162 -0
- package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
- package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
- package/dist/bundled-skills/california-archives/SKILL.md +130 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
- package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
- package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
- package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
- package/dist/bundled-skills/findagrave/SKILL.md +129 -0
- package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
- package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
- package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
- package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
- package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
- package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
- package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
- package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
- package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
- package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
- package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
- package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
- package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
- package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
- package/dist/bundled-skills/wikitree/SKILL.md +154 -0
- package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +488 -26
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +30 -5
- package/dist/client.js.map +1 -1
- package/dist/commands/ops/audit.d.ts +138 -0
- package/dist/commands/ops/audit.d.ts.map +1 -0
- package/dist/commands/ops/audit.js +872 -0
- package/dist/commands/ops/audit.js.map +1 -0
- package/dist/commands/ops/context.d.ts +100 -0
- package/dist/commands/ops/context.d.ts.map +1 -0
- package/dist/commands/ops/context.js +917 -0
- package/dist/commands/ops/context.js.map +1 -0
- package/dist/commands/ops/dates.d.ts +87 -0
- package/dist/commands/ops/dates.d.ts.map +1 -0
- package/dist/commands/ops/dates.js +228 -0
- package/dist/commands/ops/dates.js.map +1 -0
- package/dist/commands/ops/help.d.ts +8 -0
- package/dist/commands/ops/help.d.ts.map +1 -0
- package/dist/commands/ops/help.js +107 -0
- package/dist/commands/ops/help.js.map +1 -0
- package/dist/commands/ops/index.d.ts +8 -0
- package/dist/commands/ops/index.d.ts.map +1 -0
- package/dist/commands/ops/index.js +8 -0
- package/dist/commands/ops/index.js.map +1 -0
- package/dist/commands/ops/integrate.d.ts +61 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -0
- package/dist/commands/ops/integrate.js +1063 -0
- package/dist/commands/ops/integrate.js.map +1 -0
- package/dist/commands/ops/sync.d.ts +194 -0
- package/dist/commands/ops/sync.d.ts.map +1 -0
- package/dist/commands/ops/sync.js +1251 -0
- package/dist/commands/ops/sync.js.map +1 -0
- package/dist/commands/ops/telemetry.d.ts +79 -0
- package/dist/commands/ops/telemetry.d.ts.map +1 -0
- package/dist/commands/ops/telemetry.js +249 -0
- package/dist/commands/ops/telemetry.js.map +1 -0
- package/dist/commands/ops/verify.d.ts +76 -0
- package/dist/commands/ops/verify.d.ts.map +1 -0
- package/dist/commands/ops/verify.js +325 -0
- package/dist/commands/ops/verify.js.map +1 -0
- package/dist/commands/records/help.d.ts +18 -0
- package/dist/commands/records/help.d.ts.map +1 -0
- package/dist/commands/records/help.js +174 -0
- package/dist/commands/records/help.js.map +1 -0
- package/dist/commands/records/index.d.ts +5 -0
- package/dist/commands/records/index.d.ts.map +1 -0
- package/dist/commands/records/index.js +5 -0
- package/dist/commands/records/index.js.map +1 -0
- package/dist/commands/records/registry.d.ts +32 -0
- package/dist/commands/records/registry.d.ts.map +1 -0
- package/dist/commands/records/registry.js +227 -0
- package/dist/commands/records/registry.js.map +1 -0
- package/dist/commands/records/resolve.d.ts +14 -0
- package/dist/commands/records/resolve.d.ts.map +1 -0
- package/dist/commands/records/resolve.js +61 -0
- package/dist/commands/records/resolve.js.map +1 -0
- package/dist/commands/records/runner.d.ts +27 -0
- package/dist/commands/records/runner.d.ts.map +1 -0
- package/dist/commands/records/runner.js +255 -0
- package/dist/commands/records/runner.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,869 @@
|
|
|
1
|
+
#!/usr/bin/env -S uv run --script
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.11"
|
|
4
|
+
# dependencies = [
|
|
5
|
+
# "click>=8.1",
|
|
6
|
+
# "httpx>=0.27",
|
|
7
|
+
# ]
|
|
8
|
+
# ///
|
|
9
|
+
"""Search the New Jersey State Archives databases portal and the Monmouth
|
|
10
|
+
County OPRS 1875 census from the command line.
|
|
11
|
+
|
|
12
|
+
The NJ State Archives portal publishes no public API and no stable GET
|
|
13
|
+
search URL: it is ASP.NET WebForms. This CLI drives the real form flow over
|
|
14
|
+
plain HTTP: GET the portal index, POST a __doPostBack to open a database
|
|
15
|
+
search page, POST the search form, and parse the results grid. A browser
|
|
16
|
+
User-Agent is required (the portal returns 403 to a bare curl/httpx default
|
|
17
|
+
UA) and the ASP.NET session cookie must be carried across the requests.
|
|
18
|
+
|
|
19
|
+
Verified live 2026-11-24. See the skill for the full
|
|
20
|
+
verification log and the per-database field maps.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import difflib
|
|
26
|
+
import hashlib
|
|
27
|
+
import html as html_mod
|
|
28
|
+
import json
|
|
29
|
+
import math
|
|
30
|
+
import os
|
|
31
|
+
import re
|
|
32
|
+
import sys
|
|
33
|
+
import time
|
|
34
|
+
from contextlib import contextmanager
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import Any, Callable, Iterator
|
|
37
|
+
|
|
38
|
+
import click
|
|
39
|
+
import httpx
|
|
40
|
+
|
|
41
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
42
|
+
CACHE_SCHEMA = 1
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def cache_dir() -> Path:
|
|
46
|
+
override = os.environ.get("KINLOOM_NJ_ARCHIVES_CACHE_DIR")
|
|
47
|
+
if override:
|
|
48
|
+
return Path(override).expanduser()
|
|
49
|
+
return Path.home() / ".cache" / "kinloom-nj-archives"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
53
|
+
if cli_ttl is not None:
|
|
54
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
55
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
56
|
+
return float(cli_ttl)
|
|
57
|
+
raw = os.environ.get("KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS")
|
|
58
|
+
if raw is not None and raw.strip():
|
|
59
|
+
try:
|
|
60
|
+
parsed = float(raw.strip())
|
|
61
|
+
except ValueError as exc:
|
|
62
|
+
raise click.BadParameter(f"Invalid KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
63
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
64
|
+
raise click.BadParameter(
|
|
65
|
+
f"Invalid KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0).")
|
|
66
|
+
return parsed
|
|
67
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@contextmanager
|
|
71
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
72
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
73
|
+
try:
|
|
74
|
+
import fcntl
|
|
75
|
+
except ImportError:
|
|
76
|
+
yield
|
|
77
|
+
return
|
|
78
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
with open(lock_path, "a+b") as lock_file:
|
|
80
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
81
|
+
try:
|
|
82
|
+
yield
|
|
83
|
+
finally:
|
|
84
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
88
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
90
|
+
try:
|
|
91
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
92
|
+
os.replace(tmp, dest)
|
|
93
|
+
except Exception:
|
|
94
|
+
tmp.unlink(missing_ok=True)
|
|
95
|
+
raise
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
99
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
100
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
104
|
+
if not path.is_file():
|
|
105
|
+
return None
|
|
106
|
+
try:
|
|
107
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
108
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
109
|
+
return None
|
|
110
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
111
|
+
return None
|
|
112
|
+
fetched = entry.get("fetched_at")
|
|
113
|
+
if not isinstance(fetched, (int, float)):
|
|
114
|
+
return None
|
|
115
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
116
|
+
return None
|
|
117
|
+
result = entry.get("result")
|
|
118
|
+
return result if isinstance(result, dict) else None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def cached_call(kind: str, payload: dict, fetch: Callable[[], dict], *,
|
|
122
|
+
refresh: bool, ttl_hours: float) -> tuple[dict, bool]:
|
|
123
|
+
"""Return (result, cache_hit). Concurrent callers of one query serialize
|
|
124
|
+
on a per-key flock, so the second caller reads the first caller's file."""
|
|
125
|
+
key = cache_key(kind, payload)
|
|
126
|
+
root = cache_dir()
|
|
127
|
+
path = root / f"{key}.json"
|
|
128
|
+
if not refresh:
|
|
129
|
+
hit = read_cache(path, ttl_hours)
|
|
130
|
+
if hit is not None:
|
|
131
|
+
return hit, True
|
|
132
|
+
with file_lock(root / f"{key}.lock"):
|
|
133
|
+
if not refresh:
|
|
134
|
+
hit = read_cache(path, ttl_hours)
|
|
135
|
+
if hit is not None:
|
|
136
|
+
return hit, True
|
|
137
|
+
result = fetch()
|
|
138
|
+
atomic_write_json(path, {"schema": CACHE_SCHEMA, "fetched_at": time.time(),
|
|
139
|
+
"kind": kind, "query": payload, "result": result})
|
|
140
|
+
return result, False
|
|
141
|
+
|
|
142
|
+
PORTAL_BASE = "https://wwwdnet-dos.nj.gov/DOS_ArchivesDBPortal/"
|
|
143
|
+
PORTAL_INDEX = PORTAL_BASE + "index.aspx"
|
|
144
|
+
MONMOUTH_BASE = "https://oprs.co.monmouth.nj.us/oprs/Archives/"
|
|
145
|
+
MONMOUTH_SEARCH = MONMOUTH_BASE + "ASearch.aspx"
|
|
146
|
+
USER_AGENT = (
|
|
147
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
|
148
|
+
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
|
149
|
+
)
|
|
150
|
+
PREFIX = "ctl00$ContentPlaceHolder1$"
|
|
151
|
+
GRID_TARGET = "ctl00$ContentPlaceHolder1$GridView1"
|
|
152
|
+
# Registry of portal databases. `target` is the __doPostBack event target of
|
|
153
|
+
# the database row on the portal index page; `page` is the search form the
|
|
154
|
+
# postback lands on; `fields` maps CLI option names to the form field names
|
|
155
|
+
# (without the ctl00$ContentPlaceHolder1$ prefix). All verified live
|
|
156
|
+
# 2026-11-24 by navigating each row and reading its search form.
|
|
157
|
+
DATABASES = {
|
|
158
|
+
"land": {
|
|
159
|
+
"title": "Early Land Records, ca. 1650-1900s",
|
|
160
|
+
"page": "EarlyLandRecords.aspx",
|
|
161
|
+
"target": "ctl00$ContentPlaceHolder1$GridView3$ctl02$lbtnColonialMarriages",
|
|
162
|
+
"count": "75,685 land records, over 397,267 names (data entry ongoing)",
|
|
163
|
+
"fields": {"surname": "txtLN", "given": "txtFN", "role": "ddlToFrom",
|
|
164
|
+
"location": "txtLocation", "county": "ddlCounty",
|
|
165
|
+
"from_year": "EYear", "to_year": "LYear"},
|
|
166
|
+
"roles": ["Grantor", "Grantee", "Named", "Official"],
|
|
167
|
+
"notes": "First stop for colonial New Jersey landholdings. Most deeds after 1785 were recorded at the county level, not the State. Result rows link to scanned PDFs.",
|
|
168
|
+
},
|
|
169
|
+
"supreme-court": {
|
|
170
|
+
"title": "Supreme Court Case Files, 1704-1844",
|
|
171
|
+
"page": "SupremeCourt.aspx",
|
|
172
|
+
"target": "ctl00$ContentPlaceHolder1$GridView3$ctl03$lbtnColonialMarriages",
|
|
173
|
+
"count": "55,114 case files, over 234,709 names (data entry ongoing)",
|
|
174
|
+
"fields": {"surname": "txtLN", "given": "txtFN", "role": "ddlRoleList",
|
|
175
|
+
"case_type": "txtCaseType", "county": "ddlCountyList",
|
|
176
|
+
"from_year": "EYear", "to_year": "LYear", "case_number": "txtCN"},
|
|
177
|
+
"roles": ["Plaintiff", "Defendant", "Official", "Victim", "Other"],
|
|
178
|
+
},
|
|
179
|
+
"colonial-marriages": {
|
|
180
|
+
"title": "Colonial Marriage Bonds, ca. 1666-1799",
|
|
181
|
+
"page": "ColonialMarriages.aspx",
|
|
182
|
+
"target": "ctl00$ContentPlaceHolder1$GridView1$ctl02$lbtnColonialMarriages",
|
|
183
|
+
"count": "11,533 marriage bonds",
|
|
184
|
+
"fields": {"surname": "txtGRLN", "given": "txtGRFN",
|
|
185
|
+
"spouse_surname": "txtBRLN", "spouse_given": "txtBRFN",
|
|
186
|
+
"from_year": "txtEYear", "to_year": "txtLYear",
|
|
187
|
+
"location": "ddlLocationList"},
|
|
188
|
+
},
|
|
189
|
+
"marriages-1848-1900": {
|
|
190
|
+
"title": "Marriage Records, May 1848 - December 1900",
|
|
191
|
+
"page": "Marriage1867.aspx",
|
|
192
|
+
"target": "ctl00$ContentPlaceHolder1$GridView1$ctl03$lbtnColonialMarriages",
|
|
193
|
+
"count": "Approximately 492,000 marriage records",
|
|
194
|
+
"fields": {"surname": "txtGRLN", "given": "txtGRFN",
|
|
195
|
+
"spouse_surname": "txtBRLN", "spouse_given": "txtBRFN",
|
|
196
|
+
"from_year": "txtEYear", "to_year": "txtLYear",
|
|
197
|
+
"county": "ddlCountyList"},
|
|
198
|
+
},
|
|
199
|
+
"deaths-1848-1878": {
|
|
200
|
+
"title": "Death Records, May 1848 - May 1878",
|
|
201
|
+
"page": "DeathIndex1848.aspx",
|
|
202
|
+
"target": "ctl00$ContentPlaceHolder1$GridView1$ctl04$lbtnColonialMarriages",
|
|
203
|
+
"count": "Over 303,172 death records (data entry ongoing)",
|
|
204
|
+
"fields": {"surname": "txtLN", "given": "txtFN",
|
|
205
|
+
"from_year": "Year1", "to_year": "Year2",
|
|
206
|
+
"county": "ddlCountyList"},
|
|
207
|
+
},
|
|
208
|
+
"deaths-1878-1900": {
|
|
209
|
+
"title": "Death Records, June 1878 - December 1900",
|
|
210
|
+
"page": "DeathIndex.aspx",
|
|
211
|
+
"target": "ctl00$ContentPlaceHolder1$GridView1$ctl05$lbtnColonialMarriages",
|
|
212
|
+
"count": "628,584 death records (data entry complete)",
|
|
213
|
+
"fields": {"surname": "txtLN", "given": "txtFN",
|
|
214
|
+
"from_year": "Year1", "to_year": "Year2",
|
|
215
|
+
"county": "ddlCountyList"},
|
|
216
|
+
},
|
|
217
|
+
"name-changes": {
|
|
218
|
+
"title": "Legal Name Changes, 1847-1947",
|
|
219
|
+
"page": "NameChanges.aspx",
|
|
220
|
+
"target": "ctl00$ContentPlaceHolder1$GridView3$ctl04$lbtnColonialMarriages",
|
|
221
|
+
"count": "12,254 name changes, 46,010 names",
|
|
222
|
+
"fields": {"surname": "txtLN", "given": "txtFN"},
|
|
223
|
+
},
|
|
224
|
+
"census-1885": {
|
|
225
|
+
"title": "1885 State Census - Passaic County and Atlantic City",
|
|
226
|
+
"page": "Census1885.aspx",
|
|
227
|
+
"target": "ctl00$ContentPlaceHolder1$GridView3$ctl05$lbtnColonialMarriages",
|
|
228
|
+
"count": "69,302 names",
|
|
229
|
+
"fields": {"surname": "txtLN", "given": "txtFN", "location": "ddlLocation"},
|
|
230
|
+
},
|
|
231
|
+
"revwar-damage": {
|
|
232
|
+
"title": "Revolutionary War Damage Claims, 1776-1783",
|
|
233
|
+
"page": "RevWarDamages.aspx",
|
|
234
|
+
"target": "ctl00$ContentPlaceHolder1$GridView5$ctl02$lbtnColonialMarriages",
|
|
235
|
+
"count": "2,662 claims, 7,435 names",
|
|
236
|
+
"fields": {"surname": "txtLN", "given": "txtFN", "county": "ddlCounty",
|
|
237
|
+
"location": "ddlLocation", "from_year": "EYear",
|
|
238
|
+
"to_year": "LYear"},
|
|
239
|
+
},
|
|
240
|
+
"civilwar-service": {
|
|
241
|
+
"title": "Civil War Service Records, 1861-1865",
|
|
242
|
+
"page": "StrykerCivilWar.aspx",
|
|
243
|
+
"target": "ctl00$ContentPlaceHolder1$GridView5$ctl03$lbtnColonialMarriages",
|
|
244
|
+
"count": "82,471 names",
|
|
245
|
+
"fields": {"surname": "txtLN", "given": "txtFN"},
|
|
246
|
+
},
|
|
247
|
+
"civilwar-vouchers": {
|
|
248
|
+
"title": "Civil War Payment Vouchers, 1861-1865",
|
|
249
|
+
"page": "CivilWarVouchers.aspx",
|
|
250
|
+
"target": "ctl00$ContentPlaceHolder1$GridView5$ctl04$lbtnColonialMarriages",
|
|
251
|
+
"count": "15,770 vouchers, 114,212 names",
|
|
252
|
+
"fields": {"surname": "txtLN", "given": "txtFN"},
|
|
253
|
+
},
|
|
254
|
+
"wwi-deaths": {
|
|
255
|
+
"title": "World War I Deaths",
|
|
256
|
+
"page": "WWICards.aspx",
|
|
257
|
+
"target": "ctl00$ContentPlaceHolder1$GridView5$ctl05$lbtnColonialMarriages",
|
|
258
|
+
"count": "3,427 names (9,310 scanned images)",
|
|
259
|
+
"fields": {"surname": "txtLN", "given": "txtFN", "county": "ddlNJCounty"},
|
|
260
|
+
},
|
|
261
|
+
"natguard-photos": {
|
|
262
|
+
"title": "New Jersey National Guard Photographs",
|
|
263
|
+
"page": "natguard1.aspx",
|
|
264
|
+
"target": "ctl00$ContentPlaceHolder1$GridView5$ctl06$lbtnColonialMarriages",
|
|
265
|
+
"count": "1,316 images",
|
|
266
|
+
"fields": {"keyword": "txtSearch", "location": "txtLocation",
|
|
267
|
+
"from_year": "txtEYear", "to_year": "txtLYear"},
|
|
268
|
+
},
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
# Portal rows that lead to records-request (order) forms, not searchable
|
|
272
|
+
# result grids. `search` refuses these; `url` prints the form to open.
|
|
273
|
+
ORDER_ONLY = {
|
|
274
|
+
"births-1848-1925": ("Birth Record Search: May 1, 1848 - December 31, 1925",
|
|
275
|
+
"BirthRecordsRequest.aspx", "GridView2", "ctl02"),
|
|
276
|
+
"marriages-1848-1950": ("Marriage Record Search: May 1, 1848 - December 31, 1950",
|
|
277
|
+
"MarriageRecordsRequest.aspx", "GridView2", "ctl03"),
|
|
278
|
+
"deaths-1848-1950": ("Death Record Search: May 1, 1848 - December 31, 1950",
|
|
279
|
+
"DeathRecordsRequest.aspx", "GridView2", "ctl04"),
|
|
280
|
+
"county-clerks-marriages": ("County Clerks' Marriage Record Search",
|
|
281
|
+
"CountyMarriageRecordRequest.aspx", "GridView2", "ctl05"),
|
|
282
|
+
"probate": ("Probate Record Search, ca. 1660-1952",
|
|
283
|
+
"ProbateRecordRequest.aspx", "GridView4", "ctl02"),
|
|
284
|
+
"naturalization": ("County Naturalization Record Search",
|
|
285
|
+
"NaturalizationRecordRequest.aspx", "GridView4", "ctl03"),
|
|
286
|
+
"revwar-search": ("Revolutionary War Record Search",
|
|
287
|
+
"RevWarRecordRequest.aspx", "GridView6", "ctl02"),
|
|
288
|
+
"wwi-search": ("World War I Record Search",
|
|
289
|
+
"WorldWarIRecordRequest.aspx", "GridView6", "ctl03"),
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
MARRIAGE_DATABASES = {"colonial-marriages", "marriages-1848-1900"}
|
|
293
|
+
|
|
294
|
+
# Names agents actually typed (telemetry 2026-11-25) plus obvious variants.
|
|
295
|
+
DATABASE_ALIASES = {
|
|
296
|
+
"colonial-marriage": "colonial-marriages",
|
|
297
|
+
"marriages-colonial": "colonial-marriages",
|
|
298
|
+
"marriage-colonial": "colonial-marriages",
|
|
299
|
+
"colonial-marriage-bonds": "colonial-marriages",
|
|
300
|
+
"marriage-bonds": "colonial-marriages",
|
|
301
|
+
"marriages": "marriages-1848-1900",
|
|
302
|
+
"marriage": "marriages-1848-1900",
|
|
303
|
+
"marriages-1848": "marriages-1848-1900",
|
|
304
|
+
"deaths": "deaths-1878-1900",
|
|
305
|
+
"deaths-1848": "deaths-1848-1878",
|
|
306
|
+
"deaths-1878": "deaths-1878-1900",
|
|
307
|
+
"land-records": "land",
|
|
308
|
+
"early-land-records": "land",
|
|
309
|
+
"deeds": "land",
|
|
310
|
+
"supreme": "supreme-court",
|
|
311
|
+
"court": "supreme-court",
|
|
312
|
+
"name-change": "name-changes",
|
|
313
|
+
"census": "census-1885",
|
|
314
|
+
"revwar": "revwar-damage",
|
|
315
|
+
"revwar-damages": "revwar-damage",
|
|
316
|
+
"civilwar": "civilwar-service",
|
|
317
|
+
"wwi": "wwi-deaths",
|
|
318
|
+
"natguard": "natguard-photos",
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def resolve_database(name: str) -> str:
|
|
323
|
+
"""Map a typed database name to a registry key, or raise a helpful error."""
|
|
324
|
+
key = re.sub(r"[\s_]+", "-", name.strip().lower())
|
|
325
|
+
if key in DATABASES or key in ORDER_ONLY or key == "monmouth":
|
|
326
|
+
return key
|
|
327
|
+
if key in DATABASE_ALIASES:
|
|
328
|
+
return DATABASE_ALIASES[key]
|
|
329
|
+
known = [*DATABASES, *ORDER_ONLY, *DATABASE_ALIASES]
|
|
330
|
+
close = difflib.get_close_matches(key, known, n=3, cutoff=0.6)
|
|
331
|
+
hint = f" Did you mean: {', '.join(DATABASE_ALIASES.get(c, c) for c in close)}?" if close else ""
|
|
332
|
+
raise click.UsageError(
|
|
333
|
+
f"unknown database {name!r}.{hint} Valid: {', '.join(DATABASES)}. "
|
|
334
|
+
"Run `nj-archives databases` for the live list."
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
MONMOUTH_TOWNS = ["Atlantic", "Freehold", "Holmdel", "Howell", "Marlboro",
|
|
339
|
+
"Middletown", "Ocean", "Shrewsbury", "Upper Freehold", "Wall"]
|
|
340
|
+
MONMOUTH_CATEGORIES = ["Agriculture", "Commerce", "Manufactures", "Mining",
|
|
341
|
+
"Population", "Return of Births", "Return of Deaths"]
|
|
342
|
+
|
|
343
|
+
def clean(raw: str) -> str:
|
|
344
|
+
"""Strip tags, unescape entities, collapse whitespace."""
|
|
345
|
+
text = re.sub(r"<[^>]+>", " ", raw)
|
|
346
|
+
return " ".join(html_mod.unescape(text).split())
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def hidden_fields(page_html: str) -> dict[str, str]:
|
|
350
|
+
"""All ASP.NET hidden fields (__VIEWSTATE, __EVENTVALIDATION, ...)."""
|
|
351
|
+
fields: dict[str, str] = {}
|
|
352
|
+
for tag in re.findall(r"<input[^>]*type=\"hidden\"[^>]*>", page_html):
|
|
353
|
+
name = re.search(r'name="([^"]+)"', tag)
|
|
354
|
+
value = re.search(r'value="([^"]*)"', tag)
|
|
355
|
+
if name:
|
|
356
|
+
fields[name.group(1)] = html_mod.unescape(value.group(1)) if value else ""
|
|
357
|
+
return fields
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def form_action(page_html: str) -> str | None:
|
|
361
|
+
match = re.search(r"<form[^>]*action=\"([^\"]*)\"", page_html)
|
|
362
|
+
return html_mod.unescape(match.group(1)) if match else None
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def select_options(page_html: str, short_name: str) -> list[str]:
|
|
366
|
+
"""Option values of a <select> on a search page, by short field name."""
|
|
367
|
+
pattern = (
|
|
368
|
+
r"<select[^>]*name=\"" + re.escape(PREFIX + short_name) + r"\"[^>]*>(.*?)</select>"
|
|
369
|
+
)
|
|
370
|
+
match = re.search(pattern, page_html, re.S)
|
|
371
|
+
if not match:
|
|
372
|
+
return []
|
|
373
|
+
return [
|
|
374
|
+
html_mod.unescape(value)
|
|
375
|
+
for value, _label in re.findall(
|
|
376
|
+
r"<option[^>]*value=\"([^\"]*)\"[^>]*>([^<]*)", match.group(1)
|
|
377
|
+
)
|
|
378
|
+
]
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def parse_grid(page_html: str, table_hint: str) -> tuple[list[str], list[dict]]:
|
|
382
|
+
"""Parse an ASP.NET results grid into (headers, rows).
|
|
383
|
+
|
|
384
|
+
Each row is a dict keyed by header text plus a "links" list of
|
|
385
|
+
{"text", "href"} for anchors in the row (e.g. scanned-PDF links) and
|
|
386
|
+
for PopUpBig('/path.pdf') census-page links (Monmouth OPRS).
|
|
387
|
+
A single-cell 'No Records Found' grid yields ([], []). Pager rows
|
|
388
|
+
(a single cell of page numbers) are skipped. Header rows are <th>
|
|
389
|
+
rows, or, for grids like Monmouth's that use <td> headers, the first
|
|
390
|
+
row whose non-empty cells contain no digits.
|
|
391
|
+
"""
|
|
392
|
+
table = re.search(
|
|
393
|
+
r"<table[^>]*id=\"([^\"]*" + re.escape(table_hint) + r"[^\"]*)\"[^>]*>(.*?)</table>",
|
|
394
|
+
page_html,
|
|
395
|
+
re.S,
|
|
396
|
+
)
|
|
397
|
+
if not table:
|
|
398
|
+
return [], []
|
|
399
|
+
rows_html = re.findall(r"<tr[^>]*>(.*?)</tr>", table.group(2), re.S)
|
|
400
|
+
headers: list[str] = []
|
|
401
|
+
rows: list[dict] = []
|
|
402
|
+
for row_html in rows_html:
|
|
403
|
+
cells = re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", row_html, re.S)
|
|
404
|
+
texts = [clean(cell) for cell in cells]
|
|
405
|
+
if not texts or all(text == "" for text in texts):
|
|
406
|
+
continue
|
|
407
|
+
if len(texts) == 1 and texts[0] == "No Records Found":
|
|
408
|
+
return [], []
|
|
409
|
+
if len(texts) == 1 and re.fullmatch(r"[\d\s.]+", texts[0]):
|
|
410
|
+
continue # pager row ("1 2 3 4 5 6")
|
|
411
|
+
if (
|
|
412
|
+
"Page$" in row_html
|
|
413
|
+
and all(re.fullmatch(r"(?:\d+|\.{2,3})", t) for t in texts if t)
|
|
414
|
+
):
|
|
415
|
+
continue # multi-cell ASP.NET GridView pager row
|
|
416
|
+
links = [
|
|
417
|
+
{"text": clean(label), "href": html_mod.unescape(href)}
|
|
418
|
+
for href, label in re.findall(
|
|
419
|
+
r"<a[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>", row_html, re.S
|
|
420
|
+
)
|
|
421
|
+
]
|
|
422
|
+
for pdf_path in re.findall(r"PopUpBig\('([^&]+?)'\)", row_html):
|
|
423
|
+
href = pdf_path if pdf_path.startswith("http") else "https://oprs.co.monmouth.nj.us" + pdf_path
|
|
424
|
+
links.append({"text": "census page image", "href": href})
|
|
425
|
+
is_header = bool(re.search(r"<th", row_html)) or (
|
|
426
|
+
not headers
|
|
427
|
+
and all(not re.search(r"\d", text) for text in texts if text)
|
|
428
|
+
)
|
|
429
|
+
if is_header:
|
|
430
|
+
headers = texts
|
|
431
|
+
continue
|
|
432
|
+
if not headers:
|
|
433
|
+
headers = [f"col{i + 1}" for i in range(len(texts))]
|
|
434
|
+
row = {headers[i]: texts[i] for i in range(min(len(headers), len(texts)))}
|
|
435
|
+
row["links"] = links
|
|
436
|
+
rows.append(row)
|
|
437
|
+
return headers, rows
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def capped_notice(page_html: str) -> bool:
|
|
441
|
+
return "Results are limited to 500 records per search" in clean(page_html)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def has_page_link(page_html: str, page_num: int, grid_target: str = GRID_TARGET) -> bool:
|
|
445
|
+
"""Return True if the ASP.NET GridView rendered a postback link for page_num."""
|
|
446
|
+
pattern = (
|
|
447
|
+
r"__doPostBack\((?:'|')"
|
|
448
|
+
+ re.escape(grid_target)
|
|
449
|
+
+ r"(?:'|'),\s*(?:'|')Page\$"
|
|
450
|
+
+ str(page_num)
|
|
451
|
+
+ r"(?:'|')\)"
|
|
452
|
+
)
|
|
453
|
+
return bool(re.search(pattern, page_html))
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def match_option_value(value: str, options: list[str]) -> str | None:
|
|
457
|
+
"""Match a CLI option against ASP.NET <select> options (exact, case-insensitive, or County suffix)."""
|
|
458
|
+
if value in options:
|
|
459
|
+
return value
|
|
460
|
+
norm = value.strip().lower()
|
|
461
|
+
for opt in options:
|
|
462
|
+
if opt.strip().lower() == norm:
|
|
463
|
+
return opt
|
|
464
|
+
stripped = re.sub(r"\s+county$", "", norm)
|
|
465
|
+
for opt in options:
|
|
466
|
+
opt_norm = re.sub(r"\s+county$", "", opt.strip().lower())
|
|
467
|
+
if opt_norm and opt_norm == stripped:
|
|
468
|
+
return opt
|
|
469
|
+
return None
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
RETRYABLE_HTTP_STATUSES = {500, 502, 503, 504}
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
class Portal:
|
|
476
|
+
"""One cookie-carrying session against the NJ State Archives portal."""
|
|
477
|
+
|
|
478
|
+
def __init__(self, *, timeout: float = 25.0, client: httpx.Client | None = None) -> None:
|
|
479
|
+
self._timeout = timeout
|
|
480
|
+
self._external_client = client is not None
|
|
481
|
+
self.client = client or self._make_client()
|
|
482
|
+
|
|
483
|
+
def _make_client(self) -> httpx.Client:
|
|
484
|
+
return httpx.Client(
|
|
485
|
+
headers={"User-Agent": USER_AGENT},
|
|
486
|
+
follow_redirects=True,
|
|
487
|
+
timeout=self._timeout,
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
def _reset_session(self) -> None:
|
|
491
|
+
if not self._external_client:
|
|
492
|
+
self.client.close()
|
|
493
|
+
self.client = self._make_client()
|
|
494
|
+
|
|
495
|
+
def __enter__(self) -> "Portal":
|
|
496
|
+
return self
|
|
497
|
+
|
|
498
|
+
def __exit__(self, *exc: object) -> None:
|
|
499
|
+
if not self._external_client:
|
|
500
|
+
self.client.close()
|
|
501
|
+
|
|
502
|
+
def _get(self, url: str) -> str:
|
|
503
|
+
response = self.client.get(url)
|
|
504
|
+
response.raise_for_status()
|
|
505
|
+
return response.text
|
|
506
|
+
|
|
507
|
+
def _post(self, url: str, data: dict[str, str]) -> str:
|
|
508
|
+
response = self.client.post(url, data=data)
|
|
509
|
+
response.raise_for_status()
|
|
510
|
+
return response.text
|
|
511
|
+
|
|
512
|
+
def list_databases(self) -> list[dict[str, str]]:
|
|
513
|
+
"""Database rows live from the portal index, keyed where known."""
|
|
514
|
+
page = self._get(PORTAL_INDEX)
|
|
515
|
+
by_target = {spec["target"]: key for key, spec in DATABASES.items()}
|
|
516
|
+
found: list[dict[str, str]] = []
|
|
517
|
+
for grid in re.finditer(
|
|
518
|
+
r"<table[^>]*id=\"([^\"]*GridView\d+[^\"]*)\"[^>]*>(.*?)</table>", page, re.S
|
|
519
|
+
):
|
|
520
|
+
for row in re.findall(r"<tr[^>]*>(.*?)</tr>", grid.group(2), re.S):
|
|
521
|
+
target = re.search(r"__doPostBack\('([^&]+?)'", row)
|
|
522
|
+
if not target:
|
|
523
|
+
continue
|
|
524
|
+
cells = [clean(c) for c in re.findall(r"<td[^>]*>(.*?)</td>", row, re.S)]
|
|
525
|
+
found.append({
|
|
526
|
+
"key": by_target.get(target.group(1), ""),
|
|
527
|
+
"title": cells[0] if cells else "",
|
|
528
|
+
"count": cells[1] if len(cells) > 1 else "",
|
|
529
|
+
})
|
|
530
|
+
return found
|
|
531
|
+
|
|
532
|
+
def open_search_page(self, key: str) -> tuple[str, str]:
|
|
533
|
+
"""POST the database row's __doPostBack; return (page_url, html)."""
|
|
534
|
+
spec = DATABASES[key]
|
|
535
|
+
index = self._get(PORTAL_INDEX)
|
|
536
|
+
data = {
|
|
537
|
+
**hidden_fields(index),
|
|
538
|
+
"__EVENTTARGET": spec["target"],
|
|
539
|
+
"__EVENTARGUMENT": "",
|
|
540
|
+
}
|
|
541
|
+
page_html = self._post(PORTAL_INDEX, data)
|
|
542
|
+
action = form_action(page_html) or spec["page"]
|
|
543
|
+
return PORTAL_BASE + action.lstrip("./"), page_html
|
|
544
|
+
|
|
545
|
+
def _search_once(self, key: str, criteria: dict[str, str | None], pages: int) -> dict:
|
|
546
|
+
spec = DATABASES[key]
|
|
547
|
+
page_url, page_html = self.open_search_page(key)
|
|
548
|
+
resolved = self._validate(criteria, spec, page_html)
|
|
549
|
+
data: dict[str, str] = {
|
|
550
|
+
**hidden_fields(page_html),
|
|
551
|
+
"__EVENTTARGET": "",
|
|
552
|
+
"__EVENTARGUMENT": "",
|
|
553
|
+
}
|
|
554
|
+
for option, value in resolved.items():
|
|
555
|
+
if value is not None and option in spec["fields"]:
|
|
556
|
+
data[PREFIX + spec["fields"][option]] = value
|
|
557
|
+
data[PREFIX + SUBMIT_BUTTON.get(key, "Search")] = "Search"
|
|
558
|
+
result_html = self._post(page_url, data)
|
|
559
|
+
headers, rows = parse_grid(result_html, "GridView1")
|
|
560
|
+
capped = capped_notice(result_html)
|
|
561
|
+
seen_pages = 1
|
|
562
|
+
while seen_pages < pages and rows:
|
|
563
|
+
next_page = seen_pages + 1
|
|
564
|
+
if not has_page_link(result_html, next_page):
|
|
565
|
+
break
|
|
566
|
+
page_html = result_html
|
|
567
|
+
data = {
|
|
568
|
+
**hidden_fields(page_html),
|
|
569
|
+
"__EVENTTARGET": GRID_TARGET,
|
|
570
|
+
"__EVENTARGUMENT": f"Page${next_page}",
|
|
571
|
+
}
|
|
572
|
+
result_html = self._post(page_url, data)
|
|
573
|
+
_h, more = parse_grid(result_html, "GridView1")
|
|
574
|
+
if not more:
|
|
575
|
+
break
|
|
576
|
+
rows.extend(more)
|
|
577
|
+
seen_pages += 1
|
|
578
|
+
return {"database": key, "title": spec["title"], "headers": headers,
|
|
579
|
+
"rows": rows, "capped_500": capped, "pages_read": seen_pages}
|
|
580
|
+
|
|
581
|
+
def search(self, key: str, criteria: dict[str, str | None], pages: int = 1) -> dict:
|
|
582
|
+
"""Run a search and optionally page through GridView1 results (1 retry on transient 5xx/network error)."""
|
|
583
|
+
for attempt in range(2):
|
|
584
|
+
try:
|
|
585
|
+
return self._search_once(key, criteria, pages=pages)
|
|
586
|
+
except httpx.HTTPStatusError as exc:
|
|
587
|
+
if exc.response.status_code in RETRYABLE_HTTP_STATUSES and attempt == 0:
|
|
588
|
+
time.sleep(0.5)
|
|
589
|
+
self._reset_session()
|
|
590
|
+
continue
|
|
591
|
+
raise
|
|
592
|
+
except (httpx.TimeoutException, httpx.RemoteProtocolError, httpx.ConnectError):
|
|
593
|
+
if attempt == 0:
|
|
594
|
+
time.sleep(0.5)
|
|
595
|
+
self._reset_session()
|
|
596
|
+
continue
|
|
597
|
+
raise
|
|
598
|
+
raise RuntimeError("unreachable")
|
|
599
|
+
|
|
600
|
+
@staticmethod
|
|
601
|
+
def _validate(criteria: dict[str, str | None], spec: dict, page_html: str) -> dict[str, str | None]:
|
|
602
|
+
resolved = dict(criteria)
|
|
603
|
+
for option, value in criteria.items():
|
|
604
|
+
if value is None or option not in spec["fields"]:
|
|
605
|
+
continue
|
|
606
|
+
short = spec["fields"][option]
|
|
607
|
+
options = select_options(page_html, short)
|
|
608
|
+
if options:
|
|
609
|
+
matched = match_option_value(value, options)
|
|
610
|
+
if matched is None:
|
|
611
|
+
raise click.UsageError(
|
|
612
|
+
f"--{option.replace('_', '-')} {value!r} is not a valid choice for "
|
|
613
|
+
f"{spec['title']}; valid: {', '.join(o for o in options if o)}"
|
|
614
|
+
)
|
|
615
|
+
resolved[option] = matched
|
|
616
|
+
roles = spec.get("roles")
|
|
617
|
+
role = resolved.get("role")
|
|
618
|
+
if roles and role is not None:
|
|
619
|
+
matched_role = match_option_value(role, roles)
|
|
620
|
+
if matched_role is None:
|
|
621
|
+
raise click.UsageError(
|
|
622
|
+
f"--role {role!r} is not valid here; valid: {', '.join(roles)}"
|
|
623
|
+
)
|
|
624
|
+
resolved["role"] = matched_role
|
|
625
|
+
return resolved
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def monmouth_search(surname: str, town: str, category: str, match: str,
|
|
629
|
+
limit: int | None) -> dict:
|
|
630
|
+
"""Search the Monmouth County OPRS 1875 census (page 1 only; its pager
|
|
631
|
+
postback was not verified, so --pages is not offered here)."""
|
|
632
|
+
with httpx.Client(headers={"User-Agent": USER_AGENT},
|
|
633
|
+
follow_redirects=True, timeout=60.0) as client:
|
|
634
|
+
page_html = client.get(MONMOUTH_SEARCH).text
|
|
635
|
+
data = {
|
|
636
|
+
**hidden_fields(page_html),
|
|
637
|
+
"__EVENTTARGET": "",
|
|
638
|
+
"__EVENTARGUMENT": "",
|
|
639
|
+
PREFIX + "ddlTown": town,
|
|
640
|
+
PREFIX + "ddlCat": category,
|
|
641
|
+
PREFIX + "txtName": surname,
|
|
642
|
+
PREFIX + "Search": "radContains" if match == "contains" else "radStarts",
|
|
643
|
+
PREFIX + "btnSearch": "Search",
|
|
644
|
+
}
|
|
645
|
+
result_html = client.post(MONMOUTH_SEARCH, data=data).text
|
|
646
|
+
headers, rows = parse_grid(result_html, "dgdArcSearch")
|
|
647
|
+
if limit is not None:
|
|
648
|
+
rows = rows[:limit]
|
|
649
|
+
return {"database": "monmouth-1875-census", "headers": headers,
|
|
650
|
+
"rows": rows, "pages_read": 1}
|
|
651
|
+
|
|
652
|
+
SUBMIT_BUTTON = {"natguard-photos": "btnSearch"}
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def emit(result: dict, as_json: bool, limit: int | None = None) -> None:
|
|
656
|
+
total = len(result["rows"])
|
|
657
|
+
rows = result["rows"]
|
|
658
|
+
if limit is not None:
|
|
659
|
+
rows = rows[:limit]
|
|
660
|
+
if as_json:
|
|
661
|
+
click.echo(json.dumps({**result, "rows": rows}, indent=2))
|
|
662
|
+
return
|
|
663
|
+
title = result.get("title") or result["database"]
|
|
664
|
+
if not rows:
|
|
665
|
+
click.echo(f"{title}: no records found.")
|
|
666
|
+
return
|
|
667
|
+
click.echo(f"{title}: {len(rows)} result(s)" +
|
|
668
|
+
(" [cache]" if result.get("cache_hit") else "") +
|
|
669
|
+
(" (search capped at 500 records; narrow the criteria)"
|
|
670
|
+
if result.get("capped_500") and total >= 500 else "") +
|
|
671
|
+
(f" (pages read: {result.get('pages_read')})"
|
|
672
|
+
if result.get("pages_read", 1) > 1 else ""))
|
|
673
|
+
headers = [h for h in result["headers"] if h != "Select"]
|
|
674
|
+
for i, row in enumerate(rows, 1):
|
|
675
|
+
cells = [row.get(h, "") for h in headers if row.get(h, "")]
|
|
676
|
+
click.echo(f"{i}. " + " | ".join(cells))
|
|
677
|
+
for link in row.get("links", []):
|
|
678
|
+
if link["href"].lower().endswith(".pdf"):
|
|
679
|
+
click.echo(f" PDF: {link['href']}")
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
@click.group()
|
|
683
|
+
def cli() -> None:
|
|
684
|
+
"""Search New Jersey State Archives databases and the Monmouth County
|
|
685
|
+
OPRS 1875 census."""
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
@cli.command("databases")
|
|
689
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
690
|
+
def databases_cmd(as_json: bool) -> None:
|
|
691
|
+
"""List the searchable databases on the NJ State Archives portal."""
|
|
692
|
+
with Portal() as portal:
|
|
693
|
+
live = portal.list_databases()
|
|
694
|
+
if as_json:
|
|
695
|
+
click.echo(json.dumps(live, indent=2))
|
|
696
|
+
return
|
|
697
|
+
for entry in live:
|
|
698
|
+
key = f" [{entry['key']}]" if entry["key"] else ""
|
|
699
|
+
count = f" -- {entry['count']}" if entry["count"] else ""
|
|
700
|
+
click.echo(f"{entry['title']}{key}{count}")
|
|
701
|
+
click.echo("\nOrder-form only (no online search; use `nj-archives url <key>`):")
|
|
702
|
+
for key, (title, _page, _grid, _ctl) in ORDER_ONLY.items():
|
|
703
|
+
click.echo(f" {title} [{key}]")
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
@cli.command("search")
|
|
707
|
+
@click.argument("database")
|
|
708
|
+
@click.option("--surname", "--last", "--last-name", "surname", default=None,
|
|
709
|
+
help="Surname to search. Marriage databases accept --spouse-surname alone; "
|
|
710
|
+
"natguard-photos uses --keyword.")
|
|
711
|
+
@click.option("--given", "--first", "--first-name", "given", default=None, help="Given name.")
|
|
712
|
+
@click.option("--spouse-surname", "--spouse", "--bride-surname", "spouse_surname", default=None,
|
|
713
|
+
help="Spouse surname (marriage databases).")
|
|
714
|
+
@click.option("--spouse-given", "--bride-given", "spouse_given", default=None,
|
|
715
|
+
help="Spouse given name (marriage databases).")
|
|
716
|
+
@click.option("--county", default=None, help="County filter.")
|
|
717
|
+
@click.option("--location", default=None, help="Location filter.")
|
|
718
|
+
@click.option("--from-year", "--start-year", "from_year", type=int, default=None, help="Earliest year.")
|
|
719
|
+
@click.option("--to-year", "--end-year", "to_year", type=int, default=None, help="Latest year.")
|
|
720
|
+
@click.option("--role", default=None, help="Role, e.g. Grantee (land) or Defendant (supreme-court).")
|
|
721
|
+
@click.option("--case-type", default=None, help="Case type (supreme-court).")
|
|
722
|
+
@click.option("--case-number", default=None, help="Case number (supreme-court).")
|
|
723
|
+
@click.option("--keyword", default=None, help="Keyword (natguard-photos).")
|
|
724
|
+
@click.option("--limit", type=int, default=None, help="Max rows to show.")
|
|
725
|
+
@click.option("--pages", type=int, default=1, show_default=True,
|
|
726
|
+
help="Result pages to read (stops cleanly if fewer pages exist).")
|
|
727
|
+
@click.option("--refresh", is_flag=True, help="Bypass the disk cache and re-query the portal.")
|
|
728
|
+
@click.option("--cache-ttl-hours", type=float, default=None,
|
|
729
|
+
help=f"Cache TTL in hours (default {DEFAULT_CACHE_TTL_HOURS:g}; "
|
|
730
|
+
"env KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS).")
|
|
731
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
732
|
+
def search_cmd(database: str, surname: str | None, given: str | None,
|
|
733
|
+
spouse_surname: str | None, spouse_given: str | None,
|
|
734
|
+
county: str | None, location: str | None,
|
|
735
|
+
from_year: int | None, to_year: int | None,
|
|
736
|
+
role: str | None, case_type: str | None,
|
|
737
|
+
case_number: str | None, keyword: str | None,
|
|
738
|
+
limit: int | None, pages: int, refresh: bool,
|
|
739
|
+
cache_ttl_hours: float | None, as_json: bool) -> None:
|
|
740
|
+
"""Search one portal database, e.g. `nj-archives search land --surname Lincoln`.
|
|
741
|
+
|
|
742
|
+
Results are cached on disk (~/.cache/kinloom-nj-archives, 168 h TTL).
|
|
743
|
+
"""
|
|
744
|
+
database = resolve_database(database)
|
|
745
|
+
if database == "monmouth":
|
|
746
|
+
raise click.UsageError("Monmouth 1875 census is its own command: "
|
|
747
|
+
"`nj-archives monmouth --surname <name>`.")
|
|
748
|
+
if database in ORDER_ONLY:
|
|
749
|
+
title, page, _grid, _ctl = ORDER_ONLY[database]
|
|
750
|
+
raise click.UsageError(
|
|
751
|
+
f"{title} has no online search; it is a records-request (order) form. "
|
|
752
|
+
f"Open it in a browser: {PORTAL_BASE}{page}"
|
|
753
|
+
)
|
|
754
|
+
if database == "natguard-photos":
|
|
755
|
+
if not keyword and not surname:
|
|
756
|
+
raise click.UsageError("natguard-photos requires --keyword (or --surname as keyword).")
|
|
757
|
+
if not keyword and surname:
|
|
758
|
+
keyword = surname
|
|
759
|
+
elif not surname:
|
|
760
|
+
if not (database in MARRIAGE_DATABASES and spouse_surname):
|
|
761
|
+
raise click.UsageError(
|
|
762
|
+
"Missing option '--surname'"
|
|
763
|
+
+ (" (or --spouse-surname for marriage databases)." if database in MARRIAGE_DATABASES
|
|
764
|
+
else ".")
|
|
765
|
+
)
|
|
766
|
+
criteria = {
|
|
767
|
+
"surname": surname, "given": given,
|
|
768
|
+
"spouse_surname": spouse_surname, "spouse_given": spouse_given,
|
|
769
|
+
"county": county, "location": location,
|
|
770
|
+
"from_year": str(from_year) if from_year is not None else None,
|
|
771
|
+
"to_year": str(to_year) if to_year is not None else None,
|
|
772
|
+
"role": role, "case_type": case_type, "case_number": case_number,
|
|
773
|
+
"keyword": keyword,
|
|
774
|
+
}
|
|
775
|
+
pages = max(1, pages)
|
|
776
|
+
|
|
777
|
+
def fetch() -> dict:
|
|
778
|
+
with Portal() as portal:
|
|
779
|
+
return portal.search(database, criteria, pages=pages)
|
|
780
|
+
|
|
781
|
+
try:
|
|
782
|
+
result, cache_hit = cached_call(
|
|
783
|
+
"search", {"database": database, "criteria": criteria, "pages": pages}, fetch,
|
|
784
|
+
refresh=refresh, ttl_hours=resolve_ttl_hours(cache_ttl_hours))
|
|
785
|
+
except httpx.HTTPStatusError as exc:
|
|
786
|
+
raise click.ClickException(
|
|
787
|
+
f"portal returned HTTP {exc.response.status_code} for {database} after one retry; "
|
|
788
|
+
"the portal may be briefly down. Retry later or drop --pages/--from-year filters."
|
|
789
|
+
) from exc
|
|
790
|
+
except httpx.TimeoutException as exc:
|
|
791
|
+
raise click.ClickException(
|
|
792
|
+
f"portal request timed out for {database}: {exc}"
|
|
793
|
+
) from exc
|
|
794
|
+
except httpx.HTTPError as exc:
|
|
795
|
+
raise click.ClickException(
|
|
796
|
+
f"portal request failed for {database}: {exc}"
|
|
797
|
+
) from exc
|
|
798
|
+
emit({**result, "cache_hit": cache_hit}, as_json, limit)
|
|
799
|
+
|
|
800
|
+
@cli.command("monmouth")
|
|
801
|
+
@click.option("--surname", "--last", "--name", "surname", required=True, help="Person name to search.")
|
|
802
|
+
@click.option("--town", default="ALL", show_default=True,
|
|
803
|
+
help="Town, or ALL. Choices: " + ", ".join(MONMOUTH_TOWNS))
|
|
804
|
+
@click.option("--category", default="ALL", show_default=True,
|
|
805
|
+
help="Category, or ALL. Choices: " + ", ".join(MONMOUTH_CATEGORIES))
|
|
806
|
+
@click.option("--match", type=click.Choice(["starts", "contains"]),
|
|
807
|
+
default="contains", show_default=True)
|
|
808
|
+
@click.option("--limit", type=int, default=None, help="Max rows to show.")
|
|
809
|
+
@click.option("--refresh", is_flag=True, help="Bypass the disk cache and re-query Monmouth OPRS.")
|
|
810
|
+
@click.option("--cache-ttl-hours", type=float, default=None, help="Cache TTL in hours (default 168).")
|
|
811
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
812
|
+
def monmouth_cmd(surname: str, town: str, category: str, match: str,
|
|
813
|
+
limit: int | None, refresh: bool, cache_ttl_hours: float | None,
|
|
814
|
+
as_json: bool) -> None:
|
|
815
|
+
"""Search the Monmouth County OPRS 1875 census by person name."""
|
|
816
|
+
town_match = match_option_value(town, ["ALL", *MONMOUTH_TOWNS])
|
|
817
|
+
if town_match is None:
|
|
818
|
+
raise click.UsageError(
|
|
819
|
+
f"--town {town!r} is not valid; valid: ALL, " + ", ".join(MONMOUTH_TOWNS)
|
|
820
|
+
)
|
|
821
|
+
category_match = match_option_value(category, ["ALL", *MONMOUTH_CATEGORIES])
|
|
822
|
+
if category_match is None:
|
|
823
|
+
raise click.UsageError(
|
|
824
|
+
f"--category {category!r} is not valid; valid: ALL, "
|
|
825
|
+
+ ", ".join(MONMOUTH_CATEGORIES)
|
|
826
|
+
)
|
|
827
|
+
try:
|
|
828
|
+
result, cache_hit = cached_call(
|
|
829
|
+
"monmouth", {"surname": surname, "town": town_match, "category": category_match,
|
|
830
|
+
"match": match},
|
|
831
|
+
lambda: monmouth_search(surname, town_match, category_match, match, None),
|
|
832
|
+
refresh=refresh, ttl_hours=resolve_ttl_hours(cache_ttl_hours))
|
|
833
|
+
except httpx.HTTPStatusError as exc:
|
|
834
|
+
raise click.ClickException(
|
|
835
|
+
f"Monmouth OPRS returned HTTP {exc.response.status_code}; "
|
|
836
|
+
"the site may be down or blocking automated access"
|
|
837
|
+
) from exc
|
|
838
|
+
except httpx.HTTPError as exc:
|
|
839
|
+
raise click.ClickException(f"Monmouth OPRS request failed: {exc}") from exc
|
|
840
|
+
emit({**result, "cache_hit": cache_hit}, as_json, limit)
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
@cli.command("url")
|
|
844
|
+
@click.argument("database", required=False, default=None)
|
|
845
|
+
def url_cmd(database: str | None) -> None:
|
|
846
|
+
"""Print the browser URL for the portal, a database, or Monmouth OPRS."""
|
|
847
|
+
if database is None:
|
|
848
|
+
click.echo(f"Portal index: {PORTAL_INDEX}")
|
|
849
|
+
click.echo(f"Monmouth County OPRS 1875 census: {MONMOUTH_SEARCH}")
|
|
850
|
+
return
|
|
851
|
+
database = resolve_database(database)
|
|
852
|
+
if database == "monmouth":
|
|
853
|
+
click.echo(MONMOUTH_SEARCH)
|
|
854
|
+
return
|
|
855
|
+
if database in DATABASES:
|
|
856
|
+
click.echo(PORTAL_BASE + DATABASES[database]["page"])
|
|
857
|
+
return
|
|
858
|
+
if database in ORDER_ONLY:
|
|
859
|
+
title, page, _grid, _ctl = ORDER_ONLY[database]
|
|
860
|
+
click.echo(f"{title} (records-request form, no online search):")
|
|
861
|
+
click.echo(PORTAL_BASE + page)
|
|
862
|
+
return
|
|
863
|
+
raise click.UsageError(
|
|
864
|
+
f"unknown database {database!r}; run `nj-archives databases` for the list"
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
if __name__ == "__main__":
|
|
869
|
+
cli()
|