@lexapi/client 0.2.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/dist/index.js CHANGED
@@ -50,7 +50,8 @@ var LexAPIError = class _LexAPIError extends Error {
50
50
  /** The `error.details` object from the typed envelope, when present. */
51
51
  details;
52
52
  /**
53
- * Seconds to wait before retrying, when the server said so (429).
53
+ * Seconds to wait before retrying, when the server said so (429; also the
54
+ * 503 of an incomplete national semantic search).
54
55
  * Sourced from the `Retry-After` response HEADER first; the JSON
55
56
  * `retryAfter` body field is only a fallback because it historically
56
57
  * carried buggy epoch-seconds values (epoch-looking values are
@@ -114,7 +115,7 @@ var LexAPIError = class _LexAPIError extends Error {
114
115
  if (typeof record["message"] === "string") message = record["message"];
115
116
  details = record["details"];
116
117
  }
117
- if (retryAfter === void 0 && status === 429) {
118
+ if (retryAfter === void 0 && (status === 429 || status === 503 && code === "NATIONAL_SEMANTIC_UNAVAILABLE")) {
118
119
  const jsonRetryAfter = readNumber(record["retryAfter"]) ?? readNumber(detailsField(details, "retryAfter"));
119
120
  if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
120
121
  }
@@ -149,6 +150,16 @@ var LexAPIError = class _LexAPIError extends Error {
149
150
  return new TierForbiddenError(message, status, details, retryAfter, context);
150
151
  case "CREDITS_EXHAUSTED":
151
152
  return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt, context);
153
+ case "NATIONAL_ALLOWANCE_EXHAUSTED":
154
+ return new NationalAllowanceExhaustedError(message, status, details, retryAfter, context);
155
+ case "NATIONAL_SEMANTIC_NOT_ENABLED":
156
+ return new NationalSemanticNotEnabledError(message, status, details, retryAfter, context);
157
+ case "NATIONAL_SEMANTIC_UNAVAILABLE":
158
+ return new NationalSemanticUnavailableError(message, status, details, retryAfter, context);
159
+ case "NATIONAL_SEMANTIC_FILTER_UNREACHABLE":
160
+ return new NationalSemanticFilterUnreachableError(message, status, details, retryAfter, context);
161
+ case "DOCUMENT_WITHDRAWN":
162
+ return new DocumentWithdrawnError(message, status, details, retryAfter, context);
152
163
  case "UPSTREAM_ERROR":
153
164
  return new UpstreamError(message, status, details, retryAfter, context);
154
165
  case "TIMEOUT":
@@ -187,10 +198,27 @@ var InvalidUrlError = class extends LexAPIError {
187
198
  };
188
199
  var InvalidParamsError = class extends LexAPIError {
189
200
  static kind = "InvalidParamsError";
190
- constructor(message, status = 400, details, retryAfter, context) {
191
- super("INVALID_PARAMS", message, status, details, retryAfter, context);
201
+ constructor(message, status = 400, details, retryAfter, context, code = "INVALID_PARAMS") {
202
+ super(code, message, status, details, retryAfter, context);
192
203
  this.name = "InvalidParamsError";
193
204
  }
205
+ /**
206
+ * The parameter that was refused, when the server names it — e.g. an
207
+ * unknown citation-graph filter value (API 2.11.0). Read from `details`
208
+ * (typed envelope) or the top level of the body (legacy shape).
209
+ */
210
+ get param() {
211
+ return readString(detailsOrBodyField(this.details, this.body, "param"));
212
+ }
213
+ /** The refused value of {@link param}, when the server echoes it. */
214
+ get value() {
215
+ return detailsOrBodyField(this.details, this.body, "value");
216
+ }
217
+ /** The allowed values of {@link param}, when the server lists them (may be empty). */
218
+ get allowed() {
219
+ const value = detailsOrBodyField(this.details, this.body, "allowed");
220
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : void 0;
221
+ }
194
222
  };
195
223
  var AuthenticationError = class extends LexAPIError {
196
224
  static kind = "AuthenticationError";
@@ -255,6 +283,33 @@ var CreditsExhaustedError = class extends LexAPIError {
255
283
  return readString(this.details?.operation);
256
284
  }
257
285
  };
