@lexapi/client 0.1.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/README.md +225 -0
- package/dist/index.cjs +999 -0
- package/dist/index.d.cts +1511 -0
- package/dist/index.d.ts +1511 -0
- package/dist/index.js +954 -0
- package/package.json +52 -0
package/README.md
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
# @lexapi/client (TypeScript)
|
|
2
|
+
|
|
3
|
+
Official TypeScript SDK for [LexAPI](https://lex-api.com) — European legal data, made queryable. EUR-Lex, CJEU case law, and the Official Journal behind one REST API.
|
|
4
|
+
|
|
5
|
+
> **Status: pre-release (0.x).** Not yet published to npm. See [PLAN.md](PLAN.md) for the endpoint coverage matrix.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @lexapi/client # not yet published
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Requires Node ≥ 18 (native `fetch`); also works on Deno, Bun, and edge runtimes. **Server-side use 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
|
+
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { LexAPI } from "@lexapi/client";
|
|
19
|
+
|
|
20
|
+
const client = new LexAPI({ apiKey: "lex_..." }); // or set LEXAPI_API_KEY
|
|
21
|
+
const info = await client.getInfo();
|
|
22
|
+
console.log(info.subscription, info.usage);
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Keys come from the [LexAPI dashboard](https://lex-api.com) and are prefixed `lex_`.
|
|
26
|
+
|
|
27
|
+
## Search & documents
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
// Structured search (POST /search)
|
|
31
|
+
const hits = await client.search({
|
|
32
|
+
query: "artificial intelligence",
|
|
33
|
+
documentType: ["communication", "guideline"],
|
|
34
|
+
dateFrom: "2025-01-01",
|
|
35
|
+
maxPages: 2,
|
|
36
|
+
});
|
|
37
|
+
if (hits.truncated) console.warn(hits.truncatedReason); // tier-capped pagination
|
|
38
|
+
if (hits.partial) console.warn(hits.partialReason); // an upstream page timed out
|
|
39
|
+
if (hits.xWarning) console.warn(hits.xWarning); // X-Warning header (e.g. maxPages clamped)
|
|
40
|
+
|
|
41
|
+
// Single document (POST /documentContent) with payload control
|
|
42
|
+
const { document } = await client.getDocument({
|
|
43
|
+
celexNumber: "32016R0679",
|
|
44
|
+
include: ["metadata", "articles"],
|
|
45
|
+
articleId: "17",
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// Batch (POST /documentContent/batch) — per-CELEX errors don't abort the batch
|
|
49
|
+
const batch = await client.getDocumentsBatch({ celexNumbers: ["32016R0679", "62018CJ0311"] });
|
|
50
|
+
if (batch.trimmed) console.warn(`clamped to ${batch.trimmedTo}: ${batch.trimmedReason}`);
|
|
51
|
+
batch.errors.forEach((e) => console.warn(`${e.celexNumber}: ${e.error}`));
|
|
52
|
+
|
|
53
|
+
// Recent documents, metadata-only reads, URL + identifier resolution
|
|
54
|
+
const recent = await client.getRecentDocuments({ days: 7, documentType: "judgment" });
|
|
55
|
+
const meta = await client.getDocumentMetadata({ celexNumber: "32016R0679" });
|
|
56
|
+
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", ... }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Truncation/partial signals are always surfaced on the result (`truncated`, `partial`, `postFilteredBy`, `trimmed`/`trimmedTo`, and `xWarning` from the `X-Warning` header) — never swallowed.
|
|
61
|
+
|
|
62
|
+
## Citations
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
await client.extractCitations("32016R0679"); // crawl + persist (idempotent)
|
|
66
|
+
const outbound = await client.getCites("32016R0679", { citationType: "repeal" });
|
|
67
|
+
const inbound = await client.getCitedBy("32016R0679", { limit: 50 });
|
|
68
|
+
|
|
69
|
+
const network = await client.getCitationNetwork("62018CJ0311", { limit: 100 });
|
|
70
|
+
if (network.partial) console.warn(network.message); // server budget expired — network is EMPTY, not zero
|
|
71
|
+
|
|
72
|
+
const path = await client.getCitationPath("32016R0679", "31995L0046", { maxDepth: 5 });
|
|
73
|
+
if (!path.found) console.log(path.message); // graceful 200, not an error
|
|
74
|
+
|
|
75
|
+
const related = await client.getRelatedDocuments("32016R0679"); // bibliographic coupling
|
|
76
|
+
const stats = await client.getCitationStats();
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Semantic search
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
// Case law (POST /search/semantic) — 5 credits
|
|
83
|
+
const hits = await client.semanticSearch({
|
|
84
|
+
query: "transfer of personal data to third countries",
|
|
85
|
+
limit: 10,
|
|
86
|
+
minScore: 0.5, // unset applies the upstream's ~0.7 relevance floor
|
|
87
|
+
includeText: true, // full document text per hit instead of ~600-char snippets
|
|
88
|
+
});
|
|
89
|
+
if (hits.hint) console.warn(hits.hint); // present only on low-confidence result sets
|
|
90
|
+
|
|
91
|
+
// HyDE query rewriting — 15 credits instead of 5, ~1-3s extra latency.
|
|
92
|
+
// Best-effort: on LLM failure it falls back to plain retrieval, the response
|
|
93
|
+
// reports hyde: false, and the 10-credit premium is refunded automatically.
|
|
94
|
+
const hyde = await client.semanticSearch({ query: "credit scoring article 22", hyde: true });
|
|
95
|
+
console.log(hyde.hyde, hyde.hypotheticalDocument, hyde.credits?.operation_weight);
|
|
96
|
+
|
|
97
|
+
// Legislation (POST /legislation/semantic) — article-level matches; no hyde option
|
|
98
|
+
const articles = await client.semanticLegislationSearch({ query: "right to be forgotten" });
|
|
99
|
+
console.log(articles.results[0]?.article_ref, articles.results[0]?.law_id);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Persistent identity for case-law hits is `(metadata.celex_id, metadata.document_type)` — `case_id` is snapshot-scoped and does not survive index rebuilds.
|
|
103
|
+
|
|
104
|
+
## Webhooks
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
const created = await client.webhooks.create({
|
|
108
|
+
name: "New CJEU judgments",
|
|
109
|
+
url: "https://example.com/webhooks/lexapi",
|
|
110
|
+
searchCriteria: { documentType: "judgment", author: ["court-of-justice"] },
|
|
111
|
+
});
|
|
112
|
+
console.log(created.webhook.secret); // returned ONLY here — store it (HMAC-SHA256 signing key)
|
|
113
|
+
|
|
114
|
+
const { webhooks } = await client.webhooks.list();
|
|
115
|
+
const detail = await client.webhooks.get(created.webhook.id); // includes recentDeliveries
|
|
116
|
+
await client.webhooks.update(created.webhook.id, { status: "ACTIVE" }); // resets consecutiveFailures
|
|
117
|
+
await client.webhooks.test(created.webhook.id); // synchronous signed test delivery
|
|
118
|
+
const history = await client.webhooks.deliveries(created.webhook.id, { limit: 50 });
|
|
119
|
+
await client.webhooks.delete(created.webhook.id); // 204 → resolves void
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Corpus export (BUSINESS tier)
|
|
123
|
+
|
|
124
|
+
`export()` streams NDJSON rows via the fetch body stream — constant memory regardless of result size:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
const stream = await client.export({ documentType: "regulation", dateFrom: "2024-01-01", limit: 10_000 });
|
|
128
|
+
|
|
129
|
+
console.log(stream.meta); // leading _meta envelope (parsed before iteration)
|
|
130
|
+
console.log(stream.headers.total); // X-Export-Total header
|
|
131
|
+
|
|
132
|
+
for await (const row of stream) {
|
|
133
|
+
process(row.celex, row.documentTypeCode, row.parsedContent);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
console.log(stream.done); // trailing _done line (available after iteration)
|
|
137
|
+
if (stream.done?.truncated) console.warn("row cap hit — narrow filters or resume via fetchedSince");
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The `_meta`/`_done` envelope lines are never yielded as rows; the stream is single-pass.
|
|
141
|
+
|
|
142
|
+
## Configuration
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
const client = new LexAPI({
|
|
146
|
+
apiKey: "lex_...", // or LEXAPI_API_KEY env var
|
|
147
|
+
baseUrl: "https://lex-api.com/api/v1", // default
|
|
148
|
+
timeoutMs: 60_000, // per attempt; per-call override: client.getInfo({ timeoutMs: 5_000 })
|
|
149
|
+
retry: { maxRetries: 3, baseDelayMs: 500, maxDelayMs: 30_000 },
|
|
150
|
+
fetch: myFetch, // injectable transport (testing / polyfills)
|
|
151
|
+
userAgentSuffix: "my-app/1.0", // appended to `lexapi-typescript/<version>`
|
|
152
|
+
});
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Retries
|
|
156
|
+
|
|
157
|
+
Failed requests are retried up to 3 times (configurable via `retry`) with exponential backoff + full jitter:
|
|
158
|
+
|
|
159
|
+
- **Retried:** HTTP 429, 502, 503, 504 and transport-level network errors.
|
|
160
|
+
- **Server-directed waits win:** the `Retry-After` response **header** is honored first (then `RateLimit-Reset`, then the JSON `retryAfter` body field — epoch-guarded, since that field historically carried buggy absolute timestamps).
|
|
161
|
+
- **Non-idempotent safety:** non-GET requests are retried **only on 429** — never on 5xx or network errors, where the request may already have been applied.
|
|
162
|
+
- Client-side timeouts throw `TimeoutError` and are not retried.
|
|
163
|
+
|
|
164
|
+
## Typed errors
|
|
165
|
+
|
|
166
|
+
Every non-2xx response maps to a typed error carrying `code`, `status`, `details`, and `retryAfter`:
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { CreditsExhaustedError, NotFoundError, RateLimitedError } from "@lexapi/client";
|
|
170
|
+
|
|
171
|
+
try {
|
|
172
|
+
await client.getInfo();
|
|
173
|
+
} catch (err) {
|
|
174
|
+
if (err instanceof RateLimitedError) console.log(`retry in ${err.retryAfter}s`);
|
|
175
|
+
else if (err instanceof CreditsExhaustedError) console.log(`credits reset at ${err.resetsAt}`);
|
|
176
|
+
else if (err instanceof NotFoundError) console.log("no such document");
|
|
177
|
+
else throw err;
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Subclasses: `NotFoundError`, `InvalidCelexError`, `InvalidUrlError`, `InvalidParamsError`, `AuthenticationError` (401), `RateLimitedError`, `TierForbiddenError`, `CreditsExhaustedError`, `UpstreamError`, `TimeoutError`, `InternalServerError`, `NetworkError`. Both the typed envelope (`{success: false, error: {code, message, details}}`) and the legacy bare `{error, message}` shape are parsed; unknown codes stay on the base `LexAPIError` with the raw code string.
|
|
182
|
+
|
|
183
|
+
## Credit visibility
|
|
184
|
+
|
|
185
|
+
Every response keeps its raw `usage` / `credits` blocks; `getCreditUsage` normalizes them:
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { getCreditUsage } from "@lexapi/client";
|
|
189
|
+
|
|
190
|
+
const info = await client.getInfo();
|
|
191
|
+
const { unitsCharged, creditsRemaining, resetsAt } = getCreditUsage(info);
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
`unitsCharged` maps `credits.operation_weight` (0 for free ops like `/info`); `creditsRemaining` falls back to `usage.remaining` on legacy daily-call accounts.
|
|
195
|
+
|
|
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
|
+
## Development
|
|
217
|
+
|
|
218
|
+
```bash
|
|
219
|
+
npm install
|
|
220
|
+
npm run lint # tsc --noEmit (strict)
|
|
221
|
+
npm test # vitest
|
|
222
|
+
npm run build # tsup -> dist/ (ESM + CJS + d.ts)
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Zero runtime dependencies. Docs: <https://lex-api.com/docs>
|