@lexapi/client 0.1.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +394 -0
- package/LICENSE +21 -0
- package/README.md +407 -95
- package/dist/index.cjs +1723 -323
- package/dist/index.d.cts +2773 -343
- package/dist/index.d.ts +2773 -343
- package/dist/index.js +1698 -322
- package/package.json +32 -13
package/README.md
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
# @lexapi/client (TypeScript)
|
|
2
2
|
|
|
3
|
-
Official TypeScript SDK for [LexAPI](https://lex-api.com) — European legal data, made queryable. EUR-Lex, CJEU case law
|
|
3
|
+
Official TypeScript SDK for [LexAPI](https://lex-api.com/?ref=npm-sdk) — European legal data, made queryable. EUR-Lex legislation, CJEU case law and the Official Journal behind one REST API, parsed to article level.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[](https://www.npmjs.com/package/@lexapi/client) · [API docs](https://lex-api.com/docs?ref=npm-sdk) · [Changelog](CHANGELOG.md)
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
-
npm install @lexapi/client
|
|
10
|
+
npm install @lexapi/client
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Node ≥ 18 (native `fetch`); the built package is also smoke-tested on Bun and Deno in CI. Zero runtime dependencies, ESM + CommonJS, strict hand-curated types. **Server-side only** — API keys are secrets and must never ship in client-side code (the SDK also skips the `User-Agent` header on browser runtimes, where setting it is forbidden).
|
|
14
14
|
|
|
15
15
|
## Quickstart
|
|
16
16
|
|
|
@@ -18,11 +18,34 @@ Requires Node ≥ 18 (native `fetch`); also works on Deno, Bun, and edge runtime
|
|
|
18
18
|
import { LexAPI } from "@lexapi/client";
|
|
19
19
|
|
|
20
20
|
const client = new LexAPI({ apiKey: "lex_..." }); // or set LEXAPI_API_KEY
|
|
21
|
-
const info = await client.getInfo();
|
|
22
|
-
console.log(info.subscription, info.
|
|
21
|
+
const info = await client.getInfo(); // free (0 credits)
|
|
22
|
+
console.log(info.subscription?.tier, info.credits?.remaining);
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
Keys come from the [LexAPI dashboard](https://lex-api.com) and are prefixed `lex_`.
|
|
25
|
+
Keys come from the [LexAPI dashboard](https://lex-api.com/dashboard?ref=npm-sdk) and are prefixed `lex_`.
|
|
26
|
+
|
|
27
|
+
## What each call costs
|
|
28
|
+
|
|
29
|
+
LexAPI bills a monthly credit pool ([plans](https://lex-api.com/pricing?ref=npm-sdk)). The SDK method docs repeat these:
|
|
30
|
+
|
|
31
|
+
| Credits | Calls |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| 0 | `getInfo`; webhook management and deliveries |
|
|
34
|
+
| 1 | `resolve`, `getCites`, `getCitedBy`, the version endpoints |
|
|
35
|
+
| 3 per page | `search` (`maxPages`), `getRecentDocuments` (~10 results per page) — unfetched pages refunded |
|
|
36
|
+
| 5 → 4 → 1 | `getDocument`, `getDocumentsBatch` (per item), `getDocumentByUrl`, `getDocumentMetadata` — 5 for a live browser fetch, settled to **4** when the Publications Office Cellar API answered, to **1** from the LexAPI corpus (`result.headers.source`); a text-unavailable answer settles at 1 |
|
|
37
|
+
| 5 → 1 | `extractCitations` — refunded to 1 when the document was `alreadyExtracted` |
|
|
38
|
+
| 5 | `semanticSearch`, `semanticLegislationSearch` (+ per live `asOf` fetch, see below) |
|
|
39
|
+
| 5 | `getTransposition` — every plan |
|
|
40
|
+
| 15 | `semanticSearch({ hyde: true })` — refunded to 5 if HyDE falls back |
|
|
41
|
+
| 20 | `getCitationNetwork`, `getCitationPath`, `getRelatedDocuments`, `getCitationStats` |
|
|
42
|
+
| 20 | `getCounterparts` — BUSINESS, SCALE and ENTERPRISE only |
|
|
43
|
+
| 0 | `getNationalCoverage` (public) |
|
|
44
|
+
| 1 | `getNationalDocument` — every national read is a corpus read, so the 5-credit reservation always settles to 1 (an unknown id too) |
|
|
45
|
+
| 3 per call | `listNationalDocuments` — flat; pagination does not multiply the price |
|
|
46
|
+
| 5 | `nationalSemanticSearch`, `nationalLegislationSemanticSearch` — `hyde` never raises this for national case law |
|
|
47
|
+
|
|
48
|
+
Failed requests refund automatically (400/403 and 5xx in full; a 404 settles at 1). Refunds land just after the response, so a response's `credits` block can still show the upfront charge. The national-law call allowance follows the same rule: a failed call (other than a 404) gives its call back too.
|
|
26
49
|
|
|
27
50
|
## Search & documents
|
|
28
51
|
|
|
@@ -35,36 +58,111 @@ const hits = await client.search({
|
|
|
35
58
|
maxPages: 2,
|
|
36
59
|
});
|
|
37
60
|
if (hits.truncated) console.warn(hits.truncatedReason); // tier-capped pagination
|
|
38
|
-
if (hits.partial) console.warn(hits.partialReason); //
|
|
39
|
-
if (hits.
|
|
61
|
+
if (hits.partial) console.warn(hits.partialReason); // a page timed out — or source: "corpus"
|
|
62
|
+
if (hits.hint) console.log(hits.hint); // zero results → try semantic search
|
|
63
|
+
console.log(hits.headers?.searchSource, hits.headers?.searchCache); // "soap" | "cellar" | "corpus", "hit" | "miss" | "bypass"
|
|
64
|
+
await client.search({ query: "*", year: 2024, subdomain: "EU_CASE_LAW", fresh: true }); // filter-only, skip the 1 h cache
|
|
40
65
|
|
|
41
|
-
// Single document (POST /documentContent)
|
|
42
|
-
const { document } = await client.getDocument({
|
|
66
|
+
// Single document (POST /documentContent)
|
|
67
|
+
const { document, headers } = await client.getDocument({
|
|
43
68
|
celexNumber: "32016R0679",
|
|
44
69
|
include: ["metadata", "articles"],
|
|
45
70
|
articleId: "17",
|
|
46
71
|
});
|
|
72
|
+
console.log(headers?.source); // "corpus" (1 credit) | "cellar" | "cellar-oj" (4) | "live" (5)
|
|
47
73
|
|
|
48
74
|
// Batch (POST /documentContent/batch) — per-CELEX errors don't abort the batch
|
|
49
75
|
const batch = await client.getDocumentsBatch({ celexNumbers: ["32016R0679", "62018CJ0311"] });
|
|
50
76
|
if (batch.trimmed) console.warn(`clamped to ${batch.trimmedTo}: ${batch.trimmedReason}`);
|
|
51
|
-
batch.errors.forEach((e) => console.warn(`${e.
|
|
77
|
+
batch.errors.forEach((e) => console.warn(`${e.celex}: ${e.error}`)); // { celex, error: <message> }
|
|
78
|
+
console.log(batch.textUnavailable, batch.headers?.batch); // source counts — they overlap; see BatchSourceCounts
|
|
52
79
|
|
|
53
80
|
// Recent documents, metadata-only reads, URL + identifier resolution
|
|
54
|
-
const recent = await client.getRecentDocuments({ days: 7, documentType: "
|
|
81
|
+
const recent = await client.getRecentDocuments({ days: 7, documentType: "regulation" }); // one type; use search() for several
|
|
55
82
|
const meta = await client.getDocumentMetadata({ celexNumber: "32016R0679" });
|
|
56
83
|
const byUrl = await client.getDocumentByUrl({ url: "https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679" });
|
|
57
|
-
const resolved = await client.resolve("ECLI:EU:C:2020:559"); // → { celex: "62018CJ0311",
|
|
84
|
+
const resolved = await client.resolve("ECLI:EU:C:2020:559"); // → { celex: "62018CJ0311", resolvedVia: "ecli-corpus", verified: true }
|
|
85
|
+
// ELIs resolve via "eli-corpus" or "eli-cellar"; resolvedVia "eli" + verified: false = unconfirmed pattern guess, resolve again later
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Text availability and languages
|
|
89
|
+
|
|
90
|
+
A document can exist while EUR-Lex publishes no text for it. That is a `200` with metadata, `content: null` and a `textAvailability` verdict — billed 1 credit, not 5. **Check it before reading `content`:**
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const { document } = await client.getDocument({ celexNumber: "32008R1272", language: "de" });
|
|
94
|
+
const ta = document.textAvailability;
|
|
95
|
+
if (ta && !ta.available) {
|
|
96
|
+
console.log(ta.reason); // not_in_language | not_published_yet | no_machine_readable_rendition | too_large | unknown
|
|
97
|
+
console.log(ta.availableLanguages); // null = unknown, [] = known to be none
|
|
98
|
+
console.log(ta.latestConsolidated?.celex); // base acts: the consolidated version to fetch instead
|
|
99
|
+
}
|
|
58
100
|
```
|
|
59
101
|
|
|
60
|
-
|
|
102
|
+
`language` localizes the whole document and falls back to English (`languageRequested` / `languageFallback`). Pass `acceptLanguages: ["fr", "de"]` (or `"any"`) to get the authentic text in one call when the requested language has none. `titleLanguage` is present only when the title is not in the language you asked for.
|
|
103
|
+
|
|
104
|
+
Truncation/partial signals are always surfaced on the result (`truncated`, `partial`, `postFilteredBy`, `trimmed`/`trimmedTo`, `xWarning`) — never swallowed.
|
|
105
|
+
|
|
106
|
+
## Semantic search
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
// Case law (POST /search/semantic) — 5 credits
|
|
110
|
+
const cases = await client.semanticSearch({
|
|
111
|
+
query: "transfer of personal data to third countries",
|
|
112
|
+
limit: 10,
|
|
113
|
+
minScore: 0.5, // unset applies the upstream's ~0.7 relevance floor
|
|
114
|
+
includeText: true, // full text per hit instead of the default ~600-char `snippet`
|
|
115
|
+
});
|
|
116
|
+
if (cases.hint) console.warn(cases.hint); // present only on low-confidence result sets
|
|
117
|
+
|
|
118
|
+
// HyDE query rewriting — 15 credits instead of 5, ~1-3 s extra latency.
|
|
119
|
+
// Best-effort: on LLM failure the response reports hyde: false and the premium is refunded.
|
|
120
|
+
const hyde = await client.semanticSearch({ query: "credit scoring article 22", hyde: true });
|
|
121
|
+
console.log(hyde.hyde, hyde.hypotheticalDocument);
|
|
122
|
+
|
|
123
|
+
// Legislation (POST /legislation/semantic) — article-level matches, limit ≤ 50
|
|
124
|
+
const articles = await client.semanticLegislationSearch({ query: "right to be forgotten" });
|
|
125
|
+
for (const hit of articles.results) {
|
|
126
|
+
console.log(hit.law_id, hit.article_ref, hit.score, hit.snippet);
|
|
127
|
+
if (hit.consolidated) {
|
|
128
|
+
// One hit per article: the consolidated text, labelled. Consolidated texts are not
|
|
129
|
+
// authentic — cite hit.baseCelex (the Official Journal act); hit.baseAct is its own match.
|
|
130
|
+
console.log(hit.consolidatedAsOf, hit.baseCelex, hit.consolidatedNote, hit.baseAct?.score);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Persistent identity for case-law hits is `(metadata.celex_id, metadata.document_type)` — `case_id` is snapshot-scoped and does not survive index rebuilds.
|
|
136
|
+
|
|
137
|
+
### The text in force on a date (`asOf`)
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
const asOf = await client.semanticLegislationSearch({ query: "own funds requirements", asOf: "2019-06-01" });
|
|
141
|
+
|
|
142
|
+
console.log(asOf.asOfSummary); // { liveFetches, unresolved }
|
|
143
|
+
for (const hit of asOf.results) {
|
|
144
|
+
if (hit.asOfResolved) {
|
|
145
|
+
console.log(hit.asOfVersion); // { celex, date, kind: "consolidated" | "as_published" }
|
|
146
|
+
console.log(hit.matchedVersion); // when the text was swapped: what the index actually matched
|
|
147
|
+
} else {
|
|
148
|
+
console.log(hit.asOfReason); // e.g. "not_yet_in_force", "fetch_timeout" — the hit keeps its latest text
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The act must be in force on that date; the version is the act as published before its first consolidation, otherwise the consolidated version in force (later versions never count). `asOf` accepts `1952-01-01` … today (UTC); an invalid date is a 400 `InvalidParamsError`, refunded in full. **Cost:** 5 for the search; each live fetch of a version the corpus doesn't hold reserves 5 and settles by outcome (Cellar 4, browser 5, no text 1, failed 0), at most 3 per request by default. A fetch your pool can't cover is skipped (`asOfReason: "insufficient_credits"`) — never a 402. `AS_OF_REASONS` lists every documented reason.
|
|
61
154
|
|
|
62
155
|
## Citations
|
|
63
156
|
|
|
64
157
|
```ts
|
|
65
|
-
await client.extractCitations("32016R0679");
|
|
158
|
+
await client.extractCitations("32016R0679"); // crawl + persist (idempotent)
|
|
66
159
|
const outbound = await client.getCites("32016R0679", { citationType: "repeal" });
|
|
67
|
-
const inbound = await client.getCitedBy("
|
|
160
|
+
const inbound = await client.getCitedBy("32008R1272", { citationType: "corrigendum" });
|
|
161
|
+
console.log(inbound.relationSync?.status); // fresh | refreshed | pending | …
|
|
162
|
+
|
|
163
|
+
for await (const page of client.paginateCitedBy("32016R0679", { limit: 200 })) {
|
|
164
|
+
page.citedBy.forEach((g) => console.log(g.celexNumber, g.titleSource)); // 1 credit per page
|
|
165
|
+
}
|
|
68
166
|
|
|
69
167
|
const network = await client.getCitationNetwork("62018CJ0311", { limit: 100 });
|
|
70
168
|
if (network.partial) console.warn(network.message); // server budget expired — network is EMPTY, not zero
|
|
@@ -72,113 +170,347 @@ if (network.partial) console.warn(network.message); // server budget expired
|
|
|
72
170
|
const path = await client.getCitationPath("32016R0679", "31995L0046", { maxDepth: 5 });
|
|
73
171
|
if (!path.found) console.log(path.message); // graceful 200, not an error
|
|
74
172
|
|
|
75
|
-
const related = await client.getRelatedDocuments("32016R0679"); // bibliographic coupling
|
|
173
|
+
const related = await client.getRelatedDocuments("32016R0679", { limit: 10 }); // bibliographic coupling
|
|
76
174
|
const stats = await client.getCitationStats();
|
|
175
|
+
|
|
176
|
+
// National documents in the graph (BUSINESS, SCALE, ENTERPRISE only — 403 TierForbiddenError below that):
|
|
177
|
+
const withNational = await client.getCitedBy("32016R0679", { includeNational: true });
|
|
178
|
+
console.log(withNational.includeNational); // present once honoured; absent while no jurisdiction is live
|
|
179
|
+
const nationalEdges = await client.getCites("AT-NOR-10001597"); // a national id works directly, no flag needed
|
|
77
180
|
```
|
|
78
181
|
|
|
79
|
-
|
|
182
|
+
`citationType` is one of `reference`, `amendment`, `repeal`, `corrigendum`, `implementation`, `legal-basis`, `proposal`, `transposition` (`CITATION_TYPES`). All graph reads accept `language` for neighbour titles, and `includeNational` (`getCites`, `getCitedBy`, `getCitationNetwork`, `getCitationPath`, `getRelatedDocuments`, `getCitationStats`) to also return/follow national documents of live jurisdictions — BUSINESS, SCALE and ENTERPRISE only. `celexNumber` (and `getCitationPath`'s `from`/`to`) accept a national document id (e.g. `"AT-NOR-10001597"`) directly, with or without the flag; such an id whose jurisdiction isn't live is a plain `NotFoundError`.
|
|
183
|
+
|
|
184
|
+
### Provenance, filters and node identity
|
|
185
|
+
|
|
186
|
+
Every edge says where it comes from (`provenance`: `notice`, `cellar`, `notice+cellar`,
|
|
187
|
+
`cellar-nim`, `source`, `resolver`) and how its target was identified (`resolution`: `id`, `key`,
|
|
188
|
+
`abbreviation`, `text-pattern`; `null` on EUR-Lex / Cellar edges) — on `citations[]` of
|
|
189
|
+
`getCites` / `getCitedBy` and on `edgeDetails[]` of network neighbours. Every node carries `id`,
|
|
190
|
+
`jurisdiction` (`EU`, `AT`, …) and `documentKind` (`act` | `decision` | `null`) next to
|
|
191
|
+
`celexNumber`.
|
|
80
192
|
|
|
81
193
|
```ts
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
includeText: true, // full document text per hit instead of ~600-char snippets
|
|
194
|
+
const edges = await client.getCitedBy("32016L0680", {
|
|
195
|
+
citationType: ["transposition", "implementation"], // one value or a list (sent comma-separated)
|
|
196
|
+
provenance: ["source", "cellar-nim"],
|
|
197
|
+
jurisdictions: ["eu", "at", "de"], // a national code implies includeNational (BUSINESS+)
|
|
198
|
+
resolution: ["id", "key"], // leave out abbreviation matches
|
|
88
199
|
});
|
|
89
|
-
|
|
200
|
+
for (const g of edges.citedBy) console.log(g.jurisdiction, g.id, g.citations?.map((c) => c.provenance));
|
|
201
|
+
console.log(edges.totalEdges, edges.countsSource); // page until offset + limit >= totalEdges
|
|
90
202
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
const hyde = await client.semanticSearch({ query: "credit scoring article 22", hyde: true });
|
|
95
|
-
console.log(hyde.hyde, hyde.hypotheticalDocument, hyde.credits?.operation_weight);
|
|
203
|
+
const refs = await client.getCites("DE-JUD-BFH-KBRE202550123", { unresolved: true }); // national id: references with no edge
|
|
204
|
+
for (const r of refs.unresolved ?? []) console.log(r.kind, r.text, r.status, r.targetId);
|
|
205
|
+
```
|
|
96
206
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
207
|
+
`getCitationNetwork`, `getCitationPath` and `getRelatedDocuments` take the same four filters;
|
|
208
|
+
`getCitationNetwork` also takes `unresolved`. An unknown value is an `InvalidParamsError` with
|
|
209
|
+
`err.param` and `err.allowed`, refunded. `countsSource` (`stats` | `counted`, and
|
|
210
|
+
`paging.countsSource` on the network) says where the totals were read from; both are exact.
|
|
211
|
+
With `includeNational: true`, `getCitationStats` adds `byJurisdiction`, `byProvenance` and
|
|
212
|
+
`transposition`.
|
|
213
|
+
|
|
214
|
+
### Notified measures and counterparts
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
const t = await client.getTransposition("32016L0680", { jurisdictions: ["es", "cz"] }); // 5 credits, every plan
|
|
218
|
+
console.log(t.note); // a notification is not a finding that the measure transposes the act
|
|
219
|
+
for (const c of t.jurisdictions) {
|
|
220
|
+
for (const m of c.measures) console.log(c.jurisdiction, m.title, m.officialJournal.date, m.id ?? "(not held)");
|
|
221
|
+
}
|
|
222
|
+
console.log(t.source.cellar?.attribution); // keep with anything you republish
|
|
223
|
+
|
|
224
|
+
const cp = await client.getCounterparts("AT-NOR-10001597"); // 20 credits, BUSINESS+
|
|
225
|
+
for (const v of cp.via) {
|
|
226
|
+
for (const c of v.counterparts) console.log(v.euAct.id, c.rank, c.jurisdiction, c.id ?? c.title);
|
|
227
|
+
}
|
|
100
228
|
```
|
|
101
229
|
|
|
102
|
-
|
|
230
|
+
`getTransposition` lists the measures the member states notified to the Commission for an EU act
|
|
231
|
+
(CELEX sector 3), from the Publications Office's Cellar records. On BUSINESS, SCALE and ENTERPRISE,
|
|
232
|
+
for live jurisdictions, it also says which measures LexAPI holds (`id`, `resolved`, `resolution`,
|
|
233
|
+
`counts.resolved`, `source.lanes`) and adds the documents whose national source records that they
|
|
234
|
+
transpose or implement the act; `resolvedOnly: true` keeps only those. Otherwise those fields are
|
|
235
|
+
`null` (and `termsRequired: true` while the national-source terms are not accepted). A CELEX that
|
|
236
|
+
is not an EU act is a `NotFoundError`.
|
|
237
|
+
|
|
238
|
+
`getCounterparts` returns a national document's counterparts in the other live jurisdictions,
|
|
239
|
+
through the EU acts it transposes or implements, ranked `1` (the national source records it), `2`
|
|
240
|
+
(a notified measure LexAPI holds) or `3` (a notified measure LexAPI does not hold, `id: null`). A
|
|
241
|
+
lookup past the server's budget throws `TimeoutError` (503, `err.partial`), refunded. The SDK does
|
|
242
|
+
not retry it; retry yourself, or narrow with `jurisdictions`.
|
|
243
|
+
|
|
244
|
+
## National law
|
|
245
|
+
|
|
246
|
+
Member-state (and non-EU) legal orders alongside EUR-Lex. BUSINESS, SCALE and ENTERPRISE get full
|
|
247
|
+
access; FREE, STARTER and PROFESSIONAL get it within a monthly allowance of national calls. A
|
|
248
|
+
jurisdiction that isn't launched yet answers 404, exactly like a path that doesn't exist — check
|
|
249
|
+
`getNationalCoverage()` first.
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
const coverage = await client.getNationalCoverage(); // public, free — no allowance consumed
|
|
253
|
+
for (const j of coverage.jurisdictions) {
|
|
254
|
+
if (j.live) console.log(j.code, j.name, j.legislation.documents, j.sources.map((s) => s.attribution));
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const { document } = await client.getNationalDocument("AT", "AT-NOR-10001597"); // 1 credit
|
|
258
|
+
console.log(document.attribution); // always show this alongside the text
|
|
259
|
+
for (const a of document.content?.articles ?? []) console.log(a.number, a.title, a.text ?? "(no text)");
|
|
260
|
+
|
|
261
|
+
const page = await client.listNationalDocuments("AT", { q: "Datenschutz", limit: 20 }); // 3 credits flat
|
|
262
|
+
for await (const p of client.paginateNationalDocuments("AT", { q: "Datenschutz", limit: 100 })) {
|
|
263
|
+
console.log(p.results.length, p.hasMore); // cursor paging — reaches past the first 1,000 rows, `page` doesn't
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const hits = await client.nationalSemanticSearch("AT", { query: "Datenschutz bei Bankgeschäften" }); // 5 credits
|
|
267
|
+
for (const h of hits.results) console.log(h.document.documentKind, h.document.ecli, h.document.dateOfDocument);
|
|
268
|
+
const articles = await client.nationalLegislationSemanticSearch("DE", { query: "Kündigungsfrist" }); // 5 credits
|
|
269
|
+
if (articles.partial) console.warn(articles.hint); // SEARCH_INCOMPLETE: results may be missing better matches
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
**Incomplete national searches.** When the national index could not complete a semantic search,
|
|
273
|
+
results may be incomplete: with hits left the answer carries `partial: true`,
|
|
274
|
+
`partialReason: "SEARCH_INCOMPLETE"` and a `hint` (retry, or rephrase / change the filters). With
|
|
275
|
+
nothing left to return it throws instead — `NationalSemanticUnavailableError` (503,
|
|
276
|
+
`partialReason: "SEARCH_INCOMPLETE"`, `retryAfter` when a retry may help — retried at most once per call, and only with `retryReadOnlyPosts`) or
|
|
277
|
+
`NationalSemanticFilterUnreachableError` (422, not retryable as is). Both are refunded; an empty
|
|
278
|
+
answer would not have meant "no matches".
|
|
279
|
+
|
|
280
|
+
**One shape for every country (requires LexAPI API 2.8.0).** National documents have the same
|
|
281
|
+
fields, types and formats in every jurisdiction, so code written for one country works for all of
|
|
282
|
+
them. Every field is always present — one the source does not provide is `null` (or `[]`), never
|
|
283
|
+
missing:
|
|
284
|
+
|
|
285
|
+
- `documentKind` (`"act"` | `"decision"`) tells legislation from case law everywhere; `documentType`
|
|
286
|
+
is the source's own label, in its language.
|
|
287
|
+
- `decision` — on a decision, `{ court, chamber, caseNumbers, citedNorms: [{ text, documentId }] }`,
|
|
288
|
+
read server-side from whichever fields the source uses (also when the decision has no text);
|
|
289
|
+
`null` for acts. `isNationalDecision(document)` narrows it.
|
|
290
|
+
- `content` (or `null` when there is no text — see `textAvailability`) is always
|
|
291
|
+
`{ fullText, articles, textLanguages, textLanguage, embeddedForeignText, textSource, ocr, repeal, source, details }`;
|
|
292
|
+
every article is `{ number, title, section, text, inForceFrom, inForceTo, details }` (`text: null`
|
|
293
|
+
when the source publishes no text for that unit). What a source adds beyond these fields is under
|
|
294
|
+
`content.details` / `articles[].details` — source-specific, keys differ by country.
|
|
295
|
+
- Semantic hits carry `document` (the listing's summary of the matched document); legislation hits
|
|
296
|
+
always carry `law_title`, `article_ref`, `section`, `language`, `in_force`, `valid_from`,
|
|
297
|
+
`valid_to` and `law_type`, `null` when the index has nothing.
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
import { isNationalDecision } from "@lexapi/client";
|
|
301
|
+
|
|
302
|
+
const { document: d } = await client.getNationalDocument("DE", "DE-JUD-BFH-KBRE202550123");
|
|
303
|
+
if (isNationalDecision(d)) {
|
|
304
|
+
console.log(d.decision.court, d.decision.caseNumbers.join(", ")); // "BFH 3. Senat" "III R 27/24"
|
|
305
|
+
for (const n of d.decision.citedNorms) console.log(n.text, n.documentId ?? "(not identified)");
|
|
306
|
+
}
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
A document its source withdrew (a takedown, a pseudonymisation fix) throws `DocumentWithdrawnError` (410) from `getNationalDocument` and from the citation methods for a withdrawn national id — nothing of it is served, not even the title; drop any copy you hold.
|
|
310
|
+
|
|
311
|
+
`getNationalCoverage()` also reports each live jurisdiction's `citationGraph`: its extraction
|
|
312
|
+
`methods` (with `unmeasured` rates and their reason codes), `edges`, the measured rates
|
|
313
|
+
(`decisionResolutionRate`, `actEuRate`, `textPatternRate`, `nimResolvedRate`), `transposition`,
|
|
314
|
+
`precision` and `floors` — `null` wherever nothing was measured. National `content` also carries
|
|
315
|
+
`textSource` (`html` | `pdf-text` | `ocr` | `null`) and `ocr` (engine and confidence when the text
|
|
316
|
+
was machine-read — never the official text).
|
|
317
|
+
|
|
318
|
+
A used-up allowance is `NationalAllowanceExhaustedError` (402); its headroom is also on
|
|
319
|
+
`result.headers.nationalAllowance` (`{ limit, remaining, resetsAt }`) on every admitted call from a
|
|
320
|
+
plan below BUSINESS.
|
|
103
321
|
|
|
104
322
|
## Webhooks
|
|
105
323
|
|
|
106
324
|
```ts
|
|
107
325
|
const created = await client.webhooks.create({
|
|
108
|
-
name: "
|
|
326
|
+
name: "Chemicals compliance watch",
|
|
109
327
|
url: "https://example.com/webhooks/lexapi",
|
|
110
|
-
searchCriteria: { documentType: "
|
|
328
|
+
searchCriteria: { documentType: "regulation", query: "chemical*" }, // documents.new (titles)
|
|
329
|
+
watchCelex: ["32006R1907", "32008R1272"], // watchlist.changes
|
|
111
330
|
});
|
|
112
331
|
console.log(created.webhook.secret); // returned ONLY here — store it (HMAC-SHA256 signing key)
|
|
113
332
|
|
|
114
|
-
const { webhooks } = await client.webhooks.list();
|
|
115
|
-
const detail = await client.webhooks.get(created.webhook.id);
|
|
116
|
-
await client.webhooks.update(created.webhook.id, { status: "ACTIVE" });
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
await client.webhooks.
|
|
333
|
+
const { webhooks } = await client.webhooks.list(); // criteriaErrors, watchCelex, deliveryCount
|
|
334
|
+
const detail = await client.webhooks.get(created.webhook.id); // retryPolicy, recentDeliveries
|
|
335
|
+
const resumed = await client.webhooks.update(created.webhook.id, { status: "ACTIVE" });
|
|
336
|
+
console.log(resumed.requeuedDeliveries);
|
|
337
|
+
await client.webhooks.update(created.webhook.id, { searchCriteria: null }); // keep only the watch list
|
|
338
|
+
await client.webhooks.test(created.webhook.id); // synchronous signed test delivery
|
|
339
|
+
for await (const page of client.webhooks.paginateDeliveries(created.webhook.id)) console.log(page.deliveries.length);
|
|
340
|
+
await client.webhooks.delete(created.webhook.id);
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
Webhooks per account: FREE 0 · STARTER 2 · PROFESSIONAL 10 · BUSINESS 50 · SCALE 100 · ENTERPRISE 100. Unsupported criteria are refused with a 400 `InvalidParamsError` whose `details` names each problem. Write calls are never retried on 5xx.
|
|
344
|
+
|
|
345
|
+
### Receiving deliveries
|
|
346
|
+
|
|
347
|
+
```ts
|
|
348
|
+
import { verifyWebhook } from "@lexapi/client";
|
|
349
|
+
|
|
350
|
+
// Express: keep the RAW body — the signature is over the exact bytes sent.
|
|
351
|
+
app.post("/webhooks/lexapi", express.raw({ type: "application/json" }), async (req, res) => {
|
|
352
|
+
try {
|
|
353
|
+
const event = await verifyWebhook(req.body, req.get("x-webhook-signature"), process.env.LEXAPI_WEBHOOK_SECRET!);
|
|
354
|
+
// Verified signature + 5-minute replay window. Dedupe on event.delivery?.id (stable across retries).
|
|
355
|
+
if (event.event === "watchlist.changes") {
|
|
356
|
+
for (const c of event.data.changes) console.log(c.watchedCelex, c.relation, c.document.celex);
|
|
357
|
+
} else if (event.event === "documents.new") {
|
|
358
|
+
console.log(event.data.count, event.data.totalAvailable);
|
|
359
|
+
}
|
|
360
|
+
res.sendStatus(200); // respond within 10 s
|
|
361
|
+
} catch {
|
|
362
|
+
res.sendStatus(401);
|
|
363
|
+
}
|
|
364
|
+
});
|
|
120
365
|
```
|
|
121
366
|
|
|
122
|
-
|
|
367
|
+
`verifySignature(rawBody, signature, secret)` is the signature-only check. Both use Web Crypto (constant-time comparison); an empty `secret` throws `WebhookSignatureError("missing_secret")` (a configuration error, not a bad delivery).
|
|
368
|
+
|
|
369
|
+
## Corpus export (BUSINESS, SCALE, ENTERPRISE)
|
|
370
|
+
|
|
371
|
+
`export()` streams NDJSON rows via the fetch body stream — constant memory regardless of result size. BUSINESS, SCALE and ENTERPRISE only; lower tiers get a 403 `TierForbiddenError`.
|
|
372
|
+
|
|
373
|
+
**Billing (credit plans, API 2.3.0):** 1 credit per row written, at least 1 per export. The call is admitted for 1 credit, the matching rows are counted, and the rest of 1 credit per row it can return is reserved; a pool that cannot cover it throws `CreditsExhaustedError` before anything streams. Unwritten rows are refunded when the stream ends: `stream.done?.credits?.charged`.
|
|
374
|
+
|
|
375
|
+
**Filters:** `documentType` matches the stored label exactly, ignoring case; `documentTypeCode: "regulation"` selects the family (incl. implementing and delegated regulations); `author` matches whole values; `dateFrom` / `dateTo` are `YYYY-MM-DD`; `changedSince` returns rows whose text changed (the cheapest incremental sync) and `fetchedSince` rows written to at all — both an ISO date or a date-time with a timezone, or a `Date`; `limit` is a positive integer (anything else throws `RangeError`).
|
|
123
376
|
|
|
124
|
-
|
|
377
|
+
Licensing: exported content may not be used to train or evaluate ML models without a separate licence ([Terms §6](https://lex-api.com/terms?ref=npm-sdk#acceptable-use)). For training data, [Arieta Data](https://data.arietalabs.com/?ref=npm-sdk), a sister product from Arieta Labs, licenses datasets drawn from the same corpus for training, retrieval and evaluation.
|
|
125
378
|
|
|
126
379
|
```ts
|
|
127
|
-
const stream = await client.export({
|
|
380
|
+
const stream = await client.export({ documentTypeCode: "regulation", dateFrom: "2024-01-01", limit: 10_000 });
|
|
128
381
|
|
|
129
|
-
console.log(stream.meta);
|
|
130
|
-
console.log(stream.headers.total); // X-Export-Total header
|
|
382
|
+
console.log(stream.meta?.totalMatching, stream.headers.total); // leading _meta envelope / X-Export-Total
|
|
131
383
|
|
|
132
384
|
for await (const row of stream) {
|
|
133
385
|
process(row.celex, row.documentTypeCode, row.parsedContent);
|
|
134
386
|
}
|
|
135
387
|
|
|
136
|
-
console.log(stream.done);
|
|
137
|
-
if (stream.
|
|
388
|
+
console.log(stream.done?.written, stream.done?.skippedStubs);
|
|
389
|
+
if (stream.truncated) console.warn(`rows not reached (${stream.done?.truncatedBy}) — narrow filters or resume via changedSince`);
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
The `_meta`/`_done` envelope lines are never yielded as rows; the stream is single-pass (re-iterating a fully read stream yields nothing; iterating one you ended early raises `IncompleteExportError` — call `export()` again to re-read). Breaking out of the loop (or `stream.cancel()`, or the call's `signal`) releases the connection. **A stream that ends without its `_done` trailer throws `IncompleteExportError`** (so does a `_done` with `complete: false`, or an `_error` line, which is never yielded as a row) after yielding the rows that did arrive — the server stopped mid-export and they are not the whole set (`stream.complete` stays `false`; `stream.rowsRead` counts them). A dropped connection throws `NetworkError`, a stall longer than `timeoutMs` throws `TimeoutError`. Lines that are not JSON objects are counted in `stream.invalidLines`. For "did matching rows remain that this export did not reach?" read `stream.truncated` — after iterating it is the server's authoritative `_done.truncated` (`stream.done?.truncatedBy`: `limit`, `max_rows`, `credits` or `recovered`); before that, a hint from the up-front count. Metadata-only rows are skipped unless `includeStubs: true`.
|
|
393
|
+
|
|
394
|
+
## Point-in-time versions
|
|
395
|
+
|
|
396
|
+
Versions are LexAPI *observation snapshots* — the document as fetched — not legal in-force reconstructions; history begins at first ingestion. (For the text in force on a date, use a consolidated CELEX or `semanticLegislationSearch({ asOf })`.)
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
const history = await client.listDocumentVersions("32016R0679");
|
|
400
|
+
console.log(history.currentVersion, history.trackedSince);
|
|
401
|
+
|
|
402
|
+
const snapshot = await client.getDocumentVersion("32016R0679", 2);
|
|
403
|
+
console.log(snapshot.document.parsedContent, snapshot.corpusVersion);
|
|
404
|
+
|
|
405
|
+
const atDate = await client.getDocumentAtDate("32016R0679", "2026-03-20");
|
|
406
|
+
console.log(atDate.asOf, atDate.document.version);
|
|
138
407
|
```
|
|
139
408
|
|
|
140
|
-
|
|
409
|
+
Each call costs 1 credit. Dates before the document entered the corpus reject with `NotFoundError` carrying the tracking start date.
|
|
410
|
+
|
|
411
|
+
## Response headers
|
|
412
|
+
|
|
413
|
+
Every JSON result carries `headers` — the LexAPI response headers, parsed:
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
const r = await client.getDocument({ celexNumber: "32016R0679" });
|
|
417
|
+
r.headers?.source; // X-Source: corpus | cellar | cellar-oj | live
|
|
418
|
+
r.headers?.rateLimit; // { limit, remaining, reset (seconds), policy }
|
|
419
|
+
r.headers?.languageFallback; // X-Language-Fallback
|
|
420
|
+
r.headers?.textAvailable; // X-Text-Available
|
|
421
|
+
r.headers?.corpusVersion; // X-Corpus-Version
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
Also: `searchSource`, `searchCache`, `warning`, `ignoredDocumentTypes`, `postFilteredBy`, `documentTypeFanOut`, `batch`. The older `xWarning` (and `corpusVersion` on version responses) are still set.
|
|
425
|
+
|
|
426
|
+
On the four national document/semantic endpoints, `headers.nationalAllowance` (`{ limit, remaining, resetsAt }`, from `X-National-Limit`/`X-National-Remaining`/`X-National-Reset`) reports the monthly national-call allowance left — present only for FREE/STARTER/PROFESSIONAL callers (absent for BUSINESS and above, and for `getNationalCoverage`).
|
|
141
427
|
|
|
142
428
|
## Configuration
|
|
143
429
|
|
|
144
430
|
```ts
|
|
145
431
|
const client = new LexAPI({
|
|
146
|
-
apiKey: "lex_...",
|
|
432
|
+
apiKey: "lex_...", // or LEXAPI_API_KEY env var
|
|
147
433
|
baseUrl: "https://lex-api.com/api/v1", // default
|
|
148
|
-
timeoutMs:
|
|
149
|
-
retry: { maxRetries: 3, baseDelayMs: 500, maxDelayMs: 30_000 },
|
|
150
|
-
fetch: myFetch,
|
|
151
|
-
userAgentSuffix: "my-app/1.0",
|
|
434
|
+
timeoutMs: 95_000, // per attempt, incl. the body; per-call: client.getInfo({ timeoutMs: 5_000 })
|
|
435
|
+
retry: { maxRetries: 3, baseDelayMs: 500, maxDelayMs: 30_000, retryReadOnlyPosts: false },
|
|
436
|
+
fetch: myFetch, // injectable transport (testing / polyfills)
|
|
437
|
+
userAgentSuffix: "my-app/1.0", // appended to `lexapi-typescript/<version>`
|
|
152
438
|
});
|
|
153
439
|
```
|
|
154
440
|
|
|
155
|
-
## Retries
|
|
441
|
+
## Retries, timeouts and cancellation
|
|
442
|
+
|
|
443
|
+
The SDK retries automatically **only when a retry cannot charge you twice** (the shared SDK contract, [PLAN.md §1.2](PLAN.md)). Up to 3 retries (`retry.maxRetries`), exponential backoff with full jitter (base 0.5 s, cap 30 s):
|
|
444
|
+
|
|
445
|
+
| Failure | GET, billed | GET, free (`getInfo`, webhook reads) | Read-only POST | Mutating call |
|
|
446
|
+
|---|---|---|---|---|
|
|
447
|
+
| 429, not a quota | retry | retry | retry | retry |
|
|
448
|
+
| 429 reporting an exhausted quota (`RateLimitedError.quotaExhausted`) | no | no | no | no |
|
|
449
|
+
| Never reached the server (DNS failure, connection refused/unreachable, connect timeout, TLS handshake failure; Cloudflare 521/522/523) | retry | retry | retry | retry |
|
|
450
|
+
| App-origin 502 / 503 / 504 | retry | retry | only with `retry: { retryReadOnlyPosts: true }` | no |
|
|
451
|
+
| Proxy-origin 502 / 503 / 504, 520, 524 | no | retry | no | no |
|
|
452
|
+
| Any other transport error (reset, connection closed — `fetch` cannot tell before-response from mid-response — read error, `REQUEST_TIMEOUT`) | no | retry | no | no |
|
|
453
|
+
| 400 / 401 / 402 / 403 / 404 / 500 and anything else | no | no | no | no |
|
|
454
|
+
|
|
455
|
+
- **Read-only POSTs** are `search`, `getDocument`, `getDocumentsBatch`, `getDocumentByUrl`, `getDocumentMetadata`, `resolve`, `semanticSearch`, `semanticLegislationSearch`. **Mutating calls** are the webhook writes and `extractCitations` (it persists edges).
|
|
456
|
+
- **App-origin** = the response carries a non-empty `X-LexAPI-Version` header or a `RateLimit-Limit` header (the API's rate limiter sets `RateLimit-*` on every billable app response; proxies never do). A JSON error body alone is not enough. Anything else is treated as a proxy answer: the API may have charged the call and not refunded it, so a billed call is not retried.
|
|
457
|
+
- **Wait:** `Retry-After` on any status (an empty or unparseable value counts as absent); on a 429 only, then `RateLimit-Reset` and the JSON `retryAfter` field; on a 503 `NATIONAL_SEMANTIC_UNAVAILABLE` (an incomplete national search), the JSON `retryAfter` field. `X-RateLimit-*` is not read. Every hint is clamped to the 30 s cap (`retry.maxDelayMs`; a cap below the server's requested wait shortens it); numbers above 1e12 / 1e9 are read as epoch ms / s. A quota 429 has `retryAfter: undefined`.
|
|
156
458
|
|
|
157
|
-
|
|
459
|
+
**Timeout:** `timeoutMs` (default 95 s) is an *inactivity* limit per attempt: the longest the SDK waits for the next bytes — until the response head, then between body chunks (the timer restarts on every chunk), for JSON bodies and export streams alike. It is not a deadline for the whole call. On expiry you get `TimeoutError` with `code: "REQUEST_TIMEOUT"` (status 0). `fetch` cannot time the connect phase separately, so it counts inside the first window. 95 s lets the API's own 90 s limit on one live EUR-Lex fetch reach you as a typed, refunded 504; a request needing several upstream fetches can still exceed it.
|
|
158
460
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
461
|
+
**Cancellation:** every method takes `{ signal }`. Aborting cancels the in-flight request, any retry wait and an export stream (the connection is released), and rejects with `RequestAbortedError` (`code: "ABORTED"`, `cause` = the signal's reason).
|
|
462
|
+
|
|
463
|
+
```ts
|
|
464
|
+
const controller = new AbortController();
|
|
465
|
+
req.on("close", () => controller.abort());
|
|
466
|
+
await client.semanticSearch({ query: "gdpr" }, { signal: controller.signal });
|
|
467
|
+
```
|
|
163
468
|
|
|
164
469
|
## Typed errors
|
|
165
470
|
|
|
166
|
-
Every non-2xx response maps to a typed error carrying `code`, `status`, `details`, and `
|
|
471
|
+
Every non-2xx response maps to a typed error carrying `code`, `status`, `message`, `details`, `retryAfter`, the raw `body` and parsed `headers`:
|
|
167
472
|
|
|
168
473
|
```ts
|
|
169
|
-
import { CreditsExhaustedError, NotFoundError, RateLimitedError } from "@lexapi/client";
|
|
474
|
+
import { CreditsExhaustedError, NotFoundError, RateLimitedError, TierForbiddenError } from "@lexapi/client";
|
|
170
475
|
|
|
171
476
|
try {
|
|
172
|
-
await client.
|
|
477
|
+
await client.semanticSearch({ query: "gdpr" });
|
|
173
478
|
} catch (err) {
|
|
174
|
-
if (err instanceof RateLimitedError) console.log(`
|
|
175
|
-
else if (err instanceof
|
|
479
|
+
if (err instanceof RateLimitedError && err.quotaExhausted) console.log(`legacy quota resets ${err.resetsAt}`);
|
|
480
|
+
else if (err instanceof RateLimitedError) console.log(`retry in ${err.retryAfter}s`, err.rateLimit);
|
|
481
|
+
else if (err instanceof CreditsExhaustedError) console.log(`need ${err.weight}, have ${err.available}; resets ${err.resetsAt}`);
|
|
482
|
+
else if (err instanceof TierForbiddenError) console.log((err.body as { upgradeUrl?: string })?.upgradeUrl);
|
|
176
483
|
else if (err instanceof NotFoundError) console.log("no such document");
|
|
177
484
|
else throw err;
|
|
178
485
|
}
|
|
179
486
|
```
|
|
180
487
|
|
|
181
|
-
|
|
488
|
+
| Class | `code` | HTTP |
|
|
489
|
+
| --- | --- | --- |
|
|
490
|
+
| `NotFoundError` | `NOT_FOUND` | 404 |
|
|
491
|
+
| `DocumentWithdrawnError` | `DOCUMENT_WITHDRAWN` | 410 — a national document its source withdrew; nothing of it is served; `.id`/`.jurisdiction`/`.withdrawnAt`; not retryable, drop any copy you hold |
|
|
492
|
+
| `InvalidCelexError` / `InvalidUrlError` / `InvalidParamsError` | `INVALID_CELEX` / `INVALID_URL` / `INVALID_PARAMS` | 400 — `InvalidParamsError.param` / `.value` / `.allowed` name a refused filter, the value sent and the allowed values |
|
|
493
|
+
| `AuthenticationError` | `UNAUTHORIZED` (derived) | 401 |
|
|
494
|
+
| `CreditsExhaustedError` | `CREDITS_EXHAUSTED` | 402 |
|
|
495
|
+
| `NationalAllowanceExhaustedError` | `NATIONAL_ALLOWANCE_EXHAUSTED` | 402 — FREE/STARTER/PROFESSIONAL's monthly national-law call allowance is used up; `resetsAt`/`limit`/`upgradeUrl` |
|
|
496
|
+
| `NationalSemanticNotEnabledError` | `NATIONAL_SEMANTIC_NOT_ENABLED` | 409 — this jurisdiction has no semantic index to search; `.jurisdiction`; not retryable, refunded |
|
|
497
|
+
| `TierForbiddenError` | `TIER_FORBIDDEN` | 403 |
|
|
498
|
+
| `RateLimitedError` | `RATE_LIMITED`, `QUOTA_EXHAUSTED` | 429 — `QUOTA_EXHAUSTED` (legacy plans' used-up quota) is never retried; `resetsAt` says when it refills |
|
|
499
|
+
| `InternalServerError` | `INTERNAL` | 500 |
|
|
500
|
+
| `UpstreamError` | `UPSTREAM_ERROR` | 502; Cloudflare 520–523 |
|
|
501
|
+
| `ServiceUnavailableError` | `SERVICE_UNAVAILABLE` (derived) | 503 |
|
|
502
|
+
| `NationalSemanticUnavailableError` (extends `ServiceUnavailableError`) | `NATIONAL_SEMANTIC_UNAVAILABLE` | 503 — a jurisdiction's semantic index is temporarily unreachable, or could not complete this search with nothing left to return (`.partialReason === "SEARCH_INCOMPLETE"`, `retryAfter` — absent once the same search has repeatedly come back incomplete, and then not retried); `.jurisdiction`; retry later |
|
|
503
|
+
| `NationalSemanticFilterUnreachableError` (extends `InvalidParamsError`) | `NATIONAL_SEMANTIC_FILTER_UNREACHABLE` | 422 — the national index cannot search this slice (jurisdiction, document kind, filters) completely and there is nothing left to return; a coverage limit, not a malformed request (the request may be valid; `.param` is absent); `.jurisdiction`, `.partialReason`; not retryable as is — rephrase the query or change the filters; refunded |
|
|
504
|
+
| `TimeoutError` | `TIMEOUT` (504, 524; 503 from `getCounterparts`, with `.partial` / `.serverTimeoutMs`) / `REQUEST_TIMEOUT` (status 0, the SDK's own timeout) | |
|
|
505
|
+
| `NetworkError` | `CONNECTION_ERROR` | 0 (transport failure, or the connection dropped — incl. mid-export) |
|
|
506
|
+
| `RequestAbortedError` | `ABORTED` | 0 (your `signal` fired) |
|
|
507
|
+
| `InvalidResponseError` | `INVALID_RESPONSE` | a 2xx whose body was not JSON (e.g. a proxy HTML page) |
|
|
508
|
+
| `IncompleteExportError` | `INCOMPLETE_EXPORT` | 0 — an export ended without a complete `_done` trailer, or the server sent an `_error` line (`rowsRead`, `details`) |
|
|
509
|
+
| `LexAPIError` (base) | `INTERNAL` | any other status (e.g. 409, 413), with `status` kept |
|
|
510
|
+
|
|
511
|
+
**`instanceof` across builds.** The package ships an ESM and a CommonJS build; in a process that loads both (a CommonJS dependency wrapping the SDK inside an ESM app, Next.js, …) they are two copies of every class. The error classes carry a shared brand (`Symbol.for`), so `err instanceof NotFoundError` is still true for an error thrown by the other copy. `isLexAPIError(err)` / `isLexAPIError(err, NotFoundError)` does the same as a function.
|
|
512
|
+
|
|
513
|
+
Both the typed envelope (`{success: false, error: {code, message, details}}`) and the legacy bare `{error, message, details?}` shape (still used by 429s, API-key 401s, `/search` and webhook validation, the export tier gate and semantic upstream errors) are parsed; unknown codes stay on the base `LexAPIError` with the raw code string.
|
|
182
514
|
|
|
183
515
|
## Credit visibility
|
|
184
516
|
|
|
@@ -187,39 +519,19 @@ Every response keeps its raw `usage` / `credits` blocks; `getCreditUsage` normal
|
|
|
187
519
|
```ts
|
|
188
520
|
import { getCreditUsage } from "@lexapi/client";
|
|
189
521
|
|
|
190
|
-
const
|
|
191
|
-
const { unitsCharged, creditsRemaining, resetsAt } = getCreditUsage(info);
|
|
522
|
+
const { unitsCharged, creditsRemaining, resetsAt } = getCreditUsage(await client.getInfo());
|
|
192
523
|
```
|
|
193
524
|
|
|
194
525
|
`unitsCharged` maps `credits.operation_weight` (0 for free ops like `/info`); `creditsRemaining` falls back to `usage.remaining` on legacy daily-call accounts.
|
|
195
526
|
|
|
196
|
-
## Point-in-time versions
|
|
197
|
-
|
|
198
|
-
> Requires a LexAPI deployment with the point-in-time endpoints (lex-api PR #72).
|
|
199
|
-
> Versions are LexAPI *observation snapshots* — the document as fetched — not
|
|
200
|
-
> legal in-force reconstructions; history begins at first ingestion.
|
|
201
|
-
|
|
202
|
-
```ts
|
|
203
|
-
const history = await client.listDocumentVersions("32016R0679");
|
|
204
|
-
console.log(history.currentVersion, history.trackedSince);
|
|
205
|
-
|
|
206
|
-
const snapshot = await client.getDocumentVersion("32016R0679", 2);
|
|
207
|
-
console.log(snapshot.document.parsedContent);
|
|
208
|
-
|
|
209
|
-
const asOf = await client.getDocumentAtDate("32016R0679", "2026-03-20");
|
|
210
|
-
console.log(asOf.asOf, asOf.document.version);
|
|
211
|
-
```
|
|
212
|
-
|
|
213
|
-
Each call costs 1 credit. Dates before the document entered the corpus reject
|
|
214
|
-
with `NotFoundError` carrying the tracking start date.
|
|
215
|
-
|
|
216
527
|
## Development
|
|
217
528
|
|
|
218
529
|
```bash
|
|
219
|
-
npm
|
|
220
|
-
npm run lint
|
|
221
|
-
npm test
|
|
222
|
-
npm run build
|
|
530
|
+
npm ci
|
|
531
|
+
npm run lint # tsc --noEmit (strict)
|
|
532
|
+
npm test # vitest (Node ≥ 20)
|
|
533
|
+
npm run build # tsup -> dist/ (ESM + CJS + d.ts / d.cts)
|
|
534
|
+
npm run smoke:dist # framework-free check of the built bundles (runs on Node 18+)
|
|
223
535
|
```
|
|
224
536
|
|
|
225
|
-
|
|
537
|
+
See [PLAN.md](PLAN.md) for the endpoint coverage matrix and SDK contract. Docs: <https://lex-api.com/docs?ref=npm-sdk>
|