@lexapi/mcp 0.3.0 → 0.5.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/server.js CHANGED
@@ -10,12 +10,14 @@ export const PACKAGE_NAME = 'lexapi-mcp';
10
10
  */
11
11
  export const SERVER_INSTRUCTIONS = `LexAPI: EU law from EUR-Lex, the CJEU and the Official Journal — legislation parsed to article level, case law, a typed citation graph and semantic search.
12
12
 
13
- Workflow: identify the act (lex_semantic_legislation / lex_semantic_case_law for concepts, lex_search for titles and filters, lex_resolve for URLs/ELI/ECLI), then read it with lex_get_document — large documents return an outline first; fetch the article you need with articleId. Amendments: lex_cited_by with citationType "amendment".
13
+ Workflow: identify the act (lex_semantic_legislation / lex_semantic_case_law for concepts, lex_search for titles and filters, lex_resolve for URLs/ELI/ECLI), then read it with lex_get_document — large documents return an outline first; fetch the article you need with articleId. Amendments: lex_cited_by with citationType "amendment". Member-state measures for an EU act: lex_transposition — these are notifications to the Commission, not findings that a measure transposes the act (or does so completely); never present them as such.
14
14
 
15
15
  Citing: always give the CELEX number (and the EUR-Lex link). Consolidated texts (CELEX 0…-YYYYMMDD, or hits labelled consolidated: true) are documentation tools without legal force — quote them, but cite the authentic act as published in the Official Journal (baseCelex). For the law on a past date use lex_semantic_legislation with asOf; trust a hit as the text in force on that date only when asOfResolved is true. For a known article on a past date when you already know the consolidated version for that date (CELEX 0…-YYYYMMDD; lex_get_metadata and textAvailability show latestConsolidated), read it directly with lex_get_document; otherwise asOf is the route that resolves the version in force. lex_document_versions / lex_get_document_version are LexAPI's fetch snapshots, not in-force law.
16
16
 
17
17
  LexAPI provides source texts; it does not decide whether anyone is compliant — leave legal conclusions to the user and their advisers.
18
18
 
19
+ National law (member-state legislation and case law): call lex_national_coverage before any other national tool — a country can be registered but not yet launched, and availability, courts and source licensing differ by country. Always carry the sources/attribution it and the national tools return through to the user; national-law calls also draw from a separate monthly allowance on some plans, reported in each tool's response. Consolidated national texts are not authentic — only the official gazette is; never try to re-identify parties a court anonymised or pseudonymised; for French decisions, never evaluate, compare or predict individual judges (art. 33, loi n° 2019-222).
20
+
19
21
  Costs come from the user's monthly credit pool and are stated in each tool description; avoid repeated or speculative calls. On a 402 (credits exhausted) or 429 (rate limit), stop and tell the user what the error says.`;