286
+ var NationalAllowanceExhaustedError = class extends LexAPIError {
287
+ static kind = "NationalAllowanceExhaustedError";
288
+ constructor(message, status = 402, details, retryAfter, context) {
289
+ super("NATIONAL_ALLOWANCE_EXHAUSTED", message, status, details, retryAfter, context);
290
+ this.name = "NationalAllowanceExhaustedError";
291
+ }
292
+ /** The jurisdiction code of the refused call (`details.jurisdiction`). */
293
+ get jurisdiction() {
294
+ return readString(this.details?.jurisdiction);
295
+ }
296
+ /** The tier's monthly allowance of national calls (`details.limit`). */
297
+ get limit() {
298
+ return readNumber(this.details?.limit);
299
+ }
300
+ /** Always `0` (`details.remaining`). */
301
+ get remaining() {
302
+ return readNumber(this.details?.remaining);
303
+ }
304
+ /** When the allowance resets (`details.resetsAt`, ISO date-time). */
305
+ get resetsAt() {
306
+ return readString(this.details?.resetsAt);
307
+ }
308
+ /** `/pricing` (`details.upgradeUrl`). */
309
+ get upgradeUrl() {
310
+ return readString(this.details?.upgradeUrl);
311
+ }
312
+ };
258
313
  var UpstreamError = class extends LexAPIError {
259
314
  static kind = "UpstreamError";
260
315
  constructor(message, status = 502, details, retryAfter, context) {
@@ -268,14 +323,92 @@ var TimeoutError = class extends LexAPIError {
268
323
  super(status === 0 ? "REQUEST_TIMEOUT" : "TIMEOUT", message, status, details, retryAfter, context);
269
324
  this.name = "TimeoutError";
270
325
  }
326
+ /** `true` when the server answered a budget timeout with `partial: true` (nothing else was returned). */
327
+ get partial() {
328
+ const value = bodyField(this.body, "partial");
329
+ return typeof value === "boolean" ? value : void 0;
330
+ }
331
+ /** The server-side budget that expired, in ms, when the body reports it. */
332
+ get serverTimeoutMs() {
333
+ return readNumber(bodyField(this.body, "timeoutMs"));
334
+ }
271
335
  };
272
336
  var ServiceUnavailableError = class extends LexAPIError {
273
337
  static kind = "ServiceUnavailableError";
274
- constructor(message, status = 503, details, retryAfter, context) {
275
- super("SERVICE_UNAVAILABLE", message, status, details, retryAfter, context);
338
+ constructor(message, status = 503, details, retryAfter, context, code = "SERVICE_UNAVAILABLE") {
339
+ super(code, message, status, details, retryAfter, context);
276
340
  this.name = "ServiceUnavailableError";
277
341
  }
278
342
  };
343
+ var NationalSemanticNotEnabledError = class extends LexAPIError {
344
+ static kind = "NationalSemanticNotEnabledError";
345
+ constructor(message, status = 409, details, retryAfter, context) {
346
+ super("NATIONAL_SEMANTIC_NOT_ENABLED", message, status, details, retryAfter, context);
347
+ this.name = "NationalSemanticNotEnabledError";
348
+ }
349
+ /** ISO 3166-1 alpha-2 jurisdiction code (top-level `jurisdiction` on the raw body). */
350
+ get jurisdiction() {
351
+ return readString(bodyField(this.body, "jurisdiction"));
352
+ }
353
+ };
354
+ var NationalSemanticUnavailableError = class extends ServiceUnavailableError {
355
+ static kind = "NationalSemanticUnavailableError";
356
+ constructor(message, status = 503, details, retryAfter, context) {
357
+ super(message, status, details, retryAfter, context, "NATIONAL_SEMANTIC_UNAVAILABLE");
358
+ this.name = "NationalSemanticUnavailableError";
359
+ }
360
+ get jurisdiction() {
361
+ return readString(bodyField(this.body, "jurisdiction"));
362
+ }
363
+ /**
364
+ * `"SEARCH_INCOMPLETE"` when the index could not complete this search for a
365
+ * temporary reason and there was nothing left to return (an empty answer
366
+ * would not have meant "no matches"). `retryAfter` is then the wait the
367
+ * server asked for — absent once the same search has repeatedly come back
368
+ * incomplete (try again later, or rephrase or narrow it). `undefined` on
369
+ * the plain "index unavailable" 503.
370
+ */
371
+ get partialReason() {
372
+ return readString(detailsOrBodyField(this.details, this.body, "partialReason"));
373
+ }
374
+ };
375
+ var NationalSemanticFilterUnreachableError = class extends InvalidParamsError {
376
+ static kind = "NationalSemanticFilterUnreachableError";
377
+ constructor(message, status = 422, details, retryAfter, context) {
378
+ super(message, status, details, retryAfter, context, "NATIONAL_SEMANTIC_FILTER_UNREACHABLE");
379
+ this.name = "NationalSemanticFilterUnreachableError";
380
+ }
381
+ get jurisdiction() {
382
+ return readString(bodyField(this.body, "jurisdiction"));
383
+ }
384
+ /** `"SEARCH_INCOMPLETE"`. */
385
+ get partialReason() {
386
+ return readString(detailsOrBodyField(this.details, this.body, "partialReason"));
387
+ }
388
+ };
389
+ var DocumentWithdrawnError = class extends LexAPIError {
390
+ static kind = "DocumentWithdrawnError";
391
+ constructor(message, status = 410, details, retryAfter, context) {
392
+ super("DOCUMENT_WITHDRAWN", message, status, details, retryAfter, context);
393
+ this.name = "DocumentWithdrawnError";
394
+ }
395
+ field(key) {
396
+ const fromDetails = detailsField(this.details, key);
397
+ return fromDetails !== void 0 ? fromDetails : bodyField(this.body, key);
398
+ }
399
+ /** The withdrawn document's id (e.g. `AT-NOR-10001597`). */
400
+ get id() {
401
+ return readString(this.field("id"));
402
+ }
403
+ /** Upper-case jurisdiction code. */
404
+ get jurisdiction() {
405
+ return readString(this.field("jurisdiction"));
406
+ }
407
+ /** ISO date-time the source withdrew the document; `undefined` when unknown. */
408
+ get withdrawnAt() {
409
+ return readString(this.field("withdrawnAt"));
410
+ }
411
+ };
279
412
  var InternalServerError = class extends LexAPIError {
280
413
  static kind = "InternalServerError";
281
414
  constructor(message, status = 500, details, retryAfter, context) {
@@ -353,6 +486,10 @@ function isQuota429(body, headers) {
353
486
  if (headers?.retryAfter !== void 0 && headers.retryAfter.trim() !== "") return false;
354
487
  return detailsField(body, "retryAfter") === void 0;
355
488
  }
489
+ function detailsOrBodyField(details, body, key) {
490
+ const fromDetails = detailsField(details, key);
491
+ return fromDetails !== void 0 ? fromDetails : bodyField(body, key);
492
+ }
356
493
  function bodyField(body, key) {
357
494
  return detailsField(body, key);
358
495
  }
@@ -414,13 +551,18 @@ function parseResponseHeaders(source) {
414
551
  remaining: int(h, "ratelimit-remaining"),
415
552
  reset: int(h, "ratelimit-reset"),
416
553
  policy: str(h, "ratelimit-policy")
554
+ }),
555
+ nationalAllowance: compact({
556
+ limit: int(h, "x-national-limit"),
557
+ remaining: int(h, "x-national-remaining"),
558
+ resetsAt: str(h, "x-national-reset")
417
559
  })
418
560
  };
419
561
  return compact(parsed) ?? {};
420
562
  }
421
563
 
422
564
  // src/version.ts
423
- var VERSION = "0.2.0";
565
+ var VERSION = "0.4.0";
424
566
 
425
567
  // src/http.ts
426
568
  var DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
@@ -551,6 +693,7 @@ var HttpClient = class {
551
693
  headers["content-type"] = "application/json";
552
694
  serializedBody = JSON.stringify(body);
553
695
  }
696
+ let incompleteRetried = false;
554
697
  for (let attempt = 0; ; attempt++) {
555
698
  throwIfAborted(signal, method, path);
556
699
  const controller = new AbortController();
@@ -602,7 +745,9 @@ var HttpClient = class {
602
745
  await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs), signal, method, path);
603
746
  continue;
604
747
  }
