@kinloom/cli 0.1.1 → 0.2.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.
Files changed (101) hide show
  1. package/dist/assets/cached-ocr.py +556 -0
  2. package/dist/assets/ocr.md +52 -0
  3. package/dist/assets/prep-scan.md +59 -0
  4. package/dist/assets/prep-scan.py +891 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +94 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +268 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +129 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +879 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +120 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +373 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +100 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +250 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +116 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +520 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +110 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +194 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +123 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +358 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +111 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +346 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +100 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +528 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +118 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +934 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +118 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +585 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +90 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +432 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +93 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +441 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +101 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +391 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +89 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +254 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +104 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +466 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +148 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +219 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +383 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.js +1 -1
  49. package/dist/commands/ops/audit.d.ts +138 -0
  50. package/dist/commands/ops/audit.d.ts.map +1 -0
  51. package/dist/commands/ops/audit.js +867 -0
  52. package/dist/commands/ops/audit.js.map +1 -0
  53. package/dist/commands/ops/context.d.ts +100 -0
  54. package/dist/commands/ops/context.d.ts.map +1 -0
  55. package/dist/commands/ops/context.js +917 -0
  56. package/dist/commands/ops/context.js.map +1 -0
  57. package/dist/commands/ops/help.d.ts +6 -0
  58. package/dist/commands/ops/help.d.ts.map +1 -0
  59. package/dist/commands/ops/help.js +74 -0
  60. package/dist/commands/ops/help.js.map +1 -0
  61. package/dist/commands/ops/index.d.ts +6 -0
  62. package/dist/commands/ops/index.d.ts.map +1 -0
  63. package/dist/commands/ops/index.js +6 -0
  64. package/dist/commands/ops/index.js.map +1 -0
  65. package/dist/commands/ops/integrate.d.ts +56 -0
  66. package/dist/commands/ops/integrate.d.ts.map +1 -0
  67. package/dist/commands/ops/integrate.js +872 -0
  68. package/dist/commands/ops/integrate.js.map +1 -0
  69. package/dist/commands/ops/sync.d.ts +177 -0
  70. package/dist/commands/ops/sync.d.ts.map +1 -0
  71. package/dist/commands/ops/sync.js +1078 -0
  72. package/dist/commands/ops/sync.js.map +1 -0
  73. package/dist/commands/ops/telemetry.d.ts +79 -0
  74. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  75. package/dist/commands/ops/telemetry.js +249 -0
  76. package/dist/commands/ops/telemetry.js.map +1 -0
  77. package/dist/commands/records/help.d.ts +18 -0
  78. package/dist/commands/records/help.d.ts.map +1 -0
  79. package/dist/commands/records/help.js +174 -0
  80. package/dist/commands/records/help.js.map +1 -0
  81. package/dist/commands/records/index.d.ts +5 -0
  82. package/dist/commands/records/index.d.ts.map +1 -0
  83. package/dist/commands/records/index.js +5 -0
  84. package/dist/commands/records/index.js.map +1 -0
  85. package/dist/commands/records/registry.d.ts +32 -0
  86. package/dist/commands/records/registry.d.ts.map +1 -0
  87. package/dist/commands/records/registry.js +227 -0
  88. package/dist/commands/records/registry.js.map +1 -0
  89. package/dist/commands/records/resolve.d.ts +14 -0
  90. package/dist/commands/records/resolve.d.ts.map +1 -0
  91. package/dist/commands/records/resolve.js +61 -0
  92. package/dist/commands/records/resolve.js.map +1 -0
  93. package/dist/commands/records/runner.d.ts +25 -0
  94. package/dist/commands/records/runner.d.ts.map +1 -0
  95. package/dist/commands/records/runner.js +224 -0
  96. package/dist/commands/records/runner.js.map +1 -0
  97. package/dist/index.d.ts +2 -0
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +2 -0
  100. package/dist/index.js.map +1 -1
  101. package/package.json +3 -3