20
22
  export function createLexServer(client, opts = {}) {
21
23
  const server = new McpServer({
@@ -89,6 +91,7 @@ export function readOnlyFromEnv(env = process.env) {
89
91
  const v = (env.LEXAPI_MCP_READ_ONLY ?? '').trim().toLowerCase();
90
92
  return v === '1' || v === 'true' || v === 'yes';
91
93
  }
94
+ /** API-key requests (stdio and hosted): LEXAPI_BASE_URL exactly as 0.3.0 read it. */
92
95
  export function clientFromEnv(apiKey, env = process.env) {
93
96
  return new LexAPIClient({
94
97
  apiKey,
package/dist/shape.d.ts CHANGED
@@ -9,6 +9,15 @@ export declare function compact<T extends Obj>(o: T): Partial<T>;
9
9
  * nearly empty lets the model warn the user before calls start to 402.
10
10
  */
11
11
  export declare function creditNotice(body: unknown): string | undefined;
12
+ /**
13
+ * FREE/STARTER/PROFESSIONAL accounts get a monthly allowance of national
14
+ * calls, separate from the credit pool; BUSINESS and higher have no
15
+ * separate limit, so the `X-National-*` headers are simply absent for them.
16
+ * Surfaced on every national tool response (except lex_national_coverage,
17
+ * which does not count against it) so the model can warn the user before
18
+ * calls start to 402 `NATIONAL_ALLOWANCE_EXHAUSTED`.
19
+ */
20
+ export declare function nationalAllowanceOf(headers: LexResponse['headers']): Obj | undefined;
12
21
  /** `02016R0679-20160504` → { base: '32016R0679', date: '2016-05-04' }; null otherwise. */
13
22
  export declare function consolidatedBaseOf(celex: unknown): {
14
23
  base: string;
@@ -25,6 +34,12 @@ export interface ContentOptions {
25
34
  include?: string[];
26
35
  /** Skip this many items (across parts, in order) — paging after truncation. In outline view: articles. */
27
36
  offset?: number;
37
+ /**
38
+ * The calling tool has no `articleId` / `include` parameters (the national
39
+ * document tool): the outline's reading hint then points at view "full" +
40
+ * offset, the only way that tool reads on.
41
+ */
42
+ noPartSelection?: boolean;
28
43
  }
29
44
  /**
30
45
  * Shape `content` (a document's parsed body) under a character budget.
@@ -54,8 +69,47 @@ export declare function shapeLegislation(res: LexResponse<Json>): Obj;
54
69
  * the version in force could not be read; don't quote it as of that date.
55
70
  */
56
71
  export declare function asOfCaveat(results: Obj[], asOf: string): Obj | undefined;
72
+ export declare function nodeFields(n: Obj): Obj;
73
+ /** `unresolved=true` on a national id: at most this many references are shown. */
74
+ export declare const UNRESOLVED_SHOWN = 100;
57
75
  export declare function shapeCitedBy(res: LexResponse<Json>): Obj;
58
76
  export declare function shapeCites(res: LexResponse<Json>): Obj;
59
77
  export declare function shapeNetwork(res: LexResponse<Json>): Obj;
78
+ /** Character budget of one transposition / counterparts result. */
79
+ export declare const GRAPH_RESULT_BUDGET = 40000;
80
+ /**
81
+ * The measures are bounded here (`limit` / `offset`, counted across
82
+ * countries in the API's order, and a character budget: measures stop once
83
+ * it is spent, so the next offset is exact); every country's `counts` is
84
+ * always kept.
85
+ */
86
+ export declare function shapeTransposition(res: LexResponse<Json>, limit: number, offset: number, budget?: number): Obj;
87
+ /**
88
+ * Counterparts: at most `acts` EU acts per call (from `offset`), at most
89
+ * `limit` counterparts per act, and acts stop once the character budget is
90
+ * spent (the first one is always shown).
91
+ */
92
+ export declare function shapeCounterparts(res: LexResponse<Json>, limit: number, offset: number, acts: number, budget?: number): Obj;
93
+ export declare function shapeNationalSearchResult(r: unknown): Obj;
94
+ /** A full national document (from GET /{jur}/documents/{id}). */
95
+ export declare function shapeNationalDocument(doc: unknown, opts: ContentOptions): Obj;
96
+ /**
97
+ * A national case-law hit. `documentKind`, `title`, `ecli` and
98
+ * `dateOfDocument` come from the hit's `document` (LexAPI's own record, the
99
+ * same fields in every country — API 2.8.0), falling back to the index's
100
+ * own metadata; `court` / `caseNumbers` come from the index (a summary
101
+ * carries no decision block — lex_get_national_document has the normalized
102
+ * court, chamber, caseNumbers and citedNorms).
103
+ */
104
+ export declare function shapeNationalCaseLawHit(r: unknown): Obj;
105
+ export declare function shapeNationalCaseLaw(res: LexResponse<Json>): Obj;
106
+ /**
107
+ * A national legislation hit. The index fields (snake_case — the server's
108
+ * own names on this endpoint) are always sent since API 2.8.0, null when
109
+ * the index has nothing (compacted away here); `documentKind`, `title` and
110
+ * the act's validity come from the hit's `document` summary.
111
+ */
112
+ export declare function shapeNationalLegislationHit(r: unknown): Obj;
113
+ export declare function shapeNationalLegislation(res: LexResponse<Json>): Obj;
60
114
  export declare function stripEnvelope(body: unknown, drop?: string[]): Obj;
61
115
  export {};
package/dist/shape.js CHANGED
@@ -58,6 +58,22 @@ export function creditNotice(body) {
58
58
  const reset = str(c.resetsAt);
59
59
  return `LexAPI credit pool is low: ${remaining} of ${limit} credits left${reset ? ` (resets ${reset})` : ''}.`;
60
60
  }
61
+ // ── National-law allowance ──────────────────────────────────────────
62
+ /**
63
+ * FREE/STARTER/PROFESSIONAL accounts get a monthly allowance of national
64
+ * calls, separate from the credit pool; BUSINESS and higher have no
65
+ * separate limit, so the `X-National-*` headers are simply absent for them.
66
+ * Surfaced on every national tool response (except lex_national_coverage,
67
+ * which does not count against it) so the model can warn the user before
68
+ * calls start to 402 `NATIONAL_ALLOWANCE_EXHAUSTED`.
69
+ */
70
+ export function nationalAllowanceOf(headers) {
71
+ const limit = num(Number(headers['x-national-limit']));
72
+ const remaining = num(Number(headers['x-national-remaining']));
73
+ const resetsAt = str(headers['x-national-reset']);
74
+ const out = compact({ limit, remaining, resetsAt });
75
+ return Object.keys(out).length ? out : undefined;
76
+ }
61
77
  // ── Consolidated texts ─────────────────────────────────────────────
62
78
  const CONSOLIDATED_RE = /^0([0-9]{4}[A-Z]{1,2}[0-9]{4}(?:\([0-9]{2}\))?)-([0-9]{4})([0-9]{2})([0-9]{2})$/;
63
79
  /** `02016R0679-20160504` → { base: '32016R0679', date: '2016-05-04' }; null otherwise. */
@@ -200,7 +216,11 @@ function clipItem(item, budget) {
200
216
  return item.value;
201
217
  }
202
218
  /** How to read on from an outline — only suggesting parts this document has. */
203
- function readingHint(content) {
219
+ function readingHint(content, opts) {
220
+ if (opts?.noPartSelection) {
221
+ // No articleId / include on this tool — never suggest them.
222
+ return 'Read on: call again with view "full" (the body in order, up to maxChars); long bodies continue with the offset its note gives.';
223
+ }
204
224
  const has = (k) => Array.isArray(content[k]) && content[k].length > 0;
205
225
  const ways = [];
206
226
  if (has('articles'))
@@ -283,7 +303,7 @@ export function shapeContent(content, opts) {
283
303
  const { outline, note } = outlineOf(content, opts.maxChars, offset);
284
304
  return {
285
305
  content: outline,
286
- note: [`Outline only: the body is ${totalSize} characters (budget maxChars=${opts.maxChars}).`, note, readingHint(content)].filter(Boolean).join(' '),
306
+ note: [`Outline only: the body is ${totalSize} characters (budget maxChars=${opts.maxChars}).`, note, readingHint(content, opts)].filter(Boolean).join(' '),
287
307
  };
288
308
  }
289
309
  const out = {};
@@ -540,29 +560,70 @@ export function asOfCaveat(results, asOf) {
540
560
  });
541
561
  }
542
562
  // ── Citations ──────────────────────────────────────────────────────
563
+ // Node identity (API 2.11.0): every node carries `id` (= `celexNumber`),
564
+ // `jurisdiction` and `documentKind`. `jurisdiction` is kept only when it is
565
+ // not EU, so EU-only answers stay as compact as before.
566
+ export function nodeFields(n) {
567
+ return compact({
568
+ celex: n.celexNumber ?? n.id,
569
+ jurisdiction: n.jurisdiction === 'EU' ? undefined : n.jurisdiction,
570
+ documentKind: n.documentKind,
571
+ });
572
+ }
573
+ function distinct(values) {
574
+ return [...new Set(values.filter((v) => v !== undefined && v !== null && v !== ''))];
575
+ }
543
576
  function shapeEdgeGroup(g) {
544
577
  if (!isObj(g))
545
578
  return {};
546
- const edges = Array.isArray(g.citations) ? g.citations : [];
547
- const types = [...new Set(edges.map((e) => (isObj(e) ? e.citationType : undefined)).filter(Boolean))];
548
- const snippet = edges.map((e) => (isObj(e) ? str(e.contextSnippet) : undefined)).find(Boolean);
579
+ const edges = (Array.isArray(g.citations) ? g.citations : []).filter(isObj);
580
+ const snippet = edges.map((e) => str(e.contextSnippet)).find(Boolean);
549
581
  return compact({
550
- celex: g.celexNumber,
582
+ ...nodeFields(g),
551
583
  title: g.title,
552
- types,
584
+ types: distinct(edges.map((e) => e.citationType)),
585
+ provenance: distinct(edges.map((e) => e.provenance)),
586
+ resolution: distinct(edges.map((e) => e.resolution)),
553
587
  count: g.citationCount,
554
588
  context: truncate(snippet, 240),
555
589
  });
556
590
  }
591
+ /** `unresolved=true` on a national id: at most this many references are shown. */
592
+ export const UNRESOLVED_SHOWN = 100;
593
+ /** The references a national document records that could not become an edge (bounded). */
594
+ function unresolvedFields(b) {
595
+ if (!Array.isArray(b.unresolved))
596
+ return {};
597
+ const all = b.unresolved.filter(isObj);
598
+ const out = {
599
+ unresolved: all.slice(0, UNRESOLVED_SHOWN).map((u) => compact({
600
+ kind: u.kind,
601
+ text: truncate(str(u.text), 200),
602
+ status: u.status,
603
+ targetId: u.targetId,
604
+ })),
605
+ };
606
+ if (typeof b.unresolvedTruncated === 'boolean')
607
+ out.unresolvedTruncated = b.unresolvedTruncated;
608
+ if (all.length > UNRESOLVED_SHOWN)
609
+ out.unresolvedNote = `${all.length - UNRESOLVED_SHOWN} more unresolved references not shown.`;
610
+ return out;
611
+ }
557
612
  export function shapeCitedBy(res) {
558
613
  const b = res.body;
559
614
  return compact({
560
615
  target: b.targetDocument,
561
616
  totalCitations: b.totalCitations,
617
+ totalEdges: b.totalEdges,
618
+ countsSource: b.countsSource,
562
619
  limit: b.limit,
563
620
  offset: b.offset,
564
621
  citedBy: Array.isArray(b.citedBy) ? b.citedBy.map(shapeEdgeGroup) : [],
565
622
  relationSync: b.relationSync,
623
+ // Present only when the caller's account can see at least one national
624
+ // jurisdiction — absent entirely for everyone else, so EU-only
625
+ // responses are unchanged.
626
+ includeNational: b.includeNational,
566
627
  });
567
628
  }
568
629
  export function shapeCites(res) {
@@ -570,15 +631,27 @@ export function shapeCites(res) {
570
631
  return compact({
571
632
  source: b.sourceDocument,
572
633
  totalCitations: b.totalCitations,
634
+ totalEdges: b.totalEdges,
635
+ countsSource: b.countsSource,
573
636
  limit: b.limit,
574
637
  offset: b.offset,
575
638
  cites: Array.isArray(b.cites) ? b.cites.map(shapeEdgeGroup) : [],
639
+ includeNational: b.includeNational,
640
+ ...unresolvedFields(b),
576
641
  });
577
642
  }
578
643
  function shapeNeighbour(n) {
579
644
  if (!isObj(n))
580
645
  return {};
581
- return compact({ celex: n.celexNumber, title: n.title, types: n.types, count: n.count });
646
+ const details = (Array.isArray(n.edgeDetails) ? n.edgeDetails : []).filter(isObj);
647
+ return compact({
648
+ ...nodeFields(n),
649
+ title: n.title,
650
+ types: n.types,
651
+ count: n.count,
652
+ provenance: distinct(details.map((d) => d.provenance)),
653
+ resolution: distinct(details.map((d) => d.resolution)),
654
+ });
582
655
  }
583
656
  export function shapeNetwork(res) {
584
657
  const b = res.body;
@@ -592,6 +665,369 @@ export function shapeNetwork(res) {
592
665
  partialReason: b.partialReason,
593
666
  message: b.message,
594
667
  relationSync: b.relationSync,
668
+ includeNational: b.includeNational,
669
+ ...unresolvedFields(b),
670
+ });
671
+ }
672
+ // ── Transposition and counterparts (API 2.11.0) ───────────────────
673
+ // A notified measure is a notification, not a finding that the measure
674
+ // transposes the act: the API's `note` is always carried through.
675
+ function shapeMeasure(m) {
676
+ const oj = isObj(m.officialJournal) ? compact(m.officialJournal) : undefined;
677
+ const cellar = isObj(m.cellar)
678
+ ? compact({
679
+ celex: m.cellar.celex,
680
+ dateDocument: m.cellar.dateDocument,
681
+ dateNotification: m.cellar.dateNotification,
682
+ entryIntoForce: m.cellar.entryIntoForce,
683
+ })
684
+ : undefined;
685
+ return compact({
686
+ id: m.id,
687
+ resolved: m.resolved,
688
+ resolution: m.resolution,
689
+ resolutionBasis: m.resolutionBasis,
690
+ provenance: m.provenance,
691
+ citationType: m.citationType,
692
+ title: truncate(str(m.title), 300),
693
+ typeAct: m.typeAct,
694
+ officialJournal: oj,
695
+ reference: m.reference,
696
+ eli: m.eli,
697
+ link: m.link,
698
+ cellar,
699
+ });
700
+ }
701
+ /** Character budget of one transposition / counterparts result. */
702
+ export const GRAPH_RESULT_BUDGET = 40_000;
703
+ /**
704
+ * The measures are bounded here (`limit` / `offset`, counted across
705
+ * countries in the API's order, and a character budget: measures stop once
706
+ * it is spent, so the next offset is exact); every country's `counts` is
707
+ * always kept.
708
+ */
709
+ export function shapeTransposition(res, limit, offset, budget = GRAPH_RESULT_BUDGET) {
710
+ const b = res.body;
711
+ const countries = (Array.isArray(b.jurisdictions) ? b.jurisdictions : []).filter(isObj);
712
+ let index = 0;
713
+ let returned = 0;
714
+ let used = 0;
715
+ let full = false;
716
+ const jurisdictions = countries.map((c) => {
717
+ const measures = (Array.isArray(c.measures) ? c.measures : []).filter(isObj);
718
+ const shown = [];
719
+ for (const m of measures) {
720
+ if (!full && index >= offset && index < offset + limit) {
721
+ const shaped = shapeMeasure(m);
722
+ const cost = size(shaped);
723
+ if (returned > 0 && used + cost > budget)
724
+ full = true;
725
+ else {
726
+ shown.push(shaped);
727
+ returned++;
728
+ used += cost;
729
+ }
730
+ }
731
+ index++;
732
+ }
733
+ return compact({ jurisdiction: c.jurisdiction, live: c.live, counts: c.counts, measures: shown });
734
+ });
735
+ const total = index;
736
+ const doc = isObj(b.document) ? compact({ ...nodeFields(b.document), title: b.document.title }) : undefined;
737
+ const out = compact({
738
+ document: doc,
739
+ note: b.note,
740
+ includeNational: b.includeNational,
741
+ termsRequired: b.termsRequired,
742
+ source: b.source,
743
+ truncated: b.truncated,
744
+ jurisdictions,
745
+ });
746
+ out.shown = { offset, returned, total };
747
+ if (offset + returned < total) {
748
+ out.more = `Measures ${offset + 1}–${offset + returned} of the ${total} returned shown. Call again with offset ${offset + returned} (another 5 credits), or narrow with jurisdictions.`;
749
+ }
750
+ if (b.truncated === true) {
751
+ out.truncatedNote = `The API returned only part of this act's measures (truncated: true), so ${total} is not the full number: see source.cellar.measures and each country's counts.measures. Narrow with jurisdictions to see the rest.`;
752
+ }
753
+ return out;
754
+ }
755
+ /**
756
+ * Counterparts: at most `acts` EU acts per call (from `offset`), at most
757
+ * `limit` counterparts per act, and acts stop once the character budget is
758
+ * spent (the first one is always shown).
759
+ */
760
+ export function shapeCounterparts(res, limit, offset, acts, budget = GRAPH_RESULT_BUDGET) {
761
+ const b = res.body;
762
+ const via = (Array.isArray(b.via) ? b.via : []).filter(isObj);
763
+ const all = via.slice(offset, offset + acts).map((v) => {
764
+ const act = isObj(v.euAct) ? v.euAct : {};
765
+ const cps = (Array.isArray(v.counterparts) ? v.counterparts : []).filter(isObj);
766
+ const entry = compact({
767
+ euAct: compact({ ...nodeFields(act), title: truncate(str(act.title), 300), notifiedMeasures: act.notifiedMeasures }),
768
+ edge: isObj(v.edge) ? compact(v.edge) : undefined,
769
+ counterparts: cps.slice(0, limit).map((c) => compact({
770
+ jurisdiction: c.jurisdiction,
771
+ id: c.id,
772
+ resolved: c.resolved,
773
+ title: truncate(str(c.title), 200),
774
+ citationType: c.citationType,
775
+ provenance: c.provenance,
776
+ rank: c.rank,
777
+ })),
778
+ truncated: v.truncated === true ? true : undefined,
779
+ });
780
+ if (cps.length > limit)
781
+ entry.more = `${cps.length - limit} more counterparts for this act not shown (raise limit, up to 50).`;
782
+ return entry;
783
+ });
784
+ const shapedVia = [];
785
+ let used = 0;
786
+ for (const entry of all) {
787
+ const cost = size(entry);
788
+ if (shapedVia.length > 0 && used + cost > budget)
789
+ break;
790
+ shapedVia.push(entry);
791
+ used += cost;
792
+ }
793
+ const window = shapedVia;
794
+ const out = compact({
795
+ document: isObj(b.document) ? compact({ ...nodeFields(b.document), title: b.document.title }) : undefined,
796
+ includeNational: b.includeNational,
797
+ truncated: b.truncated,
798
+ via: shapedVia,
799
+ });
800
+ out.note = 'Rank 2 and 3 counterparts are measures a member state notified to the Commission: a notification is not a finding that the measure transposes the act, or transposes it completely.';
801
+ if (offset + window.length < via.length) {
802
+ out.more = `EU acts ${offset + 1}–${offset + window.length} of ${via.length} shown. Call again with offset ${offset + window.length} (another 20 credits).`;
803
+ }
804
+ return out;
805
+ }
806
+ // ── National law ─────────────────────────────────────────────────
807
+ // National documents key on `id` (not `celex`) and always carry
808
+ // `attribution` (per-source licence/attribution text) — never dropped by
809
+ // compacting, since it is the legally required attribution for the source.
810
+ //
811
+ // Since API 2.8.0 every national response has ONE shape
812
+ // for every jurisdiction: `documentKind` ('act' | 'decision'), a decision's
813
+ // `decision: { court, chamber, caseNumbers, citedNorms }`, and a closed
814
+ // `content` key set (lane extras only under `content.details` /
815
+ // `articles[].details`). The tools present the same uniform fields
816
+ // everywhere — `documentKind`, `court`, `chamber`, `caseNumbers`,
817
+ // `citedNorms`, `dateOfDocument`, `ecli` — whatever the country, and never
818
+ // read a source's raw keys (gericht, aktenzeichen, zaaknummer, …).
819
+ /** The listing-summary fields (API 2.8.0 NationalDocumentSummary), compacted. */
820
+ function nationalSummaryFields(r) {
821
+ return compact({
822
+ id: r.id,
823
+ jurisdiction: r.jurisdiction,
824
+ language: r.language,
825
+ documentKind: r.documentKind,
826
+ title: r.title,
827
+ documentType: r.documentType,
828
+ ecli: r.ecli,
829
+ eli: r.eli,
830
+ dateOfDocument: r.dateOfDocument,
831
+ version: r.version,
832
+ fetchedAt: r.fetchedAt,
833
+ validTo: r.validTo,
834
+ inForce: r.inForce,
835
+ });
836
+ }
837
+ export function shapeNationalSearchResult(r) {
838
+ if (!isObj(r))
839
+ return {};
840
+ return nationalSummaryFields(r);
841
+ }
842
+ /** A decision's normalized case-law metadata (`document.decision`), flattened; {} for acts. */
843
+ function nationalDecisionFields(decision) {
844
+ if (!isObj(decision))
845
+ return {};
846
+ const citedNorms = Array.isArray(decision.citedNorms)
847
+ ? decision.citedNorms.filter(isObj).map((n) => compact({ text: n.text, documentId: n.documentId }))
848
+ : undefined;
849
+ return compact({
850
+ court: decision.court,
851
+ chamber: decision.chamber,
852
+ caseNumbers: decision.caseNumbers,
853
+ citedNorms,
854
+ });
855
+ }
856
+ /**
857
+ * One national article for the model: the uniform unit fields only. The
858
+ * unit's `details` (source unit ids, kinds) are dropped as noise; a unit the
859
+ * source publishes no text for keeps an explicit `text: null`.
860
+ */
861
+ function shapeNationalArticle(a) {
862
+ if (!isObj(a))
863
+ return a;
864
+ const out = compact({
865
+ number: a.number,
866
+ title: a.title,
867
+ section: a.section,
868
+ inForceFrom: a.inForceFrom,
869
+ inForceTo: a.inForceTo,
870
+ });
871
+ out.text = typeof a.text === 'string' ? a.text : null;
872
+ return out;
873
+ }
874
+ /** A full national document (from GET /{jur}/documents/{id}). */
875
+ export function shapeNationalDocument(doc, opts) {
876
+ if (!isObj(doc))
877
+ return {};
878
+ // `compact` drops `null` values — build the metadata fields through it
879
+ // first, then set `content: null` (when that's the case) on the result
880
+ // directly, never through another `compact` call, or the "no text" signal
881
+ // would be lost (same pitfall shapeDocument's content:null branch avoids).
882
+ const out = {
883
+ ...nationalSummaryFields(doc),
884
+ // Case-law metadata, same fields in every country; served also when the
885
+ // decision has no text. Absent for acts (`decision: null`).
886
+ ...nationalDecisionFields(doc.decision),
887
+ ...compact({
888
+ textBasis: doc.textBasis,
889
+ // Required legal attribution for the source (RIS, gesetze-im-internet.de,
890
+ // Normattiva, Légifrance/Judilibre, the Rechtspraak open data, …): always
891
+ // kept, never dropped by compacting elsewhere.
892
+ attribution: doc.attribution,
893
+ }),
894
+ };
895
+ // A text-availability block that just says "available" is noise (mirrors
896
+ // shapeMetadata); any other state (no text, why, which languages) is kept.
897
+ const ta = doc.textAvailability;
898
+ if (isObj(ta) && !(ta.available === true && Object.keys(ta).length === 1))
899
+ out.textAvailability = ta;
900
+ if (doc.content === null) {
901
+ out.content = null; // no text published — textAvailability says why
902
+ return out;
903
+ }
904
+ const c = isObj(doc.content) ? doc.content : undefined;
905
+ if (c) {
906
+ // The language facts of the text change how it must be read/cited —
907
+ // surfaced only when they say something beyond the document's language.
908
+ const langs = Array.isArray(c.textLanguages) ? c.textLanguages : [];
909
+ if (langs.length > 1 || (langs.length === 1 && langs[0] !== doc.language))
910
+ out.textLanguages = langs;
911
+ if (str(c.textLanguage))
912
+ out.textLanguage = c.textLanguage;
913
+ if (c.embeddedForeignText === true)
914
+ out.embeddedForeignText = true;
915
+ if (isObj(c.repeal))
916
+ out.repeal = compact({ validTo: c.repeal.validTo, basis: c.repeal.basis, detectedAt: c.repeal.detectedAt });
917
+ }
918
+ const body = c
919
+ ? { fullText: c.fullText, articles: Array.isArray(c.articles) ? c.articles.map(shapeNationalArticle) : [] }
920
+ : doc.content;
921
+ const { content, note } = shapeContent(body, { ...opts, noPartSelection: true });
922
+ if (content)
923
+ out.content = content;
924
+ if (note)
925
+ out.note = note;
926
+ return out;
927
+ }
928
+ /**
929
+ * A national case-law hit. `documentKind`, `title`, `ecli` and
930
+ * `dateOfDocument` come from the hit's `document` (LexAPI's own record, the
931
+ * same fields in every country — API 2.8.0), falling back to the index's
932
+ * own metadata; `court` / `caseNumbers` come from the index (a summary
933
+ * carries no decision block — lex_get_national_document has the normalized
934
+ * court, chamber, caseNumbers and citedNorms).
935
+ */
936
+ export function shapeNationalCaseLawHit(r) {
937
+ if (!isObj(r))
938
+ return {};
939
+ const md = isObj(r.metadata) ? r.metadata : {};
940
+ const d = isObj(r.document) ? r.document : {};
941
+ const caseNumber = str(r.case_number);
942
+ const out = {
943
+ documentId: r.documentId ?? d.id ?? md.celex_id,
944
+ jurisdiction: r.jurisdiction ?? d.jurisdiction,
945
+ documentKind: d.documentKind,
946
+ score: round3(r.score),
947
+ title: d.title ?? r.case_name,
948
+ documentType: d.documentType,
949
+ ecli: d.ecli ?? r.ecli,
950
+ dateOfDocument: d.dateOfDocument ?? r.decision_date,
951
+ court: r.court,
952
+ caseNumbers: caseNumber ? [caseNumber] : undefined,
953
+ parties: r.parties,
954
+ language: r.language && r.language !== 'en' ? r.language : undefined,
955
+ summary: r.summary,
956
+ snippet: r.summary ? undefined : r.snippet,
957
+ text: r.text,
958
+ validTo: r.validTo ?? d.validTo,
959
+ inForce: r.inForce ?? d.inForce,
960
+ // Required legal attribution for the source — always kept.
961
+ attribution: r.attribution,
962
+ };
963
+ for (const k of CASE_ANALYTICS)
964
+ out[k] = r[k];
965
+ return compact(out);
966
+ }
967
+ export function shapeNationalCaseLaw(res) {
968
+ const b = res.body;
969
+ const results = Array.isArray(b.results) ? b.results.map(shapeNationalCaseLawHit) : [];
970
+ return compact({
971
+ jurisdiction: b.jurisdiction,
972
+ resultCount: results.length,
973
+ results,
974
+ hint: b.hint,
975
+ // Present when the national index could not complete the search: the
976
+ // results may be missing better matches (the hint says what may help).
977
+ partial: b.partial,
978
+ partialReason: b.partialReason,
979
+ // The national index never rewrites (the response always answers
980
+ // hyde: false) — the request's hyde was accepted but did not cost the
981
+ // HyDE premium.
982
+ hyde: b.hyde,
983
+ attribution: b.attribution,
984
+ });
985
+ }
986
+ /**
987
+ * A national legislation hit. The index fields (snake_case — the server's
988
+ * own names on this endpoint) are always sent since API 2.8.0, null when
989
+ * the index has nothing (compacted away here); `documentKind`, `title` and
990
+ * the act's validity come from the hit's `document` summary.
991
+ */
992
+ export function shapeNationalLegislationHit(r) {
993
+ if (!isObj(r))
994
+ return {};
995
+ const d = isObj(r.document) ? r.document : {};
996
+ return compact({
997
+ law_id: r.law_id,
998
+ documentId: r.documentId ?? d.id,
999
+ jurisdiction: r.jurisdiction ?? d.jurisdiction,
1000
+ documentKind: d.documentKind,
1001
+ law_title: r.law_title ?? d.title,
1002
+ documentType: d.documentType,
1003
+ article_ref: r.article_ref,
1004
+ section: r.section,
1005
+ chapter: r.chapter,
1006
+ score: round3(r.score),
1007
+ language: r.language,
1008
+ snippet: r.snippet,
1009
+ text: r.text,
1010
+ // From the index (as of today), or our row's confirmed-repeal override
1011
+ // toward false (with valid_to). null = unknown, dropped.
1012
+ in_force: r.in_force,
1013
+ valid_from: r.valid_from,
1014
+ valid_to: r.valid_to,
1015
+ law_type: r.law_type,
1016
+ // Required legal attribution for the source — always kept.
1017
+ attribution: r.attribution,
1018
+ });
1019
+ }
1020
+ export function shapeNationalLegislation(res) {
1021
+ const b = res.body;
1022
+ const results = Array.isArray(b.results) ? b.results.map(shapeNationalLegislationHit) : [];
1023
+ return compact({
1024
+ jurisdiction: b.jurisdiction,
1025
+ resultCount: results.length,
1026
+ results,
1027
+ hint: b.hint,
1028
+ partial: b.partial,
1029
+ partialReason: b.partialReason,
1030
+ attribution: b.attribution,
595
1031
  });
596
1032
  }
597
1033
  export function stripEnvelope(body, drop = []) {
package/dist/tools.d.ts CHANGED
@@ -8,7 +8,11 @@ export declare const AUTHORS: readonly ["commission", "council", "parliament", "
8
8
  export declare const PROCEDURES: readonly ["ordinary", "codecision", "consent", "consultation", "budget", "implementing", "delegated", "comitology", "appointment", "non-legislative"];
9
9
  /** EUR-Lex subdomain codes plus the friendly aliases the API maps to them. */
10
10
  export declare const SUBDOMAINS: readonly ["LEGISLATION", "CONSLEG", "TREATIES", "EU_CASE_LAW", "LEGAL_PROCEDURE", "INTER_AGREE", "PRE_ACTS", "PAR_QUESTION", "NAT_CASE_LAW", "legislation", "consolidated", "treaties", "case-law", "legal-procedure", "international", "preparatory", "questions", "national-case-law"];
11
- export declare const CITATION_TYPES: readonly ["reference", "amendment", "repeal", "corrigendum", "implementation", "legal-basis", "proposal"];
11
+ export declare const CITATION_TYPES: readonly ["reference", "amendment", "repeal", "corrigendum", "implementation", "legal-basis", "proposal", "transposition"];
12
+ /** Where an edge comes from (API 2.11.0 CitationProvenance). */
13
+ export declare const CITATION_PROVENANCES: readonly ["notice", "cellar", "notice+cellar", "cellar-nim", "source", "resolver"];
14
+ /** How a national edge's target was identified (API 2.11.0 CitationResolution). */
15
+ export declare const CITATION_RESOLUTIONS: readonly ["id", "key", "abbreviation", "text-pattern"];
12
16
  export declare function isApiDate(value: string): boolean;
13
17
  export declare function isApiTimestamp(value: string): boolean;
14
18
  export declare function normCelex(v: string): string;