@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/dist/index.js
CHANGED
|
@@ -6,10 +6,43 @@ var STATUS_TO_CODE = {
|
|
|
6
6
|
403: "TIER_FORBIDDEN",
|
|
7
7
|
404: "NOT_FOUND",
|
|
8
8
|
429: "RATE_LIMITED",
|
|
9
|
+
500: "INTERNAL",
|
|
9
10
|
502: "UPSTREAM_ERROR",
|
|
10
|
-
|
|
11
|
+
503: "SERVICE_UNAVAILABLE",
|
|
12
|
+
504: "TIMEOUT",
|
|
13
|
+
// Cloudflare edge errors (non-JSON bodies). SDK contract §1.3.
|
|
14
|
+
520: "UPSTREAM_ERROR",
|
|
15
|
+
521: "UPSTREAM_ERROR",
|
|
16
|
+
522: "UPSTREAM_ERROR",
|
|
17
|
+
523: "UPSTREAM_ERROR",
|
|
18
|
+
524: "TIMEOUT"
|
|
11
19
|
};
|
|
20
|
+
var ERROR_KINDS = /* @__PURE__ */ Symbol.for("@lexapi/client.errorKinds");
|
|
21
|
+
function collectKinds(ctor) {
|
|
22
|
+
const kinds = [];
|
|
23
|
+
let current = ctor;
|
|
24
|
+
while (typeof current === "function") {
|
|
25
|
+
const kind = current.kind;
|
|
26
|
+
if (Object.prototype.hasOwnProperty.call(current, "kind") && typeof kind === "string") {
|
|
27
|
+
kinds.push(kind);
|
|
28
|
+
}
|
|
29
|
+
current = Object.getPrototypeOf(current);
|
|
30
|
+
}
|
|
31
|
+
return kinds;
|
|
32
|
+
}
|
|
33
|
+
function brandedHasInstance(ctor, value) {
|
|
34
|
+
if (typeof value !== "object" || value === null) return false;
|
|
35
|
+
if (Function.prototype[Symbol.hasInstance].call(ctor, value)) return true;
|
|
36
|
+
if (!Object.prototype.hasOwnProperty.call(ctor, "kind")) return false;
|
|
37
|
+
const kinds = value[ERROR_KINDS];
|
|
38
|
+
return Array.isArray(kinds) && kinds.includes(ctor.kind);
|
|
39
|
+
}
|
|
12
40
|
var LexAPIError = class _LexAPIError extends Error {
|
|
41
|
+
/** Stable class tag used by the cross-build `instanceof` brand check. */
|
|
42
|
+
static kind = "LexAPIError";
|
|
43
|
+
static [Symbol.hasInstance](value) {
|
|
44
|
+
return brandedHasInstance(this, value);
|
|
45
|
+
}
|
|
13
46
|
/** Stable machine-readable code (`error.code`, or derived from the HTTP status for legacy bodies). */
|
|
14
47
|
code;
|
|
15
48
|
/** HTTP status. `0` for client-side failures (network error, client-side timeout). */
|
|
@@ -17,27 +50,41 @@ var LexAPIError = class _LexAPIError extends Error {
|
|
|
17
50
|
/** The `error.details` object from the typed envelope, when present. */
|
|
18
51
|
details;
|
|
19
52
|
/**
|
|
20
|
-
* 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).
|
|
21
55
|
* Sourced from the `Retry-After` response HEADER first; the JSON
|
|
22
56
|
* `retryAfter` body field is only a fallback because it historically
|
|
23
57
|
* carried buggy epoch-seconds values (epoch-looking values are
|
|
24
58
|
* normalized to a delta).
|
|
25
59
|
*/
|
|
26
60
|
retryAfter;
|
|
27
|
-
|
|
61
|
+
/**
|
|
62
|
+
* The parsed JSON error body, verbatim. Useful for legacy-shape fields the
|
|
63
|
+
* typed properties don't cover (`upgradeUrl` on tier gates, `current` /
|
|
64
|
+
* `limit` on the webhook ceiling, `usage` on legacy quota 429s).
|
|
65
|
+
*/
|
|
66
|
+
body;
|
|
67
|
+
/** Parsed response headers, when the error came from an HTTP response. */
|
|
68
|
+
headers;
|
|
69
|
+
constructor(code, message, status, details, retryAfter, context) {
|
|
28
70
|
super(`[${code}] ${message} (HTTP ${status})`);
|
|
29
71
|
this.name = "LexAPIError";
|
|
30
72
|
this.code = code;
|
|
31
73
|
this.status = status;
|
|
32
74
|
this.details = details;
|
|
33
75
|
this.retryAfter = retryAfter;
|
|
76
|
+
this.body = context?.body;
|
|
77
|
+
this.headers = context?.headers;
|
|
78
|
+
Object.defineProperty(this, ERROR_KINDS, { value: collectKinds(new.target), enumerable: false });
|
|
34
79
|
}
|
|
35
80
|
/**
|
|
36
81
|
* Build the most specific error subclass for a non-2xx response.
|
|
37
82
|
* Accepts both the typed envelope and the legacy bare `{error, message}` shape.
|
|
38
83
|
*/
|
|
39
|
-
static fromResponse(status, body, headerRetryAfter) {
|
|
40
|
-
|
|
84
|
+
static fromResponse(status, body, headerRetryAfter, headers) {
|
|
85
|
+
const statusCode = STATUS_TO_CODE[status];
|
|
86
|
+
let code = statusCode ?? "INTERNAL";
|
|
87
|
+
let typedCode = false;
|
|
41
88
|
let message = `HTTP ${status}`;
|
|
42
89
|
let details;
|
|
43
90
|
let retryAfter = headerRetryAfter;
|
|
@@ -47,125 +94,373 @@ var LexAPIError = class _LexAPIError extends Error {
|
|
|
47
94
|
const err = record["error"];
|
|
48
95
|
if (typeof err === "object" && err !== null) {
|
|
49
96
|
const e = err;
|
|
50
|
-
if (typeof e["code"] === "string")
|
|
97
|
+
if (typeof e["code"] === "string") {
|
|
98
|
+
code = e["code"];
|
|
99
|
+
typedCode = true;
|
|
100
|
+
}
|
|
51
101
|
if (typeof e["message"] === "string") message = e["message"];
|
|
52
102
|
details = e["details"];
|
|
53
103
|
} else if (typeof err === "string") {
|
|
104
|
+
if (typeof record["code"] === "string" && record["code"] !== "") {
|
|
105
|
+
code = record["code"];
|
|
106
|
+
typedCode = true;
|
|
107
|
+
}
|
|
54
108
|
message = typeof record["message"] === "string" && record["message"] !== err ? `${err}: ${record["message"]}` : err;
|
|
55
|
-
|
|
56
|
-
|
|
109
|
+
details = record["details"];
|
|
110
|
+
} else {
|
|
111
|
+
if (typeof record["code"] === "string" && record["code"] !== "") {
|
|
112
|
+
code = record["code"];
|
|
113
|
+
typedCode = true;
|
|
114
|
+
}
|
|
115
|
+
if (typeof record["message"] === "string") message = record["message"];
|
|
116
|
+
details = record["details"];
|
|
57
117
|
}
|
|
58
|
-
if (retryAfter === void 0) {
|
|
118
|
+
if (retryAfter === void 0 && (status === 429 || status === 503 && code === "NATIONAL_SEMANTIC_UNAVAILABLE")) {
|
|
59
119
|
const jsonRetryAfter = readNumber(record["retryAfter"]) ?? readNumber(detailsField(details, "retryAfter"));
|
|
60
120
|
if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
|
|
61
121
|
}
|
|
62
122
|
resetsAt = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
|
|
63
123
|
}
|
|
124
|
+
const context = { body, ...headers ? { headers } : {} };
|
|
125
|
+
if (!typedCode && statusCode === void 0 && status < 500) {
|
|
126
|
+
return new _LexAPIError(code, message, status, details, retryAfter, context);
|
|
127
|
+
}
|
|
128
|
+
if (code === "QUOTA_EXHAUSTED" || code === "RATE_LIMITED" && isQuota429(body, headers)) {
|
|
129
|
+
return new RateLimitedError(
|
|
130
|
+
message,
|
|
131
|
+
status,
|
|
132
|
+
details,
|
|
133
|
+
void 0,
|
|
134
|
+
context,
|
|
135
|
+
code === "QUOTA_EXHAUSTED" ? "QUOTA_EXHAUSTED" : "RATE_LIMITED"
|
|
136
|
+
);
|
|
137
|
+
}
|
|
64
138
|
switch (code) {
|
|
65
139
|
case "NOT_FOUND":
|
|
66
|
-
return new NotFoundError(message, status, details, retryAfter);
|
|
140
|
+
return new NotFoundError(message, status, details, retryAfter, context);
|
|
67
141
|
case "INVALID_CELEX":
|
|
68
|
-
return new InvalidCelexError(message, status, details, retryAfter);
|
|
142
|
+
return new InvalidCelexError(message, status, details, retryAfter, context);
|
|
69
143
|
case "INVALID_URL":
|
|
70
|
-
return new InvalidUrlError(message, status, details, retryAfter);
|
|
144
|
+
return new InvalidUrlError(message, status, details, retryAfter, context);
|
|
71
145
|
case "INVALID_PARAMS":
|
|
72
|
-
return new InvalidParamsError(message, status, details, retryAfter);
|
|
146
|
+
return new InvalidParamsError(message, status, details, retryAfter, context);
|
|
73
147
|
case "RATE_LIMITED":
|
|
74
|
-
return new RateLimitedError(message, status, details, retryAfter);
|
|
148
|
+
return new RateLimitedError(message, status, details, retryAfter, context);
|
|
75
149
|
case "TIER_FORBIDDEN":
|
|
76
|
-
return new TierForbiddenError(message, status, details, retryAfter);
|
|
150
|
+
return new TierForbiddenError(message, status, details, retryAfter, context);
|
|
77
151
|
case "CREDITS_EXHAUSTED":
|
|
78
|
-
return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt);
|
|
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);
|
|
79
163
|
case "UPSTREAM_ERROR":
|
|
80
|
-
return new UpstreamError(message, status, details, retryAfter);
|
|
164
|
+
return new UpstreamError(message, status, details, retryAfter, context);
|
|
81
165
|
case "TIMEOUT":
|
|
82
|
-
return new TimeoutError(message, status, details, retryAfter);
|
|
166
|
+
return new TimeoutError(message, status, details, retryAfter, context);
|
|
83
167
|
case "UNAUTHORIZED":
|
|
84
|
-
return new AuthenticationError(message, status, details, retryAfter);
|
|
168
|
+
return new AuthenticationError(message, status, details, retryAfter, context);
|
|
169
|
+
case "SERVICE_UNAVAILABLE":
|
|
170
|
+
return new ServiceUnavailableError(message, status, details, retryAfter, context);
|
|
85
171
|
case "INTERNAL":
|
|
86
|
-
return new InternalServerError(message, status, details, retryAfter);
|
|
172
|
+
return new InternalServerError(message, status, details, retryAfter, context);
|
|
87
173
|
default:
|
|
88
|
-
return new _LexAPIError(code, message, status, details, retryAfter);
|
|
174
|
+
return new _LexAPIError(code, message, status, details, retryAfter, context);
|
|
89
175
|
}
|
|
90
176
|
}
|
|
91
177
|
};
|
|
92
178
|
var NotFoundError = class extends LexAPIError {
|
|
93
|
-
|
|
94
|
-
|
|
179
|
+
static kind = "NotFoundError";
|
|
180
|
+
constructor(message, status = 404, details, retryAfter, context) {
|
|
181
|
+
super("NOT_FOUND", message, status, details, retryAfter, context);
|
|
95
182
|
this.name = "NotFoundError";
|
|
96
183
|
}
|
|
97
184
|
};
|
|
98
185
|
var InvalidCelexError = class extends LexAPIError {
|
|
99
|
-
|
|
100
|
-
|
|
186
|
+
static kind = "InvalidCelexError";
|
|
187
|
+
constructor(message, status = 400, details, retryAfter, context) {
|
|
188
|
+
super("INVALID_CELEX", message, status, details, retryAfter, context);
|
|
101
189
|
this.name = "InvalidCelexError";
|
|
102
190
|
}
|
|
103
191
|
};
|
|
104
192
|
var InvalidUrlError = class extends LexAPIError {
|
|
105
|
-
|
|
106
|
-
|
|
193
|
+
static kind = "InvalidUrlError";
|
|
194
|
+
constructor(message, status = 400, details, retryAfter, context) {
|
|
195
|
+
super("INVALID_URL", message, status, details, retryAfter, context);
|
|
107
196
|
this.name = "InvalidUrlError";
|
|
108
197
|
}
|
|
109
198
|
};
|
|
110
199
|
var InvalidParamsError = class extends LexAPIError {
|
|
111
|
-
|
|
112
|
-
|
|
200
|
+
static kind = "InvalidParamsError";
|
|
201
|
+
constructor(message, status = 400, details, retryAfter, context, code = "INVALID_PARAMS") {
|
|
202
|
+
super(code, message, status, details, retryAfter, context);
|
|
113
203
|
this.name = "InvalidParamsError";
|
|
114
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
|
+
}
|
|
115
222
|
};
|
|
116
223
|
var AuthenticationError = class extends LexAPIError {
|
|
117
|
-
|
|
118
|
-
|
|
224
|
+
static kind = "AuthenticationError";
|
|
225
|
+
constructor(message, status = 401, details, retryAfter, context) {
|
|
226
|
+
super("UNAUTHORIZED", message, status, details, retryAfter, context);
|
|
119
227
|
this.name = "AuthenticationError";
|
|
120
228
|
}
|
|
121
229
|
};
|
|
122
230
|
var RateLimitedError = class extends LexAPIError {
|
|
123
|
-
|
|
124
|
-
|
|
231
|
+
static kind = "RateLimitedError";
|
|
232
|
+
constructor(message, status = 429, details, retryAfter, context, code = "RATE_LIMITED") {
|
|
233
|
+
super(code, message, status, details, retryAfter, context);
|
|
125
234
|
this.name = "RateLimitedError";
|
|
126
235
|
}
|
|
236
|
+
/** `RateLimit-*` headers from the 429 response (limit / remaining / reset seconds). */
|
|
237
|
+
get rateLimit() {
|
|
238
|
+
return this.headers?.rateLimit;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* `true` for a legacy-plan quota 429 (daily call quota, or the monthly
|
|
242
|
+
* semantic quota) rather than the per-minute limiter (SDK contract §1.2):
|
|
243
|
+
* `code` is `QUOTA_EXHAUSTED`, or — servers before lex-api #304, which
|
|
244
|
+
* send no code — the body carries `usage.resetsAt` with neither a
|
|
245
|
+
* `Retry-After` header nor a `retryAfter` body field. It cannot succeed
|
|
246
|
+
* before `resetsAt`, so the SDK does not retry it and `retryAfter` is
|
|
247
|
+
* `undefined`.
|
|
248
|
+
*/
|
|
249
|
+
get quotaExhausted() {
|
|
250
|
+
return this.code === "QUOTA_EXHAUSTED" || isQuota429(this.body, this.headers);
|
|
251
|
+
}
|
|
252
|
+
/** When a legacy quota resets: the body's `resetsAt`, else `usage.resetsAt`. */
|
|
253
|
+
get resetsAt() {
|
|
254
|
+
return readString(bodyField(this.body, "resetsAt")) ?? readString(detailsField(bodyField(this.body, "usage"), "resetsAt"));
|
|
255
|
+
}
|
|
127
256
|
};
|
|
128
257
|
var TierForbiddenError = class extends LexAPIError {
|
|
129
|
-
|
|
130
|
-
|
|
258
|
+
static kind = "TierForbiddenError";
|
|
259
|
+
constructor(message, status = 403, details, retryAfter, context) {
|
|
260
|
+
super("TIER_FORBIDDEN", message, status, details, retryAfter, context);
|
|
131
261
|
this.name = "TierForbiddenError";
|
|
132
262
|
}
|
|
133
263
|
};
|
|
134
264
|
var CreditsExhaustedError = class extends LexAPIError {
|
|
265
|
+
static kind = "CreditsExhaustedError";
|
|
135
266
|
/** When the monthly credit allowance resets (ISO date-time), when the server said so. */
|
|
136
267
|
resetsAt;
|
|
137
|
-
constructor(message, status = 402, details, retryAfter, resetsAt) {
|
|
138
|
-
super("CREDITS_EXHAUSTED", message, status, details, retryAfter);
|
|
268
|
+
constructor(message, status = 402, details, retryAfter, resetsAt, context) {
|
|
269
|
+
super("CREDITS_EXHAUSTED", message, status, details, retryAfter, context);
|
|
139
270
|
this.name = "CreditsExhaustedError";
|
|
140
271
|
this.resetsAt = resetsAt;
|
|
141
272
|
}
|
|
273
|
+
/** The refused operation's credit weight (`details.weight`). */
|
|
274
|
+
get weight() {
|
|
275
|
+
return readNumber(this.details?.weight);
|
|
276
|
+
}
|
|
277
|
+
/** Credits left in the pool (`details.available`). */
|
|
278
|
+
get available() {
|
|
279
|
+
return readNumber(this.details?.available);
|
|
280
|
+
}
|
|
281
|
+
/** The refused operation (`details.operation`). */
|
|
282
|
+
get operation() {
|
|
283
|
+
return readString(this.details?.operation);
|
|
284
|
+
}
|
|
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
|
+
}
|
|
142
312
|
};
|
|
143
313
|
var UpstreamError = class extends LexAPIError {
|
|
144
|
-
|
|
145
|
-
|
|
314
|
+
static kind = "UpstreamError";
|
|
315
|
+
constructor(message, status = 502, details, retryAfter, context) {
|
|
316
|
+
super("UPSTREAM_ERROR", message, status, details, retryAfter, context);
|
|
146
317
|
this.name = "UpstreamError";
|
|
147
318
|
}
|
|
148
319
|
};
|
|
149
320
|
var TimeoutError = class extends LexAPIError {
|
|
150
|
-
|
|
151
|
-
|
|
321
|
+
static kind = "TimeoutError";
|
|
322
|
+
constructor(message, status = 0, details, retryAfter, context) {
|
|
323
|
+
super(status === 0 ? "REQUEST_TIMEOUT" : "TIMEOUT", message, status, details, retryAfter, context);
|
|
152
324
|
this.name = "TimeoutError";
|
|
153
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
|
+
}
|
|
335
|
+
};
|
|
336
|
+
var ServiceUnavailableError = class extends LexAPIError {
|
|
337
|
+
static kind = "ServiceUnavailableError";
|
|
338
|
+
constructor(message, status = 503, details, retryAfter, context, code = "SERVICE_UNAVAILABLE") {
|
|
339
|
+
super(code, message, status, details, retryAfter, context);
|
|
340
|
+
this.name = "ServiceUnavailableError";
|
|
341
|
+
}
|
|
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
|
+
}
|
|
154
411
|
};
|
|
155
412
|
var InternalServerError = class extends LexAPIError {
|
|
156
|
-
|
|
157
|
-
|
|
413
|
+
static kind = "InternalServerError";
|
|
414
|
+
constructor(message, status = 500, details, retryAfter, context) {
|
|
415
|
+
super("INTERNAL", message, status, details, retryAfter, context);
|
|
158
416
|
this.name = "InternalServerError";
|
|
159
417
|
}
|
|
160
418
|
};
|
|
161
419
|
var NetworkError = class extends LexAPIError {
|
|
420
|
+
static kind = "NetworkError";
|
|
162
421
|
cause;
|
|
163
422
|
constructor(message, cause) {
|
|
164
|
-
super("
|
|
423
|
+
super("CONNECTION_ERROR", message, 0);
|
|
165
424
|
this.name = "NetworkError";
|
|
166
425
|
this.cause = cause;
|
|
167
426
|
}
|
|
168
427
|
};
|
|
428
|
+
var RequestAbortedError = class extends LexAPIError {
|
|
429
|
+
static kind = "RequestAbortedError";
|
|
430
|
+
cause;
|
|
431
|
+
constructor(message, cause) {
|
|
432
|
+
super("ABORTED", message, 0);
|
|
433
|
+
this.name = "RequestAbortedError";
|
|
434
|
+
this.cause = cause;
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
var InvalidResponseError = class extends LexAPIError {
|
|
438
|
+
static kind = "InvalidResponseError";
|
|
439
|
+
constructor(message, status, rawText, context) {
|
|
440
|
+
super("INVALID_RESPONSE", message, status, void 0, void 0, {
|
|
441
|
+
...context,
|
|
442
|
+
body: rawText === void 0 ? void 0 : rawText.slice(0, 500)
|
|
443
|
+
});
|
|
444
|
+
this.name = "InvalidResponseError";
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
var IncompleteExportError = class extends LexAPIError {
|
|
448
|
+
static kind = "IncompleteExportError";
|
|
449
|
+
/** Rows yielded before the stream ended. */
|
|
450
|
+
rowsRead;
|
|
451
|
+
/**
|
|
452
|
+
* @param details the server's `_error` line body (`{ code, message }`) when
|
|
453
|
+
* one arrived; `undefined` for a missing or `complete: false` trailer.
|
|
454
|
+
*/
|
|
455
|
+
constructor(message, rowsRead, details) {
|
|
456
|
+
super("INCOMPLETE_EXPORT", message, 0, details);
|
|
457
|
+
this.name = "IncompleteExportError";
|
|
458
|
+
this.rowsRead = rowsRead;
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
function isLexAPIError(value, errorClass) {
|
|
462
|
+
return value instanceof (errorClass ?? LexAPIError);
|
|
463
|
+
}
|
|
169
464
|
function normalizeRetryAfterSeconds(value) {
|
|
170
465
|
if (!Number.isFinite(value)) return 0;
|
|
171
466
|
if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
|
|
@@ -184,54 +479,211 @@ function detailsField(details, key) {
|
|
|
184
479
|
}
|
|
185
480
|
return void 0;
|
|
186
481
|
}
|
|
482
|
+
function isQuota429(body, headers) {
|
|
483
|
+
if (detailsField(body, "code") === "QUOTA_EXHAUSTED") return true;
|
|
484
|
+
const resetsAt = detailsField(detailsField(body, "usage"), "resetsAt");
|
|
485
|
+
if (typeof resetsAt !== "string") return false;
|
|
486
|
+
if (headers?.retryAfter !== void 0 && headers.retryAfter.trim() !== "") return false;
|
|
487
|
+
return detailsField(body, "retryAfter") === void 0;
|
|
488
|
+
}
|
|
489
|
+
function detailsOrBodyField(details, body, key) {
|
|
490
|
+
const fromDetails = detailsField(details, key);
|
|
491
|
+
return fromDetails !== void 0 ? fromDetails : bodyField(body, key);
|
|
492
|
+
}
|
|
493
|
+
function bodyField(body, key) {
|
|
494
|
+
return detailsField(body, key);
|
|
495
|
+
}
|
|
187
496
|
function usageField(record, key) {
|
|
188
497
|
return detailsField(record["usage"], key);
|
|
189
498
|
}
|
|
190
499
|
|
|
500
|
+
// src/headers.ts
|
|
501
|
+
function str(headers, name) {
|
|
502
|
+
const value = headers.get(name);
|
|
503
|
+
return value === null ? void 0 : value;
|
|
504
|
+
}
|
|
505
|
+
function int(headers, name) {
|
|
506
|
+
const value = headers.get(name);
|
|
507
|
+
if (value === null) return void 0;
|
|
508
|
+
const parsed = Number.parseInt(value, 10);
|
|
509
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
510
|
+
}
|
|
511
|
+
function compact(obj) {
|
|
512
|
+
const out = {};
|
|
513
|
+
for (const [k, v] of Object.entries(obj)) if (v !== void 0) out[k] = v;
|
|
514
|
+
return Object.keys(out).length ? out : void 0;
|
|
515
|
+
}
|
|
516
|
+
function parseResponseHeaders(source) {
|
|
517
|
+
const h = "headers" in source ? source.headers : source;
|
|
518
|
+
const textAvailable = str(h, "x-text-available");
|
|
519
|
+
const ignored = str(h, "x-ignored-documenttypes");
|
|
520
|
+
const parsed = {
|
|
521
|
+
source: str(h, "x-source"),
|
|
522
|
+
searchSource: str(h, "x-search-source"),
|
|
523
|
+
searchCache: str(h, "x-search-cache"),
|
|
524
|
+
language: str(h, "x-language"),
|
|
525
|
+
languageFallback: str(h, "x-language-fallback"),
|
|
526
|
+
textAvailable: textAvailable === void 0 ? void 0 : textAvailable !== "false",
|
|
527
|
+
corpusVersion: int(h, "x-corpus-version"),
|
|
528
|
+
corpusFetchedAt: str(h, "x-corpus-fetchedat"),
|
|
529
|
+
cache: str(h, "x-cache"),
|
|
530
|
+
warning: str(h, "x-warning"),
|
|
531
|
+
ignoredDocumentTypes: ignored === void 0 ? void 0 : ignored.split(",").filter(Boolean),
|
|
532
|
+
postFilteredBy: str(h, "x-postfiltered-by"),
|
|
533
|
+
postFilteredKept: str(h, "x-postfiltered-kept"),
|
|
534
|
+
documentTypeFanOut: int(h, "x-documenttype-fanout"),
|
|
535
|
+
languageFilter: str(h, "x-language-filter"),
|
|
536
|
+
languageKept: str(h, "x-language-kept"),
|
|
537
|
+
batch: compact({
|
|
538
|
+
corpusHits: int(h, "x-batch-corpus-hits"),
|
|
539
|
+
cellarServed: int(h, "x-batch-cellar-served"),
|
|
540
|
+
ojRecovered: int(h, "x-batch-oj-recovered"),
|
|
541
|
+
liveFetches: int(h, "x-batch-live-fetches"),
|
|
542
|
+
textUnavailable: int(h, "x-batch-text-unavailable")
|
|
543
|
+
}),
|
|
544
|
+
retryAfter: str(h, "retry-after"),
|
|
545
|
+
apiVersion: str(h, "x-lexapi-version")?.trim() || void 0,
|
|
546
|
+
release: str(h, "x-lexapi-release"),
|
|
547
|
+
languagePartialKept: int(h, "x-language-partial-kept"),
|
|
548
|
+
cacheAge: int(h, "x-cache-age"),
|
|
549
|
+
rateLimit: compact({
|
|
550
|
+
limit: int(h, "ratelimit-limit"),
|
|
551
|
+
remaining: int(h, "ratelimit-remaining"),
|
|
552
|
+
reset: int(h, "ratelimit-reset"),
|
|
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")
|
|
559
|
+
})
|
|
560
|
+
};
|
|
561
|
+
return compact(parsed) ?? {};
|
|
562
|
+
}
|
|
563
|
+
|
|
191
564
|
// src/version.ts
|
|
192
|
-
var VERSION = "0.
|
|
565
|
+
var VERSION = "0.4.0";
|
|
193
566
|
|
|
194
567
|
// src/http.ts
|
|
195
568
|
var DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
|
|
196
|
-
var DEFAULT_TIMEOUT_MS =
|
|
197
|
-
var
|
|
569
|
+
var DEFAULT_TIMEOUT_MS = 95e3;
|
|
570
|
+
var NEVER_REACHED_CODES = /* @__PURE__ */ new Set([
|
|
571
|
+
// DNS
|
|
572
|
+
"ENOTFOUND",
|
|
573
|
+
"EAI_AGAIN",
|
|
574
|
+
// TCP connect
|
|
575
|
+
"ECONNREFUSED",
|
|
576
|
+
"EHOSTUNREACH",
|
|
577
|
+
"ENETUNREACH",
|
|
578
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
579
|
+
// TLS certificate verification (handshake)
|
|
580
|
+
"CERT_HAS_EXPIRED",
|
|
581
|
+
"CERT_NOT_YET_VALID",
|
|
582
|
+
"CERT_REVOKED",
|
|
583
|
+
"CERT_UNTRUSTED",
|
|
584
|
+
"CERT_REJECTED",
|
|
585
|
+
"CERT_SIGNATURE_FAILURE",
|
|
586
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
587
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
588
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
589
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
590
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
591
|
+
"HOSTNAME_MISMATCH",
|
|
592
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
593
|
+
// TLS handshake alerts / protocol negotiation
|
|
594
|
+
"ERR_SSL_WRONG_VERSION_NUMBER",
|
|
595
|
+
"ERR_SSL_UNSUPPORTED_PROTOCOL",
|
|
596
|
+
"ERR_SSL_NO_PROTOCOLS_AVAILABLE",
|
|
597
|
+
"ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE",
|
|
598
|
+
"ERR_SSL_TLSV1_ALERT_PROTOCOL_VERSION",
|
|
599
|
+
"ERR_SSL_TLSV1_ALERT_UNKNOWN_CA",
|
|
600
|
+
"ERR_SSL_SSLV3_ALERT_BAD_CERTIFICATE",
|
|
601
|
+
"ERR_SSL_SSLV3_ALERT_CERTIFICATE_EXPIRED"
|
|
602
|
+
]);
|
|
603
|
+
var CONNECT_SYSCALL_CODES = /* @__PURE__ */ new Set(["ETIMEDOUT"]);
|
|
604
|
+
var NEVER_REACHED_STATUSES = /* @__PURE__ */ new Set([521, 522, 523]);
|
|
605
|
+
var ORIGIN_DEPENDENT_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
|
|
606
|
+
var PROXY_STATUSES = /* @__PURE__ */ new Set([520, 524]);
|
|
607
|
+
function isNeverReachedError(error, depth = 0) {
|
|
608
|
+
if (depth > 6 || typeof error !== "object" || error === null) return false;
|
|
609
|
+
const { code, syscall, cause, errors } = error;
|
|
610
|
+
if (typeof code === "string") {
|
|
611
|
+
if (NEVER_REACHED_CODES.has(code)) return true;
|
|
612
|
+
if (CONNECT_SYSCALL_CODES.has(code) && syscall === "connect") return true;
|
|
613
|
+
}
|
|
614
|
+
if (Array.isArray(errors) && errors.length > 0 && errors.every((e) => isNeverReachedError(e, depth + 1))) {
|
|
615
|
+
return true;
|
|
616
|
+
}
|
|
617
|
+
return isNeverReachedError(cause, depth + 1);
|
|
618
|
+
}
|
|
619
|
+
function isAppOrigin(error) {
|
|
620
|
+
return error.headers?.apiVersion !== void 0 || error.headers?.rateLimit?.limit !== void 0;
|
|
621
|
+
}
|
|
198
622
|
function isBrowserRuntime() {
|
|
199
623
|
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
200
624
|
}
|
|
625
|
+
var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
201
626
|
var HttpClient = class {
|
|
627
|
+
#apiKey;
|
|
202
628
|
opts;
|
|
203
629
|
userAgent;
|
|
204
630
|
constructor(opts) {
|
|
205
|
-
|
|
631
|
+
const { apiKey, ...rest } = opts;
|
|
632
|
+
this.#apiKey = apiKey;
|
|
633
|
+
this.opts = rest;
|
|
206
634
|
this.userAgent = opts.userAgentSuffix ? `lexapi-typescript/${VERSION} ${opts.userAgentSuffix}` : `lexapi-typescript/${VERSION}`;
|
|
207
635
|
}
|
|
208
|
-
/**
|
|
636
|
+
/** API base URL. */
|
|
637
|
+
get baseUrl() {
|
|
638
|
+
return this.opts.baseUrl;
|
|
639
|
+
}
|
|
640
|
+
/** Client-level per-attempt timeout (ms). */
|
|
641
|
+
get timeoutMs() {
|
|
642
|
+
return this.opts.timeoutMs;
|
|
643
|
+
}
|
|
644
|
+
/** Redacted view for `JSON.stringify` — never includes the API key. */
|
|
645
|
+
toJSON() {
|
|
646
|
+
return { baseUrl: this.opts.baseUrl, apiKey: "[redacted]" };
|
|
647
|
+
}
|
|
648
|
+
/** Redacted view for `util.inspect` / `console.log`. */
|
|
649
|
+
[INSPECT]() {
|
|
650
|
+
return `HttpClient { baseUrl: '${this.opts.baseUrl}', apiKey: '[redacted]' }`;
|
|
651
|
+
}
|
|
652
|
+
/** Perform a request and parse the JSON body (204 / empty body yields `{}`). */
|
|
209
653
|
async requestJson(options) {
|
|
210
654
|
const { data } = await this.requestJsonWithResponse(options);
|
|
211
655
|
return data;
|
|
212
656
|
}
|
|
213
|
-
/**
|
|
657
|
+
/**
|
|
658
|
+
* Like `requestJson`, but also exposes the raw `Response` (for header
|
|
659
|
+
* signals). The body is read inside the attempt, under its timeout.
|
|
660
|
+
*/
|
|
214
661
|
async requestJsonWithResponse(options) {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
219
|
-
return { data: await response.json(), response };
|
|
662
|
+
return this.execute(options, async (response, ctx) => ({
|
|
663
|
+
data: await readJsonBody(response, ctx.touch),
|
|
664
|
+
response
|
|
665
|
+
}));
|
|
220
666
|
}
|
|
221
667
|
/**
|
|
222
668
|
* Perform a request and return the raw successful `Response` without
|
|
223
|
-
* consuming the body (
|
|
224
|
-
*
|
|
225
|
-
*
|
|
669
|
+
* consuming the body (streaming endpoints such as `/export`). The attempt
|
|
670
|
+
* timeout covers only the response headers; the caller applies its own
|
|
671
|
+
* idle timeout to body reads. Non-2xx responses are parsed and thrown as
|
|
672
|
+
* typed errors; the retry policy applies before the first body byte.
|
|
226
673
|
*/
|
|
227
674
|
async requestRaw(options) {
|
|
228
|
-
|
|
675
|
+
return this.execute(options, async (response) => response);
|
|
676
|
+
}
|
|
677
|
+
async execute(options, onSuccess) {
|
|
678
|
+
const { method, path, query, body, signal } = options;
|
|
229
679
|
const url = `${this.opts.baseUrl}${path}${buildQuery(query)}`;
|
|
230
680
|
const timeoutMs = options.timeoutMs ?? this.opts.timeoutMs;
|
|
231
|
-
const { maxRetries, baseDelayMs, maxDelayMs } = this.opts.retry;
|
|
681
|
+
const { maxRetries, baseDelayMs, maxDelayMs, retryReadOnlyPosts } = this.opts.retry;
|
|
682
|
+
const isGet = method === "GET";
|
|
683
|
+
const free = isGet && options.free === true;
|
|
232
684
|
const headers = {
|
|
233
|
-
"x-api-key": this
|
|
234
|
-
accept: "application/json"
|
|
685
|
+
"x-api-key": this.#apiKey,
|
|
686
|
+
accept: options.accept ?? "application/json"
|
|
235
687
|
};
|
|
236
688
|
if (!isBrowserRuntime()) {
|
|
237
689
|
headers["user-agent"] = this.userAgent;
|
|
@@ -241,190 +693,453 @@ var HttpClient = class {
|
|
|
241
693
|
headers["content-type"] = "application/json";
|
|
242
694
|
serializedBody = JSON.stringify(body);
|
|
243
695
|
}
|
|
696
|
+
let incompleteRetried = false;
|
|
244
697
|
for (let attempt = 0; ; attempt++) {
|
|
698
|
+
throwIfAborted(signal, method, path);
|
|
699
|
+
const controller = new AbortController();
|
|
700
|
+
let timedOut = false;
|
|
701
|
+
let timer;
|
|
702
|
+
const touch = () => {
|
|
703
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
704
|
+
timer = setTimeout(() => {
|
|
705
|
+
timedOut = true;
|
|
706
|
+
controller.abort();
|
|
707
|
+
}, timeoutMs);
|
|
708
|
+
};
|
|
709
|
+
touch();
|
|
710
|
+
const onAbort = () => controller.abort();
|
|
711
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
712
|
+
let error;
|
|
245
713
|
let response;
|
|
714
|
+
let retryTransport = false;
|
|
246
715
|
try {
|
|
247
|
-
response = await this.
|
|
716
|
+
response = await this.opts.fetchFn(url, {
|
|
248
717
|
method,
|
|
249
718
|
headers,
|
|
250
719
|
...serializedBody !== void 0 ? { body: serializedBody } : {},
|
|
251
|
-
|
|
720
|
+
signal: controller.signal
|
|
252
721
|
});
|
|
722
|
+
touch();
|
|
723
|
+
if (response.ok) {
|
|
724
|
+
return await onSuccess(response, { signal: controller.signal, timeoutMs, touch });
|
|
725
|
+
}
|
|
726
|
+
error = await parseErrorResponse(response, touch);
|
|
253
727
|
} catch (cause) {
|
|
254
|
-
if (
|
|
255
|
-
|
|
256
|
-
await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs));
|
|
257
|
-
continue;
|
|
728
|
+
if (signal?.aborted) {
|
|
729
|
+
throw new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason);
|
|
258
730
|
}
|
|
259
|
-
|
|
731
|
+
if (cause instanceof LexAPIError && !timedOut) throw cause;
|
|
732
|
+
const failure = timedOut ? new TimeoutError(`No response bytes for ${timeoutMs}ms (${method} ${path})`, 0) : new NetworkError(
|
|
733
|
+
response === void 0 ? `Network error calling ${method} ${path}` : `Connection lost while reading the response to ${method} ${path}`,
|
|
734
|
+
cause
|
|
735
|
+
);
|
|
736
|
+
const neverReached = !timedOut && response === void 0 && isNeverReachedError(cause);
|
|
737
|
+
retryTransport = attempt < maxRetries && (neverReached || free);
|
|
738
|
+
if (!retryTransport) throw failure;
|
|
739
|
+
error = failure;
|
|
740
|
+
} finally {
|
|
741
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
742
|
+
signal?.removeEventListener("abort", onAbort);
|
|
260
743
|
}
|
|
261
|
-
if (
|
|
262
|
-
|
|
263
|
-
const retryable = RETRYABLE_STATUSES.has(response.status) && (method === "GET" || response.status === 429);
|
|
264
|
-
if (attempt < maxRetries && retryable) {
|
|
265
|
-
const serverWaitSeconds = serverDirectedWaitSeconds(response, error);
|
|
266
|
-
const waitMs = serverWaitSeconds !== void 0 ? Math.min(serverWaitSeconds * 1e3, maxDelayMs) : fullJitterBackoff(attempt, baseDelayMs, maxDelayMs);
|
|
267
|
-
await sleep(waitMs);
|
|
744
|
+
if (retryTransport) {
|
|
745
|
+
await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs), signal, method, path);
|
|
268
746
|
continue;
|
|
269
747
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
try {
|
|
277
|
-
return await this.opts.fetchFn(url, {
|
|
278
|
-
method: init.method,
|
|
279
|
-
headers: init.headers,
|
|
280
|
-
...init.body !== void 0 ? { body: init.body } : {},
|
|
281
|
-
signal: controller.signal
|
|
282
|
-
});
|
|
283
|
-
} catch (cause) {
|
|
284
|
-
if (controller.signal.aborted) {
|
|
285
|
-
throw new TimeoutError(`Request timed out after ${init.timeoutMs}ms`, 0);
|
|
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;
|
|
751
|
+
const waitMs = error.retryAfter !== void 0 ? Math.min(error.retryAfter * 1e3, maxDelayMs) : fullJitterBackoff(attempt, baseDelayMs, maxDelayMs);
|
|
752
|
+
await sleep(waitMs, signal, method, path);
|
|
753
|
+
continue;
|
|
286
754
|
}
|
|
287
|
-
throw
|
|
288
|
-
} finally {
|
|
289
|
-
clearTimeout(timer);
|
|
755
|
+
throw error;
|
|
290
756
|
}
|
|
291
757
|
}
|
|
292
758
|
};
|
|
293
|
-
|
|
294
|
-
|
|
759
|
+
function shouldRetryStatus(error, call) {
|
|
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;
|
|
763
|
+
if (status === 429) return !(error instanceof RateLimitedError && error.quotaExhausted);
|
|
764
|
+
if (NEVER_REACHED_STATUSES.has(status)) return true;
|
|
765
|
+
if (ORIGIN_DEPENDENT_STATUSES.has(status)) {
|
|
766
|
+
if (isAppOrigin(error)) return call.isGet || call.readOnly;
|
|
767
|
+
return call.free;
|
|
768
|
+
}
|
|
769
|
+
if (PROXY_STATUSES.has(status)) return call.free;
|
|
770
|
+
return false;
|
|
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
|
+
}
|
|
779
|
+
async function readBodyText(response, touch) {
|
|
780
|
+
if (response.body === null || touch === void 0) return response.text();
|
|
781
|
+
const reader = response.body.getReader();
|
|
782
|
+
const decoder = new TextDecoder();
|
|
783
|
+
const parts = [];
|
|
784
|
+
for (; ; ) {
|
|
785
|
+
const { done, value } = await reader.read();
|
|
786
|
+
if (done) break;
|
|
787
|
+
touch();
|
|
788
|
+
parts.push(decoder.decode(value, { stream: true }));
|
|
789
|
+
}
|
|
790
|
+
parts.push(decoder.decode());
|
|
791
|
+
return parts.join("");
|
|
792
|
+
}
|
|
793
|
+
async function readJsonBody(response, touch) {
|
|
794
|
+
if (response.status === 204) return {};
|
|
795
|
+
const text = await readBodyText(response, touch);
|
|
796
|
+
if (text.trim() === "") return {};
|
|
295
797
|
try {
|
|
296
|
-
|
|
798
|
+
return JSON.parse(text);
|
|
297
799
|
} catch {
|
|
800
|
+
throw new InvalidResponseError(
|
|
801
|
+
`Expected a JSON body (HTTP ${response.status}, content-type ${response.headers.get("content-type") ?? "none"})`,
|
|
802
|
+
response.status,
|
|
803
|
+
text,
|
|
804
|
+
{ headers: parseResponseHeaders(response) }
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
function throwIfAborted(signal, method, path) {
|
|
809
|
+
if (signal?.aborted) {
|
|
810
|
+
throw new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
async function parseErrorResponse(response, touch) {
|
|
814
|
+
let body;
|
|
815
|
+
try {
|
|
816
|
+
const text = await readBodyText(response, touch);
|
|
817
|
+
body = text.trim() === "" ? void 0 : JSON.parse(text);
|
|
818
|
+
} catch (cause) {
|
|
819
|
+
if (!(cause instanceof SyntaxError)) throw cause;
|
|
298
820
|
body = void 0;
|
|
299
821
|
}
|
|
300
|
-
|
|
822
|
+
const hint = headerRetryAfterSeconds(response) ?? (response.status === 429 ? resetHeaderSeconds(response, "ratelimit-reset") : void 0);
|
|
823
|
+
return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response));
|
|
301
824
|
}
|
|
302
825
|
function headerRetryAfterSeconds(response) {
|
|
303
|
-
const
|
|
304
|
-
if (
|
|
305
|
-
const
|
|
306
|
-
if (
|
|
826
|
+
const raw = response.headers.get("retry-after");
|
|
827
|
+
if (raw === null) return void 0;
|
|
828
|
+
const header = raw.trim();
|
|
829
|
+
if (header === "") return void 0;
|
|
830
|
+
if (/^\d+(\.\d+)?$/.test(header)) return normalizeRetryAfterSeconds(Number(header));
|
|
831
|
+
if (/^[-+]?\d/.test(header)) return void 0;
|
|
307
832
|
const date = Date.parse(header);
|
|
308
833
|
if (!Number.isNaN(date)) return Math.max(0, Math.round((date - Date.now()) / 1e3));
|
|
309
834
|
return void 0;
|
|
310
835
|
}
|
|
311
|
-
function
|
|
312
|
-
const
|
|
313
|
-
if (
|
|
314
|
-
const
|
|
315
|
-
if (
|
|
316
|
-
|
|
317
|
-
if (Number.isFinite(seconds)) return normalizeRetryAfterSeconds(seconds);
|
|
318
|
-
}
|
|
319
|
-
return error.retryAfter;
|
|
836
|
+
function resetHeaderSeconds(response, name) {
|
|
837
|
+
const raw = response.headers.get(name);
|
|
838
|
+
if (raw === null || raw.trim() === "") return void 0;
|
|
839
|
+
const seconds = Number(raw);
|
|
840
|
+
if (!Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
841
|
+
return normalizeRetryAfterSeconds(seconds);
|
|
320
842
|
}
|
|
321
843
|
function fullJitterBackoff(attempt, baseDelayMs, maxDelayMs) {
|
|
322
844
|
return Math.random() * Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
|
|
323
845
|
}
|
|
324
|
-
function sleep(ms) {
|
|
325
|
-
return new Promise((resolve) =>
|
|
846
|
+
function sleep(ms, signal, method, path) {
|
|
847
|
+
return new Promise((resolve, reject) => {
|
|
848
|
+
if (signal?.aborted) {
|
|
849
|
+
reject(new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason));
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
const onAbort = () => {
|
|
853
|
+
clearTimeout(timer);
|
|
854
|
+
reject(new RequestAbortedError(`Request ${method} ${path} was aborted during a retry wait`, signal?.reason));
|
|
855
|
+
};
|
|
856
|
+
const timer = setTimeout(() => {
|
|
857
|
+
signal?.removeEventListener("abort", onAbort);
|
|
858
|
+
resolve();
|
|
859
|
+
}, ms);
|
|
860
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
861
|
+
});
|
|
326
862
|
}
|
|
327
863
|
function buildQuery(query) {
|
|
328
864
|
if (!query) return "";
|
|
329
865
|
const params = new URLSearchParams();
|
|
330
866
|
for (const [key, value] of Object.entries(query)) {
|
|
331
|
-
if (value
|
|
867
|
+
if (value === void 0) continue;
|
|
868
|
+
if (Array.isArray(value)) {
|
|
869
|
+
for (const item of value) {
|
|
870
|
+
params.append(key, String(item));
|
|
871
|
+
}
|
|
872
|
+
} else {
|
|
873
|
+
params.set(key, String(value));
|
|
874
|
+
}
|
|
332
875
|
}
|
|
333
876
|
const qs = params.toString();
|
|
334
877
|
return qs ? `?${qs}` : "";
|
|
335
878
|
}
|
|
336
879
|
|
|
337
880
|
// src/export.ts
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
881
|
+
var NdjsonReader = class {
|
|
882
|
+
constructor(body, options) {
|
|
883
|
+
this.options = options;
|
|
884
|
+
this.reader = body.getReader();
|
|
885
|
+
const { signal } = options;
|
|
886
|
+
if (signal?.aborted) this.cancel();
|
|
887
|
+
else signal?.addEventListener("abort", this.onAbort, { once: true });
|
|
888
|
+
}
|
|
889
|
+
reader;
|
|
890
|
+
decoder = new TextDecoder();
|
|
891
|
+
/** Pieces of the line currently being received. */
|
|
892
|
+
partial = [];
|
|
893
|
+
/** Complete lines not yet handed out. */
|
|
894
|
+
ready = [];
|
|
895
|
+
eof = false;
|
|
896
|
+
released = false;
|
|
897
|
+
/** Data rows handed out so far (for error messages). */
|
|
898
|
+
rows = 0;
|
|
899
|
+
/** Releases the connection the moment the caller aborts — even while nobody is reading. */
|
|
900
|
+
onAbort = () => this.cancel();
|
|
901
|
+
/** Next trimmed, non-empty line, or `undefined` at EOF. */
|
|
902
|
+
async nextLine() {
|
|
903
|
+
const { signal } = this.options;
|
|
904
|
+
if (signal?.aborted) {
|
|
905
|
+
this.cancel();
|
|
906
|
+
throw new RequestAbortedError("Export stream was aborted", signal.reason);
|
|
907
|
+
}
|
|
343
908
|
for (; ; ) {
|
|
344
|
-
const
|
|
345
|
-
if (
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
909
|
+
const line = this.ready.shift();
|
|
910
|
+
if (line !== void 0) return line;
|
|
911
|
+
if (this.eof) {
|
|
912
|
+
const tail = this.partial.join("").trim();
|
|
913
|
+
this.partial = [];
|
|
914
|
+
return tail || void 0;
|
|
915
|
+
}
|
|
916
|
+
const chunk = await this.read();
|
|
917
|
+
if (chunk === void 0) {
|
|
918
|
+
this.eof = true;
|
|
919
|
+
this.ingest(this.decoder.decode());
|
|
920
|
+
this.release();
|
|
921
|
+
} else {
|
|
922
|
+
this.ingest(this.decoder.decode(chunk, { stream: true }));
|
|
352
923
|
}
|
|
353
924
|
}
|
|
354
|
-
buffer += decoder.decode();
|
|
355
|
-
const tail = buffer.trim();
|
|
356
|
-
if (tail) yield tail;
|
|
357
|
-
} finally {
|
|
358
|
-
reader.releaseLock();
|
|
359
925
|
}
|
|
926
|
+
ingest(text) {
|
|
927
|
+
let pos = 0;
|
|
928
|
+
for (; ; ) {
|
|
929
|
+
const newline = text.indexOf("\n", pos);
|
|
930
|
+
if (newline === -1) break;
|
|
931
|
+
this.partial.push(text.slice(pos, newline));
|
|
932
|
+
const line = this.partial.join("").trim();
|
|
933
|
+
this.partial = [];
|
|
934
|
+
if (line) this.ready.push(line);
|
|
935
|
+
pos = newline + 1;
|
|
936
|
+
}
|
|
937
|
+
if (pos < text.length) this.partial.push(text.slice(pos));
|
|
938
|
+
}
|
|
939
|
+
async read() {
|
|
940
|
+
const { idleTimeoutMs, signal } = this.options;
|
|
941
|
+
if (signal?.aborted) {
|
|
942
|
+
this.cancel();
|
|
943
|
+
throw new RequestAbortedError("Export stream was aborted", signal.reason);
|
|
944
|
+
}
|
|
945
|
+
let timer;
|
|
946
|
+
let onAbort;
|
|
947
|
+
const interruptions = new Promise((_, reject) => {
|
|
948
|
+
if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0) {
|
|
949
|
+
timer = setTimeout(() => {
|
|
950
|
+
reject(
|
|
951
|
+
new TimeoutError(`Export stream received no data for ${idleTimeoutMs}ms (after ${this.rows} rows)`, 0)
|
|
952
|
+
);
|
|
953
|
+
}, idleTimeoutMs);
|
|
954
|
+
}
|
|
955
|
+
if (signal) {
|
|
956
|
+
onAbort = () => reject(new RequestAbortedError("Export stream was aborted", signal.reason));
|
|
957
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
958
|
+
}
|
|
959
|
+
});
|
|
960
|
+
try {
|
|
961
|
+
const result = await Promise.race([this.reader.read(), interruptions]);
|
|
962
|
+
if (signal?.aborted) throw new RequestAbortedError("Export stream was aborted", signal.reason);
|
|
963
|
+
return result.done ? void 0 : result.value;
|
|
964
|
+
} catch (cause) {
|
|
965
|
+
this.cancel();
|
|
966
|
+
if (cause instanceof LexAPIError) throw cause;
|
|
967
|
+
throw new NetworkError(`Export stream interrupted after ${this.rows} rows`, cause);
|
|
968
|
+
} finally {
|
|
969
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
970
|
+
if (onAbort) signal?.removeEventListener("abort", onAbort);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* Cancel the body immediately (even while a read is pending) and release
|
|
975
|
+
* the connection. Not awaited: a tee'd (cloned) body only settles
|
|
976
|
+
* `cancel()` once every branch is cancelled.
|
|
977
|
+
*/
|
|
978
|
+
cancel() {
|
|
979
|
+
if (this.released) return;
|
|
980
|
+
this.eof = true;
|
|
981
|
+
void this.reader.cancel().catch(() => void 0);
|
|
982
|
+
this.release();
|
|
983
|
+
}
|
|
984
|
+
release() {
|
|
985
|
+
if (this.released) return;
|
|
986
|
+
this.released = true;
|
|
987
|
+
this.options.signal?.removeEventListener("abort", this.onAbort);
|
|
988
|
+
try {
|
|
989
|
+
this.reader.releaseLock();
|
|
990
|
+
} catch {
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
function liftEnvelope(parsed, key) {
|
|
995
|
+
const inner = parsed[key];
|
|
996
|
+
if (typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
|
|
997
|
+
return { ...inner, ...parsed };
|
|
998
|
+
}
|
|
999
|
+
return parsed;
|
|
1000
|
+
}
|
|
1001
|
+
function errorLine(parsed) {
|
|
1002
|
+
const keys = Object.keys(parsed);
|
|
1003
|
+
if (keys.length !== 1 || keys[0] !== "_error") return void 0;
|
|
1004
|
+
const value = parsed._error;
|
|
1005
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: String(value) };
|
|
360
1006
|
}
|
|
361
1007
|
function parseLine(line) {
|
|
362
1008
|
try {
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
`Malformed NDJSON line in export stream: ${line.slice(0, 120)}`,
|
|
368
|
-
0,
|
|
369
|
-
cause
|
|
370
|
-
);
|
|
1009
|
+
const value = JSON.parse(line);
|
|
1010
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
1011
|
+
} catch {
|
|
1012
|
+
return void 0;
|
|
371
1013
|
}
|
|
372
1014
|
}
|
|
373
1015
|
var ExportStreamImpl = class {
|
|
374
1016
|
meta;
|
|
375
1017
|
done;
|
|
1018
|
+
error;
|
|
376
1019
|
headers;
|
|
377
1020
|
lines;
|
|
378
1021
|
pendingFirstRow;
|
|
379
1022
|
consumed = false;
|
|
1023
|
+
invalidLines = 0;
|
|
1024
|
+
get complete() {
|
|
1025
|
+
return this.done !== void 0 && this.done.complete !== false && this.error === void 0;
|
|
1026
|
+
}
|
|
1027
|
+
incomplete(reason) {
|
|
1028
|
+
return new IncompleteExportError(
|
|
1029
|
+
`Export stream is incomplete after ${this.lines.rows} rows: ${reason}`,
|
|
1030
|
+
this.lines.rows,
|
|
1031
|
+
this.error
|
|
1032
|
+
);
|
|
1033
|
+
}
|
|
1034
|
+
failureReason() {
|
|
1035
|
+
if (this.error !== void 0) {
|
|
1036
|
+
return `the server reported an error mid-stream (${String(this.error.code ?? "UNKNOWN")}: ${String(this.error.message ?? "")})`;
|
|
1037
|
+
}
|
|
1038
|
+
return "its _done trailer says complete: false";
|
|
1039
|
+
}
|
|
1040
|
+
get rowsRead() {
|
|
1041
|
+
return this.lines.rows;
|
|
1042
|
+
}
|
|
1043
|
+
get truncated() {
|
|
1044
|
+
if (typeof this.done?.truncated === "boolean") return this.done.truncated;
|
|
1045
|
+
if (this.headers.truncated !== void 0) return this.headers.truncated;
|
|
1046
|
+
if (typeof this.meta?.truncated === "boolean") return this.meta.truncated;
|
|
1047
|
+
return void 0;
|
|
1048
|
+
}
|
|
380
1049
|
constructor(lines, headers) {
|
|
381
1050
|
this.lines = lines;
|
|
382
1051
|
this.headers = headers;
|
|
383
1052
|
}
|
|
1053
|
+
async cancel() {
|
|
1054
|
+
this.consumed = true;
|
|
1055
|
+
this.lines.cancel();
|
|
1056
|
+
}
|
|
384
1057
|
/** Read the leading line so `meta` is available before iteration starts. */
|
|
385
1058
|
async init() {
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
1059
|
+
let parsed;
|
|
1060
|
+
for (; ; ) {
|
|
1061
|
+
const first = await this.lines.nextLine();
|
|
1062
|
+
if (first === void 0) return;
|
|
1063
|
+
parsed = parseLine(first);
|
|
1064
|
+
if (parsed !== void 0) {
|
|
1065
|
+
const error = errorLine(parsed);
|
|
1066
|
+
if (error === void 0) break;
|
|
1067
|
+
this.error = error;
|
|
1068
|
+
continue;
|
|
1069
|
+
}
|
|
1070
|
+
this.invalidLines++;
|
|
1071
|
+
}
|
|
389
1072
|
if ("_meta" in parsed) {
|
|
390
|
-
this.meta = parsed;
|
|
1073
|
+
this.meta = liftEnvelope(parsed, "_meta");
|
|
391
1074
|
} else if ("_done" in parsed) {
|
|
392
|
-
this.done = parsed;
|
|
1075
|
+
this.done = liftEnvelope(parsed, "_done");
|
|
1076
|
+
this.lines.cancel();
|
|
393
1077
|
} else {
|
|
394
1078
|
this.pendingFirstRow = parsed;
|
|
395
1079
|
}
|
|
396
1080
|
}
|
|
397
1081
|
async *[Symbol.asyncIterator]() {
|
|
398
1082
|
if (this.consumed) {
|
|
399
|
-
|
|
1083
|
+
if (this.complete) return;
|
|
1084
|
+
if (this.done !== void 0 || this.error !== void 0) throw this.incomplete(this.failureReason());
|
|
1085
|
+
throw new IncompleteExportError(
|
|
1086
|
+
`Export stream was ended before its _done trailer (after ${this.lines.rows} rows) \u2014 call export() again to re-read`,
|
|
1087
|
+
this.lines.rows
|
|
1088
|
+
);
|
|
400
1089
|
}
|
|
401
1090
|
this.consumed = true;
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
if (
|
|
410
|
-
|
|
411
|
-
if ("_done" in parsed) {
|
|
412
|
-
this.done = parsed;
|
|
1091
|
+
try {
|
|
1092
|
+
if (this.pendingFirstRow !== void 0) {
|
|
1093
|
+
const row = this.pendingFirstRow;
|
|
1094
|
+
this.pendingFirstRow = void 0;
|
|
1095
|
+
this.lines.rows++;
|
|
1096
|
+
yield row;
|
|
1097
|
+
}
|
|
1098
|
+
if (this.done !== void 0) {
|
|
1099
|
+
if (!this.complete) throw this.incomplete(this.failureReason());
|
|
413
1100
|
return;
|
|
414
1101
|
}
|
|
415
|
-
|
|
416
|
-
|
|
1102
|
+
for (; ; ) {
|
|
1103
|
+
const line = await this.lines.nextLine();
|
|
1104
|
+
if (line === void 0) {
|
|
1105
|
+
if (this.error !== void 0) throw this.incomplete(this.failureReason());
|
|
1106
|
+
throw new IncompleteExportError(
|
|
1107
|
+
`Export stream ended without its _done trailer after ${this.lines.rows} rows \u2014 the export is incomplete`,
|
|
1108
|
+
this.lines.rows
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
const parsed = parseLine(line);
|
|
1112
|
+
if (parsed === void 0) {
|
|
1113
|
+
this.invalidLines++;
|
|
1114
|
+
continue;
|
|
1115
|
+
}
|
|
1116
|
+
if ("_done" in parsed) {
|
|
1117
|
+
this.done = liftEnvelope(parsed, "_done");
|
|
1118
|
+
if (!this.complete) throw this.incomplete(this.failureReason());
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
if ("_meta" in parsed) continue;
|
|
1122
|
+
const error = errorLine(parsed);
|
|
1123
|
+
if (error !== void 0) {
|
|
1124
|
+
this.error = error;
|
|
1125
|
+
continue;
|
|
1126
|
+
}
|
|
1127
|
+
this.lines.rows++;
|
|
1128
|
+
yield parsed;
|
|
1129
|
+
}
|
|
1130
|
+
} finally {
|
|
1131
|
+
this.lines.cancel();
|
|
417
1132
|
}
|
|
418
1133
|
}
|
|
419
1134
|
};
|
|
420
|
-
async function createExportStream(response) {
|
|
1135
|
+
async function createExportStream(response, options = {}) {
|
|
421
1136
|
if (response.body === null) {
|
|
422
1137
|
throw new LexAPIError("INTERNAL", "Export response had no body stream", response.status);
|
|
423
1138
|
}
|
|
424
1139
|
const totalHeader = response.headers.get("x-export-total");
|
|
425
1140
|
const streamingHeader = response.headers.get("x-export-streaming");
|
|
426
1141
|
const truncatedHeader = response.headers.get("x-export-truncated");
|
|
427
|
-
const stream = new ExportStreamImpl(
|
|
1142
|
+
const stream = new ExportStreamImpl(new NdjsonReader(response.body, options), {
|
|
428
1143
|
total: totalHeader !== null ? Number(totalHeader) : void 0,
|
|
429
1144
|
streaming: streamingHeader !== null ? Number(streamingHeader) : void 0,
|
|
430
1145
|
truncated: truncatedHeader !== null ? truncatedHeader === "1" : void 0
|
|
@@ -439,87 +1154,139 @@ var WebhooksAPI = class {
|
|
|
439
1154
|
constructor(http) {
|
|
440
1155
|
this.http = http;
|
|
441
1156
|
}
|
|
1157
|
+
async call(options) {
|
|
1158
|
+
const { data, response } = await this.http.requestJsonWithResponse(options);
|
|
1159
|
+
if (typeof data !== "object" || data === null) return data;
|
|
1160
|
+
return { ...data, headers: parseResponseHeaders(response) };
|
|
1161
|
+
}
|
|
442
1162
|
/**
|
|
443
1163
|
* `GET /webhooks` — every webhook owned by the caller, newest first.
|
|
444
1164
|
* The `secret` is never returned here (only once, on creation).
|
|
445
1165
|
*/
|
|
446
1166
|
async list(options) {
|
|
447
|
-
return this.
|
|
1167
|
+
return this.call({
|
|
448
1168
|
method: "GET",
|
|
449
1169
|
path: "/webhooks",
|
|
450
|
-
|
|
1170
|
+
free: true,
|
|
1171
|
+
timeoutMs: options?.timeoutMs,
|
|
1172
|
+
signal: options?.signal
|
|
451
1173
|
});
|
|
452
1174
|
}
|
|
453
1175
|
/**
|
|
454
|
-
* `POST /webhooks` —
|
|
455
|
-
*
|
|
456
|
-
*
|
|
457
|
-
*
|
|
458
|
-
*
|
|
1176
|
+
* `POST /webhooks` — needs `searchCriteria`, `watchCelex`, or both. If
|
|
1177
|
+
* `secret` is omitted the server generates one and returns it in this
|
|
1178
|
+
* response ONLY — store it. Rejected with 400 (`InvalidParamsError`):
|
|
1179
|
+
* unsupported criteria or a watch list above the plan limit carry a
|
|
1180
|
+
* `details` list; the tier webhook ceiling (FREE=0, STARTER=2,
|
|
1181
|
+
* PROFESSIONAL=10, BUSINESS=50, SCALE=100, ENTERPRISE=100) has no
|
|
1182
|
+
* `details` — read `current` / `limit` from `error.body`.
|
|
459
1183
|
*/
|
|
460
1184
|
async create(request, options) {
|
|
461
|
-
return this.
|
|
1185
|
+
return this.call({
|
|
462
1186
|
method: "POST",
|
|
463
1187
|
path: "/webhooks",
|
|
464
1188
|
body: request,
|
|
465
|
-
timeoutMs: options?.timeoutMs
|
|
1189
|
+
timeoutMs: options?.timeoutMs,
|
|
1190
|
+
signal: options?.signal
|
|
466
1191
|
});
|
|
467
1192
|
}
|
|
468
|
-
/** `GET /webhooks/{id}` — full details
|
|
1193
|
+
/** `GET /webhooks/{id}` — full details incl. `retryPolicy` and the 20 most recent deliveries. */
|
|
469
1194
|
async get(id, options) {
|
|
470
|
-
return this.
|
|
1195
|
+
return this.call({
|
|
471
1196
|
method: "GET",
|
|
472
1197
|
path: `/webhooks/${encodeURIComponent(id)}`,
|
|
473
|
-
|
|
1198
|
+
free: true,
|
|
1199
|
+
timeoutMs: options?.timeoutMs,
|
|
1200
|
+
signal: options?.signal
|
|
474
1201
|
});
|
|
475
1202
|
}
|
|
476
1203
|
/**
|
|
477
1204
|
* `PUT /webhooks/{id}` — partial update; only supplied fields change.
|
|
478
|
-
*
|
|
479
|
-
* (
|
|
1205
|
+
* `watchCelex` replaces the whole list; `searchCriteria: null` removes the
|
|
1206
|
+
* criteria (one of the two must remain). Setting `status: "ACTIVE"`
|
|
1207
|
+
* resets `consecutiveFailures`; moving a `FAILED` or `PAUSED` webhook to
|
|
1208
|
+
* `ACTIVE` also re-queues its deliveries from the last 7 days that ran out
|
|
1209
|
+
* of retries (count in `requeuedDeliveries`, 0 otherwise).
|
|
480
1210
|
*/
|
|
481
1211
|
async update(id, request, options) {
|
|
482
|
-
return this.
|
|
1212
|
+
return this.call({
|
|
483
1213
|
method: "PUT",
|
|
484
1214
|
path: `/webhooks/${encodeURIComponent(id)}`,
|
|
485
1215
|
body: request,
|
|
486
|
-
timeoutMs: options?.timeoutMs
|
|
1216
|
+
timeoutMs: options?.timeoutMs,
|
|
1217
|
+
signal: options?.signal
|
|
487
1218
|
});
|
|
488
1219
|
}
|
|
489
1220
|
/**
|
|
490
1221
|
* `DELETE /webhooks/{id}` — permanently deletes the webhook and its
|
|
491
|
-
* delivery history. Resolves
|
|
492
|
-
* `
|
|
1222
|
+
* delivery history. Resolves with the server's `{ success, message }`
|
|
1223
|
+
* (an empty object plus `headers` on a bodiless 204); a repeat delete
|
|
1224
|
+
* throws `NotFoundError`.
|
|
493
1225
|
*/
|
|
494
1226
|
async delete(id, options) {
|
|
495
|
-
|
|
1227
|
+
return this.call({
|
|
496
1228
|
method: "DELETE",
|
|
497
1229
|
path: `/webhooks/${encodeURIComponent(id)}`,
|
|
498
|
-
timeoutMs: options?.timeoutMs
|
|
1230
|
+
timeoutMs: options?.timeoutMs,
|
|
1231
|
+
signal: options?.signal
|
|
499
1232
|
});
|
|
500
1233
|
}
|
|
501
1234
|
/**
|
|
502
1235
|
* `POST /webhooks/{id}/test` — synchronously POSTs a `webhook.test`
|
|
503
1236
|
* payload (HMAC-SHA256 signed via `X-Webhook-Signature`) to the webhook
|
|
504
1237
|
* URL and returns the upstream result. 10 s timeout; redirects are not
|
|
505
|
-
* followed.
|
|
1238
|
+
* followed; not recorded in the delivery history.
|
|
506
1239
|
*/
|
|
507
1240
|
async test(id, options) {
|
|
508
|
-
return this.
|
|
1241
|
+
return this.call({
|
|
509
1242
|
method: "POST",
|
|
510
1243
|
path: `/webhooks/${encodeURIComponent(id)}/test`,
|
|
511
|
-
timeoutMs: options?.timeoutMs
|
|
1244
|
+
timeoutMs: options?.timeoutMs,
|
|
1245
|
+
signal: options?.signal
|
|
512
1246
|
});
|
|
513
1247
|
}
|
|
514
1248
|
/** `GET /webhooks/{id}/deliveries` — delivery history, most recent first. */
|
|
515
1249
|
async deliveries(id, params = {}, options) {
|
|
516
|
-
return this.
|
|
1250
|
+
return this.call({
|
|
517
1251
|
method: "GET",
|
|
518
1252
|
path: `/webhooks/${encodeURIComponent(id)}/deliveries`,
|
|
1253
|
+
free: true,
|
|
519
1254
|
query: { limit: params.limit, offset: params.offset },
|
|
520
|
-
timeoutMs: options?.timeoutMs
|
|
1255
|
+
timeoutMs: options?.timeoutMs,
|
|
1256
|
+
signal: options?.signal
|
|
521
1257
|
});
|
|
522
1258
|
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Walk the whole delivery history page by page (`limit` per page, default
|
|
1261
|
+
* 50), starting at `offset`, newest first (SDK contract §1.4). Each
|
|
1262
|
+
* delivery is yielded at most once (deduplicated on `id`): a delivery
|
|
1263
|
+
* created during the walk shifts later pages by one. Stops on an empty page
|
|
1264
|
+
* or when the offset reaches `total`. Pages are free (0 credits).
|
|
1265
|
+
*
|
|
1266
|
+
* ```ts
|
|
1267
|
+
* for await (const page of client.webhooks.paginateDeliveries(id)) {
|
|
1268
|
+
* for (const d of page.deliveries) console.log(d.status, d.responseStatus);
|
|
1269
|
+
* }
|
|
1270
|
+
* ```
|
|
1271
|
+
*/
|
|
1272
|
+
async *paginateDeliveries(id, params = {}, options) {
|
|
1273
|
+
const limit = params.limit ?? 50;
|
|
1274
|
+
let offset = params.offset ?? 0;
|
|
1275
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1276
|
+
for (; ; ) {
|
|
1277
|
+
const page = await this.deliveries(id, { limit, offset }, options);
|
|
1278
|
+
const count = page.deliveries.length;
|
|
1279
|
+
const fresh = page.deliveries.filter((d) => {
|
|
1280
|
+
if (typeof d.id !== "string") return true;
|
|
1281
|
+
if (seen.has(d.id)) return false;
|
|
1282
|
+
seen.add(d.id);
|
|
1283
|
+
return true;
|
|
1284
|
+
});
|
|
1285
|
+
yield { ...page, deliveries: fresh };
|
|
1286
|
+
offset += count;
|
|
1287
|
+
if (count === 0 || page.total !== void 0 && offset >= page.total) return;
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
523
1290
|
};
|
|
524
1291
|
|
|
525
1292
|
// src/client.ts
|
|
@@ -540,83 +1307,125 @@ var LexAPI = class {
|
|
|
540
1307
|
retry: {
|
|
541
1308
|
maxRetries: options.retry?.maxRetries ?? 3,
|
|
542
1309
|
baseDelayMs: options.retry?.baseDelayMs ?? 500,
|
|
543
|
-
maxDelayMs: options.retry?.maxDelayMs ?? 3e4
|
|
1310
|
+
maxDelayMs: options.retry?.maxDelayMs ?? 3e4,
|
|
1311
|
+
retryReadOnlyPosts: options.retry?.retryReadOnlyPosts ?? false
|
|
544
1312
|
},
|
|
545
1313
|
userAgentSuffix: options.userAgentSuffix
|
|
546
1314
|
});
|
|
547
1315
|
this.webhooks = new WebhooksAPI(this.http);
|
|
548
1316
|
}
|
|
1317
|
+
/** Redacted view for `JSON.stringify` — never includes the API key. */
|
|
1318
|
+
toJSON() {
|
|
1319
|
+
return { client: "LexAPI", http: this.http.toJSON() };
|
|
1320
|
+
}
|
|
1321
|
+
/** Redacted view for `util.inspect` / `console.log` — never includes the API key. */
|
|
1322
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
1323
|
+
return `LexAPI { baseUrl: '${this.http.baseUrl}', apiKey: '[redacted]' }`;
|
|
1324
|
+
}
|
|
1325
|
+
/** Perform a JSON request and attach the parsed response headers (+ legacy header fields). */
|
|
1326
|
+
async call(options, extra = {}) {
|
|
1327
|
+
const { data, response } = await this.http.requestJsonWithResponse(options);
|
|
1328
|
+
return withHeaders(data, response, extra.corpusVersion === true);
|
|
1329
|
+
}
|
|
549
1330
|
/**
|
|
550
1331
|
* `GET /info` — API capabilities, subscription tier, and current usage.
|
|
551
1332
|
* Free operation (0 credits); useful as a connection probe.
|
|
552
1333
|
*/
|
|
553
1334
|
async getInfo(options) {
|
|
554
|
-
return this.
|
|
1335
|
+
return this.call({
|
|
555
1336
|
method: "GET",
|
|
556
1337
|
path: "/info",
|
|
557
|
-
|
|
1338
|
+
free: true,
|
|
1339
|
+
timeoutMs: options?.timeoutMs,
|
|
1340
|
+
signal: options?.signal
|
|
558
1341
|
});
|
|
559
1342
|
}
|
|
560
1343
|
/**
|
|
561
1344
|
* `POST /search` — search EUR-Lex with structured filters.
|
|
562
1345
|
*
|
|
1346
|
+
* **Cost: 3 credits per result page** (`maxPages`, tier-clamped), charged
|
|
1347
|
+
* upfront and refunded for pages never fetched; a search that fails
|
|
1348
|
+
* before its first page is refunded in full. Identical searches within
|
|
1349
|
+
* 60 minutes are served from a result cache (`headers.searchCache: "hit"`,
|
|
1350
|
+
* same price) — pass `fresh: true` to force a re-fetch.
|
|
1351
|
+
*
|
|
563
1352
|
* At least one filter is required. Truncation and partial-result signals
|
|
564
|
-
* are surfaced
|
|
565
|
-
*
|
|
566
|
-
* `
|
|
567
|
-
*
|
|
568
|
-
* `
|
|
569
|
-
* (the `X-Warning`
|
|
1353
|
+
* are surfaced, not hidden: `truncated` / `truncatedAt` / `truncatedReason`
|
|
1354
|
+
* (tier-capped pagination), `partial` / `partialReason` (an upstream page
|
|
1355
|
+
* timed out, or `source: "corpus"` — EUR-Lex unreachable, answered from
|
|
1356
|
+
* the corpus mirror), `postFilteredBy` (`"date"` → raise `maxPages`),
|
|
1357
|
+
* `ignoredDocumentTypes`, `hint` (zero results → try semantic search), and
|
|
1358
|
+
* `xWarning` (the `X-Warning` header, e.g. `maxPages` clamped).
|
|
570
1359
|
*/
|
|
571
1360
|
async search(request, options) {
|
|
572
|
-
|
|
1361
|
+
return this.call({
|
|
573
1362
|
method: "POST",
|
|
574
1363
|
path: "/search",
|
|
575
1364
|
body: request,
|
|
576
|
-
|
|
1365
|
+
idempotent: true,
|
|
1366
|
+
timeoutMs: options?.timeoutMs,
|
|
1367
|
+
signal: options?.signal
|
|
577
1368
|
});
|
|
578
|
-
return withHeaderSignals(data, response);
|
|
579
1369
|
}
|
|
580
1370
|
/**
|
|
581
1371
|
* `POST /documentContent` — fetch a single fully-parsed document by CELEX.
|
|
582
1372
|
*
|
|
583
|
-
*
|
|
584
|
-
*
|
|
1373
|
+
* **Cost: 5 credits, settled by source** — 1 from the LexAPI corpus
|
|
1374
|
+
* (`headers.source === "corpus"`), 4 from the Publications Office Cellar
|
|
1375
|
+
* API (`"cellar"` / `"cellar-oj"`), 5 for a browser fetch (`"live"`).
|
|
1376
|
+
*
|
|
1377
|
+
* Check `document.textAvailability.available` before reading
|
|
1378
|
+
* `document.content`: a document whose text EUR-Lex does not publish is a
|
|
1379
|
+
* 200 with metadata and `content: null` (billed 1 credit), with the reason
|
|
1380
|
+
* and — for base acts — a pointer to the consolidated version. Use
|
|
1381
|
+
* `language` / `acceptLanguages` for other renditions and
|
|
1382
|
+
* `include`/`fields`/`articleId` to trim the payload.
|
|
585
1383
|
*/
|
|
586
1384
|
async getDocument(request, options) {
|
|
587
|
-
return this.
|
|
1385
|
+
return this.call({
|
|
588
1386
|
method: "POST",
|
|
589
1387
|
path: "/documentContent",
|
|
590
1388
|
body: request,
|
|
591
|
-
|
|
1389
|
+
idempotent: true,
|
|
1390
|
+
timeoutMs: options?.timeoutMs,
|
|
1391
|
+
signal: options?.signal
|
|
592
1392
|
});
|
|
593
1393
|
}
|
|
594
1394
|
/**
|
|
595
1395
|
* `POST /documentContent/batch` — fetch multiple documents in one request.
|
|
596
1396
|
*
|
|
597
|
-
*
|
|
598
|
-
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
1397
|
+
* **Cost: 5 credits per processed item, settled by source** (corpus 1,
|
|
1398
|
+
* Cellar / OJ 4, browser 5; `headers.batch` has the source counts). The
|
|
1399
|
+
* batch is clamped to the tier ceiling (FREE=1, STARTER=5,
|
|
1400
|
+
* PROFESSIONAL=20, BUSINESS+=50); trimmed items are not charged. Clamping
|
|
1401
|
+
* is surfaced: `trimmed` / `trimmedTo` / `trimmedReason` and `xWarning`.
|
|
1402
|
+
* Per-CELEX failures are collected in `errors`; text-unavailable items
|
|
1403
|
+
* stay in `documents` (counted in `textUnavailable`).
|
|
602
1404
|
*/
|
|
603
1405
|
async getDocumentsBatch(request, options) {
|
|
604
|
-
|
|
1406
|
+
return this.call({
|
|
605
1407
|
method: "POST",
|
|
606
1408
|
path: "/documentContent/batch",
|
|
607
1409
|
body: request,
|
|
608
|
-
|
|
1410
|
+
idempotent: true,
|
|
1411
|
+
timeoutMs: options?.timeoutMs,
|
|
1412
|
+
signal: options?.signal
|
|
609
1413
|
});
|
|
610
|
-
return withHeaderSignals(data, response);
|
|
611
1414
|
}
|
|
612
1415
|
/**
|
|
613
1416
|
* `GET /documents/recent` — recently-published documents (last `days`
|
|
614
|
-
* days, default 7
|
|
615
|
-
*
|
|
616
|
-
*
|
|
1417
|
+
* days, default 7; up to `limit`, default 50).
|
|
1418
|
+
*
|
|
1419
|
+
* **Cost: 3 credits per result page** (~10 results each, tier-capped);
|
|
1420
|
+
* unfiltered requests are answered from Cellar in one query
|
|
1421
|
+
* (`headers.source === "cellar"`) and settle at a single page. `author`
|
|
1422
|
+
* arrays are sent as repeated query parameters; `documentType` and
|
|
1423
|
+
* `subdomain` take ONE value — EUR-Lex applies only the first of several
|
|
1424
|
+
* on this path (use `search` for multi-type / multi-subdomain queries). `languageFilter`
|
|
1425
|
+
* reports rows dropped by the language post-filter.
|
|
617
1426
|
*/
|
|
618
1427
|
async getRecentDocuments(params = {}, options) {
|
|
619
|
-
|
|
1428
|
+
return this.call({
|
|
620
1429
|
method: "GET",
|
|
621
1430
|
path: "/documents/recent",
|
|
622
1431
|
query: {
|
|
@@ -628,62 +1437,72 @@ var LexAPI = class {
|
|
|
628
1437
|
language: params.language,
|
|
629
1438
|
limit: params.limit
|
|
630
1439
|
},
|
|
631
|
-
timeoutMs: options?.timeoutMs
|
|
1440
|
+
timeoutMs: options?.timeoutMs,
|
|
1441
|
+
signal: options?.signal
|
|
632
1442
|
});
|
|
633
|
-
return withHeaderSignals(data, response);
|
|
634
1443
|
}
|
|
635
1444
|
/**
|
|
636
|
-
* `POST /documents/url` — fetch a document by any EUR-Lex URL.
|
|
637
|
-
*
|
|
638
|
-
*
|
|
1445
|
+
* `POST /documents/url` — fetch a document by any EUR-Lex URL. Shaped like
|
|
1446
|
+
* `getDocument` plus `sourceUrl` and `extractedCelex` echo-backs. Same
|
|
1447
|
+
* settle-by-source pricing (corpus 1, Cellar 4, browser 5).
|
|
639
1448
|
*/
|
|
640
1449
|
async getDocumentByUrl(request, options) {
|
|
641
|
-
return this.
|
|
1450
|
+
return this.call({
|
|
642
1451
|
method: "POST",
|
|
643
1452
|
path: "/documents/url",
|
|
644
1453
|
body: request,
|
|
645
|
-
|
|
1454
|
+
idempotent: true,
|
|
1455
|
+
timeoutMs: options?.timeoutMs,
|
|
1456
|
+
signal: options?.signal
|
|
646
1457
|
});
|
|
647
1458
|
}
|
|
648
1459
|
/**
|
|
649
1460
|
* `POST /documents/metadata` — metadata only (title, dates, ECLI/ELI,
|
|
650
|
-
* keywords, subjects). Skips the body parse:
|
|
651
|
-
*
|
|
1461
|
+
* keywords, subjects, URLs). Skips the body parse: faster than
|
|
1462
|
+
* `getDocument`. **Cost: 5 credits, settled by source** (corpus 1, Cellar 4).
|
|
652
1463
|
*/
|
|
653
1464
|
async getDocumentMetadata(request, options) {
|
|
654
|
-
return this.
|
|
1465
|
+
return this.call({
|
|
655
1466
|
method: "POST",
|
|
656
1467
|
path: "/documents/metadata",
|
|
657
1468
|
body: request,
|
|
658
|
-
|
|
1469
|
+
idempotent: true,
|
|
1470
|
+
timeoutMs: options?.timeoutMs,
|
|
1471
|
+
signal: options?.signal
|
|
659
1472
|
});
|
|
660
1473
|
}
|
|
661
1474
|
/**
|
|
662
1475
|
* `POST /resolve` — resolve any legal identifier (bare CELEX, EUR-Lex
|
|
663
1476
|
* URL, ELI URI, or ECLI) to the canonical CELEX plus access URLs.
|
|
1477
|
+
* 1 credit. ECLIs (and unmappable ELIs) resolve via the corpus
|
|
1478
|
+
* (`resolvedVia: "ecli-corpus"` / `"eli-corpus"`).
|
|
664
1479
|
*/
|
|
665
1480
|
async resolve(identifier, options) {
|
|
666
|
-
return this.
|
|
1481
|
+
return this.call({
|
|
667
1482
|
method: "POST",
|
|
668
1483
|
path: "/resolve",
|
|
669
1484
|
body: { identifier },
|
|
670
|
-
|
|
1485
|
+
idempotent: true,
|
|
1486
|
+
timeoutMs: options?.timeoutMs,
|
|
1487
|
+
signal: options?.signal
|
|
671
1488
|
});
|
|
672
1489
|
}
|
|
673
1490
|
// ── Point-in-time versions ────────────────────────────────────────
|
|
674
|
-
//
|
|
675
|
-
//
|
|
676
|
-
//
|
|
1491
|
+
// Versions are LexAPI observation snapshots (content-hash changes between
|
|
1492
|
+
// fetches), NOT legal in-force reconstructions; history begins at first
|
|
1493
|
+
// ingestion. For the text in force on a date, use a consolidated CELEX or
|
|
1494
|
+
// semanticLegislationSearch({ asOf }).
|
|
677
1495
|
/**
|
|
678
1496
|
* `GET /documents/{celex}/versions` — version history, newest first,
|
|
679
1497
|
* current version included and flagged. 1 credit.
|
|
680
1498
|
*/
|
|
681
1499
|
async listDocumentVersions(celex, params = {}, options) {
|
|
682
|
-
return this.
|
|
1500
|
+
return this.call({
|
|
683
1501
|
method: "GET",
|
|
684
1502
|
path: `/documents/${encodeURIComponent(celex)}/versions`,
|
|
685
1503
|
query: { language: params.language },
|
|
686
|
-
timeoutMs: options?.timeoutMs
|
|
1504
|
+
timeoutMs: options?.timeoutMs,
|
|
1505
|
+
signal: options?.signal
|
|
687
1506
|
});
|
|
688
1507
|
}
|
|
689
1508
|
/**
|
|
@@ -692,13 +1511,13 @@ var LexAPI = class {
|
|
|
692
1511
|
* `X-Corpus-Version` response header. 1 credit.
|
|
693
1512
|
*/
|
|
694
1513
|
async getDocumentVersion(celex, version, params = {}, options) {
|
|
695
|
-
|
|
1514
|
+
return this.call({
|
|
696
1515
|
method: "GET",
|
|
697
1516
|
path: `/documents/${encodeURIComponent(celex)}/versions/${version}`,
|
|
698
1517
|
query: { language: params.language },
|
|
699
|
-
timeoutMs: options?.timeoutMs
|
|
700
|
-
|
|
701
|
-
|
|
1518
|
+
timeoutMs: options?.timeoutMs,
|
|
1519
|
+
signal: options?.signal
|
|
1520
|
+
}, { corpusVersion: true });
|
|
702
1521
|
}
|
|
703
1522
|
/**
|
|
704
1523
|
* `GET /documents/{celex}/at/{date}` — the snapshot LexAPI observed as
|
|
@@ -707,102 +1526,404 @@ var LexAPI = class {
|
|
|
707
1526
|
* carrying the tracking start date. 1 credit.
|
|
708
1527
|
*/
|
|
709
1528
|
async getDocumentAtDate(celex, date, params = {}, options) {
|
|
710
|
-
|
|
1529
|
+
return this.call({
|
|
711
1530
|
method: "GET",
|
|
712
1531
|
path: `/documents/${encodeURIComponent(celex)}/at/${encodeURIComponent(date)}`,
|
|
713
1532
|
query: { language: params.language },
|
|
714
|
-
timeoutMs: options?.timeoutMs
|
|
715
|
-
|
|
716
|
-
|
|
1533
|
+
timeoutMs: options?.timeoutMs,
|
|
1534
|
+
signal: options?.signal
|
|
1535
|
+
}, { corpusVersion: true });
|
|
717
1536
|
}
|
|
718
1537
|
// ── Citations ─────────────────────────────────────────────────────
|
|
719
1538
|
/**
|
|
720
1539
|
* `POST /citations/extract` — crawl a document's EUR-Lex metadata page
|
|
721
1540
|
* for citations and persist them into the graph. Idempotent: an already
|
|
722
|
-
* processed document returns
|
|
1541
|
+
* processed document returns `alreadyExtracted: true`. 5 credits,
|
|
1542
|
+
* refunded to 1 on `alreadyExtracted`.
|
|
723
1543
|
*/
|
|
724
1544
|
async extractCitations(celexNumber, options) {
|
|
725
|
-
return this.
|
|
1545
|
+
return this.call({
|
|
726
1546
|
method: "POST",
|
|
727
1547
|
path: "/citations/extract",
|
|
728
1548
|
body: { celexNumber },
|
|
729
|
-
timeoutMs: options?.timeoutMs
|
|
1549
|
+
timeoutMs: options?.timeoutMs,
|
|
1550
|
+
signal: options?.signal
|
|
730
1551
|
});
|
|
731
1552
|
}
|
|
732
1553
|
/**
|
|
733
1554
|
* `GET /citations/cites/{celexNumber}` — documents this one cites
|
|
734
1555
|
* (outbound edges), grouped by target. The document must first have been
|
|
735
|
-
* crawled via `extractCitations` to appear here.
|
|
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.
|
|
736
1569
|
*/
|
|
737
1570
|
async getCites(celexNumber, params = {}, options) {
|
|
738
|
-
return this.
|
|
1571
|
+
return this.call({
|
|
739
1572
|
method: "GET",
|
|
740
1573
|
path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
|
|
741
|
-
query: {
|
|
742
|
-
timeoutMs: options?.timeoutMs
|
|
1574
|
+
query: { ...edgeQuery(params), unresolved: params.unresolved },
|
|
1575
|
+
timeoutMs: options?.timeoutMs,
|
|
1576
|
+
signal: options?.signal
|
|
743
1577
|
});
|
|
744
1578
|
}
|
|
745
1579
|
/**
|
|
746
1580
|
* `GET /citations/cited-by/{celexNumber}` — documents that cite this one
|
|
747
|
-
* (inbound edges), grouped by source.
|
|
1581
|
+
* (inbound edges), grouped by source. 1 credit. For legislation, inbound
|
|
1582
|
+
* amendment / corrigendum / repeal edges are refreshed from Cellar when
|
|
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`.
|
|
748
1588
|
*/
|
|
749
1589
|
async getCitedBy(celexNumber, params = {}, options) {
|
|
750
|
-
return this.
|
|
1590
|
+
return this.call({
|
|
751
1591
|
method: "GET",
|
|
752
1592
|
path: `/citations/cited-by/${encodeURIComponent(celexNumber)}`,
|
|
753
|
-
query:
|
|
754
|
-
timeoutMs: options?.timeoutMs
|
|
1593
|
+
query: edgeQuery(params),
|
|
1594
|
+
timeoutMs: options?.timeoutMs,
|
|
1595
|
+
signal: options?.signal
|
|
755
1596
|
});
|
|
756
1597
|
}
|
|
1598
|
+
/**
|
|
1599
|
+
* Walk every page of `getCites` (offset in edge rows) until a short or
|
|
1600
|
+
* empty page (SDK contract §1.4). Each page is a billed call (1 credit).
|
|
1601
|
+
* Edges are ordered by extraction time only, so edges extracted at the
|
|
1602
|
+
* same instant or during the walk can shift: an edge may repeat or be
|
|
1603
|
+
* missed. A target's edges can straddle a page boundary, so the same
|
|
1604
|
+
* `celexNumber` may appear in two consecutive pages — merge by
|
|
1605
|
+
* `celexNumber` if you need one group per document.
|
|
1606
|
+
*/
|
|
1607
|
+
async *paginateCites(celexNumber, params = {}, options) {
|
|
1608
|
+
yield* paginateEdges(
|
|
1609
|
+
(p) => this.getCites(celexNumber, p, options),
|
|
1610
|
+
(page) => page.cites.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
|
|
1611
|
+
params
|
|
1612
|
+
);
|
|
1613
|
+
}
|
|
1614
|
+
/**
|
|
1615
|
+
* Walk every page of `getCitedBy` (offset in edge rows) until a short or
|
|
1616
|
+
* empty page (SDK contract §1.4). Each page is a billed call (1 credit);
|
|
1617
|
+
* edges may repeat or be missed if extractions happen during the walk. A source's edges can straddle a page boundary, so the same
|
|
1618
|
+
* `celexNumber` may appear in two consecutive pages.
|
|
1619
|
+
*/
|
|
1620
|
+
async *paginateCitedBy(celexNumber, params = {}, options) {
|
|
1621
|
+
yield* paginateEdges(
|
|
1622
|
+
(p) => this.getCitedBy(celexNumber, p, options),
|
|
1623
|
+
(page) => page.citedBy.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
|
|
1624
|
+
params
|
|
1625
|
+
);
|
|
1626
|
+
}
|
|
757
1627
|
/**
|
|
758
1628
|
* `GET /citations/network/{celexNumber}` — inbound and outbound
|
|
759
|
-
* neighbourhood in one call, paginated per direction.
|
|
1629
|
+
* neighbourhood in one call, paginated per direction. 20 credits.
|
|
760
1630
|
*
|
|
761
1631
|
* If the server-side wall-clock budget expires the endpoint still
|
|
762
1632
|
* returns 200 with `partial: true`, an EMPTY `network`, and `null`
|
|
763
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`.
|
|
764
1638
|
*/
|
|
765
1639
|
async getCitationNetwork(celexNumber, params = {}, options) {
|
|
766
|
-
return this.
|
|
1640
|
+
return this.call({
|
|
767
1641
|
method: "GET",
|
|
768
1642
|
path: `/citations/network/${encodeURIComponent(celexNumber)}`,
|
|
769
|
-
query: {
|
|
770
|
-
|
|
1643
|
+
query: {
|
|
1644
|
+
...filterQuery(params),
|
|
1645
|
+
limit: params.limit,
|
|
1646
|
+
offset: params.offset,
|
|
1647
|
+
language: params.language,
|
|
1648
|
+
includeNational: params.includeNational,
|
|
1649
|
+
unresolved: params.unresolved
|
|
1650
|
+
},
|
|
1651
|
+
timeoutMs: options?.timeoutMs,
|
|
1652
|
+
signal: options?.signal
|
|
771
1653
|
});
|
|
772
1654
|
}
|
|
773
1655
|
/**
|
|
774
1656
|
* `GET /citations/path/{from}/{to}` — shortest citation path (BFS over
|
|
775
|
-
* outbound edges). `found: false` is a graceful HTTP 200,
|
|
776
|
-
* Default `maxDepth` 3 (max 8); the visited set is bounded
|
|
1657
|
+
* outbound edges). 20 credits. `found: false` is a graceful HTTP 200,
|
|
1658
|
+
* not an error. Default `maxDepth` 3 (max 8); the visited set is bounded
|
|
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`.
|
|
777
1664
|
*/
|
|
778
1665
|
async getCitationPath(from, to, params = {}, options) {
|
|
779
|
-
return this.
|
|
1666
|
+
return this.call({
|
|
780
1667
|
method: "GET",
|
|
781
1668
|
path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
|
|
782
|
-
query: {
|
|
783
|
-
|
|
1669
|
+
query: {
|
|
1670
|
+
...filterQuery(params),
|
|
1671
|
+
maxDepth: params.maxDepth,
|
|
1672
|
+
language: params.language,
|
|
1673
|
+
includeNational: params.includeNational
|
|
1674
|
+
},
|
|
1675
|
+
timeoutMs: options?.timeoutMs,
|
|
1676
|
+
signal: options?.signal
|
|
784
1677
|
});
|
|
785
1678
|
}
|
|
786
1679
|
/**
|
|
787
1680
|
* `GET /citations/related/{celexNumber}` — bibliographic-coupling
|
|
788
1681
|
* neighbours (documents sharing the most outbound citation targets with
|
|
789
|
-
* the seed). Returns a graceful empty list with `message`
|
|
790
|
-
* has no outbound citations to couple on.
|
|
1682
|
+
* the seed). 20 credits. Returns a graceful empty list with `message`
|
|
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`.
|
|
791
1688
|
*/
|
|
792
1689
|
async getRelatedDocuments(celexNumber, params = {}, options) {
|
|
793
|
-
return this.
|
|
1690
|
+
return this.call({
|
|
794
1691
|
method: "GET",
|
|
795
1692
|
path: `/citations/related/${encodeURIComponent(celexNumber)}`,
|
|
796
|
-
query: {
|
|
797
|
-
|
|
1693
|
+
query: {
|
|
1694
|
+
...filterQuery(params),
|
|
1695
|
+
limit: params.limit,
|
|
1696
|
+
language: params.language,
|
|
1697
|
+
includeNational: params.includeNational
|
|
1698
|
+
},
|
|
1699
|
+
timeoutMs: options?.timeoutMs,
|
|
1700
|
+
signal: options?.signal
|
|
798
1701
|
});
|
|
799
1702
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
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
|
+
}
|
|
1712
|
+
return this.call({
|
|
803
1713
|
method: "GET",
|
|
804
1714
|
path: "/citations/stats",
|
|
805
|
-
|
|
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,
|
|
1925
|
+
timeoutMs: options?.timeoutMs,
|
|
1926
|
+
signal: options?.signal
|
|
806
1927
|
});
|
|
807
1928
|
}
|
|
808
1929
|
// ── Semantic search ───────────────────────────────────────────────
|
|
@@ -812,89 +1933,118 @@ var LexAPI = class {
|
|
|
812
1933
|
* keyword matching is literal.
|
|
813
1934
|
*
|
|
814
1935
|
* **Billing:** 5 credits per call — **15 credits with `hyde: true`**
|
|
815
|
-
* (HyDE query rewriting
|
|
816
|
-
*
|
|
817
|
-
*
|
|
818
|
-
*
|
|
819
|
-
* 10-credit premium is **refunded automatically** — verify via
|
|
820
|
-
* `credits.operation_weight`.
|
|
821
|
-
*
|
|
822
|
-
* The response exposes `hint` (present only on low-confidence,
|
|
823
|
-
* best-effort result sets — its presence is itself the signal), `hyde`
|
|
824
|
-
* (whether HyDE actually ran), and `hypotheticalDocument` (the drafted
|
|
825
|
-
* passage, present only when HyDE ran).
|
|
1936
|
+
* (HyDE query rewriting; ~1–3 s extra latency). HyDE is best-effort: on
|
|
1937
|
+
* LLM failure the search falls back to plain retrieval, the response
|
|
1938
|
+
* reports `hyde: false`, and the 10-credit premium is **refunded
|
|
1939
|
+
* automatically**.
|
|
826
1940
|
*
|
|
827
|
-
*
|
|
828
|
-
*
|
|
1941
|
+
* Hits carry a ~600-char `snippet` by default; `includeText: true`
|
|
1942
|
+
* returns the full text instead. `hint` is present only on
|
|
1943
|
+
* low-confidence result sets. Fewer results than `limit`? The ~0.7
|
|
1944
|
+
* default relevance floor cut in — pass `minScore: 0.5` (or `0`).
|
|
829
1945
|
*
|
|
830
1946
|
* Persistent document identity is `(metadata.celex_id,
|
|
831
|
-
* metadata.document_type)`; `case_id` is snapshot-scoped
|
|
832
|
-
* survive index rebuilds.
|
|
1947
|
+
* metadata.document_type)`; `case_id` is snapshot-scoped.
|
|
833
1948
|
*/
|
|
834
1949
|
async semanticSearch(request, options) {
|
|
835
|
-
return this.
|
|
1950
|
+
return this.call({
|
|
836
1951
|
method: "POST",
|
|
837
1952
|
path: "/search/semantic",
|
|
838
1953
|
body: semanticWireBody(request),
|
|
839
|
-
|
|
1954
|
+
idempotent: true,
|
|
1955
|
+
timeoutMs: options?.timeoutMs,
|
|
1956
|
+
signal: options?.signal
|
|
840
1957
|
});
|
|
841
1958
|
}
|
|
842
1959
|
/**
|
|
843
1960
|
* `POST /legislation/semantic` — embedding-based semantic search over EU
|
|
844
1961
|
* legislation; results are article-level matches (`article_ref`,
|
|
845
|
-
* `law_id`, `law_title`, `score`).
|
|
1962
|
+
* `law_id`, `law_title`, `score`). `limit` is never above 50 here.
|
|
1963
|
+
*
|
|
1964
|
+
* **Consolidated texts:** when an act and its consolidated version match
|
|
1965
|
+
* the same article you get ONE hit — the consolidated article, labelled
|
|
1966
|
+
* `consolidated` / `consolidatedAsOf` / `baseCelex` / `consolidatedNote`,
|
|
1967
|
+
* with the authentic act's own match under `baseAct`. Consolidated texts
|
|
1968
|
+
* are not authentic; cite `baseCelex`.
|
|
846
1969
|
*
|
|
847
|
-
*
|
|
848
|
-
*
|
|
849
|
-
*
|
|
850
|
-
*
|
|
1970
|
+
* **`asOf` (YYYY-MM-DD):** each hit answers with the version in force on
|
|
1971
|
+
* that date (`asOfResolved`, `asOfVersion`, `matchedVersion`); a hit that
|
|
1972
|
+
* cannot be answered keeps its latest text with `asOfResolved: false` and
|
|
1973
|
+
* an `asOfReason`. The response adds `asOf` and `asOfSummary`.
|
|
1974
|
+
*
|
|
1975
|
+
* **Cost:** 5 credits for the search; with `asOf`, each live fetch of a
|
|
1976
|
+
* version the corpus does not hold reserves 5 and settles by outcome
|
|
1977
|
+
* (Cellar 4, browser 5, no text 1, failed 0) — at most 3 per request by
|
|
1978
|
+
* default. Corpus reads are free; an unaffordable fetch is skipped
|
|
1979
|
+
* (`insufficient_credits`), never a 402. The `hyde` option is case-law only.
|
|
851
1980
|
*/
|
|
852
1981
|
async semanticLegislationSearch(request, options) {
|
|
853
|
-
return this.
|
|
1982
|
+
return this.call({
|
|
854
1983
|
method: "POST",
|
|
855
1984
|
path: "/legislation/semantic",
|
|
856
1985
|
body: semanticWireBody(request),
|
|
857
|
-
|
|
1986
|
+
idempotent: true,
|
|
1987
|
+
timeoutMs: options?.timeoutMs,
|
|
1988
|
+
signal: options?.signal
|
|
858
1989
|
});
|
|
859
1990
|
}
|
|
860
1991
|
// ── Export ────────────────────────────────────────────────────────
|
|
861
1992
|
/**
|
|
862
|
-
* `GET /export` — stream matching corpus rows as NDJSON (BUSINESS
|
|
863
|
-
*
|
|
1993
|
+
* `GET /export` — stream matching corpus rows as NDJSON (BUSINESS, SCALE
|
|
1994
|
+
* and ENTERPRISE; lower tiers get 403 `TierForbiddenError`). Metadata-only
|
|
1995
|
+
* rows are skipped unless `includeStubs: true`.
|
|
1996
|
+
*
|
|
1997
|
+
* Billing (credit plans, API 2.3.0): 1 credit per row written, at least 1
|
|
1998
|
+
* per export. The call is admitted for 1 credit, the matching rows are
|
|
1999
|
+
* counted, and the rest of 1 credit per row it can return is reserved; a
|
|
2000
|
+
* pool that cannot cover it throws `CreditsExhaustedError` before anything
|
|
2001
|
+
* streams. Unwritten rows are refunded when the stream ends; the settled
|
|
2002
|
+
* charge is `stream.done?.credits` (`charged`).
|
|
864
2003
|
*
|
|
865
2004
|
* Returns a single-pass async iterator over document rows. The leading
|
|
866
2005
|
* `_meta` envelope is parsed before this resolves (`stream.meta`); the
|
|
867
|
-
* trailing `_done` line is exposed as `stream.done` after iteration
|
|
868
|
-
*
|
|
869
|
-
*
|
|
870
|
-
*
|
|
2006
|
+
* trailing `_done` line is exposed as `stream.done` after iteration —
|
|
2007
|
+
* check `stream.truncated` (`_done.truncated` once read; the header / `_meta`
|
|
2008
|
+
* hints before) to detect rows the export did not reach instead of assuming
|
|
2009
|
+
* it was complete.
|
|
871
2010
|
*
|
|
872
2011
|
* ```ts
|
|
873
|
-
* const stream = await client.export({
|
|
874
|
-
* console.log(stream.meta, stream.headers.total);
|
|
2012
|
+
* const stream = await client.export({ documentTypeCode: "regulation", limit: 1000 });
|
|
2013
|
+
* console.log(stream.meta?.totalMatching, stream.headers.total);
|
|
875
2014
|
* for await (const row of stream) process(row.celex, row.parsedContent);
|
|
876
|
-
* if (stream.
|
|
2015
|
+
* if (stream.truncated) console.warn(`not every row reached (${stream.done?.truncatedBy}) — narrow the filters or resume with changedSince`);
|
|
877
2016
|
* ```
|
|
878
2017
|
*/
|
|
879
2018
|
async export(params = {}, options) {
|
|
2019
|
+
if (params.limit !== void 0 && !(Number.isInteger(params.limit) && params.limit >= 1)) {
|
|
2020
|
+
throw new RangeError(`limit must be a positive integer, got ${String(params.limit)}`);
|
|
2021
|
+
}
|
|
880
2022
|
const response = await this.http.requestRaw({
|
|
881
2023
|
method: "GET",
|
|
882
2024
|
path: "/export",
|
|
2025
|
+
accept: "application/x-ndjson, application/json",
|
|
883
2026
|
query: {
|
|
884
|
-
documentType: params.documentType,
|
|
885
|
-
|
|
886
|
-
|
|
2027
|
+
documentType: listParam(params.documentType),
|
|
2028
|
+
documentTypeCode: listParam(params.documentTypeCode),
|
|
2029
|
+
author: listParam(params.author),
|
|
2030
|
+
subdomain: listParam(params.subdomain),
|
|
887
2031
|
language: params.language,
|
|
888
2032
|
dateFrom: params.dateFrom,
|
|
889
2033
|
dateTo: params.dateTo,
|
|
890
|
-
fetchedSince: params.fetchedSince,
|
|
2034
|
+
fetchedSince: timestampParam(params.fetchedSince),
|
|
2035
|
+
changedSince: timestampParam(params.changedSince),
|
|
891
2036
|
includeHtml: params.includeHtml,
|
|
892
2037
|
includeContent: params.includeContent,
|
|
2038
|
+
includeStubs: params.includeStubs,
|
|
893
2039
|
limit: params.limit
|
|
894
2040
|
},
|
|
895
|
-
timeoutMs: options?.timeoutMs
|
|
2041
|
+
timeoutMs: options?.timeoutMs,
|
|
2042
|
+
signal: options?.signal
|
|
2043
|
+
});
|
|
2044
|
+
return createExportStream(response, {
|
|
2045
|
+
idleTimeoutMs: options?.timeoutMs ?? this.http.timeoutMs,
|
|
2046
|
+
...options?.signal ? { signal: options.signal } : {}
|
|
896
2047
|
});
|
|
897
|
-
return createExportStream(response);
|
|
898
2048
|
}
|
|
899
2049
|
};
|
|
900
2050
|
function semanticWireBody(request) {
|
|
@@ -905,50 +2055,276 @@ function semanticWireBody(request) {
|
|
|
905
2055
|
if (request.includeText) body["include"] = ["text"];
|
|
906
2056
|
if (request.filters !== void 0) body["filters"] = request.filters;
|
|
907
2057
|
if (request.hyde !== void 0) body["hyde"] = request.hyde;
|
|
2058
|
+
if (request.asOf !== void 0) body["asOf"] = request.asOf;
|
|
908
2059
|
return body;
|
|
909
2060
|
}
|
|
910
|
-
function
|
|
911
|
-
const
|
|
912
|
-
if (
|
|
913
|
-
|
|
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
|
+
}
|
|
2087
|
+
function edgeQuery(params) {
|
|
2088
|
+
return {
|
|
2089
|
+
...filterQuery(params),
|
|
2090
|
+
limit: params.limit,
|
|
2091
|
+
offset: params.offset,
|
|
2092
|
+
language: params.language,
|
|
2093
|
+
includeNational: params.includeNational
|
|
2094
|
+
};
|
|
2095
|
+
}
|
|
2096
|
+
function timestampParam(value) {
|
|
2097
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
2098
|
+
}
|
|
2099
|
+
function listParam(value) {
|
|
2100
|
+
if (value === void 0) return void 0;
|
|
2101
|
+
return typeof value === "string" ? value : value.join(",");
|
|
2102
|
+
}
|
|
2103
|
+
async function* paginateEdges(fetchPage, rawRowsIn, params) {
|
|
2104
|
+
const limit = params.limit ?? 100;
|
|
2105
|
+
let offset = params.offset ?? 0;
|
|
2106
|
+
for (; ; ) {
|
|
2107
|
+
const page = await fetchPage({ ...params, limit, offset });
|
|
2108
|
+
yield page;
|
|
2109
|
+
const pageLimit = page.limit && page.limit > 0 ? page.limit : limit;
|
|
2110
|
+
const rows = rawRowsIn(page);
|
|
2111
|
+
offset += rows;
|
|
2112
|
+
if (rows === 0 || rows < pageLimit) return;
|
|
914
2113
|
}
|
|
915
|
-
return data;
|
|
916
2114
|
}
|
|
917
|
-
function
|
|
918
|
-
|
|
919
|
-
const
|
|
920
|
-
|
|
921
|
-
|
|
2115
|
+
function withHeaders(data, response, corpusVersion) {
|
|
2116
|
+
if (typeof data !== "object" || data === null || Array.isArray(data)) return data;
|
|
2117
|
+
const headers = parseResponseHeaders(response);
|
|
2118
|
+
const out = { ...data, headers };
|
|
2119
|
+
if (headers.warning !== void 0) out["xWarning"] = headers.warning;
|
|
2120
|
+
if (corpusVersion && headers.corpusVersion !== void 0) {
|
|
2121
|
+
out["corpusVersion"] = headers.corpusVersion;
|
|
922
2122
|
}
|
|
923
|
-
return
|
|
2123
|
+
return out;
|
|
924
2124
|
}
|
|
925
2125
|
|
|
926
2126
|
// src/credits.ts
|
|
927
2127
|
function getCreditUsage(response) {
|
|
928
2128
|
return {
|
|
929
|
-
unitsCharged: response.credits?.operation_weight,
|
|
2129
|
+
unitsCharged: response.credits?.operation_weight ?? 0,
|
|
930
2130
|
creditsRemaining: response.credits?.remaining ?? response.usage?.remaining,
|
|
931
2131
|
resetsAt: response.credits?.resetsAt ?? response.usage?.resetsAt
|
|
932
2132
|
};
|
|
933
2133
|
}
|
|
2134
|
+
|
|
2135
|
+
// src/webhookSignature.ts
|
|
2136
|
+
var WEBHOOK_SIGNATURE_HEADER = "x-webhook-signature";
|
|
2137
|
+
var WEBHOOK_DELIVERY_HEADER = "x-webhook-delivery";
|
|
2138
|
+
var WEBHOOK_ID_HEADER = "x-webhook-id";
|
|
2139
|
+
var VERIFICATION_BRAND = /* @__PURE__ */ Symbol.for("@lexapi/client.webhookSignatureError");
|
|
2140
|
+
var WebhookSignatureError = class _WebhookSignatureError extends Error {
|
|
2141
|
+
reason;
|
|
2142
|
+
static [Symbol.hasInstance](value) {
|
|
2143
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2144
|
+
if (Function.prototype[Symbol.hasInstance].call(this, value)) return true;
|
|
2145
|
+
return this === _WebhookSignatureError && value[VERIFICATION_BRAND] === true;
|
|
2146
|
+
}
|
|
2147
|
+
constructor(reason, message) {
|
|
2148
|
+
super(message);
|
|
2149
|
+
this.name = "WebhookSignatureError";
|
|
2150
|
+
this.reason = reason;
|
|
2151
|
+
Object.defineProperty(this, VERIFICATION_BRAND, { value: true, enumerable: false });
|
|
2152
|
+
}
|
|
2153
|
+
};
|
|
2154
|
+
function assertSecret(secret) {
|
|
2155
|
+
if (typeof secret !== "string" || secret.length === 0) {
|
|
2156
|
+
throw new WebhookSignatureError(
|
|
2157
|
+
"missing_secret",
|
|
2158
|
+
"Webhook secret is empty \u2014 pass the secret returned when the webhook was created"
|
|
2159
|
+
);
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
async function getSubtle() {
|
|
2163
|
+
const globalCrypto = globalThis.crypto;
|
|
2164
|
+
if (globalCrypto?.subtle) return globalCrypto.subtle;
|
|
2165
|
+
const specifier = "node:crypto";
|
|
2166
|
+
const nodeCrypto = await import(
|
|
2167
|
+
/* webpackIgnore: true */
|
|
2168
|
+
/* @vite-ignore */
|
|
2169
|
+
specifier
|
|
2170
|
+
);
|
|
2171
|
+
if (nodeCrypto.webcrypto?.subtle) return nodeCrypto.webcrypto.subtle;
|
|
2172
|
+
throw new Error("Web Crypto (crypto.subtle) is not available in this runtime");
|
|
2173
|
+
}
|
|
2174
|
+
function toBytes(body) {
|
|
2175
|
+
if (typeof body === "string") return new TextEncoder().encode(body);
|
|
2176
|
+
if (body instanceof Uint8Array) return body;
|
|
2177
|
+
return new Uint8Array(body);
|
|
2178
|
+
}
|
|
2179
|
+
function toHex(buffer) {
|
|
2180
|
+
let hex = "";
|
|
2181
|
+
for (const byte of new Uint8Array(buffer)) hex += byte.toString(16).padStart(2, "0");
|
|
2182
|
+
return hex;
|
|
2183
|
+
}
|
|
2184
|
+
function timingSafeEqual(a, b) {
|
|
2185
|
+
if (a.length !== b.length) return false;
|
|
2186
|
+
let diff = 0;
|
|
2187
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
2188
|
+
return diff === 0;
|
|
2189
|
+
}
|
|
2190
|
+
async function computeSignature(rawBody, secret) {
|
|
2191
|
+
assertSecret(secret);
|
|
2192
|
+
const subtle = await getSubtle();
|
|
2193
|
+
const key = await subtle.importKey(
|
|
2194
|
+
"raw",
|
|
2195
|
+
new TextEncoder().encode(secret),
|
|
2196
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
2197
|
+
false,
|
|
2198
|
+
["sign"]
|
|
2199
|
+
);
|
|
2200
|
+
return toHex(await subtle.sign("HMAC", key, toBytes(rawBody)));
|
|
2201
|
+
}
|
|
2202
|
+
async function verifySignature(rawBody, signature, secret) {
|
|
2203
|
+
const candidate = typeof signature === "string" ? signature.trim().toLowerCase() : "";
|
|
2204
|
+
const expected = await computeSignature(rawBody, secret);
|
|
2205
|
+
if (!/^[0-9a-f]{64}$/.test(candidate)) return false;
|
|
2206
|
+
return timingSafeEqual(expected, candidate);
|
|
2207
|
+
}
|
|
2208
|
+
async function verifyWebhook(rawBody, signature, secret, options = {}) {
|
|
2209
|
+
assertSecret(secret);
|
|
2210
|
+
if (!signature) {
|
|
2211
|
+
throw new WebhookSignatureError("missing_signature", "Missing X-Webhook-Signature header");
|
|
2212
|
+
}
|
|
2213
|
+
if (!await verifySignature(rawBody, signature, secret)) {
|
|
2214
|
+
throw new WebhookSignatureError("invalid_signature", "X-Webhook-Signature does not match the body");
|
|
2215
|
+
}
|
|
2216
|
+
let payload;
|
|
2217
|
+
try {
|
|
2218
|
+
const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(toBytes(rawBody));
|
|
2219
|
+
payload = JSON.parse(text);
|
|
2220
|
+
} catch {
|
|
2221
|
+
throw new WebhookSignatureError("malformed_body", "Webhook body is not valid JSON");
|
|
2222
|
+
}
|
|
2223
|
+
const toleranceMs = options.toleranceMs ?? 3e5;
|
|
2224
|
+
if (toleranceMs > 0) {
|
|
2225
|
+
const sentAt = Date.parse(String(payload.timestamp));
|
|
2226
|
+
const now = options.now ?? Date.now();
|
|
2227
|
+
if (Number.isNaN(sentAt) || Math.abs(now - sentAt) > toleranceMs) {
|
|
2228
|
+
throw new WebhookSignatureError(
|
|
2229
|
+
"stale_timestamp",
|
|
2230
|
+
`Webhook timestamp is outside the ${toleranceMs} ms tolerance window`
|
|
2231
|
+
);
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
return payload;
|
|
2235
|
+
}
|
|
2236
|
+
|
|
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
|
+
];
|
|
2262
|
+
var AS_OF_REASONS = [
|
|
2263
|
+
"not_yet_adopted",
|
|
2264
|
+
"not_yet_in_force",
|
|
2265
|
+
"no_longer_in_force",
|
|
2266
|
+
"in_force_dates_unknown",
|
|
2267
|
+
"not_in_language",
|
|
2268
|
+
"text_unavailable",
|
|
2269
|
+
"article_not_in_version",
|
|
2270
|
+
"part_not_resolvable",
|
|
2271
|
+
"article_unknown",
|
|
2272
|
+
"version_list_unavailable",
|
|
2273
|
+
"version_lookup_cap",
|
|
2274
|
+
"fetch_budget_exhausted",
|
|
2275
|
+
"fetch_pending",
|
|
2276
|
+
"fetch_capacity",
|
|
2277
|
+
"fetch_failed",
|
|
2278
|
+
"fetch_timeout",
|
|
2279
|
+
"request_deadline",
|
|
2280
|
+
"insufficient_credits",
|
|
2281
|
+
"credit_check_failed"
|
|
2282
|
+
];
|
|
2283
|
+
function isNationalDecision(document2) {
|
|
2284
|
+
return document2.documentKind === "decision" && document2.decision != null;
|
|
2285
|
+
}
|
|
934
2286
|
export {
|
|
2287
|
+
AS_OF_REASONS,
|
|
935
2288
|
AuthenticationError,
|
|
2289
|
+
CITATION_PROVENANCES,
|
|
2290
|
+
CITATION_RESOLUTIONS,
|
|
2291
|
+
CITATION_TYPES,
|
|
936
2292
|
CreditsExhaustedError,
|
|
937
2293
|
DEFAULT_BASE_URL,
|
|
938
2294
|
DEFAULT_TIMEOUT_MS,
|
|
2295
|
+
DocumentWithdrawnError,
|
|
2296
|
+
IncompleteExportError,
|
|
939
2297
|
InternalServerError,
|
|
940
2298
|
InvalidCelexError,
|
|
941
2299
|
InvalidParamsError,
|
|
2300
|
+
InvalidResponseError,
|
|
942
2301
|
InvalidUrlError,
|
|
943
2302
|
LexAPI,
|
|
944
2303
|
LexAPIError,
|
|
2304
|
+
NationalAllowanceExhaustedError,
|
|
2305
|
+
NationalSemanticFilterUnreachableError,
|
|
2306
|
+
NationalSemanticNotEnabledError,
|
|
2307
|
+
NationalSemanticUnavailableError,
|
|
945
2308
|
NetworkError,
|
|
946
2309
|
NotFoundError,
|
|
947
2310
|
RateLimitedError,
|
|
2311
|
+
RequestAbortedError,
|
|
2312
|
+
ServiceUnavailableError,
|
|
948
2313
|
TierForbiddenError,
|
|
949
2314
|
TimeoutError,
|
|
950
2315
|
UpstreamError,
|
|
951
2316
|
VERSION,
|
|
2317
|
+
WEBHOOK_DELIVERY_HEADER,
|
|
2318
|
+
WEBHOOK_ID_HEADER,
|
|
2319
|
+
WEBHOOK_SIGNATURE_HEADER,
|
|
2320
|
+
WebhookSignatureError,
|
|
952
2321
|
WebhooksAPI,
|
|
953
|
-
|
|
2322
|
+
computeSignature,
|
|
2323
|
+
getCreditUsage,
|
|
2324
|
+
isLexAPIError,
|
|
2325
|
+
isNationalDecision,
|
|
2326
|
+
normalizeRetryAfterSeconds,
|
|
2327
|
+
parseResponseHeaders,
|
|
2328
|
+
verifySignature,
|
|
2329
|
+
verifyWebhook
|
|
954
2330
|
};
|