@@ -0,0 +1,585 @@
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 html as html_mod
26
+ import json
27
+ import re
28
+ import sys
29
+
30
+ import click
31
+ import httpx
32
+
33
+ PORTAL_BASE = "https://wwwdnet-dos.nj.gov/DOS_ArchivesDBPortal/"
34
+ PORTAL_INDEX = PORTAL_BASE + "index.aspx"
35
+ MONMOUTH_BASE = "https://oprs.co.monmouth.nj.us/oprs/Archives/"
36
+ MONMOUTH_SEARCH = MONMOUTH_BASE + "ASearch.aspx"
37
+ USER_AGENT = (
38
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
39
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
40
+ )
41
+ PREFIX = "ctl00$ContentPlaceHolder1$"
42
+ GRID_TARGET = "ctl00$ContentPlaceHolder1$GridView1"
43
+ # Registry of portal databases. `target` is the __doPostBack event target of
44
+ # the database row on the portal index page; `page` is the search form the
45
+ # postback lands on; `fields` maps CLI option names to the form field names
46
+ # (without the ctl00$ContentPlaceHolder1$ prefix). All verified live
47
+ # 2026-11-24 by navigating each row and reading its search form.
48
+ DATABASES = {
49
+ "land": {
50
+ "title": "Early Land Records, ca. 1650-1900s",
51
+ "page": "EarlyLandRecords.aspx",
52
+ "target": "ctl00$ContentPlaceHolder1$GridView3$ctl02$lbtnColonialMarriages",
53
+ "count": "75,685 land records, over 397,267 names (data entry ongoing)",
54
+ "fields": {"surname": "txtLN", "given": "txtFN", "role": "ddlToFrom",
55
+ "location": "txtLocation", "county": "ddlCounty",
56
+ "from_year": "EYear", "to_year": "LYear"},
57
+ "roles": ["Grantor", "Grantee", "Named", "Official"],
58
+ "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.",
59
+ },
60
+ "supreme-court": {
61
+ "title": "Supreme Court Case Files, 1704-1844",
62
+ "page": "SupremeCourt.aspx",
63
+ "target": "ctl00$ContentPlaceHolder1$GridView3$ctl03$lbtnColonialMarriages",
64
+ "count": "55,114 case files, over 234,709 names (data entry ongoing)",
65
+ "fields": {"surname": "txtLN", "given": "txtFN", "role": "ddlRoleList",
66
+ "case_type": "txtCaseType", "county": "ddlCountyList",
67
+ "from_year": "EYear", "to_year": "LYear", "case_number": "txtCN"},
68
+ "roles": ["Plaintiff", "Defendant", "Official", "Victim", "Other"],
69
+ },
70
+ "colonial-marriages": {
71
+ "title": "Colonial Marriage Bonds, ca. 1666-1799",
72
+ "page": "ColonialMarriages.aspx",
73
+ "target": "ctl00$ContentPlaceHolder1$GridView1$ctl02$lbtnColonialMarriages",
74
+ "count": "11,533 marriage bonds",
75
+ "fields": {"surname": "txtGRLN", "given": "txtGRFN",
76
+ "spouse_surname": "txtBRLN", "spouse_given": "txtBRFN",
77
+ "from_year": "txtEYear", "to_year": "txtLYear",
78
+ "location": "ddlLocationList"},
79
+ },
80
+ "marriages-1848-1900": {
81
+ "title": "Marriage Records, May 1848 - December 1900",
82
+ "page": "Marriage1867.aspx",
83
+ "target": "ctl00$ContentPlaceHolder1$GridView1$ctl03$lbtnColonialMarriages",
84
+ "count": "Approximately 492,000 marriage records",
85
+ "fields": {"surname": "txtGRLN", "given": "txtGRFN",
86
+ "spouse_surname": "txtBRLN", "spouse_given": "txtBRFN",
87
+ "from_year": "txtEYear", "to_year": "txtLYear",
88
+ "county": "ddlCountyList"},
89
+ },
90
+ "deaths-1848-1878": {
91
+ "title": "Death Records, May 1848 - May 1878",
92
+ "page": "DeathIndex1848.aspx",
93
+ "target": "ctl00$ContentPlaceHolder1$GridView1$ctl04$lbtnColonialMarriages",
94
+ "count": "Over 303,172 death records (data entry ongoing)",
95
+ "fields": {"surname": "txtLN", "given": "txtFN",
96
+ "from_year": "Year1", "to_year": "Year2",
97
+ "county": "ddlCountyList"},
98
+ },
99
+ "deaths-1878-1900": {
100
+ "title": "Death Records, June 1878 - December 1900",
101
+ "page": "DeathIndex.aspx",
102
+ "target": "ctl00$ContentPlaceHolder1$GridView1$ctl05$lbtnColonialMarriages",
103
+ "count": "628,584 death records (data entry complete)",
104
+ "fields": {"surname": "txtLN", "given": "txtFN",
105
+ "from_year": "Year1", "to_year": "Year2",
106
+ "county": "ddlCountyList"},
107
+ },
108
+ "name-changes": {
109
+ "title": "Legal Name Changes, 1847-1947",
110
+ "page": "NameChanges.aspx",
111
+ "target": "ctl00$ContentPlaceHolder1$GridView3$ctl04$lbtnColonialMarriages",
112
+ "count": "12,254 name changes, 46,010 names",
113
+ "fields": {"surname": "txtLN", "given": "txtFN"},
114
+ },
115
+ "census-1885": {
116
+ "title": "1885 State Census - Passaic County and Atlantic City",
117
+ "page": "Census1885.aspx",
118
+ "target": "ctl00$ContentPlaceHolder1$GridView3$ctl05$lbtnColonialMarriages",
119
+ "count": "69,302 names",
120
+ "fields": {"surname": "txtLN", "given": "txtFN", "location": "ddlLocation"},
121
+ },
122
+ "revwar-damage": {
123
+ "title": "Revolutionary War Damage Claims, 1776-1783",
124
+ "page": "RevWarDamages.aspx",
125
+ "target": "ctl00$ContentPlaceHolder1$GridView5$ctl02$lbtnColonialMarriages",
126
+ "count": "2,662 claims, 7,435 names",
127
+ "fields": {"surname": "txtLN", "given": "txtFN", "county": "ddlCounty",
128
+ "location": "ddlLocation", "from_year": "EYear",
129
+ "to_year": "LYear"},
130
+ },
131
+ "civilwar-service": {
132
+ "title": "Civil War Service Records, 1861-1865",
133
+ "page": "StrykerCivilWar.aspx",
134
+ "target": "ctl00$ContentPlaceHolder1$GridView5$ctl03$lbtnColonialMarriages",
135
+ "count": "82,471 names",
136
+ "fields": {"surname": "txtLN", "given": "txtFN"},
137
+ },
138
+ "civilwar-vouchers": {
139
+ "title": "Civil War Payment Vouchers, 1861-1865",
140
+ "page": "CivilWarVouchers.aspx",
141
+ "target": "ctl00$ContentPlaceHolder1$GridView5$ctl04$lbtnColonialMarriages",
142
+ "count": "15,770 vouchers, 114,212 names",
143
+ "fields": {"surname": "txtLN", "given": "txtFN"},
144
+ },
145
+ "wwi-deaths": {
146
+ "title": "World War I Deaths",
147
+ "page": "WWICards.aspx",
148
+ "target": "ctl00$ContentPlaceHolder1$GridView5$ctl05$lbtnColonialMarriages",
149
+ "count": "3,427 names (9,310 scanned images)",
150
+ "fields": {"surname": "txtLN", "given": "txtFN", "county": "ddlNJCounty"},
151
+ },
152
+ "natguard-photos": {
153
+ "title": "New Jersey National Guard Photographs",
154
+ "page": "natguard1.aspx",
155
+ "target": "ctl00$ContentPlaceHolder1$GridView5$ctl06$lbtnColonialMarriages",
156
+ "count": "1,316 images",
157
+ "fields": {"keyword": "txtSearch", "location": "txtLocation",
158
+ "from_year": "txtEYear", "to_year": "txtLYear"},
159
+ },
160
+ }
161
+
162
+ # Portal rows that lead to records-request (order) forms, not searchable
163
+ # result grids. `search` refuses these; `url` prints the form to open.
164
+ ORDER_ONLY = {
165
+ "births-1848-1925": ("Birth Record Search: May 1, 1848 - December 31, 1925",
166
+ "BirthRecordsRequest.aspx", "GridView2", "ctl02"),
167
+ "marriages-1848-1950": ("Marriage Record Search: May 1, 1848 - December 31, 1950",
168
+ "MarriageRecordsRequest.aspx", "GridView2", "ctl03"),
169
+ "deaths-1848-1950": ("Death Record Search: May 1, 1848 - December 31, 1950",
170
+ "DeathRecordsRequest.aspx", "GridView2", "ctl04"),
171
+ "county-clerks-marriages": ("County Clerks' Marriage Record Search",
172
+ "CountyMarriageRecordRequest.aspx", "GridView2", "ctl05"),
173
+ "probate": ("Probate Record Search, ca. 1660-1952",
174
+ "ProbateRecordRequest.aspx", "GridView4", "ctl02"),
175
+ "naturalization": ("County Naturalization Record Search",
176
+ "NaturalizationRecordRequest.aspx", "GridView4", "ctl03"),
177
+ "revwar-search": ("Revolutionary War Record Search",
178
+ "RevWarRecordRequest.aspx", "GridView6", "ctl02"),
179
+ "wwi-search": ("World War I Record Search",
180
+ "WorldWarIRecordRequest.aspx", "GridView6", "ctl03"),
181
+ }
182
+
183
+ MONMOUTH_TOWNS = ["Atlantic", "Freehold", "Holmdel", "Howell", "Marlboro",
184
+ "Middletown", "Ocean", "Shrewsbury", "Upper Freehold", "Wall"]
185
+ MONMOUTH_CATEGORIES = ["Agriculture", "Commerce", "Manufactures", "Mining",
186
+ "Population", "Return of Births", "Return of Deaths"]
187
+
188
+ def clean(raw: str) -> str:
189
+ """Strip tags, unescape entities, collapse whitespace."""
190
+ text = re.sub(r"<[^>]+>", " ", raw)
191
+ return " ".join(html_mod.unescape(text).split())
192
+
193
+
194
+ def hidden_fields(page_html: str) -> dict[str, str]:
195
+ """All ASP.NET hidden fields (__VIEWSTATE, __EVENTVALIDATION, ...)."""
196
+ fields: dict[str, str] = {}
197
+ for tag in re.findall(r"<input[^>]*type=\"hidden\"[^>]*>", page_html):
198
+ name = re.search(r'name="([^"]+)"', tag)
199
+ value = re.search(r'value="([^"]*)"', tag)
200
+ if name:
201
+ fields[name.group(1)] = html_mod.unescape(value.group(1)) if value else ""
202
+ return fields
203
+
204
+
205
+ def form_action(page_html: str) -> str | None:
206
+ match = re.search(r"<form[^>]*action=\"([^\"]*)\"", page_html)
207
+ return html_mod.unescape(match.group(1)) if match else None
208
+
209
+
210
+ def select_options(page_html: str, short_name: str) -> list[str]:
211
+ """Option values of a <select> on a search page, by short field name."""
212
+ pattern = (
213
+ r"<select[^>]*name=\"" + re.escape(PREFIX + short_name) + r"\"[^>]*>(.*?)</select>"
214
+ )
215
+ match = re.search(pattern, page_html, re.S)
216
+ if not match:
217
+ return []
218
+ return [
219
+ html_mod.unescape(value)
220
+ for value, _label in re.findall(
221
+ r"<option[^>]*value=\"([^\"]*)\"[^>]*>([^<]*)", match.group(1)
222
+ )
223
+ ]
224
+
225
+
226
+ def parse_grid(page_html: str, table_hint: str) -> tuple[list[str], list[dict]]:
227
+ """Parse an ASP.NET results grid into (headers, rows).
228
+
229
+ Each row is a dict keyed by header text plus a "links" list of
230
+ {"text", "href"} for anchors in the row (e.g. scanned-PDF links) and
231
+ for PopUpBig('/path.pdf') census-page links (Monmouth OPRS).
232
+ A single-cell 'No Records Found' grid yields ([], []). Pager rows
233
+ (a single cell of page numbers) are skipped. Header rows are <th>
234
+ rows, or, for grids like Monmouth's that use <td> headers, the first
235
+ row whose non-empty cells contain no digits.
236
+ """
237
+ table = re.search(
238
+ r"<table[^>]*id=\"([^\"]*" + re.escape(table_hint) + r"[^\"]*)\"[^>]*>(.*?)</table>",
239
+ page_html,
240
+ re.S,
241
+ )
242
+ if not table:
243
+ return [], []
244
+ rows_html = re.findall(r"<tr[^>]*>(.*?)</tr>", table.group(2), re.S)
245
+ headers: list[str] = []
246
+ rows: list[dict] = []
247
+ for row_html in rows_html:
248
+ cells = re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", row_html, re.S)
249
+ texts = [clean(cell) for cell in cells]
250
+ if not texts or all(text == "" for text in texts):
251
+ continue
252
+ if len(texts) == 1 and texts[0] == "No Records Found":
253
+ return [], []
254
+ if len(texts) == 1 and re.fullmatch(r"[\d\s]+", texts[0]):
255
+ continue # pager row ("1 2 3 4 5 6")
256
+ links = [
257
+ {"text": clean(label), "href": html_mod.unescape(href)}
258
+ for href, label in re.findall(
259
+ r"<a[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>", row_html, re.S
260
+ )
261
+ ]
262
+ for pdf_path in re.findall(r"PopUpBig\(&#39;([^&]+?)&#39;\)", row_html):
263
+ href = pdf_path if pdf_path.startswith("http") else "https://oprs.co.monmouth.nj.us" + pdf_path
264
+ links.append({"text": "census page image", "href": href})
265
+ is_header = bool(re.search(r"<th", row_html)) or (
266
+ not headers
267
+ and all(not re.search(r"\d", text) for text in texts if text)
268
+ )
269
+ if is_header:
270
+ headers = texts
271
+ continue
272
+ if not headers:
273
+ headers = [f"col{i + 1}" for i in range(len(texts))]
274
+ row = {headers[i]: texts[i] for i in range(min(len(headers), len(texts)))}
275
+ row["links"] = links
276
+ rows.append(row)
277
+ return headers, rows
278
+
279
+
280
+ def capped_notice(page_html: str) -> bool:
281
+ return "Results are limited to 500 records per search" in clean(page_html)
282
+
283
+ class Portal:
284
+ """One cookie-carrying session against the NJ State Archives portal."""
285
+
286
+ def __init__(self) -> None:
287
+ self.client = httpx.Client(
288
+ headers={"User-Agent": USER_AGENT},
289
+ follow_redirects=True,
290
+ timeout=60.0,
291
+ )
292
+
293
+ def __enter__(self) -> "Portal":
294
+ return self
295
+
296
+ def __exit__(self, *exc: object) -> None:
297
+ self.client.close()
298
+
299
+ def _get(self, url: str) -> str:
300
+ response = self.client.get(url)
301
+ response.raise_for_status()
302
+ return response.text
303
+
304
+ def _post(self, url: str, data: dict[str, str]) -> str:
305
+ response = self.client.post(url, data=data)
306
+ response.raise_for_status()
307
+ return response.text
308
+
309
+ def list_databases(self) -> list[dict[str, str]]:
310
+ """Database rows live from the portal index, keyed where known."""
311
+ page = self._get(PORTAL_INDEX)
312
+ by_target = {spec["target"]: key for key, spec in DATABASES.items()}
313
+ found: list[dict[str, str]] = []
314
+ for grid in re.finditer(
315
+ r"<table[^>]*id=\"([^\"]*GridView\d+[^\"]*)\"[^>]*>(.*?)</table>", page, re.S
316
+ ):
317
+ for row in re.findall(r"<tr[^>]*>(.*?)</tr>", grid.group(2), re.S):
318
+ target = re.search(r"__doPostBack\(&#39;([^&]+?)&#39;", row)
319
+ if not target:
320
+ continue
321
+ cells = [clean(c) for c in re.findall(r"<td[^>]*>(.*?)</td>", row, re.S)]
322
+ found.append({
323
+ "key": by_target.get(target.group(1), ""),
324
+ "title": cells[0] if cells else "",
325
+ "count": cells[1] if len(cells) > 1 else "",
326
+ })
327
+ return found
328
+
329
+ def open_search_page(self, key: str) -> tuple[str, str]:
330
+ """POST the database row's __doPostBack; return (page_url, html)."""
331
+ spec = DATABASES[key]
332
+ index = self._get(PORTAL_INDEX)
333
+ data = {
334
+ **hidden_fields(index),
335
+ "__EVENTTARGET": spec["target"],
336
+ "__EVENTARGUMENT": "",
337
+ }
338
+ page_html = self._post(PORTAL_INDEX, data)
339
+ action = form_action(page_html) or spec["page"]
340
+ return PORTAL_BASE + action.lstrip("./"), page_html
341
+
342
+ def search(self, key: str, criteria: dict[str, str | None], pages: int = 1) -> dict:
343
+ """Run a search and optionally page through GridView1 results."""
344
+ spec = DATABASES[key]
345
+ page_url, page_html = self.open_search_page(key)
346
+ self._validate(criteria, spec, page_html)
347
+ data: dict[str, str] = {
348
+ **hidden_fields(page_html),
349
+ "__EVENTTARGET": "",
350
+ "__EVENTARGUMENT": "",
351
+ }
352
+ for option, value in criteria.items():
353
+ if value is not None and option in spec["fields"]:
354
+ data[PREFIX + spec["fields"][option]] = value
355
+ data[PREFIX + SUBMIT_BUTTON.get(key, "Search")] = "Search"
356
+ result_html = self._post(page_url, data)
357
+ headers, rows = parse_grid(result_html, "GridView1")
358
+ capped = capped_notice(result_html)
359
+ seen_pages = 1
360
+ while seen_pages < pages and rows:
361
+ page_html = result_html
362
+ data = {
363
+ **hidden_fields(page_html),
364
+ "__EVENTTARGET": GRID_TARGET,
365
+ "__EVENTARGUMENT": f"Page${seen_pages + 1}",
366
+ }
367
+ result_html = self._post(page_url, data)
368
+ _h, more = parse_grid(result_html, "GridView1")
369
+ if not more:
370
+ break
371
+ rows.extend(more)
372
+ seen_pages += 1
373
+ return {"database": key, "title": spec["title"], "headers": headers,
374
+ "rows": rows, "capped_500": capped, "pages_read": seen_pages}
375
+
376
+ @staticmethod
377
+ def _validate(criteria: dict[str, str | None], spec: dict, page_html: str) -> None:
378
+ for option, value in criteria.items():
379
+ if value is None or option not in spec["fields"]:
380
+ continue
381
+ short = spec["fields"][option]
382
+ options = select_options(page_html, short)
383
+ if options and value not in options:
384
+ raise click.UsageError(
385
+ f"--{option.replace('_', '-')} {value!r} is not a valid choice for "
386
+ f"{spec['title']}; valid: {', '.join(o for o in options if o)}"
387
+ )
388
+ roles = spec.get("roles")
389
+ role = criteria.get("role")
390
+ if roles and role is not None and role not in roles:
391
+ raise click.UsageError(
392
+ f"--role {role!r} is not valid here; valid: {', '.join(roles)}"
393
+ )
394
+
395
+
396
+ def monmouth_search(surname: str, town: str, category: str, match: str,
397
+ limit: int | None) -> dict:
398
+ """Search the Monmouth County OPRS 1875 census (page 1 only; its pager
399
+ postback was not verified, so --pages is not offered here)."""
400
+ with httpx.Client(headers={"User-Agent": USER_AGENT},
401
+ follow_redirects=True, timeout=60.0) as client:
402
+ page_html = client.get(MONMOUTH_SEARCH).text
403
+ data = {
404
+ **hidden_fields(page_html),
405
+ "__EVENTTARGET": "",
406
+ "__EVENTARGUMENT": "",
407
+ PREFIX + "ddlTown": town,
408
+ PREFIX + "ddlCat": category,
409
+ PREFIX + "txtName": surname,
410
+ PREFIX + "Search": "radContains" if match == "contains" else "radStarts",
411
+ PREFIX + "btnSearch": "Search",
412
+ }
413
+ result_html = client.post(MONMOUTH_SEARCH, data=data).text
414
+ headers, rows = parse_grid(result_html, "dgdArcSearch")
415
+ if limit is not None:
416
+ rows = rows[:limit]
417
+ return {"database": "monmouth-1875-census", "headers": headers,
418
+ "rows": rows, "pages_read": 1}
419
+
420
+ SUBMIT_BUTTON = {"natguard-photos": "btnSearch"}
421
+
422
+
423
+ def emit(result: dict, as_json: bool, limit: int | None = None) -> None:
424
+ total = len(result["rows"])
425
+ rows = result["rows"]
426
+ if limit is not None:
427
+ rows = rows[:limit]
428
+ if as_json:
429
+ click.echo(json.dumps({**result, "rows": rows}, indent=2))
430
+ return
431
+ title = result.get("title") or result["database"]
432
+ if not rows:
433
+ click.echo(f"{title}: no records found.")
434
+ return
435
+ click.echo(f"{title}: {len(rows)} result(s)" +
436
+ (" (search capped at 500 records; narrow the criteria)"
437
+ if result.get("capped_500") and total >= 500 else "") +
438
+ (f" (pages read: {result.get('pages_read')})"
439
+ if result.get("pages_read", 1) > 1 else ""))
440
+ headers = [h for h in result["headers"] if h != "Select"]
441
+ for i, row in enumerate(rows, 1):
442
+ cells = [row.get(h, "") for h in headers if row.get(h, "")]
443
+ click.echo(f"{i}. " + " | ".join(cells))
444
+ for link in row.get("links", []):
445
+ if link["href"].lower().endswith(".pdf"):
446
+ click.echo(f" PDF: {link['href']}")
447
+
448
+
449
+ @click.group()
450
+ def cli() -> None:
451
+ """Search New Jersey State Archives databases and the Monmouth County
452
+ OPRS 1875 census."""
453
+
454
+
455
+ @cli.command("databases")
456
+ @click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
457
+ def databases_cmd(as_json: bool) -> None:
458
+ """List the searchable databases on the NJ State Archives portal."""
459
+ with Portal() as portal:
460
+ live = portal.list_databases()
461
+ if as_json:
462
+ click.echo(json.dumps(live, indent=2))
463
+ return
464
+ for entry in live:
465
+ key = f" [{entry['key']}]" if entry["key"] else ""
466
+ count = f" -- {entry['count']}" if entry["count"] else ""
467
+ click.echo(f"{entry['title']}{key}{count}")
468
+ click.echo("\nOrder-form only (no online search; use `nj-archives url <key>`):")
469
+ for key, (title, _page, _grid, _ctl) in ORDER_ONLY.items():
470
+ click.echo(f" {title} [{key}]")
471
+
472
+
473
+ @cli.command("search")
474
+ @click.argument("database")
475
+ @click.option("--surname", required=True, help="Surname to search.")
476
+ @click.option("--given", default=None, help="Given name.")
477
+ @click.option("--spouse-surname", default=None, help="Spouse surname (marriage databases).")
478
+ @click.option("--spouse-given", default=None, help="Spouse given name (marriage databases).")
479
+ @click.option("--county", default=None, help="County filter.")
480
+ @click.option("--location", default=None, help="Location filter.")
481
+ @click.option("--from-year", type=int, default=None, help="Earliest year.")
482
+ @click.option("--to-year", type=int, default=None, help="Latest year.")
483
+ @click.option("--role", default=None, help="Role, e.g. Grantee (land) or Defendant (supreme-court).")
484
+ @click.option("--case-type", default=None, help="Case type (supreme-court).")
485
+ @click.option("--case-number", default=None, help="Case number (supreme-court).")
486
+ @click.option("--keyword", default=None, help="Keyword (natguard-photos).")
487
+ @click.option("--limit", type=int, default=None, help="Max rows to show.")
488
+ @click.option("--pages", type=int, default=1, show_default=True,
489
+ help="Result pages to read (10 rows per page).")
490
+ @click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
491
+ def search_cmd(database: str, surname: str, given: str | None,
492
+ spouse_surname: str | None, spouse_given: str | None,
493
+ county: str | None, location: str | None,
494
+ from_year: int | None, to_year: int | None,
495
+ role: str | None, case_type: str | None,
496
+ case_number: str | None, keyword: str | None,
497
+ limit: int | None, pages: int, as_json: bool) -> None:
498
+ """Search one portal database, e.g. `nj-archives search land --surname Lincoln`."""
499
+ if database in ORDER_ONLY:
500
+ title, page, _grid, _ctl = ORDER_ONLY[database]
501
+ raise click.UsageError(
502
+ f"{title} has no online search; it is a records-request (order) form. "
503
+ f"Open it in a browser: {PORTAL_BASE}{page}"
504
+ )
505
+ if database not in DATABASES:
506
+ raise click.UsageError(
507
+ f"unknown database {database!r}; run `nj-archives databases` for the list"
508
+ )
509
+ criteria = {
510
+ "surname": surname, "given": given,
511
+ "spouse_surname": spouse_surname, "spouse_given": spouse_given,
512
+ "county": county, "location": location,
513
+ "from_year": str(from_year) if from_year is not None else None,
514
+ "to_year": str(to_year) if to_year is not None else None,
515
+ "role": role, "case_type": case_type, "case_number": case_number,
516
+ "keyword": keyword,
517
+ }
518
+ try:
519
+ with Portal() as portal:
520
+ result = portal.search(database, criteria, pages=max(1, pages))
521
+ except httpx.HTTPStatusError as exc:
522
+ raise click.ClickException(
523
+ f"portal returned HTTP {exc.response.status_code} for {database}; "
524
+ "the portal may be down or blocking automated access"
525
+ ) from exc
526
+ emit(result, as_json, limit)
527
+
528
+ @cli.command("monmouth")
529
+ @click.option("--surname", required=True, help="Person name to search.")
530
+ @click.option("--town", default="ALL", show_default=True,
531
+ help="Town, or ALL. Choices: " + ", ".join(MONMOUTH_TOWNS))
532
+ @click.option("--category", default="ALL", show_default=True,
533
+ help="Category, or ALL. Choices: " + ", ".join(MONMOUTH_CATEGORIES))
534
+ @click.option("--match", type=click.Choice(["starts", "contains"]),
535
+ default="contains", show_default=True)
536
+ @click.option("--limit", type=int, default=None, help="Max rows to show.")
537
+ @click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
538
+ def monmouth_cmd(surname: str, town: str, category: str, match: str,
539
+ limit: int | None, as_json: bool) -> None:
540
+ """Search the Monmouth County OPRS 1875 census by person name."""
541
+ if town != "ALL" and town not in MONMOUTH_TOWNS:
542
+ raise click.UsageError(
543
+ f"--town {town!r} is not valid; valid: ALL, " + ", ".join(MONMOUTH_TOWNS)
544
+ )
545
+ if category != "ALL" and category not in MONMOUTH_CATEGORIES:
546
+ raise click.UsageError(
547
+ f"--category {category!r} is not valid; valid: ALL, "
548
+ + ", ".join(MONMOUTH_CATEGORIES)
549
+ )
550
+ try:
551
+ result = monmouth_search(surname, town, category, match, limit)
552
+ except httpx.HTTPStatusError as exc:
553
+ raise click.ClickException(
554
+ f"Monmouth OPRS returned HTTP {exc.response.status_code}; "
555
+ "the site may be down or blocking automated access"
556
+ ) from exc
557
+ emit(result, as_json, limit)
558
+
559
+
560
+ @cli.command("url")
561
+ @click.argument("database", required=False, default=None)
562
+ def url_cmd(database: str | None) -> None:
563
+ """Print the browser URL for the portal, a database, or Monmouth OPRS."""
564
+ if database is None:
565
+ click.echo(f"Portal index: {PORTAL_INDEX}")
566
+ click.echo(f"Monmouth County OPRS 1875 census: {MONMOUTH_SEARCH}")
567
+ return
568
+ if database == "monmouth":
569
+ click.echo(MONMOUTH_SEARCH)
570
+ return
571
+ if database in DATABASES:
572
+ click.echo(PORTAL_BASE + DATABASES[database]["page"])
573
+ return
574
+ if database in ORDER_ONLY:
575
+ title, page, _grid, _ctl = ORDER_ONLY[database]
576
+ click.echo(f"{title} (records-request form, no online search):")
577
+ click.echo(PORTAL_BASE + page)
578
+ return
579
+ raise click.UsageError(
580
+ f"unknown database {database!r}; run `nj-archives databases` for the list"
581
+ )
582
+
583
+
584
+ if __name__ == "__main__":
585
+ cli()