605
- if (attempt < maxRetries && shouldRetryStatus(error, { isGet, free, readOnly: options.idempotent === true && retryReadOnlyPosts })) {
748
+ const incomplete = error.status === 503 && isSearchIncomplete(error);
749
+ if (attempt < maxRetries && !(incomplete && incompleteRetried) && shouldRetryStatus(error, { isGet, free, readOnly: options.idempotent === true && retryReadOnlyPosts })) {
750
+ if (incomplete) incompleteRetried = true;
606
751
  const waitMs = error.retryAfter !== void 0 ? Math.min(error.retryAfter * 1e3, maxDelayMs) : fullJitterBackoff(attempt, baseDelayMs, maxDelayMs);
607
752
  await sleep(waitMs, signal, method, path);
608
753
  continue;
@@ -613,6 +758,8 @@ var HttpClient = class {
613
758
  };
614
759
  function shouldRetryStatus(error, call) {
615
760
  const status = error.status;
761
+ if (status === 503 && isBudgetTimeout(error.body)) return false;
762
+ if (status === 503 && isSearchIncomplete(error) && error.retryAfter === void 0) return false;
616
763
  if (status === 429) return !(error instanceof RateLimitedError && error.quotaExhausted);
617
764
  if (NEVER_REACHED_STATUSES.has(status)) return true;
618
765
  if (ORIGIN_DEPENDENT_STATUSES.has(status)) {
@@ -622,6 +769,13 @@ function shouldRetryStatus(error, call) {
622
769
  if (PROXY_STATUSES.has(status)) return call.free;
623
770
  return false;
624
771
  }
772
+ function isBudgetTimeout(body) {
773
+ return typeof body === "object" && body !== null && body["partialReason"] === "TIMEOUT";
774
+ }
775
+ function isSearchIncomplete(error) {
776
+ const field = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v["partialReason"] : void 0;
777
+ return (field(error.details) ?? field(error.body)) === "SEARCH_INCOMPLETE";
778
+ }
625
779
  async function readBodyText(response, touch) {
626
780
  if (response.body === null || touch === void 0) return response.text();
627
781
  const reader = response.body.getReader();
@@ -1400,12 +1554,24 @@ var LexAPI = class {
1400
1554
  * `GET /citations/cites/{celexNumber}` — documents this one cites
1401
1555
  * (outbound edges), grouped by target. The document must first have been
1402
1556
  * crawled via `extractCitations` to appear here. 1 credit.
1557
+ *
1558
+ * `celexNumber` may be a national document id (e.g. `AT-NOR-10001597`);
1559
+ * `params.includeNational` also pulls in national neighbours of live
1560
+ * jurisdictions — BUSINESS, SCALE and ENTERPRISE only (`403
1561
+ * TierForbiddenError` below that, refunded in full). A national id whose
1562
+ * jurisdiction is not live is `404 NotFoundError`.
1563
+ *
1564
+ * Filters (API 2.11.0): `citationType`, `provenance`, `jurisdictions` and
1565
+ * `resolution` each take one value or a list (sent comma-separated). On a
1566
+ * national id, `unresolved: true` also returns the references the
1567
+ * document records that could not be turned into an edge
1568
+ * (`unresolved` / `unresolvedTruncated`), at no extra cost.
1403
1569
  */
1404
1570
  async getCites(celexNumber, params = {}, options) {
1405
1571
  return this.call({
1406
1572
  method: "GET",
1407
1573
  path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
1408
- query: edgeQuery(params),
1574
+ query: { ...edgeQuery(params), unresolved: params.unresolved },
1409
1575
  timeoutMs: options?.timeoutMs,
1410
1576
  signal: options?.signal
1411
1577
  });
@@ -1415,6 +1581,10 @@ var LexAPI = class {
1415
1581
  * (inbound edges), grouped by source. 1 credit. For legislation, inbound
1416
1582
  * amendment / corrigendum / repeal edges are refreshed from Cellar when
1417
1583
  * older than 7 days (waits ≤ ~2.5 s) — see `relationSync`.
1584
+ *
1585
+ * `celexNumber` may be a national document id; `params.includeNational`
1586
+ * also pulls in national neighbours of live jurisdictions — BUSINESS+
1587
+ * only (`403 TierForbiddenError` below that). Filters as on `getCites`.
1418
1588
  */
1419
1589
  async getCitedBy(celexNumber, params = {}, options) {
1420
1590
  return this.call({
@@ -1461,16 +1631,22 @@ var LexAPI = class {
1461
1631
  * If the server-side wall-clock budget expires the endpoint still
1462
1632
  * returns 200 with `partial: true`, an EMPTY `network`, and `null`
1463
1633
  * paging totals — check `partial` before treating the network as empty.
1634
+ *
1635
+ * `celexNumber` may be a national document id; `params.includeNational`
1636
+ * also pulls in national neighbours of live jurisdictions — BUSINESS+
1637
+ * only (`403 TierForbiddenError` below that). See `getCites`.
1464
1638
  */
1465
1639
  async getCitationNetwork(celexNumber, params = {}, options) {
1466
1640
  return this.call({
1467
1641
  method: "GET",
1468
1642
  path: `/citations/network/${encodeURIComponent(celexNumber)}`,
1469
1643
  query: {
1470
- citationType: params.citationType,
1644
+ ...filterQuery(params),
1471
1645
  limit: params.limit,
1472
1646
  offset: params.offset,
1473
- language: params.language
1647
+ language: params.language,
1648
+ includeNational: params.includeNational,
1649
+ unresolved: params.unresolved
1474
1650
  },
1475
1651
  timeoutMs: options?.timeoutMs,
1476
1652
  signal: options?.signal
@@ -1481,12 +1657,21 @@ var LexAPI = class {
1481
1657
  * outbound edges). 20 credits. `found: false` is a graceful HTTP 200,
1482
1658
  * not an error. Default `maxDepth` 3 (max 8); the visited set is bounded
1483
1659
  * to 5000 nodes.
1660
+ *
1661
+ * `from`/`to` may be national document ids; `params.includeNational` also
1662
+ * follows national documents of live jurisdictions along the way —
1663
+ * BUSINESS+ only (`403 TierForbiddenError` below that). See `getCites`.
1484
1664
  */
1485
1665
  async getCitationPath(from, to, params = {}, options) {
1486
1666
  return this.call({
1487
1667
  method: "GET",
1488
1668
  path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
1489
- query: { maxDepth: params.maxDepth, language: params.language },
1669
+ query: {
1670
+ ...filterQuery(params),
1671
+ maxDepth: params.maxDepth,
1672
+ language: params.language,
1673
+ includeNational: params.includeNational
1674
+ },
1490
1675
  timeoutMs: options?.timeoutMs,
1491
1676
  signal: options?.signal
1492
1677
  });
@@ -1496,21 +1681,247 @@ var LexAPI = class {
1496
1681
  * neighbours (documents sharing the most outbound citation targets with
1497
1682
  * the seed). 20 credits. Returns a graceful empty list with `message`
1498
1683
  * when the seed has no outbound citations to couple on.
1684
+ *
1685
+ * `celexNumber` may be a national document id; `params.includeNational`
1686
+ * also considers national documents of live jurisdictions — BUSINESS+
1687
+ * only (`403 TierForbiddenError` below that). See `getCites`.
1499
1688
  */
1500
1689
  async getRelatedDocuments(celexNumber, params = {}, options) {
1501
1690
  return this.call({
1502
1691
  method: "GET",
1503
1692
  path: `/citations/related/${encodeURIComponent(celexNumber)}`,
1504
- query: { limit: params.limit, language: params.language },
1693
+ query: {
1694
+ ...filterQuery(params),
1695
+ limit: params.limit,
1696
+ language: params.language,
1697
+ includeNational: params.includeNational
1698
+ },
1505
1699
  timeoutMs: options?.timeoutMs,
1506
1700
  signal: options?.signal
1507
1701
  });
1508
1702
  }
1509
- /** `GET /citations/stats` — global citation graph statistics. 20 credits. */
1510
- async getCitationStats(options) {
1703
+ async getCitationStats(params, options) {
1704
+ let effectiveParams;
1705
+ let effectiveOptions;
1706
+ if (isLegacyCitationStatsCallOptions(params)) {
1707
+ effectiveOptions = params;
1708
+ } else {
1709
+ effectiveParams = params;
1710
+ effectiveOptions = options;
1711
+ }
1511
1712
  return this.call({
1512
1713
  method: "GET",
1513
1714
  path: "/citations/stats",
1715
+ query: { includeNational: effectiveParams?.includeNational },
1716
+ timeoutMs: effectiveOptions?.timeoutMs,
1717
+ signal: effectiveOptions?.signal
1718
+ });
1719
+ }
1720
+ /**
1721
+ * `GET /citations/transposition/{celexNumber}` — the measures the member
1722
+ * states notified to the Commission for an EU act (CELEX sector 3),
1723
+ * grouped by country, from the Publications Office's Cellar records of the
1724
+ * notifications (API 2.11.0). **A notification is not a finding that the
1725
+ * measure transposes the act, or transposes it completely** — `note` says
1726
+ * so on every answer. 5 credits, every plan; a 5xx is refunded.
1727
+ *
1728
+ * On BUSINESS, SCALE and ENTERPRISE, for live jurisdictions, the answer
1729
+ * also says which measures LexAPI holds (`id`, `resolved`, `resolution`,
1730
+ * `resolutionBasis`, `counts.resolved`, `source.lanes`) and adds the
1731
+ * documents whose national source records that they transpose or
1732
+ * implement the act (`provenance: "source"`); `resolvedOnly: true` keeps
1733
+ * only the held ones. Below BUSINESS, for a jurisdiction that is not live,
1734
+ * and while the national-source terms are not accepted (`termsRequired:
1735
+ * true` — never a 403) those fields are `null`.
1736
+ *
1737
+ * A CELEX that is not an EU act (sector 3) is `404 NotFoundError`.
1738
+ */
1739
+ async getTransposition(celexNumber, params = {}, options) {
1740
+ return this.call({
1741
+ method: "GET",
1742
+ path: `/citations/transposition/${encodeURIComponent(celexNumber)}`,
1743
+ query: {
1744
+ jurisdictions: listParam(params.jurisdictions),
1745
+ resolvedOnly: params.resolvedOnly,
1746
+ language: params.language
1747
+ },
1748
+ timeoutMs: options?.timeoutMs,
1749
+ signal: options?.signal
1750
+ });
1751
+ }
1752
+ /**
1753
+ * `GET /citations/counterparts/{id}` — a national document's counterparts
1754
+ * in the other live jurisdictions, through the EU acts it transposes or
1755
+ * implements (API 2.11.0). Each `via[]` entry is one EU act, with the
1756
+ * other jurisdictions' measures for it ranked `1` (the national source
1757
+ * records the relation), `2` (a notified measure LexAPI holds) or `3` (a
1758
+ * notified Cellar record LexAPI does not hold, `id: null`). An EU act
1759
+ * CELEX as `id` lists its own measures the same way.
1760
+ *
1761
+ * **20 credits; BUSINESS, SCALE and ENTERPRISE only** (`403
1762
+ * TierForbiddenError` below that, refunded). A lookup past its 20-second
1763
+ * server-side budget throws `TimeoutError` (503, `err.partial === true`),
1764
+ * refunded. The SDK does not retry it (the same lookup would hit the same
1765
+ * budget); retry yourself, or narrow with `jurisdictions`.
1766
+ */
1767
+ async getCounterparts(id, params = {}, options) {
1768
+ return this.call({
1769
+ method: "GET",
1770
+ path: `/citations/counterparts/${encodeURIComponent(id)}`,
1771
+ query: {
1772
+ jurisdictions: listParam(params.jurisdictions),
1773
+ language: params.language
1774
+ },
1775
+ timeoutMs: options?.timeoutMs,
1776
+ signal: options?.signal
1777
+ });
1778
+ }
1779
+ // ── National law ──────────────────────────────────────────────────
1780
+ // Member-state (and non-EU) legal orders alongside EUR-Lex. BUSINESS and
1781
+ // above get full access; FREE/STARTER/PROFESSIONAL get it within a
1782
+ // monthly allowance of national calls (`X-National-Limit`/
1783
+ // `X-National-Remaining`/`X-National-Reset`, `result.headers.nationalAllowance`;
1784
+ // a used-up allowance is `NationalAllowanceExhaustedError`, 402). An
1785
+ // unlaunched or unknown jurisdiction answers 404 exactly like a path that
1786
+ // doesn't exist — call `getNationalCoverage()` first.
1787
+ /**
1788
+ * `GET /national/coverage` — which jurisdictions are live, what each one
1789
+ * covers (legislation / case law, semantic search, sources with their
1790
+ * attribution), and when each was last synced. Public: no API key or
1791
+ * allowance required, free.
1792
+ */
1793
+ async getNationalCoverage(options) {
1794
+ return this.call({
1795
+ method: "GET",
1796
+ path: "/national/coverage",
1797
+ free: true,
1798
+ timeoutMs: options?.timeoutMs,
1799
+ signal: options?.signal
1800
+ });
1801
+ }
1802
+ /**
1803
+ * `GET /{jurisdiction}/documents/{id}` — one national document by its
1804
+ * corpus id (e.g. `"AT-NOR-12345"`), analogous to `getDocument`.
1805
+ *
1806
+ * **Cost: 1 credit** — every national read is a corpus read (there is no
1807
+ * live-fetch fallback), so the 5-credit upfront reservation always
1808
+ * settles to 1 (an unknown id too). Check
1809
+ * `document.textAvailability.available` before reading `content`, and
1810
+ * always show `document.attribution` to the user alongside the text.
1811
+ * The document has one shape for every jurisdiction (API 2.8.0):
1812
+ * `documentKind` (`act` | `decision`), `decision` (court, chamber,
1813
+ * caseNumbers, citedNorms — `null` for acts; see `isNationalDecision`)
1814
+ * and the closed `content` key set.
1815
+ *
1816
+ * A document its source withdrew (a takedown, a pseudonymisation fix)
1817
+ * throws `DocumentWithdrawnError` (410) instead of answering — nothing of
1818
+ * it is served, not even the title; drop any copy you hold.
1819
+ */
1820
+ async getNationalDocument(jurisdiction, id, params = {}, options) {
1821
+ return this.call({
1822
+ method: "GET",
1823
+ path: `/${jurisdictionSegment(jurisdiction)}/documents/${encodeURIComponent(id)}`,
1824
+ query: { language: params.language },
1825
+ timeoutMs: options?.timeoutMs,
1826
+ signal: options?.signal
1827
+ });
1828
+ }
1829
+ /**
1830
+ * `GET /{jurisdiction}/documents` — browse a jurisdiction's corpus by
1831
+ * title (`q`), type, and in-force status. Newest-first by the document's
1832
+ * own date.
1833
+ *
1834
+ * **Cost: 3 credits per call** — flat; pagination does not multiply the
1835
+ * price, unlike `search`. **Paging:** `page` only reaches the first 1,000
1836
+ * rows (a 400 past that); page further with `cursor` (each response's
1837
+ * `nextCursor`), which works at any depth — see
1838
+ * `paginateNationalDocuments` for a ready-made walk. A slow page is a
1839
+ * retry-safe `TimeoutError` (504, refunded); the `total` count is capped
1840
+ * at 10,000 and flagged `totalExact: false` past that or on a slow count.
1841
+ */
1842
+ async listNationalDocuments(jurisdiction, params = {}, options) {
1843
+ return this.call({
1844
+ method: "GET",
1845
+ path: `/${jurisdictionSegment(jurisdiction)}/documents`,
1846
+ query: {
1847
+ page: params.page,
1848
+ cursor: params.cursor,
1849
+ limit: params.limit,
1850
+ q: params.q,
1851
+ type: params.documentType,
1852
+ includeRepealed: params.includeRepealed
1853
+ },
1854
+ timeoutMs: options?.timeoutMs,
1855
+ signal: options?.signal
1856
+ });
1857
+ }
1858
+ /**
1859
+ * Walk every page of `listNationalDocuments` via `cursor` (works past the
1860
+ * 1,000-row `page` ceiling, unlike passing `page` yourself). Each page is
1861
+ * a separate billed call. Stops after a page with `hasMore: false` (or an
1862
+ * empty page). Any `params.page` is ignored and never sent — pass
1863
+ * `params.cursor` only to resume a walk you saved partway through;
1864
+ * `page` together with `cursor` is a 400 ("Use either cursor or page,
1865
+ * not both"), so this strips `page` at runtime, not just in the type
1866
+ * (`Omit` alone only guards TypeScript callers — a JS caller, or one
1867
+ * using `as`, could otherwise still pass it through).
1868
+ */
1869
+ async *paginateNationalDocuments(jurisdiction, params = {}, options) {
1870
+ const { page: _ignoredPage, ...rest } = params;
1871
+ let cursor = rest.cursor;
1872
+ for (; ; ) {
1873
+ const page = await this.listNationalDocuments(
1874
+ jurisdiction,
1875
+ cursor !== void 0 ? { ...rest, cursor } : { ...rest },
1876
+ options
1877
+ );
1878
+ yield page;
1879
+ if (!page.hasMore || !page.nextCursor || page.results.length === 0) return;
1880
+ cursor = page.nextCursor;
1881
+ }
1882
+ }
1883
+ /**
1884
+ * `POST /{jurisdiction}/search/semantic` — embedding-based semantic
1885
+ * search over a jurisdiction's case law. Same request/response shape as
1886
+ * `semanticSearch`, plus `jurisdiction`/`documentId`/`attribution` and
1887
+ * `document` (the matched decision as the listing returns it — the same
1888
+ * fields in every jurisdiction, API 2.8.0) on every hit.
1889
+ *
1890
+ * **Cost: a flat 5 credits** — `hyde` is accepted but never changes the
1891
+ * price or the billing tier here: the national index never rewrites, so
1892
+ * the response reports `hyde: false` (never `true`) when requested.
1893
+ */
1894
+ async nationalSemanticSearch(jurisdiction, request, options) {
1895
+ return this.call({
1896
+ method: "POST",
1897
+ path: `/${jurisdictionSegment(jurisdiction)}/search/semantic`,
1898
+ body: nationalSemanticWireBody(request),
1899
+ idempotent: true,
1900
+ timeoutMs: options?.timeoutMs,
1901
+ signal: options?.signal
1902
+ });
1903
+ }
1904
+ /**
1905
+ * `POST /{jurisdiction}/legislation/semantic` — embedding-based semantic
1906
+ * search over a jurisdiction's legislation; article-level matches. Same
1907
+ * shape as `semanticLegislationSearch`, plus `jurisdiction`/`documentId`/
1908
+ * `attribution` and `document` (the matched act's listing summary) on
1909
+ * every hit; the index fields (`law_title`, `article_ref`, `section`,
1910
+ * `language`, `in_force`, `valid_from`, `valid_to`, `law_type`) are
1911
+ * always present, `null` when the index has nothing (API 2.8.0). No `hyde`, no `asOf` — both are EU-only.
1912
+ * `NationalSemanticLegislationOptions` has no `hyde` field, and this SDK
1913
+ * never forwards one on this call even if a caller bypasses the type
1914
+ * system — the server now validates `hyde` as a boolean on this route too
1915
+ * (400 otherwise), so a stray non-boolean value would 400 for nothing.
1916
+ *
1917
+ * **Cost: 5 credits.**
1918
+ */
1919
+ async nationalLegislationSemanticSearch(jurisdiction, request, options) {
1920
+ return this.call({
1921
+ method: "POST",
1922
+ path: `/${jurisdictionSegment(jurisdiction)}/legislation/semantic`,
1923
+ body: nationalSemanticWireBody(request, { allowHyde: false }),
1924
+ idempotent: true,
1514
1925
  timeoutMs: options?.timeoutMs,
1515
1926
  signal: options?.signal
1516
1927
  });
@@ -1647,12 +2058,39 @@ function semanticWireBody(request) {
1647
2058
  if (request.asOf !== void 0) body["asOf"] = request.asOf;
1648
2059
  return body;
1649
2060
  }
2061
+ function nationalSemanticWireBody(request, { allowHyde = true } = {}) {
2062
+ const body = { query: request.query };
2063
+ if (request.limit !== void 0) body["limit"] = request.limit;
2064
+ if (request.minScore !== void 0) body["min_score"] = request.minScore;
2065
+ if (request.language !== void 0) body["language"] = request.language;
2066
+ if (request.includeText) body["include"] = ["text"];
2067
+ if (request.filters !== void 0) body["filters"] = request.filters;
2068
+ if (allowHyde && request.hyde !== void 0) body["hyde"] = request.hyde;
2069
+ return body;
2070
+ }
2071
+ function jurisdictionSegment(jurisdiction) {
2072
+ return encodeURIComponent(jurisdiction.trim().toLowerCase());
2073
+ }
2074
+ function isLegacyCitationStatsCallOptions(value) {
2075
+ if (!value || typeof value !== "object") return false;
2076
+ if ("includeNational" in value) return false;
2077
+ return "timeoutMs" in value || "signal" in value;
2078
+ }
2079
+ function filterQuery(params) {
2080
+ return {
2081
+ citationType: listParam(params.citationType),
2082
+ provenance: listParam(params.provenance),
2083
+ jurisdictions: listParam(params.jurisdictions),
2084
+ resolution: listParam(params.resolution)
2085
+ };
2086
+ }
1650
2087
  function edgeQuery(params) {
1651
2088
  return {
1652
- citationType: params.citationType,
2089
+ ...filterQuery(params),
1653
2090
  limit: params.limit,
1654
2091
  offset: params.offset,
1655
- language: params.language
2092
+ language: params.language,
2093
+ includeNational: params.includeNational
1656
2094
  };
1657
2095
  }
1658
2096
  function timestampParam(value) {
@@ -1797,6 +2235,30 @@ async function verifyWebhook(rawBody, signature, secret, options = {}) {
1797
2235
  }
1798
2236
 
1799
2237
  // src/types.ts
2238
+ var CITATION_TYPES = [
2239
+ "reference",
2240
+ "amendment",
2241
+ "repeal",
2242
+ "corrigendum",
2243
+ "implementation",
2244
+ "legal-basis",
2245
+ "proposal",
2246
+ "transposition"
2247
+ ];
2248
+ var CITATION_PROVENANCES = [
2249
+ "notice",
2250
+ "cellar",
2251
+ "notice+cellar",
2252
+ "cellar-nim",
2253
+ "source",
2254
+ "resolver"
2255
+ ];
2256
+ var CITATION_RESOLUTIONS = [
2257
+ "id",
2258
+ "key",
2259
+ "abbreviation",
2260
+ "text-pattern"
2261
+ ];
1800
2262
  var AS_OF_REASONS = [
1801
2263
  "not_yet_adopted",
1802
2264
  "not_yet_in_force",
@@ -1818,12 +2280,19 @@ var AS_OF_REASONS = [
1818
2280
  "insufficient_credits",
1819
2281
  "credit_check_failed"
1820
2282
  ];
2283
+ function isNationalDecision(document2) {
2284
+ return document2.documentKind === "decision" && document2.decision != null;
2285
+ }
1821
2286
  export {
1822
2287
  AS_OF_REASONS,
1823
2288
  AuthenticationError,
2289
+ CITATION_PROVENANCES,
2290
+ CITATION_RESOLUTIONS,
2291
+ CITATION_TYPES,
1824
2292
  CreditsExhaustedError,
1825
2293
  DEFAULT_BASE_URL,
1826
2294
  DEFAULT_TIMEOUT_MS,
2295
+ DocumentWithdrawnError,
1827
2296
  IncompleteExportError,
1828
2297
  InternalServerError,
1829
2298
  InvalidCelexError,
@@ -1832,6 +2301,10 @@ export {
1832
2301
  InvalidUrlError,
1833
2302
  LexAPI,
1834
2303
  LexAPIError,
2304
+ NationalAllowanceExhaustedError,
2305
+ NationalSemanticFilterUnreachableError,
2306
+ NationalSemanticNotEnabledError,
2307
+ NationalSemanticUnavailableError,
1835
2308
  NetworkError,
1836
2309
  NotFoundError,
1837
2310
  RateLimitedError,
@@ -1849,6 +2322,7 @@ export {
1849
2322
  computeSignature,
1850
2323
  getCreditUsage,
1851
2324
  isLexAPIError,
2325
+ isNationalDecision,
1852
2326
  normalizeRetryAfterSeconds,
1853
2327
  parseResponseHeaders,
1854
2328
  verifySignature,