@lexapi/client 0.2.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +431 -15
- package/README.md +256 -23
- package/dist/index.cjs +1623 -215
- package/dist/index.d.cts +3002 -928
- package/dist/index.d.ts +3002 -928
- package/dist/index.js +1610 -215
- package/package.json +3 -2
package/dist/index.cjs
CHANGED
|
@@ -20,11 +20,16 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
|
+
AS_OF_LOOKUP_REASONS: () => AS_OF_LOOKUP_REASONS,
|
|
23
24
|
AS_OF_REASONS: () => AS_OF_REASONS,
|
|
24
25
|
AuthenticationError: () => AuthenticationError,
|
|
26
|
+
CITATION_PROVENANCES: () => CITATION_PROVENANCES,
|
|
27
|
+
CITATION_RESOLUTIONS: () => CITATION_RESOLUTIONS,
|
|
28
|
+
CITATION_TYPES: () => CITATION_TYPES,
|
|
25
29
|
CreditsExhaustedError: () => CreditsExhaustedError,
|
|
26
30
|
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
27
31
|
DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
|
|
32
|
+
DocumentWithdrawnError: () => DocumentWithdrawnError,
|
|
28
33
|
IncompleteExportError: () => IncompleteExportError,
|
|
29
34
|
InternalServerError: () => InternalServerError,
|
|
30
35
|
InvalidCelexError: () => InvalidCelexError,
|
|
@@ -33,8 +38,14 @@ __export(index_exports, {
|
|
|
33
38
|
InvalidUrlError: () => InvalidUrlError,
|
|
34
39
|
LexAPI: () => LexAPI,
|
|
35
40
|
LexAPIError: () => LexAPIError,
|
|
41
|
+
NATIONAL_AS_OF_REASONS: () => NATIONAL_AS_OF_REASONS,
|
|
42
|
+
NationalAllowanceExhaustedError: () => NationalAllowanceExhaustedError,
|
|
43
|
+
NationalSemanticFilterUnreachableError: () => NationalSemanticFilterUnreachableError,
|
|
44
|
+
NationalSemanticNotEnabledError: () => NationalSemanticNotEnabledError,
|
|
45
|
+
NationalSemanticUnavailableError: () => NationalSemanticUnavailableError,
|
|
36
46
|
NetworkError: () => NetworkError,
|
|
37
47
|
NotFoundError: () => NotFoundError,
|
|
48
|
+
PaymentPastDueError: () => PaymentPastDueError,
|
|
38
49
|
RateLimitedError: () => RateLimitedError,
|
|
39
50
|
RequestAbortedError: () => RequestAbortedError,
|
|
40
51
|
ServiceUnavailableError: () => ServiceUnavailableError,
|
|
@@ -50,6 +61,8 @@ __export(index_exports, {
|
|
|
50
61
|
computeSignature: () => computeSignature,
|
|
51
62
|
getCreditUsage: () => getCreditUsage,
|
|
52
63
|
isLexAPIError: () => isLexAPIError,
|
|
64
|
+
isNationalAsOfVersion: () => isNationalAsOfVersion,
|
|
65
|
+
isNationalDecision: () => isNationalDecision,
|
|
53
66
|
normalizeRetryAfterSeconds: () => normalizeRetryAfterSeconds,
|
|
54
67
|
parseResponseHeaders: () => parseResponseHeaders,
|
|
55
68
|
verifySignature: () => verifySignature,
|
|
@@ -57,6 +70,91 @@ __export(index_exports, {
|
|
|
57
70
|
});
|
|
58
71
|
module.exports = __toCommonJS(index_exports);
|
|
59
72
|
|
|
73
|
+
// src/retryHints.ts
|
|
74
|
+
function normalizeRetryAfterSeconds(value) {
|
|
75
|
+
if (!Number.isFinite(value)) return 0;
|
|
76
|
+
if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
|
|
77
|
+
if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
|
|
78
|
+
return Math.max(0, value);
|
|
79
|
+
}
|
|
80
|
+
function trimSpaces(value) {
|
|
81
|
+
return value.replace(/^[ \t]+|[ \t]+$/g, "");
|
|
82
|
+
}
|
|
83
|
+
function decimalSeconds(raw) {
|
|
84
|
+
if (typeof raw !== "string") return void 0;
|
|
85
|
+
const value = trimSpaces(raw);
|
|
86
|
+
if (!/^[0-9]+(\.[0-9]+)?$/.test(value)) return void 0;
|
|
87
|
+
const seconds = Number(value);
|
|
88
|
+
return Number.isFinite(seconds) ? normalizeRetryAfterSeconds(seconds) : void 0;
|
|
89
|
+
}
|
|
90
|
+
function bodySeconds(value) {
|
|
91
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
|
|
92
|
+
return normalizeRetryAfterSeconds(value);
|
|
93
|
+
}
|
|
94
|
+
var DAYS = "Mon|Tue|Wed|Thu|Fri|Sat|Sun";
|
|
95
|
+
var LONG_DAYS = "Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday";
|
|
96
|
+
var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
|
|
97
|
+
var MONTH = MONTHS.join("|");
|
|
98
|
+
var TIME = "([0-9]{2}):([0-9]{2}):([0-9]{2})";
|
|
99
|
+
var ZONE = "(?:GMT|UTC|\\+0000)";
|
|
100
|
+
var IMF_FIXDATE = new RegExp(`^(?:${DAYS}), ([0-9]{2}) (${MONTH}) ([0-9]{4}) ${TIME} ${ZONE}$`, "i");
|
|
101
|
+
var RFC850_DATE = new RegExp(`^(?:${LONG_DAYS}), ([0-9]{2})-(${MONTH})-([0-9]{2}) ${TIME} ${ZONE}$`, "i");
|
|
102
|
+
var ASCTIME_DATE = new RegExp(`^(?:${DAYS}) (${MONTH}) ([0-9]{2}| [0-9]) ${TIME} ([0-9]{4})$`, "i");
|
|
103
|
+
function dateKey(year, month, day, h, m, s) {
|
|
104
|
+
return ((((year * 12 + month) * 31 + day) * 24 + h) * 60 + m) * 60 + s;
|
|
105
|
+
}
|
|
106
|
+
function fullYear(twoDigits, month, day, h, m, s, now) {
|
|
107
|
+
const at = new Date(now);
|
|
108
|
+
const limit = dateKey(at.getUTCFullYear() + 50, at.getUTCMonth(), at.getUTCDate(), at.getUTCHours(), at.getUTCMinutes(), at.getUTCSeconds());
|
|
109
|
+
const monthIndex = MONTHS.indexOf(month.toLowerCase());
|
|
110
|
+
let year = Math.floor(at.getUTCFullYear() / 100) * 100 + 100 + twoDigits;
|
|
111
|
+
while (dateKey(year, monthIndex, day, h, m, s) > limit) year -= 100;
|
|
112
|
+
return year;
|
|
113
|
+
}
|
|
114
|
+
function utcMs(year, month, day, h, m, s) {
|
|
115
|
+
const monthIndex = MONTHS.indexOf(month.toLowerCase());
|
|
116
|
+
if (monthIndex < 0 || h > 23 || m > 59 || s > 59 || day < 1) return void 0;
|
|
117
|
+
const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
|
|
118
|
+
const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][monthIndex];
|
|
119
|
+
if (day > daysInMonth) return void 0;
|
|
120
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
121
|
+
date.setUTCFullYear(year, monthIndex, day);
|
|
122
|
+
date.setUTCHours(h, m, s, 0);
|
|
123
|
+
return date.getTime();
|
|
124
|
+
}
|
|
125
|
+
function httpDateMs(value, now = Date.now()) {
|
|
126
|
+
let match = IMF_FIXDATE.exec(value);
|
|
127
|
+
if (match) {
|
|
128
|
+
const [, day, month, year, h, m, s] = match;
|
|
129
|
+
return utcMs(Number(year), month, Number(day), Number(h), Number(m), Number(s));
|
|
130
|
+
}
|
|
131
|
+
match = RFC850_DATE.exec(value);
|
|
132
|
+
if (match) {
|
|
133
|
+
const [, day, month, year, h, m, s] = match;
|
|
134
|
+
const [d, hh, mm, ss] = [Number(day), Number(h), Number(m), Number(s)];
|
|
135
|
+
return utcMs(fullYear(Number(year), month, d, hh, mm, ss, now), month, d, hh, mm, ss);
|
|
136
|
+
}
|
|
137
|
+
match = ASCTIME_DATE.exec(value);
|
|
138
|
+
if (match) {
|
|
139
|
+
const [, month, day, h, m, s, year] = match;
|
|
140
|
+
return utcMs(Number(year), month, Number(day.trim()), Number(h), Number(m), Number(s));
|
|
141
|
+
}
|
|
142
|
+
return void 0;
|
|
143
|
+
}
|
|
144
|
+
function retryAfterHeaderSeconds(raw) {
|
|
145
|
+
if (typeof raw !== "string") return void 0;
|
|
146
|
+
const value = trimSpaces(raw);
|
|
147
|
+
if (/^[0-9]/.test(value)) return decimalSeconds(value);
|
|
148
|
+
const now = Date.now();
|
|
149
|
+
const date = httpDateMs(value, now);
|
|
150
|
+
return date === void 0 ? void 0 : Math.max(0, Math.round((date - now) / 1e3));
|
|
151
|
+
}
|
|
152
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
153
|
+
function timerDelay(ms) {
|
|
154
|
+
if (Number.isNaN(ms)) return 0;
|
|
155
|
+
return Math.min(Math.max(ms, 0), MAX_TIMER_MS);
|
|
156
|
+
}
|
|
157
|
+
|
|
60
158
|
// src/errors.ts
|
|
61
159
|
var STATUS_TO_CODE = {
|
|
62
160
|
400: "INVALID_PARAMS",
|
|
@@ -77,6 +175,8 @@ var STATUS_TO_CODE = {
|
|
|
77
175
|
524: "TIMEOUT"
|
|
78
176
|
};
|
|
79
177
|
var ERROR_KINDS = /* @__PURE__ */ Symbol.for("@lexapi/client.errorKinds");
|
|
178
|
+
var EXCERPTS = /* @__PURE__ */ new WeakMap();
|
|
179
|
+
var INVALID_BODIES = /* @__PURE__ */ new WeakMap();
|
|
80
180
|
function collectKinds(ctor) {
|
|
81
181
|
const kinds = [];
|
|
82
182
|
let current = ctor;
|
|
@@ -109,10 +209,11 @@ var LexAPIError = class _LexAPIError extends Error {
|
|
|
109
209
|
/** The `error.details` object from the typed envelope, when present. */
|
|
110
210
|
details;
|
|
111
211
|
/**
|
|
112
|
-
* Seconds to wait before retrying, when the server said so (429
|
|
212
|
+
* Seconds to wait before retrying, when the server said so (429; also the
|
|
213
|
+
* 503 of an incomplete national semantic search).
|
|
113
214
|
* Sourced from the `Retry-After` response HEADER first; the JSON
|
|
114
|
-
* `retryAfter` body field is only a fallback because it
|
|
115
|
-
*
|
|
215
|
+
* `retryAfter` body field is only a fallback because it can carry
|
|
216
|
+
* epoch-seconds values (epoch-looking values are
|
|
116
217
|
* normalized to a delta).
|
|
117
218
|
*/
|
|
118
219
|
retryAfter;
|
|
@@ -133,64 +234,89 @@ var LexAPIError = class _LexAPIError extends Error {
|
|
|
133
234
|
this.retryAfter = retryAfter;
|
|
134
235
|
this.body = context?.body;
|
|
135
236
|
this.headers = context?.headers;
|
|
237
|
+
if (context?.bodyExcerpt !== void 0) EXCERPTS.set(this, context.bodyExcerpt);
|
|
136
238
|
Object.defineProperty(this, ERROR_KINDS, { value: collectKinds(new.target), enumerable: false });
|
|
137
239
|
}
|
|
240
|
+
/**
|
|
241
|
+
* For a response body that is not JSON, its first 200 characters (code
|
|
242
|
+
* points); `undefined` otherwise. Raw response text; may contain document
|
|
243
|
+
* text; do not show to a model or log by default. Not an own property of
|
|
244
|
+
* the error, so `console.log` (also with `%o`), `util.inspect` with
|
|
245
|
+
* `showHidden` or with `getters`, `JSON.stringify`, spread and
|
|
246
|
+
* `structuredClone` leave it out (`util.inspect` with `showHidden` and
|
|
247
|
+
* `getters` together shows it); never part of `message`. Assigning to it
|
|
248
|
+
* replaces it (`undefined` clears it).
|
|
249
|
+
*/
|
|
250
|
+
get bodyExcerpt() {
|
|
251
|
+
return EXCERPTS.get(this);
|
|
252
|
+
}
|
|
253
|
+
set bodyExcerpt(value) {
|
|
254
|
+
if (value === void 0) EXCERPTS.delete(this);
|
|
255
|
+
else EXCERPTS.set(this, value);
|
|
256
|
+
}
|
|
138
257
|
/**
|
|
139
258
|
* Build the most specific error subclass for a non-2xx response.
|
|
140
259
|
* Accepts both the typed envelope and the legacy bare `{error, message}` shape.
|
|
260
|
+
* `code` and `message` are read only when they are non-empty strings.
|
|
141
261
|
*/
|
|
142
|
-
static fromResponse(status, body, headerRetryAfter, headers) {
|
|
262
|
+
static fromResponse(status, body, headerRetryAfter, headers, bodyExcerpt) {
|
|
143
263
|
const statusCode = STATUS_TO_CODE[status];
|
|
144
264
|
let code = statusCode ?? "INTERNAL";
|
|
145
265
|
let typedCode = false;
|
|
146
266
|
let message = `HTTP ${status}`;
|
|
147
267
|
let details;
|
|
148
268
|
let retryAfter = headerRetryAfter;
|
|
149
|
-
let
|
|
269
|
+
let resetsAt2;
|
|
150
270
|
if (typeof body === "object" && body !== null) {
|
|
151
271
|
const record = body;
|
|
152
272
|
const err = record["error"];
|
|
153
|
-
|
|
273
|
+
const topCode = nonEmptyString(record["code"]);
|
|
274
|
+
const topMessage = nonEmptyString(record["message"]);
|
|
275
|
+
if (typeof err === "object" && err !== null && !Array.isArray(err)) {
|
|
154
276
|
const e = err;
|
|
155
|
-
|
|
156
|
-
|
|
277
|
+
const typed = nonEmptyString(e["code"]);
|
|
278
|
+
if (typed !== void 0) {
|
|
279
|
+
code = typed;
|
|
157
280
|
typedCode = true;
|
|
158
281
|
}
|
|
159
|
-
|
|
282
|
+
message = nonEmptyString(e["message"]) ?? message;
|
|
160
283
|
details = e["details"];
|
|
161
|
-
} else if (typeof err === "string") {
|
|
162
|
-
if (
|
|
163
|
-
code =
|
|
284
|
+
} else if (typeof err === "string" && err !== "") {
|
|
285
|
+
if (topCode !== void 0) {
|
|
286
|
+
code = topCode;
|
|
164
287
|
typedCode = true;
|
|
165
288
|
}
|
|
166
|
-
message =
|
|
289
|
+
message = topMessage !== void 0 && topMessage !== err ? `${err}: ${topMessage}` : err;
|
|
167
290
|
details = record["details"];
|
|
168
291
|
} else {
|
|
169
|
-
if (
|
|
170
|
-
code =
|
|
292
|
+
if (topCode !== void 0) {
|
|
293
|
+
code = topCode;
|
|
171
294
|
typedCode = true;
|
|
172
295
|
}
|
|
173
|
-
|
|
296
|
+
message = topMessage ?? message;
|
|
174
297
|
details = record["details"];
|
|
175
298
|
}
|
|
176
|
-
if (retryAfter === void 0 && status === 429) {
|
|
177
|
-
|
|
178
|
-
if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
|
|
299
|
+
if (retryAfter === void 0 && (status === 429 || status === 503 && code === "NATIONAL_SEMANTIC_UNAVAILABLE")) {
|
|
300
|
+
retryAfter = bodyWait(record, details);
|
|
179
301
|
}
|
|
180
|
-
|
|
302
|
+
resetsAt2 = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
|
|
181
303
|
}
|
|
182
|
-
const context = {
|
|
304
|
+
const context = {
|
|
305
|
+
body,
|
|
306
|
+
...headers ? { headers } : {},
|
|
307
|
+
...bodyExcerpt !== void 0 ? { bodyExcerpt } : {}
|
|
308
|
+
};
|
|
183
309
|
if (!typedCode && statusCode === void 0 && status < 500) {
|
|
184
310
|
return new _LexAPIError(code, message, status, details, retryAfter, context);
|
|
185
311
|
}
|
|
186
|
-
if (code === "QUOTA_EXHAUSTED" || code === "RATE_LIMITED" && isQuota429(body, headers)) {
|
|
312
|
+
if (code === "QUOTA_EXHAUSTED" || status === 429 && hasQuotaCode(body) || status === 429 && code === "RATE_LIMITED" && isQuota429(body, headers)) {
|
|
187
313
|
return new RateLimitedError(
|
|
188
314
|
message,
|
|
189
315
|
status,
|
|
190
316
|
details,
|
|
191
|
-
void 0,
|
|
317
|
+
status === 429 ? void 0 : retryAfter,
|
|
192
318
|
context,
|
|
193
|
-
code === "
|
|
319
|
+
code === "RATE_LIMITED" ? "RATE_LIMITED" : "QUOTA_EXHAUSTED"
|
|
194
320
|
);
|
|
195
321
|
}
|
|
196
322
|
switch (code) {
|
|
@@ -206,8 +332,20 @@ var LexAPIError = class _LexAPIError extends Error {
|
|
|
206
332
|
return new RateLimitedError(message, status, details, retryAfter, context);
|
|
207
333
|
case "TIER_FORBIDDEN":
|
|
208
334
|
return new TierForbiddenError(message, status, details, retryAfter, context);
|
|
335
|
+
case "PAYMENT_PAST_DUE":
|
|
336
|
+
return new PaymentPastDueError(message, status, details, retryAfter, context);
|
|
209
337
|
case "CREDITS_EXHAUSTED":
|
|
210
|
-
return new CreditsExhaustedError(message, status, details, retryAfter,
|
|
338
|
+
return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt2, context);
|
|
339
|
+
case "NATIONAL_ALLOWANCE_EXHAUSTED":
|
|
340
|
+
return new NationalAllowanceExhaustedError(message, status, details, retryAfter, context);
|
|
341
|
+
case "NATIONAL_SEMANTIC_NOT_ENABLED":
|
|
342
|
+
return new NationalSemanticNotEnabledError(message, status, details, retryAfter, context);
|
|
343
|
+
case "NATIONAL_SEMANTIC_UNAVAILABLE":
|
|
344
|
+
return new NationalSemanticUnavailableError(message, status, details, retryAfter, context);
|
|
345
|
+
case "NATIONAL_SEMANTIC_FILTER_UNREACHABLE":
|
|
346
|
+
return new NationalSemanticFilterUnreachableError(message, status, details, retryAfter, context);
|
|
347
|
+
case "DOCUMENT_WITHDRAWN":
|
|
348
|
+
return new DocumentWithdrawnError(message, status, details, retryAfter, context);
|
|
211
349
|
case "UPSTREAM_ERROR":
|
|
212
350
|
return new UpstreamError(message, status, details, retryAfter, context);
|
|
213
351
|
case "TIMEOUT":
|
|
@@ -229,7 +367,107 @@ var NotFoundError = class extends LexAPIError {
|
|
|
229
367
|
super("NOT_FOUND", message, status, details, retryAfter, context);
|
|
230
368
|
this.name = "NotFoundError";
|
|
231
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* `true` when the API (2.27.0 or later) has no such endpoint
|
|
372
|
+
* (`details.reason` is `"unknown_endpoint"`): a mistyped path, a method
|
|
373
|
+
* newer than the API, or a national route for a country that is not
|
|
374
|
+
* available. Always `false` on APIs before 2.27.0; there the message
|
|
375
|
+
* contains "Unknown API endpoint". Read from `details` only, never from
|
|
376
|
+
* the message.
|
|
377
|
+
*/
|
|
378
|
+
get unknownEndpoint() {
|
|
379
|
+
return ownField(this.details, "reason") === "unknown_endpoint";
|
|
380
|
+
}
|
|
381
|
+
// The accessors below read `details` only when it is a plain JSON object,
|
|
382
|
+
// and only its own keys; anything else gives each accessor's default.
|
|
383
|
+
/**
|
|
384
|
+
* `details.reason` when it is a string: `unknown_endpoint`, or on
|
|
385
|
+
* `getDocumentAtDate` (API 2.28.0) `before_tracking` / `boundary_unknown`.
|
|
386
|
+
* `undefined` on a 404 without one (e.g. a document not in the corpus).
|
|
387
|
+
*/
|
|
388
|
+
get reason() {
|
|
389
|
+
return readString(ownField(this.details, "reason"));
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* `true` when `getDocumentAtDate` was asked about a date before the
|
|
393
|
+
* document entered the corpus (`details.reason` is `"before_tracking"`);
|
|
394
|
+
* {@link trackedSince} says when that was.
|
|
395
|
+
*/
|
|
396
|
+
get beforeTracking() {
|
|
397
|
+
return ownField(this.details, "reason") === "before_tracking";
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* `true` when LexAPI has no record of when a version stored before API
|
|
401
|
+
* 2.28.0 began, so it cannot say which snapshot it held on the date and
|
|
402
|
+
* does not guess (`details.reason` is `"boundary_unknown"`). Refunded.
|
|
403
|
+
* Read the {@link candidates} with `getDocumentVersion`.
|
|
404
|
+
*/
|
|
405
|
+
get boundaryUnknown() {
|
|
406
|
+
return ownField(this.details, "reason") === "boundary_unknown";
|
|
407
|
+
}
|
|
408
|
+
/** `before_tracking` only: when the document entered the corpus (`details.trackedSince`). */
|
|
409
|
+
get trackedSince() {
|
|
410
|
+
return readString(ownField(this.details, "trackedSince"));
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* On `before_tracking` for an EU act: the request that answers which
|
|
414
|
+
* version is listed for a date (`legislationAsOf`).
|
|
415
|
+
*/
|
|
416
|
+
get inForceLookup() {
|
|
417
|
+
const value = ownField(this.details, "inForceLookup");
|
|
418
|
+
if (!isPlainJsonObject(value)) return void 0;
|
|
419
|
+
const lookup2 = {};
|
|
420
|
+
const method = readString(ownField(value, "method"));
|
|
421
|
+
const path = readString(ownField(value, "path"));
|
|
422
|
+
if (method !== void 0) lookup2.method = method;
|
|
423
|
+
if (path !== void 0) lookup2.path = path;
|
|
424
|
+
return lookup2;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* `boundary_unknown` only: the versions the date could fall in — the
|
|
428
|
+
* first 10 items of `details.candidates`
|
|
429
|
+
* that are objects with an integer `version` (`fetchedAt` / `observedFrom`
|
|
430
|
+
* are `null` when not strings). `[]` when there are none. For these
|
|
431
|
+
* versions `fetchedAt` can be the last fetch and later than the date.
|
|
432
|
+
*/
|
|
433
|
+
get candidates() {
|
|
434
|
+
return readCandidates(this.details).kept;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* `boundary_unknown` only: `true` when more versions matched than
|
|
438
|
+
* {@link candidates} lists (`details.candidatesTruncated` is `true`, or
|
|
439
|
+
* more than 10 usable candidates were sent).
|
|
440
|
+
*/
|
|
441
|
+
get candidatesTruncated() {
|
|
442
|
+
return ownField(this.details, "candidatesTruncated") === true || readCandidates(this.details).more;
|
|
443
|
+
}
|
|
232
444
|
};
|
|
445
|
+
var MAX_SNAPSHOT_CANDIDATES = 10;
|
|
446
|
+
function readCandidates(details) {
|
|
447
|
+
const list = ownField(details, "candidates");
|
|
448
|
+
const kept = [];
|
|
449
|
+
if (!Array.isArray(list)) return { kept, more: false };
|
|
450
|
+
for (const item of list) {
|
|
451
|
+
const version = ownField(item, "version");
|
|
452
|
+
if (typeof version !== "number" || !Number.isInteger(version)) continue;
|
|
453
|
+
if (kept.length === MAX_SNAPSHOT_CANDIDATES) return { kept, more: true };
|
|
454
|
+
const fetchedAt = ownField(item, "fetchedAt");
|
|
455
|
+
const observedFrom = ownField(item, "observedFrom");
|
|
456
|
+
kept.push({
|
|
457
|
+
version: version + 0,
|
|
458
|
+
// -0 → 0
|
|
459
|
+
fetchedAt: typeof fetchedAt === "string" ? fetchedAt : null,
|
|
460
|
+
observedFrom: typeof observedFrom === "string" ? observedFrom : null
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
return { kept, more: false };
|
|
464
|
+
}
|
|
465
|
+
function isPlainJsonObject(value) {
|
|
466
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
|
|
467
|
+
}
|
|
468
|
+
function ownField(value, key) {
|
|
469
|
+
return isPlainJsonObject(value) && Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
|
|
470
|
+
}
|
|
233
471
|
var InvalidCelexError = class extends LexAPIError {
|
|
234
472
|
static kind = "InvalidCelexError";
|
|
235
473
|
constructor(message, status = 400, details, retryAfter, context) {
|
|
@@ -246,10 +484,27 @@ var InvalidUrlError = class extends LexAPIError {
|
|
|
246
484
|
};
|
|
247
485
|
var InvalidParamsError = class extends LexAPIError {
|
|
248
486
|
static kind = "InvalidParamsError";
|
|
249
|
-
constructor(message, status = 400, details, retryAfter, context) {
|
|
250
|
-
super(
|
|
487
|
+
constructor(message, status = 400, details, retryAfter, context, code = "INVALID_PARAMS") {
|
|
488
|
+
super(code, message, status, details, retryAfter, context);
|
|
251
489
|
this.name = "InvalidParamsError";
|
|
252
490
|
}
|
|
491
|
+
/**
|
|
492
|
+
* The parameter that was refused, when the server names it — e.g. an
|
|
493
|
+
* unknown citation-graph filter value (API 2.11.0). Read from `details`
|
|
494
|
+
* (typed envelope) or the top level of the body (legacy shape).
|
|
495
|
+
*/
|
|
496
|
+
get param() {
|
|
497
|
+
return readString(detailsOrBodyField(this.details, this.body, "param"));
|
|
498
|
+
}
|
|
499
|
+
/** The refused value of {@link param}, when the server echoes it. */
|
|
500
|
+
get value() {
|
|
501
|
+
return detailsOrBodyField(this.details, this.body, "value");
|
|
502
|
+
}
|
|
503
|
+
/** The allowed values of {@link param}, when the server lists them (may be empty). */
|
|
504
|
+
get allowed() {
|
|
505
|
+
const value = detailsOrBodyField(this.details, this.body, "allowed");
|
|
506
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : void 0;
|
|
507
|
+
}
|
|
253
508
|
};
|
|
254
509
|
var AuthenticationError = class extends LexAPIError {
|
|
255
510
|
static kind = "AuthenticationError";
|
|
@@ -271,14 +526,14 @@ var RateLimitedError = class extends LexAPIError {
|
|
|
271
526
|
/**
|
|
272
527
|
* `true` for a legacy-plan quota 429 (daily call quota, or the monthly
|
|
273
528
|
* semantic quota) rather than the per-minute limiter (SDK contract §1.2):
|
|
274
|
-
* `code` is `QUOTA_EXHAUSTED`, or — servers before
|
|
529
|
+
* `code` is `QUOTA_EXHAUSTED`, or — servers before API 2.4.0, which
|
|
275
530
|
* send no code — the body carries `usage.resetsAt` with neither a
|
|
276
531
|
* `Retry-After` header nor a `retryAfter` body field. It cannot succeed
|
|
277
532
|
* before `resetsAt`, so the SDK does not retry it and `retryAfter` is
|
|
278
533
|
* `undefined`.
|
|
279
534
|
*/
|
|
280
535
|
get quotaExhausted() {
|
|
281
|
-
return this.code === "QUOTA_EXHAUSTED" || isQuota429(this.body, this.headers);
|
|
536
|
+
return this.code === "QUOTA_EXHAUSTED" || this.status === 429 && this.code === "RATE_LIMITED" && isQuota429(this.body, this.headers);
|
|
282
537
|
}
|
|
283
538
|
/** When a legacy quota resets: the body's `resetsAt`, else `usage.resetsAt`. */
|
|
284
539
|
get resetsAt() {
|
|
@@ -287,19 +542,34 @@ var RateLimitedError = class extends LexAPIError {
|
|
|
287
542
|
};
|
|
288
543
|
var TierForbiddenError = class extends LexAPIError {
|
|
289
544
|
static kind = "TierForbiddenError";
|
|
290
|
-
constructor(message, status = 403, details, retryAfter, context) {
|
|
291
|
-
super(
|
|
545
|
+
constructor(message, status = 403, details, retryAfter, context, code = "TIER_FORBIDDEN") {
|
|
546
|
+
super(code, message, status, details, retryAfter, context);
|
|
292
547
|
this.name = "TierForbiddenError";
|
|
293
548
|
}
|
|
294
549
|
};
|
|
550
|
+
var PaymentPastDueError = class extends TierForbiddenError {
|
|
551
|
+
static kind = "PaymentPastDueError";
|
|
552
|
+
constructor(message, status = 403, details, retryAfter, context) {
|
|
553
|
+
super(message, status, details, retryAfter, context, "PAYMENT_PAST_DUE");
|
|
554
|
+
this.name = "PaymentPastDueError";
|
|
555
|
+
}
|
|
556
|
+
/** When API access ended (ISO date-time); `undefined` when the server does not say. */
|
|
557
|
+
get accessEndedAt() {
|
|
558
|
+
return readString(detailsOrBodyField(this.details, this.body, "accessEndedAt"));
|
|
559
|
+
}
|
|
560
|
+
/** Where to pay the open invoice (absolute URL of the dashboard's billing page). */
|
|
561
|
+
get billingUrl() {
|
|
562
|
+
return readString(detailsOrBodyField(this.details, this.body, "billingUrl"));
|
|
563
|
+
}
|
|
564
|
+
};
|
|
295
565
|
var CreditsExhaustedError = class extends LexAPIError {
|
|
296
566
|
static kind = "CreditsExhaustedError";
|
|
297
567
|
/** When the monthly credit allowance resets (ISO date-time), when the server said so. */
|
|
298
568
|
resetsAt;
|
|
299
|
-
constructor(message, status = 402, details, retryAfter,
|
|
569
|
+
constructor(message, status = 402, details, retryAfter, resetsAt2, context) {
|
|
300
570
|
super("CREDITS_EXHAUSTED", message, status, details, retryAfter, context);
|
|
301
571
|
this.name = "CreditsExhaustedError";
|
|
302
|
-
this.resetsAt =
|
|
572
|
+
this.resetsAt = resetsAt2;
|
|
303
573
|
}
|
|
304
574
|
/** The refused operation's credit weight (`details.weight`). */
|
|
305
575
|
get weight() {
|
|
@@ -314,6 +584,33 @@ var CreditsExhaustedError = class extends LexAPIError {
|
|
|
314
584
|
return readString(this.details?.operation);
|
|
315
585
|
}
|
|
316
586
|
};
|
|
587
|
+
var NationalAllowanceExhaustedError = class extends LexAPIError {
|
|
588
|
+
static kind = "NationalAllowanceExhaustedError";
|
|
589
|
+
constructor(message, status = 402, details, retryAfter, context) {
|
|
590
|
+
super("NATIONAL_ALLOWANCE_EXHAUSTED", message, status, details, retryAfter, context);
|
|
591
|
+
this.name = "NationalAllowanceExhaustedError";
|
|
592
|
+
}
|
|
593
|
+
/** The jurisdiction code of the refused call (`details.jurisdiction`). */
|
|
594
|
+
get jurisdiction() {
|
|
595
|
+
return readString(this.details?.jurisdiction);
|
|
596
|
+
}
|
|
597
|
+
/** The tier's monthly allowance of national calls (`details.limit`). */
|
|
598
|
+
get limit() {
|
|
599
|
+
return readNumber(this.details?.limit);
|
|
600
|
+
}
|
|
601
|
+
/** Always `0` (`details.remaining`). */
|
|
602
|
+
get remaining() {
|
|
603
|
+
return readNumber(this.details?.remaining);
|
|
604
|
+
}
|
|
605
|
+
/** When the allowance resets (`details.resetsAt`, ISO date-time). */
|
|
606
|
+
get resetsAt() {
|
|
607
|
+
return readString(this.details?.resetsAt);
|
|
608
|
+
}
|
|
609
|
+
/** `/pricing` (`details.upgradeUrl`). */
|
|
610
|
+
get upgradeUrl() {
|
|
611
|
+
return readString(this.details?.upgradeUrl);
|
|
612
|
+
}
|
|
613
|
+
};
|
|
317
614
|
var UpstreamError = class extends LexAPIError {
|
|
318
615
|
static kind = "UpstreamError";
|
|
319
616
|
constructor(message, status = 502, details, retryAfter, context) {
|
|
@@ -327,14 +624,92 @@ var TimeoutError = class extends LexAPIError {
|
|
|
327
624
|
super(status === 0 ? "REQUEST_TIMEOUT" : "TIMEOUT", message, status, details, retryAfter, context);
|
|
328
625
|
this.name = "TimeoutError";
|
|
329
626
|
}
|
|
627
|
+
/** `true` when the server answered a budget timeout with `partial: true` (nothing else was returned). */
|
|
628
|
+
get partial() {
|
|
629
|
+
const value = bodyField(this.body, "partial");
|
|
630
|
+
return typeof value === "boolean" ? value : void 0;
|
|
631
|
+
}
|
|
632
|
+
/** The server-side budget that expired, in ms, when the body reports it. */
|
|
633
|
+
get serverTimeoutMs() {
|
|
634
|
+
return readNumber(bodyField(this.body, "timeoutMs"));
|
|
635
|
+
}
|
|
330
636
|
};
|
|
331
637
|
var ServiceUnavailableError = class extends LexAPIError {
|
|
332
638
|
static kind = "ServiceUnavailableError";
|
|
333
|
-
constructor(message, status = 503, details, retryAfter, context) {
|
|
334
|
-
super(
|
|
639
|
+
constructor(message, status = 503, details, retryAfter, context, code = "SERVICE_UNAVAILABLE") {
|
|
640
|
+
super(code, message, status, details, retryAfter, context);
|
|
335
641
|
this.name = "ServiceUnavailableError";
|
|
336
642
|
}
|
|
337
643
|
};
|
|
644
|
+
var NationalSemanticNotEnabledError = class extends LexAPIError {
|
|
645
|
+
static kind = "NationalSemanticNotEnabledError";
|
|
646
|
+
constructor(message, status = 409, details, retryAfter, context) {
|
|
647
|
+
super("NATIONAL_SEMANTIC_NOT_ENABLED", message, status, details, retryAfter, context);
|
|
648
|
+
this.name = "NationalSemanticNotEnabledError";
|
|
649
|
+
}
|
|
650
|
+
/** ISO 3166-1 alpha-2 jurisdiction code (top-level `jurisdiction` on the raw body). */
|
|
651
|
+
get jurisdiction() {
|
|
652
|
+
return readString(bodyField(this.body, "jurisdiction"));
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
var NationalSemanticUnavailableError = class extends ServiceUnavailableError {
|
|
656
|
+
static kind = "NationalSemanticUnavailableError";
|
|
657
|
+
constructor(message, status = 503, details, retryAfter, context) {
|
|
658
|
+
super(message, status, details, retryAfter, context, "NATIONAL_SEMANTIC_UNAVAILABLE");
|
|
659
|
+
this.name = "NationalSemanticUnavailableError";
|
|
660
|
+
}
|
|
661
|
+
get jurisdiction() {
|
|
662
|
+
return readString(bodyField(this.body, "jurisdiction"));
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* `"SEARCH_INCOMPLETE"` when the index could not complete this search for a
|
|
666
|
+
* temporary reason and there was nothing left to return (an empty answer
|
|
667
|
+
* would not have meant "no matches"). `retryAfter` is then the wait the
|
|
668
|
+
* server asked for — absent once the same search has repeatedly come back
|
|
669
|
+
* incomplete (try again later, or rephrase or narrow it). `undefined` on
|
|
670
|
+
* the plain "index unavailable" 503.
|
|
671
|
+
*/
|
|
672
|
+
get partialReason() {
|
|
673
|
+
return readString(detailsOrBodyField(this.details, this.body, "partialReason"));
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
var NationalSemanticFilterUnreachableError = class extends InvalidParamsError {
|
|
677
|
+
static kind = "NationalSemanticFilterUnreachableError";
|
|
678
|
+
constructor(message, status = 422, details, retryAfter, context) {
|
|
679
|
+
super(message, status, details, retryAfter, context, "NATIONAL_SEMANTIC_FILTER_UNREACHABLE");
|
|
680
|
+
this.name = "NationalSemanticFilterUnreachableError";
|
|
681
|
+
}
|
|
682
|
+
get jurisdiction() {
|
|
683
|
+
return readString(bodyField(this.body, "jurisdiction"));
|
|
684
|
+
}
|
|
685
|
+
/** `"SEARCH_INCOMPLETE"`. */
|
|
686
|
+
get partialReason() {
|
|
687
|
+
return readString(detailsOrBodyField(this.details, this.body, "partialReason"));
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
var DocumentWithdrawnError = class extends LexAPIError {
|
|
691
|
+
static kind = "DocumentWithdrawnError";
|
|
692
|
+
constructor(message, status = 410, details, retryAfter, context) {
|
|
693
|
+
super("DOCUMENT_WITHDRAWN", message, status, details, retryAfter, context);
|
|
694
|
+
this.name = "DocumentWithdrawnError";
|
|
695
|
+
}
|
|
696
|
+
field(key) {
|
|
697
|
+
const fromDetails = detailsField(this.details, key);
|
|
698
|
+
return fromDetails !== void 0 ? fromDetails : bodyField(this.body, key);
|
|
699
|
+
}
|
|
700
|
+
/** The withdrawn document's id (e.g. `AT-NOR-10001597`). */
|
|
701
|
+
get id() {
|
|
702
|
+
return readString(this.field("id"));
|
|
703
|
+
}
|
|
704
|
+
/** Upper-case jurisdiction code. */
|
|
705
|
+
get jurisdiction() {
|
|
706
|
+
return readString(this.field("jurisdiction"));
|
|
707
|
+
}
|
|
708
|
+
/** ISO date-time the source withdrew the document; `undefined` when unknown. */
|
|
709
|
+
get withdrawnAt() {
|
|
710
|
+
return readString(this.field("withdrawnAt"));
|
|
711
|
+
}
|
|
712
|
+
};
|
|
338
713
|
var InternalServerError = class extends LexAPIError {
|
|
339
714
|
static kind = "InternalServerError";
|
|
340
715
|
constructor(message, status = 500, details, retryAfter, context) {
|
|
@@ -362,14 +737,25 @@ var RequestAbortedError = class extends LexAPIError {
|
|
|
362
737
|
};
|
|
363
738
|
var InvalidResponseError = class extends LexAPIError {
|
|
364
739
|
static kind = "InvalidResponseError";
|
|
365
|
-
constructor(message, status,
|
|
366
|
-
super("INVALID_RESPONSE", message, status, void 0, void 0,
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
});
|
|
740
|
+
constructor(message, status, body, context) {
|
|
741
|
+
super("INVALID_RESPONSE", message, status, void 0, void 0, context);
|
|
742
|
+
delete this.body;
|
|
743
|
+
if (body !== void 0) INVALID_BODIES.set(this, body);
|
|
370
744
|
this.name = "InvalidResponseError";
|
|
371
745
|
}
|
|
372
746
|
};
|
|
747
|
+
Object.defineProperty(InvalidResponseError.prototype, "body", {
|
|
748
|
+
get() {
|
|
749
|
+
return INVALID_BODIES.get(this);
|
|
750
|
+
},
|
|
751
|
+
// Assigning replaces the stored value (`undefined` clears it), as on 0.4.0.
|
|
752
|
+
set(value) {
|
|
753
|
+
if (value === void 0) INVALID_BODIES.delete(this);
|
|
754
|
+
else INVALID_BODIES.set(this, value);
|
|
755
|
+
},
|
|
756
|
+
enumerable: false,
|
|
757
|
+
configurable: true
|
|
758
|
+
});
|
|
373
759
|
var IncompleteExportError = class extends LexAPIError {
|
|
374
760
|
static kind = "IncompleteExportError";
|
|
375
761
|
/** Rows yielded before the stream ended. */
|
|
@@ -387,15 +773,19 @@ var IncompleteExportError = class extends LexAPIError {
|
|
|
387
773
|
function isLexAPIError(value, errorClass) {
|
|
388
774
|
return value instanceof (errorClass ?? LexAPIError);
|
|
389
775
|
}
|
|
390
|
-
function normalizeRetryAfterSeconds(value) {
|
|
391
|
-
if (!Number.isFinite(value)) return 0;
|
|
392
|
-
if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
|
|
393
|
-
if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
|
|
394
|
-
return Math.max(0, value);
|
|
395
|
-
}
|
|
396
776
|
function readNumber(value) {
|
|
397
777
|
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
398
778
|
}
|
|
779
|
+
function bodyDetails(body) {
|
|
780
|
+
const err = detailsField(body, "error");
|
|
781
|
+
return typeof err === "object" && err !== null && !Array.isArray(err) ? detailsField(err, "details") : detailsField(body, "details");
|
|
782
|
+
}
|
|
783
|
+
function bodyWait(body, details) {
|
|
784
|
+
return bodySeconds(detailsField(body, "retryAfter")) ?? bodySeconds(detailsField(details, "retryAfter"));
|
|
785
|
+
}
|
|
786
|
+
function nonEmptyString(value) {
|
|
787
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
788
|
+
}
|
|
399
789
|
function readString(value) {
|
|
400
790
|
return typeof value === "string" ? value : void 0;
|
|
401
791
|
}
|
|
@@ -405,12 +795,19 @@ function detailsField(details, key) {
|
|
|
405
795
|
}
|
|
406
796
|
return void 0;
|
|
407
797
|
}
|
|
798
|
+
function hasQuotaCode(body) {
|
|
799
|
+
return detailsField(body, "code") === "QUOTA_EXHAUSTED" || detailsField(bodyField(body, "error"), "code") === "QUOTA_EXHAUSTED";
|
|
800
|
+
}
|
|
408
801
|
function isQuota429(body, headers) {
|
|
409
|
-
if (
|
|
410
|
-
const
|
|
411
|
-
if (typeof
|
|
412
|
-
if (headers?.retryAfter !== void 0
|
|
413
|
-
return
|
|
802
|
+
if (hasQuotaCode(body)) return true;
|
|
803
|
+
const resetsAt2 = detailsField(detailsField(body, "usage"), "resetsAt");
|
|
804
|
+
if (typeof resetsAt2 !== "string") return false;
|
|
805
|
+
if (retryAfterHeaderSeconds(headers?.retryAfter) !== void 0) return false;
|
|
806
|
+
return bodyWait(body, bodyDetails(body)) === void 0;
|
|
807
|
+
}
|
|
808
|
+
function detailsOrBodyField(details, body, key) {
|
|
809
|
+
const fromDetails = detailsField(details, key);
|
|
810
|
+
return fromDetails !== void 0 ? fromDetails : bodyField(body, key);
|
|
414
811
|
}
|
|
415
812
|
function bodyField(body, key) {
|
|
416
813
|
return detailsField(body, key);
|
|
@@ -424,11 +821,15 @@ function str(headers, name) {
|
|
|
424
821
|
const value = headers.get(name);
|
|
425
822
|
return value === null ? void 0 : value;
|
|
426
823
|
}
|
|
824
|
+
function parseHeaderInteger(value) {
|
|
825
|
+
if (typeof value !== "string") return void 0;
|
|
826
|
+
const text2 = value.replace(/^[ \t]+|[ \t]+$/g, "");
|
|
827
|
+
if (!/^[0-9]+$/.test(text2)) return void 0;
|
|
828
|
+
const parsed = Number(text2);
|
|
829
|
+
return Number.isSafeInteger(parsed) ? parsed : void 0;
|
|
830
|
+
}
|
|
427
831
|
function int(headers, name) {
|
|
428
|
-
|
|
429
|
-
if (value === null) return void 0;
|
|
430
|
-
const parsed = Number.parseInt(value, 10);
|
|
431
|
-
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
832
|
+
return parseHeaderInteger(headers.get(name));
|
|
432
833
|
}
|
|
433
834
|
function compact(obj) {
|
|
434
835
|
const out = {};
|
|
@@ -473,17 +874,23 @@ function parseResponseHeaders(source) {
|
|
|
473
874
|
remaining: int(h, "ratelimit-remaining"),
|
|
474
875
|
reset: int(h, "ratelimit-reset"),
|
|
475
876
|
policy: str(h, "ratelimit-policy")
|
|
877
|
+
}),
|
|
878
|
+
nationalAllowance: compact({
|
|
879
|
+
limit: int(h, "x-national-limit"),
|
|
880
|
+
remaining: int(h, "x-national-remaining"),
|
|
881
|
+
resetsAt: str(h, "x-national-reset")
|
|
476
882
|
})
|
|
477
883
|
};
|
|
478
884
|
return compact(parsed) ?? {};
|
|
479
885
|
}
|
|
480
886
|
|
|
481
887
|
// src/version.ts
|
|
482
|
-
var VERSION = "0.
|
|
888
|
+
var VERSION = "0.5.0";
|
|
483
889
|
|
|
484
890
|
// src/http.ts
|
|
485
891
|
var DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
|
|
486
892
|
var DEFAULT_TIMEOUT_MS = 95e3;
|
|
893
|
+
var KIND_NAMES = { object: "an object", string: "a string", boolean: "a boolean" };
|
|
487
894
|
var NEVER_REACHED_CODES = /* @__PURE__ */ new Set([
|
|
488
895
|
// DNS
|
|
489
896
|
"ENOTFOUND",
|
|
@@ -521,6 +928,33 @@ var CONNECT_SYSCALL_CODES = /* @__PURE__ */ new Set(["ETIMEDOUT"]);
|
|
|
521
928
|
var NEVER_REACHED_STATUSES = /* @__PURE__ */ new Set([521, 522, 523]);
|
|
522
929
|
var ORIGIN_DEPENDENT_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
|
|
523
930
|
var PROXY_STATUSES = /* @__PURE__ */ new Set([520, 524]);
|
|
931
|
+
var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
932
|
+
var MAX_REDIRECTS = 5;
|
|
933
|
+
function redirectTarget(location, from) {
|
|
934
|
+
let to;
|
|
935
|
+
try {
|
|
936
|
+
to = new URL(location, from);
|
|
937
|
+
} catch {
|
|
938
|
+
throw new NetworkError("Refused to follow a redirect with an invalid Location header");
|
|
939
|
+
}
|
|
940
|
+
if (to.protocol !== "http:" && to.protocol !== "https:") {
|
|
941
|
+
throw new NetworkError("Refused to follow a redirect to a URL that is not http(s)");
|
|
942
|
+
}
|
|
943
|
+
if (to.username !== "" || to.password !== "") {
|
|
944
|
+
throw new NetworkError(`Refused to follow a redirect to a URL that carries credentials (${to.origin})`);
|
|
945
|
+
}
|
|
946
|
+
const httpsUpgrade = from.protocol === "http:" && to.protocol === "https:" && to.hostname === from.hostname && from.port === "" && to.port === "";
|
|
947
|
+
if (to.origin !== from.origin && !httpsUpgrade) {
|
|
948
|
+
throw new NetworkError(`Refused to follow a redirect to another origin (${to.origin})`);
|
|
949
|
+
}
|
|
950
|
+
return to;
|
|
951
|
+
}
|
|
952
|
+
function discardBody(response) {
|
|
953
|
+
try {
|
|
954
|
+
response.body?.cancel().catch(() => void 0);
|
|
955
|
+
} catch {
|
|
956
|
+
}
|
|
957
|
+
}
|
|
524
958
|
function isNeverReachedError(error, depth = 0) {
|
|
525
959
|
if (depth > 6 || typeof error !== "object" || error === null) return false;
|
|
526
960
|
const { code, syscall, cause, errors } = error;
|
|
@@ -566,7 +1000,10 @@ var HttpClient = class {
|
|
|
566
1000
|
[INSPECT]() {
|
|
567
1001
|
return `HttpClient { baseUrl: '${this.opts.baseUrl}', apiKey: '[redacted]' }`;
|
|
568
1002
|
}
|
|
569
|
-
/**
|
|
1003
|
+
/**
|
|
1004
|
+
* Perform a request and parse the JSON body. A 2xx that is not the
|
|
1005
|
+
* documented shape (`options.shape`) throws `InvalidResponseError`.
|
|
1006
|
+
*/
|
|
570
1007
|
async requestJson(options) {
|
|
571
1008
|
const { data } = await this.requestJsonWithResponse(options);
|
|
572
1009
|
return data;
|
|
@@ -577,7 +1014,7 @@ var HttpClient = class {
|
|
|
577
1014
|
*/
|
|
578
1015
|
async requestJsonWithResponse(options) {
|
|
579
1016
|
return this.execute(options, async (response, ctx) => ({
|
|
580
|
-
data: await readJsonBody(response, ctx.touch),
|
|
1017
|
+
data: await readJsonBody(response, options.shape ?? {}, ctx.touch),
|
|
581
1018
|
response
|
|
582
1019
|
}));
|
|
583
1020
|
}
|
|
@@ -610,6 +1047,7 @@ var HttpClient = class {
|
|
|
610
1047
|
headers["content-type"] = "application/json";
|
|
611
1048
|
serializedBody = JSON.stringify(body);
|
|
612
1049
|
}
|
|
1050
|
+
let incompleteRetried = false;
|
|
613
1051
|
for (let attempt = 0; ; attempt++) {
|
|
614
1052
|
throwIfAborted(signal, method, path);
|
|
615
1053
|
const controller = new AbortController();
|
|
@@ -617,10 +1055,11 @@ var HttpClient = class {
|
|
|
617
1055
|
let timer;
|
|
618
1056
|
const touch = () => {
|
|
619
1057
|
if (timer !== void 0) clearTimeout(timer);
|
|
1058
|
+
if (timeoutMs === Infinity) return;
|
|
620
1059
|
timer = setTimeout(() => {
|
|
621
1060
|
timedOut = true;
|
|
622
1061
|
controller.abort();
|
|
623
|
-
}, timeoutMs);
|
|
1062
|
+
}, timerDelay(timeoutMs));
|
|
624
1063
|
};
|
|
625
1064
|
touch();
|
|
626
1065
|
const onAbort = () => controller.abort();
|
|
@@ -629,12 +1068,7 @@ var HttpClient = class {
|
|
|
629
1068
|
let response;
|
|
630
1069
|
let retryTransport = false;
|
|
631
1070
|
try {
|
|
632
|
-
response = await this.
|
|
633
|
-
method,
|
|
634
|
-
headers,
|
|
635
|
-
...serializedBody !== void 0 ? { body: serializedBody } : {},
|
|
636
|
-
signal: controller.signal
|
|
637
|
-
});
|
|
1071
|
+
response = await this.fetchWithinOrigin(url, method, headers, serializedBody, controller.signal);
|
|
638
1072
|
touch();
|
|
639
1073
|
if (response.ok) {
|
|
640
1074
|
return await onSuccess(response, { signal: controller.signal, timeoutMs, touch });
|
|
@@ -661,7 +1095,9 @@ var HttpClient = class {
|
|
|
661
1095
|
await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs), signal, method, path);
|
|
662
1096
|
continue;
|
|
663
1097
|
}
|
|
664
|
-
|
|
1098
|
+
const incomplete = error.status === 503 && isSearchIncomplete(error);
|
|
1099
|
+
if (attempt < maxRetries && !(incomplete && incompleteRetried) && shouldRetryStatus(error, { isGet, free, readOnly: options.idempotent === true && retryReadOnlyPosts })) {
|
|
1100
|
+
if (incomplete) incompleteRetried = true;
|
|
665
1101
|
const waitMs = error.retryAfter !== void 0 ? Math.min(error.retryAfter * 1e3, maxDelayMs) : fullJitterBackoff(attempt, baseDelayMs, maxDelayMs);
|
|
666
1102
|
await sleep(waitMs, signal, method, path);
|
|
667
1103
|
continue;
|
|
@@ -669,9 +1105,61 @@ var HttpClient = class {
|
|
|
669
1105
|
throw error;
|
|
670
1106
|
}
|
|
671
1107
|
}
|
|
1108
|
+
/**
|
|
1109
|
+
* `fetch` with redirects followed here rather than by the runtime, which
|
|
1110
|
+
* would repeat every request header to whichever host a redirect names.
|
|
1111
|
+
* Method and body change as `fetch` changes them: a 303, or a 301/302
|
|
1112
|
+
* answer to a POST, continues as a body-less GET; 307/308 repeat the request.
|
|
1113
|
+
* The body of a redirect response is cancelled, so its connection is released.
|
|
1114
|
+
* A response that says it was already redirected (a custom `fetch` that did
|
|
1115
|
+
* not honour `redirect: "manual"`) is refused.
|
|
1116
|
+
*/
|
|
1117
|
+
async fetchWithinOrigin(url, method, headers, body, signal) {
|
|
1118
|
+
const fetchFn = this.opts.fetchFn;
|
|
1119
|
+
let target = url;
|
|
1120
|
+
for (let hop = 0; ; hop++) {
|
|
1121
|
+
const response = await fetchFn(target, {
|
|
1122
|
+
method,
|
|
1123
|
+
headers,
|
|
1124
|
+
...body !== void 0 ? { body } : {},
|
|
1125
|
+
redirect: "manual",
|
|
1126
|
+
signal
|
|
1127
|
+
});
|
|
1128
|
+
if (response.redirected === true) {
|
|
1129
|
+
discardBody(response);
|
|
1130
|
+
throw new NetworkError('The custom fetch followed a redirect itself; it must honour redirect: "manual"');
|
|
1131
|
+
}
|
|
1132
|
+
if (response.type === "opaqueredirect") {
|
|
1133
|
+
throw new NetworkError("The API answered with a redirect, which this runtime does not expose");
|
|
1134
|
+
}
|
|
1135
|
+
const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null;
|
|
1136
|
+
if (location === null) return response;
|
|
1137
|
+
discardBody(response);
|
|
1138
|
+
let from;
|
|
1139
|
+
try {
|
|
1140
|
+
from = new URL(target);
|
|
1141
|
+
} catch {
|
|
1142
|
+
throw new NetworkError("Refused to follow a redirect from a request URL that is not absolute");
|
|
1143
|
+
}
|
|
1144
|
+
const next = redirectTarget(location, from);
|
|
1145
|
+
if (hop >= MAX_REDIRECTS) {
|
|
1146
|
+
throw new NetworkError(`Too many redirects (more than ${MAX_REDIRECTS})`);
|
|
1147
|
+
}
|
|
1148
|
+
if (response.status === 303 && method !== "GET" || (response.status === 301 || response.status === 302) && method === "POST") {
|
|
1149
|
+
method = "GET";
|
|
1150
|
+
body = void 0;
|
|
1151
|
+
headers = { ...headers };
|
|
1152
|
+
delete headers["content-type"];
|
|
1153
|
+
}
|
|
1154
|
+
target = next.href;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
672
1157
|
};
|
|
673
1158
|
function shouldRetryStatus(error, call) {
|
|
674
1159
|
const status = error.status;
|
|
1160
|
+
if (error.code === "PAYMENT_PAST_DUE") return false;
|
|
1161
|
+
if (status === 503 && isBudgetTimeout(error.body)) return false;
|
|
1162
|
+
if (status === 503 && isSearchIncomplete(error) && error.retryAfter === void 0) return false;
|
|
675
1163
|
if (status === 429) return !(error instanceof RateLimitedError && error.quotaExhausted);
|
|
676
1164
|
if (NEVER_REACHED_STATUSES.has(status)) return true;
|
|
677
1165
|
if (ORIGIN_DEPENDENT_STATUSES.has(status)) {
|
|
@@ -681,34 +1169,140 @@ function shouldRetryStatus(error, call) {
|
|
|
681
1169
|
if (PROXY_STATUSES.has(status)) return call.free;
|
|
682
1170
|
return false;
|
|
683
1171
|
}
|
|
684
|
-
|
|
685
|
-
|
|
1172
|
+
function isBudgetTimeout(body) {
|
|
1173
|
+
return typeof body === "object" && body !== null && body["partialReason"] === "TIMEOUT";
|
|
1174
|
+
}
|
|
1175
|
+
function isSearchIncomplete(error) {
|
|
1176
|
+
const field = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v["partialReason"] : void 0;
|
|
1177
|
+
return (field(error.details) ?? field(error.body)) === "SEARCH_INCOMPLETE";
|
|
1178
|
+
}
|
|
1179
|
+
async function readBodyBytes(response, touch) {
|
|
1180
|
+
if (response.body === null || touch === void 0) return new Uint8Array(await response.arrayBuffer());
|
|
686
1181
|
const reader = response.body.getReader();
|
|
687
|
-
const
|
|
688
|
-
|
|
1182
|
+
const chunks = [];
|
|
1183
|
+
let length = 0;
|
|
689
1184
|
for (; ; ) {
|
|
690
1185
|
const { done, value } = await reader.read();
|
|
691
1186
|
if (done) break;
|
|
692
1187
|
touch();
|
|
693
|
-
|
|
1188
|
+
chunks.push(value);
|
|
1189
|
+
length += value.byteLength;
|
|
1190
|
+
}
|
|
1191
|
+
const bytes = new Uint8Array(length);
|
|
1192
|
+
let offset = 0;
|
|
1193
|
+
for (const chunk of chunks) {
|
|
1194
|
+
bytes.set(chunk, offset);
|
|
1195
|
+
offset += chunk.byteLength;
|
|
694
1196
|
}
|
|
695
|
-
|
|
696
|
-
return parts.join("");
|
|
1197
|
+
return bytes;
|
|
697
1198
|
}
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
1199
|
+
var EXCERPT_CHARS = 200;
|
|
1200
|
+
var EXCERPT_BYTES = EXCERPT_CHARS * 4;
|
|
1201
|
+
var NOT_JSON = /* @__PURE__ */ Symbol("not JSON");
|
|
1202
|
+
function parseJsonBytes(bytes) {
|
|
702
1203
|
try {
|
|
703
|
-
return JSON.parse(
|
|
1204
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
704
1205
|
} catch {
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
1206
|
+
return NOT_JSON;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
function excerptOf(bytes) {
|
|
1210
|
+
if (bytes.byteLength === 0) return void 0;
|
|
1211
|
+
const text2 = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(0, EXCERPT_BYTES));
|
|
1212
|
+
let out = "";
|
|
1213
|
+
let count2 = 0;
|
|
1214
|
+
for (const char of text2) {
|
|
1215
|
+
if (count2++ === EXCERPT_CHARS) break;
|
|
1216
|
+
out += char;
|
|
1217
|
+
}
|
|
1218
|
+
return out;
|
|
1219
|
+
}
|
|
1220
|
+
function mediaTypeOf(response) {
|
|
1221
|
+
const value = response.headers.get("content-type") ?? "";
|
|
1222
|
+
const media = Array.from(value.split(";", 1)[0].replace(/^[ \t]+|[ \t]+$/g, "")).slice(0, 100).join("");
|
|
1223
|
+
return media === "" ? "no content type" : media;
|
|
1224
|
+
}
|
|
1225
|
+
function jsonKind(value) {
|
|
1226
|
+
if (value === null) return "null";
|
|
1227
|
+
if (Array.isArray(value)) return "array";
|
|
1228
|
+
return typeof value;
|
|
1229
|
+
}
|
|
1230
|
+
function isJsonObject(value) {
|
|
1231
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1232
|
+
}
|
|
1233
|
+
var MISSING = /* @__PURE__ */ Symbol("missing");
|
|
1234
|
+
function lookup(body, path) {
|
|
1235
|
+
let value = body;
|
|
1236
|
+
for (const key of path.split(".")) {
|
|
1237
|
+
if (!isJsonObject(value) || !Object.prototype.hasOwnProperty.call(value, key)) return MISSING;
|
|
1238
|
+
value = value[key];
|
|
1239
|
+
}
|
|
1240
|
+
return value;
|
|
1241
|
+
}
|
|
1242
|
+
function shapeProblem(body, shape) {
|
|
1243
|
+
const missing = (path) => `Expected "${path}" in the response; it is missing`;
|
|
1244
|
+
const wrongKind = (path, expected, value) => `Expected "${path}" to be ${KIND_NAMES[expected]}, got ${jsonKind(value)}`;
|
|
1245
|
+
for (const path of shape.required ?? []) {
|
|
1246
|
+
const value = lookup(body, path);
|
|
1247
|
+
if (value === MISSING || value === null) return missing(path);
|
|
1248
|
+
}
|
|
1249
|
+
for (const { path, kind } of shape.fields ?? []) {
|
|
1250
|
+
const value = lookup(body, path);
|
|
1251
|
+
if (value === MISSING || value === null || kind === "string" && value === "") return missing(path);
|
|
1252
|
+
const ok = kind === "object" ? isJsonObject(value) : typeof value === kind;
|
|
1253
|
+
if (!ok) return wrongKind(path, kind, value);
|
|
1254
|
+
}
|
|
1255
|
+
for (const path of shape.optionalObjects ?? []) {
|
|
1256
|
+
const value = lookup(body, path);
|
|
1257
|
+
if (value !== MISSING && value !== null && !isJsonObject(value)) return wrongKind(path, "object", value);
|
|
1258
|
+
}
|
|
1259
|
+
for (const path of shape.lists ?? []) {
|
|
1260
|
+
const value = lookup(body, path);
|
|
1261
|
+
if (value === MISSING || value === null) continue;
|
|
1262
|
+
if (!Array.isArray(value)) return `Expected "${path}" to be a list, got ${jsonKind(value)}`;
|
|
1263
|
+
for (let index = 0; index < value.length; index++) {
|
|
1264
|
+
const item = value[index];
|
|
1265
|
+
if (!isJsonObject(item)) {
|
|
1266
|
+
return `Expected every item of "${path}" to be an object, got ${jsonKind(item)} at index ${index}`;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
return void 0;
|
|
1271
|
+
}
|
|
1272
|
+
function hasErrorEnvelope(body) {
|
|
1273
|
+
const err = body["error"];
|
|
1274
|
+
return isJsonObject(err) || typeof err === "string" && err !== "";
|
|
1275
|
+
}
|
|
1276
|
+
async function readJsonBody(response, shape, touch) {
|
|
1277
|
+
const status = response.status;
|
|
1278
|
+
const headers = parseResponseHeaders(response);
|
|
1279
|
+
const invalid = (message, body2, bodyExcerpt) => new InvalidResponseError(message, status, body2, { headers, ...bodyExcerpt !== void 0 ? { bodyExcerpt } : {} });
|
|
1280
|
+
if (status === 204) {
|
|
1281
|
+
discardBody(response);
|
|
1282
|
+
if (shape.allowEmpty === true) return {};
|
|
1283
|
+
throw invalid("Expected JSON, got no body");
|
|
1284
|
+
}
|
|
1285
|
+
const bytes = await readBodyBytes(response, touch);
|
|
1286
|
+
if (bytes.byteLength === 0) {
|
|
1287
|
+
if (shape.allowEmpty === true) return {};
|
|
1288
|
+
throw invalid("Expected JSON, got no body");
|
|
1289
|
+
}
|
|
1290
|
+
const body = parseJsonBytes(bytes);
|
|
1291
|
+
if (body === NOT_JSON) {
|
|
1292
|
+
throw invalid(
|
|
1293
|
+
`Expected JSON, got ${mediaTypeOf(response)} that does not parse as JSON (${bytes.byteLength} bytes)`,
|
|
1294
|
+
void 0,
|
|
1295
|
+
excerptOf(bytes)
|
|
710
1296
|
);
|
|
711
1297
|
}
|
|
1298
|
+
if (!isJsonObject(body)) throw invalid(`Expected a JSON object, got ${jsonKind(body)}`, body);
|
|
1299
|
+
if (body["success"] === false && shape.successFalseOk !== true) {
|
|
1300
|
+
if (hasErrorEnvelope(body)) throw LexAPIError.fromResponse(status, body, void 0, headers);
|
|
1301
|
+
throw invalid("Response reported success: false without an error", body);
|
|
1302
|
+
}
|
|
1303
|
+
const problem = shapeProblem(body, shape);
|
|
1304
|
+
if (problem !== void 0) throw invalid(problem, body);
|
|
1305
|
+
return body;
|
|
712
1306
|
}
|
|
713
1307
|
function throwIfAborted(signal, method, path) {
|
|
714
1308
|
if (signal?.aborted) {
|
|
@@ -716,39 +1310,24 @@ function throwIfAborted(signal, method, path) {
|
|
|
716
1310
|
}
|
|
717
1311
|
}
|
|
718
1312
|
async function parseErrorResponse(response, touch) {
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
} catch (cause) {
|
|
724
|
-
if (!(cause instanceof SyntaxError)) throw cause;
|
|
725
|
-
body = void 0;
|
|
726
|
-
}
|
|
1313
|
+
const bytes = await readBodyBytes(response, touch);
|
|
1314
|
+
const parsed = bytes.byteLength === 0 ? NOT_JSON : parseJsonBytes(bytes);
|
|
1315
|
+
const body = parsed === NOT_JSON ? void 0 : parsed;
|
|
1316
|
+
const bodyExcerpt = parsed === NOT_JSON ? excerptOf(bytes) : void 0;
|
|
727
1317
|
const hint = headerRetryAfterSeconds(response) ?? (response.status === 429 ? resetHeaderSeconds(response, "ratelimit-reset") : void 0);
|
|
728
|
-
return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response));
|
|
1318
|
+
return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response), bodyExcerpt);
|
|
729
1319
|
}
|
|
730
1320
|
function headerRetryAfterSeconds(response) {
|
|
731
|
-
|
|
732
|
-
if (raw === null) return void 0;
|
|
733
|
-
const header = raw.trim();
|
|
734
|
-
if (header === "") return void 0;
|
|
735
|
-
if (/^\d+(\.\d+)?$/.test(header)) return normalizeRetryAfterSeconds(Number(header));
|
|
736
|
-
if (/^[-+]?\d/.test(header)) return void 0;
|
|
737
|
-
const date = Date.parse(header);
|
|
738
|
-
if (!Number.isNaN(date)) return Math.max(0, Math.round((date - Date.now()) / 1e3));
|
|
739
|
-
return void 0;
|
|
1321
|
+
return retryAfterHeaderSeconds(response.headers.get("retry-after"));
|
|
740
1322
|
}
|
|
741
1323
|
function resetHeaderSeconds(response, name) {
|
|
742
|
-
|
|
743
|
-
if (raw === null || raw.trim() === "") return void 0;
|
|
744
|
-
const seconds = Number(raw);
|
|
745
|
-
if (!Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
746
|
-
return normalizeRetryAfterSeconds(seconds);
|
|
1324
|
+
return decimalSeconds(response.headers.get(name));
|
|
747
1325
|
}
|
|
748
1326
|
function fullJitterBackoff(attempt, baseDelayMs, maxDelayMs) {
|
|
749
1327
|
return Math.random() * Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
|
|
750
1328
|
}
|
|
751
1329
|
function sleep(ms, signal, method, path) {
|
|
1330
|
+
ms = timerDelay(ms);
|
|
752
1331
|
return new Promise((resolve, reject) => {
|
|
753
1332
|
if (signal?.aborted) {
|
|
754
1333
|
reject(new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason));
|
|
@@ -783,6 +1362,39 @@ function buildQuery(query) {
|
|
|
783
1362
|
}
|
|
784
1363
|
|
|
785
1364
|
// src/export.ts
|
|
1365
|
+
var INVALID_LINE = /* @__PURE__ */ Symbol("invalid line");
|
|
1366
|
+
var NO_BYTES = new Uint8Array(0);
|
|
1367
|
+
function heldBytes(previous, chunk) {
|
|
1368
|
+
const n = chunk.length;
|
|
1369
|
+
if (n > 0 && chunk[n - 1] < 128) return NO_BYTES;
|
|
1370
|
+
const tail = n >= 3 ? chunk.subarray(n - 3) : new Uint8Array([...previous, ...chunk].slice(-3));
|
|
1371
|
+
for (let k = 1; k <= tail.length; k++) {
|
|
1372
|
+
const byte = tail[tail.length - k];
|
|
1373
|
+
if ((byte & 192) === 128) continue;
|
|
1374
|
+
const size = byte >= 240 ? 4 : byte >= 224 ? 3 : byte >= 192 ? 2 : 1;
|
|
1375
|
+
return size > k ? tail.slice(tail.length - k) : NO_BYTES;
|
|
1376
|
+
}
|
|
1377
|
+
return NO_BYTES;
|
|
1378
|
+
}
|
|
1379
|
+
function strictDecoder() {
|
|
1380
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
1381
|
+
}
|
|
1382
|
+
function byteView(chunk) {
|
|
1383
|
+
if (chunk instanceof Uint8Array) return chunk;
|
|
1384
|
+
if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
|
|
1385
|
+
if (ArrayBuffer.isView(chunk)) return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
1386
|
+
return void 0;
|
|
1387
|
+
}
|
|
1388
|
+
function trimLine(line) {
|
|
1389
|
+
let start = 0;
|
|
1390
|
+
let end = line.length;
|
|
1391
|
+
while (start < end && isLineSpace(line.charCodeAt(start))) start++;
|
|
1392
|
+
while (end > start && isLineSpace(line.charCodeAt(end - 1))) end--;
|
|
1393
|
+
return start === 0 && end === line.length ? line : line.slice(start, end);
|
|
1394
|
+
}
|
|
1395
|
+
function isLineSpace(code) {
|
|
1396
|
+
return code === 32 || code === 9 || code === 13;
|
|
1397
|
+
}
|
|
786
1398
|
var NdjsonReader = class {
|
|
787
1399
|
constructor(body, options) {
|
|
788
1400
|
this.options = options;
|
|
@@ -792,54 +1404,175 @@ var NdjsonReader = class {
|
|
|
792
1404
|
else signal?.addEventListener("abort", this.onAbort, { once: true });
|
|
793
1405
|
}
|
|
794
1406
|
reader;
|
|
795
|
-
|
|
796
|
-
|
|
1407
|
+
/** Decodes the line in progress; holds the bytes of a character split across chunks. */
|
|
1408
|
+
decoder = strictDecoder();
|
|
1409
|
+
/** A copy of the bytes the decoder holds (a character not yet complete), so it can be rebuilt. */
|
|
1410
|
+
carry = NO_BYTES;
|
|
1411
|
+
/** Text pieces of the line in progress. */
|
|
797
1412
|
partial = [];
|
|
1413
|
+
/** The line in progress already holds bytes that are not UTF-8. */
|
|
1414
|
+
broken = false;
|
|
798
1415
|
/** Complete lines not yet handed out. */
|
|
799
1416
|
ready = [];
|
|
1417
|
+
/** No line has been completed yet. */
|
|
1418
|
+
atStart = true;
|
|
1419
|
+
/** The first line of the stream was blank (so the first line handed out is not the stream's first). */
|
|
1420
|
+
firstLineBlank = false;
|
|
800
1421
|
eof = false;
|
|
801
1422
|
released = false;
|
|
802
1423
|
/** Data rows handed out so far (for error messages). */
|
|
803
1424
|
rows = 0;
|
|
804
1425
|
/** Releases the connection the moment the caller aborts — even while nobody is reading. */
|
|
805
1426
|
onAbort = () => this.cancel();
|
|
806
|
-
/** Next
|
|
1427
|
+
/** Next non-blank line (trimmed), or `INVALID_LINE`, or `undefined` at EOF. */
|
|
807
1428
|
async nextLine() {
|
|
808
1429
|
const { signal } = this.options;
|
|
809
1430
|
if (signal?.aborted) {
|
|
810
1431
|
this.cancel();
|
|
811
1432
|
throw new RequestAbortedError("Export stream was aborted", signal.reason);
|
|
812
1433
|
}
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
1434
|
+
try {
|
|
1435
|
+
for (; ; ) {
|
|
1436
|
+
const line = this.ready.shift();
|
|
1437
|
+
if (line !== void 0) return line;
|
|
1438
|
+
if (this.eof) return void 0;
|
|
1439
|
+
const result = await this.read();
|
|
1440
|
+
if (result.done) {
|
|
1441
|
+
this.finish();
|
|
1442
|
+
this.release();
|
|
1443
|
+
} else {
|
|
1444
|
+
this.ingest(result.value);
|
|
1445
|
+
}
|
|
820
1446
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
1447
|
+
} catch (cause) {
|
|
1448
|
+
this.cancel();
|
|
1449
|
+
if (cause instanceof LexAPIError) throw cause;
|
|
1450
|
+
throw new NetworkError(`Export stream interrupted after ${this.rows} rows`, cause);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
ingest(value) {
|
|
1454
|
+
const chunk = byteView(value);
|
|
1455
|
+
if (chunk === void 0) throw new TypeError("Export stream yielded a chunk that is not bytes");
|
|
1456
|
+
if (!this.broken) {
|
|
1457
|
+
let text2;
|
|
1458
|
+
try {
|
|
1459
|
+
text2 = this.decoder.decode(chunk, { stream: true });
|
|
1460
|
+
} catch {
|
|
1461
|
+
this.decoder = strictDecoder();
|
|
1462
|
+
if (this.carry.length > 0) this.decoder.decode(this.carry, { stream: true });
|
|
1463
|
+
}
|
|
1464
|
+
if (text2 !== void 0) {
|
|
1465
|
+
this.carry = heldBytes(this.carry, chunk);
|
|
1466
|
+
let pos = 0;
|
|
1467
|
+
for (; ; ) {
|
|
1468
|
+
const newline = text2.indexOf("\n", pos);
|
|
1469
|
+
if (newline === -1) break;
|
|
1470
|
+
this.partial.push(text2.slice(pos, newline));
|
|
1471
|
+
const line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
|
|
1472
|
+
this.partial = [];
|
|
1473
|
+
this.complete(line);
|
|
1474
|
+
pos = newline + 1;
|
|
1475
|
+
}
|
|
1476
|
+
if (pos < text2.length) this.partial.push(pos === 0 ? text2 : text2.slice(pos));
|
|
1477
|
+
return;
|
|
828
1478
|
}
|
|
829
1479
|
}
|
|
1480
|
+
this.ingestBytes(chunk);
|
|
830
1481
|
}
|
|
831
|
-
|
|
1482
|
+
/** A chunk that is not all UTF-8, or that continues a line that is not. */
|
|
1483
|
+
ingestBytes(chunk) {
|
|
1484
|
+
const first = chunk.indexOf(10);
|
|
1485
|
+
if (first === -1) {
|
|
1486
|
+
this.feed(chunk);
|
|
1487
|
+
return;
|
|
1488
|
+
}
|
|
1489
|
+
const last = chunk.lastIndexOf(10);
|
|
1490
|
+
let line = INVALID_LINE;
|
|
1491
|
+
if (!this.broken) {
|
|
1492
|
+
try {
|
|
1493
|
+
const text2 = this.decoder.decode(chunk.subarray(0, first + 1), { stream: true });
|
|
1494
|
+
this.partial.push(text2.slice(0, -1));
|
|
1495
|
+
line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
|
|
1496
|
+
} catch {
|
|
1497
|
+
this.decoder = strictDecoder();
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
this.partial = [];
|
|
1501
|
+
this.broken = false;
|
|
1502
|
+
this.carry = NO_BYTES;
|
|
1503
|
+
this.complete(line);
|
|
1504
|
+
if (first < last) this.completeRegion(chunk.subarray(first + 1, last + 1));
|
|
1505
|
+
if (last + 1 < chunk.length) this.feed(chunk.subarray(last + 1));
|
|
1506
|
+
}
|
|
1507
|
+
/** Whole lines, each ending with its line feed. */
|
|
1508
|
+
completeRegion(region) {
|
|
1509
|
+
let text2;
|
|
1510
|
+
try {
|
|
1511
|
+
text2 = this.decoder.decode(region, { stream: true });
|
|
1512
|
+
} catch {
|
|
1513
|
+
this.decoder = strictDecoder();
|
|
1514
|
+
}
|
|
1515
|
+
if (text2 !== void 0) {
|
|
1516
|
+
let pos2 = 0;
|
|
1517
|
+
for (; ; ) {
|
|
1518
|
+
const newline = text2.indexOf("\n", pos2);
|
|
1519
|
+
if (newline === -1) break;
|
|
1520
|
+
this.complete(text2.slice(pos2, newline));
|
|
1521
|
+
pos2 = newline + 1;
|
|
1522
|
+
}
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
832
1525
|
let pos = 0;
|
|
833
|
-
|
|
834
|
-
const newline =
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
1526
|
+
while (pos < region.length) {
|
|
1527
|
+
const newline = region.indexOf(10, pos);
|
|
1528
|
+
try {
|
|
1529
|
+
this.complete(this.decoder.decode(region.subarray(pos, newline + 1), { stream: true }).slice(0, -1));
|
|
1530
|
+
} catch {
|
|
1531
|
+
this.decoder = strictDecoder();
|
|
1532
|
+
this.complete(INVALID_LINE);
|
|
1533
|
+
}
|
|
840
1534
|
pos = newline + 1;
|
|
841
1535
|
}
|
|
842
|
-
|
|
1536
|
+
}
|
|
1537
|
+
/** Bytes of the line in progress (after a line feed, or continuing a line that is not UTF-8). */
|
|
1538
|
+
feed(bytes) {
|
|
1539
|
+
if (this.broken || bytes.length === 0) return;
|
|
1540
|
+
try {
|
|
1541
|
+
const text2 = this.decoder.decode(bytes, { stream: true });
|
|
1542
|
+
if (text2) this.partial.push(text2);
|
|
1543
|
+
this.carry = heldBytes(this.carry, bytes);
|
|
1544
|
+
} catch {
|
|
1545
|
+
this.broken = true;
|
|
1546
|
+
this.decoder = strictDecoder();
|
|
1547
|
+
this.carry = NO_BYTES;
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
/** End of stream: the line in progress, if any. */
|
|
1551
|
+
finish() {
|
|
1552
|
+
this.eof = true;
|
|
1553
|
+
let line = INVALID_LINE;
|
|
1554
|
+
if (!this.broken) {
|
|
1555
|
+
try {
|
|
1556
|
+
this.partial.push(this.decoder.decode());
|
|
1557
|
+
line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
|
|
1558
|
+
} catch {
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
this.partial = [];
|
|
1562
|
+
this.broken = false;
|
|
1563
|
+
this.complete(line);
|
|
1564
|
+
}
|
|
1565
|
+
/** Queue a complete line: a byte order mark leading the stream is dropped; blank lines are skipped. */
|
|
1566
|
+
complete(line) {
|
|
1567
|
+
const first = this.atStart;
|
|
1568
|
+
this.atStart = false;
|
|
1569
|
+
if (line === INVALID_LINE) {
|
|
1570
|
+
this.ready.push(line);
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
const text2 = trimLine(first && line.charCodeAt(0) === 65279 ? line.slice(1) : line);
|
|
1574
|
+
if (text2) this.ready.push(text2);
|
|
1575
|
+
else if (first) this.firstLineBlank = true;
|
|
843
1576
|
}
|
|
844
1577
|
async read() {
|
|
845
1578
|
const { idleTimeoutMs, signal } = this.options;
|
|
@@ -850,12 +1583,12 @@ var NdjsonReader = class {
|
|
|
850
1583
|
let timer;
|
|
851
1584
|
let onAbort;
|
|
852
1585
|
const interruptions = new Promise((_, reject) => {
|
|
853
|
-
if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0) {
|
|
1586
|
+
if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0 && idleTimeoutMs !== Infinity) {
|
|
854
1587
|
timer = setTimeout(() => {
|
|
855
1588
|
reject(
|
|
856
1589
|
new TimeoutError(`Export stream received no data for ${idleTimeoutMs}ms (after ${this.rows} rows)`, 0)
|
|
857
1590
|
);
|
|
858
|
-
}, idleTimeoutMs);
|
|
1591
|
+
}, timerDelay(idleTimeoutMs));
|
|
859
1592
|
}
|
|
860
1593
|
if (signal) {
|
|
861
1594
|
onAbort = () => reject(new RequestAbortedError("Export stream was aborted", signal.reason));
|
|
@@ -865,7 +1598,7 @@ var NdjsonReader = class {
|
|
|
865
1598
|
try {
|
|
866
1599
|
const result = await Promise.race([this.reader.read(), interruptions]);
|
|
867
1600
|
if (signal?.aborted) throw new RequestAbortedError("Export stream was aborted", signal.reason);
|
|
868
|
-
return result
|
|
1601
|
+
return result;
|
|
869
1602
|
} catch (cause) {
|
|
870
1603
|
this.cancel();
|
|
871
1604
|
if (cause instanceof LexAPIError) throw cause;
|
|
@@ -899,17 +1632,25 @@ var NdjsonReader = class {
|
|
|
899
1632
|
function liftEnvelope(parsed, key) {
|
|
900
1633
|
const inner = parsed[key];
|
|
901
1634
|
if (typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
|
|
902
|
-
return { ...inner,
|
|
1635
|
+
return { ...inner, [key]: inner };
|
|
903
1636
|
}
|
|
904
1637
|
return parsed;
|
|
905
1638
|
}
|
|
1639
|
+
function text(value) {
|
|
1640
|
+
try {
|
|
1641
|
+
return String(value);
|
|
1642
|
+
} catch {
|
|
1643
|
+
return Array.isArray(value) ? "array" : typeof value;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
906
1646
|
function errorLine(parsed) {
|
|
907
1647
|
const keys = Object.keys(parsed);
|
|
908
1648
|
if (keys.length !== 1 || keys[0] !== "_error") return void 0;
|
|
909
1649
|
const value = parsed._error;
|
|
910
|
-
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message:
|
|
1650
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: text(value) };
|
|
911
1651
|
}
|
|
912
1652
|
function parseLine(line) {
|
|
1653
|
+
if (line === INVALID_LINE) return void 0;
|
|
913
1654
|
try {
|
|
914
1655
|
const value = JSON.parse(line);
|
|
915
1656
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
@@ -938,7 +1679,7 @@ var ExportStreamImpl = class {
|
|
|
938
1679
|
}
|
|
939
1680
|
failureReason() {
|
|
940
1681
|
if (this.error !== void 0) {
|
|
941
|
-
return `the server reported an error mid-stream (${
|
|
1682
|
+
return `the server reported an error mid-stream (${text(this.error.code ?? "UNKNOWN")}: ${text(this.error.message ?? "")})`;
|
|
942
1683
|
}
|
|
943
1684
|
return "its _done trailer says complete: false";
|
|
944
1685
|
}
|
|
@@ -949,7 +1690,7 @@ var ExportStreamImpl = class {
|
|
|
949
1690
|
if (typeof this.done?.truncated === "boolean") return this.done.truncated;
|
|
950
1691
|
if (this.headers.truncated !== void 0) return this.headers.truncated;
|
|
951
1692
|
if (typeof this.meta?.truncated === "boolean") return this.meta.truncated;
|
|
952
|
-
return
|
|
1693
|
+
return false;
|
|
953
1694
|
}
|
|
954
1695
|
constructor(lines, headers) {
|
|
955
1696
|
this.lines = lines;
|
|
@@ -961,21 +1702,20 @@ var ExportStreamImpl = class {
|
|
|
961
1702
|
}
|
|
962
1703
|
/** Read the leading line so `meta` is available before iteration starts. */
|
|
963
1704
|
async init() {
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
parsed = parseLine(first);
|
|
969
|
-
if (parsed !== void 0) {
|
|
970
|
-
const error = errorLine(parsed);
|
|
971
|
-
if (error === void 0) break;
|
|
972
|
-
this.error = error;
|
|
973
|
-
continue;
|
|
974
|
-
}
|
|
1705
|
+
const first = await this.lines.nextLine();
|
|
1706
|
+
if (first === void 0) return;
|
|
1707
|
+
const parsed = parseLine(first);
|
|
1708
|
+
if (parsed === void 0) {
|
|
975
1709
|
this.invalidLines++;
|
|
1710
|
+
return;
|
|
1711
|
+
}
|
|
1712
|
+
const error = errorLine(parsed);
|
|
1713
|
+
if (error !== void 0) {
|
|
1714
|
+
this.error = error;
|
|
1715
|
+
return;
|
|
976
1716
|
}
|
|
977
1717
|
if ("_meta" in parsed) {
|
|
978
|
-
this.meta = liftEnvelope(parsed, "_meta");
|
|
1718
|
+
if (!this.lines.firstLineBlank) this.meta = liftEnvelope(parsed, "_meta");
|
|
979
1719
|
} else if ("_done" in parsed) {
|
|
980
1720
|
this.done = liftEnvelope(parsed, "_done");
|
|
981
1721
|
this.lines.cancel();
|
|
@@ -1018,12 +1758,12 @@ var ExportStreamImpl = class {
|
|
|
1018
1758
|
this.invalidLines++;
|
|
1019
1759
|
continue;
|
|
1020
1760
|
}
|
|
1761
|
+
if ("_meta" in parsed) continue;
|
|
1021
1762
|
if ("_done" in parsed) {
|
|
1022
1763
|
this.done = liftEnvelope(parsed, "_done");
|
|
1023
1764
|
if (!this.complete) throw this.incomplete(this.failureReason());
|
|
1024
1765
|
return;
|
|
1025
1766
|
}
|
|
1026
|
-
if ("_meta" in parsed) continue;
|
|
1027
1767
|
const error = errorLine(parsed);
|
|
1028
1768
|
if (error !== void 0) {
|
|
1029
1769
|
this.error = error;
|
|
@@ -1037,6 +1777,10 @@ var ExportStreamImpl = class {
|
|
|
1037
1777
|
}
|
|
1038
1778
|
}
|
|
1039
1779
|
};
|
|
1780
|
+
function truncatedFlag(value) {
|
|
1781
|
+
const flag = value === null ? void 0 : trimSpaces(value);
|
|
1782
|
+
return flag === "1" ? true : flag === "0" ? false : void 0;
|
|
1783
|
+
}
|
|
1040
1784
|
async function createExportStream(response, options = {}) {
|
|
1041
1785
|
if (response.body === null) {
|
|
1042
1786
|
throw new LexAPIError("INTERNAL", "Export response had no body stream", response.status);
|
|
@@ -1045,14 +1789,63 @@ async function createExportStream(response, options = {}) {
|
|
|
1045
1789
|
const streamingHeader = response.headers.get("x-export-streaming");
|
|
1046
1790
|
const truncatedHeader = response.headers.get("x-export-truncated");
|
|
1047
1791
|
const stream = new ExportStreamImpl(new NdjsonReader(response.body, options), {
|
|
1048
|
-
total:
|
|
1049
|
-
streaming:
|
|
1050
|
-
truncated: truncatedHeader
|
|
1792
|
+
total: parseHeaderInteger(totalHeader),
|
|
1793
|
+
streaming: parseHeaderInteger(streamingHeader),
|
|
1794
|
+
truncated: truncatedFlag(truncatedHeader)
|
|
1051
1795
|
});
|
|
1052
1796
|
await stream.init();
|
|
1053
1797
|
return stream;
|
|
1054
1798
|
}
|
|
1055
1799
|
|
|
1800
|
+
// src/paging.ts
|
|
1801
|
+
function count(value) {
|
|
1802
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
1803
|
+
}
|
|
1804
|
+
var REPEATS_BEFORE_THROW = 3;
|
|
1805
|
+
function startingPosition(offset, limit, defaultLimit) {
|
|
1806
|
+
if (offset !== void 0 && count(offset) === void 0) {
|
|
1807
|
+
throw new RangeError(`offset must be a non-negative integer, got ${String(offset)}`);
|
|
1808
|
+
}
|
|
1809
|
+
if (limit !== void 0 && !(count(limit) !== void 0 && limit > 0)) {
|
|
1810
|
+
throw new RangeError(`limit must be a positive integer, got ${String(limit)}`);
|
|
1811
|
+
}
|
|
1812
|
+
return { offset: offset ?? 0, limit: limit ?? defaultLimit };
|
|
1813
|
+
}
|
|
1814
|
+
function stalled(reason, page) {
|
|
1815
|
+
return new InvalidResponseError(`Pagination stopped: ${reason}`, 200, page);
|
|
1816
|
+
}
|
|
1817
|
+
var Token = class {
|
|
1818
|
+
constructor(text2) {
|
|
1819
|
+
this.text = text2;
|
|
1820
|
+
}
|
|
1821
|
+
};
|
|
1822
|
+
function compactForm(value) {
|
|
1823
|
+
let out = "";
|
|
1824
|
+
const stack = [value];
|
|
1825
|
+
while (stack.length > 0) {
|
|
1826
|
+
const item = stack.pop();
|
|
1827
|
+
if (item instanceof Token) out += item.text;
|
|
1828
|
+
else if (typeof item === "string") out += JSON.stringify(item);
|
|
1829
|
+
else if (Array.isArray(item)) {
|
|
1830
|
+
out += "[";
|
|
1831
|
+
stack.push(new Token("]"));
|
|
1832
|
+
for (let i = item.length - 1; i >= 0; i--) {
|
|
1833
|
+
stack.push(item[i]);
|
|
1834
|
+
if (i > 0) stack.push(new Token(","));
|
|
1835
|
+
}
|
|
1836
|
+
} else if (typeof item === "object" && item !== null) {
|
|
1837
|
+
out += "{";
|
|
1838
|
+
stack.push(new Token("}"));
|
|
1839
|
+
const keys = Object.keys(item).sort();
|
|
1840
|
+
for (let i = keys.length - 1; i >= 0; i--) {
|
|
1841
|
+
stack.push(item[keys[i]]);
|
|
1842
|
+
stack.push(new Token(`${i > 0 ? "," : ""}${JSON.stringify(keys[i])}:`));
|
|
1843
|
+
}
|
|
1844
|
+
} else out += String(item);
|
|
1845
|
+
}
|
|
1846
|
+
return out;
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1056
1849
|
// src/webhooks.ts
|
|
1057
1850
|
var WebhooksAPI = class {
|
|
1058
1851
|
http;
|
|
@@ -1072,6 +1865,7 @@ var WebhooksAPI = class {
|
|
|
1072
1865
|
return this.call({
|
|
1073
1866
|
method: "GET",
|
|
1074
1867
|
path: "/webhooks",
|
|
1868
|
+
shape: { lists: ["webhooks"] },
|
|
1075
1869
|
free: true,
|
|
1076
1870
|
timeoutMs: options?.timeoutMs,
|
|
1077
1871
|
signal: options?.signal
|
|
@@ -1132,6 +1926,7 @@ var WebhooksAPI = class {
|
|
|
1132
1926
|
return this.call({
|
|
1133
1927
|
method: "DELETE",
|
|
1134
1928
|
path: `/webhooks/${encodeURIComponent(id)}`,
|
|
1929
|
+
shape: { allowEmpty: true },
|
|
1135
1930
|
timeoutMs: options?.timeoutMs,
|
|
1136
1931
|
signal: options?.signal
|
|
1137
1932
|
});
|
|
@@ -1146,6 +1941,7 @@ var WebhooksAPI = class {
|
|
|
1146
1941
|
return this.call({
|
|
1147
1942
|
method: "POST",
|
|
1148
1943
|
path: `/webhooks/${encodeURIComponent(id)}/test`,
|
|
1944
|
+
shape: { successFalseOk: true },
|
|
1149
1945
|
timeoutMs: options?.timeoutMs,
|
|
1150
1946
|
signal: options?.signal
|
|
1151
1947
|
});
|
|
@@ -1155,6 +1951,7 @@ var WebhooksAPI = class {
|
|
|
1155
1951
|
return this.call({
|
|
1156
1952
|
method: "GET",
|
|
1157
1953
|
path: `/webhooks/${encodeURIComponent(id)}/deliveries`,
|
|
1954
|
+
shape: { lists: ["deliveries"] },
|
|
1158
1955
|
free: true,
|
|
1159
1956
|
query: { limit: params.limit, offset: params.offset },
|
|
1160
1957
|
timeoutMs: options?.timeoutMs,
|
|
@@ -1166,7 +1963,13 @@ var WebhooksAPI = class {
|
|
|
1166
1963
|
* 50), starting at `offset`, newest first (SDK contract §1.4). Each
|
|
1167
1964
|
* delivery is yielded at most once (deduplicated on `id`): a delivery
|
|
1168
1965
|
* created during the walk shifts later pages by one. Stops on an empty page
|
|
1169
|
-
* or when the offset reaches `total`.
|
|
1966
|
+
* or when the offset reaches `total`. Without a usable `total`, three pages
|
|
1967
|
+
* in a row that bring no unseen `id` throw `InvalidResponseError` (a page
|
|
1968
|
+
* with a usable `total` ends a run). When a walk throws, the pages already
|
|
1969
|
+
* yielded stay valid; the page that showed the stall is not yielded and is
|
|
1970
|
+
* on the error's `body`. A starting `offset` or `limit` that is not a
|
|
1971
|
+
* non-negative (positive) integer is a `RangeError` before any request.
|
|
1972
|
+
* Pages are free (0 credits).
|
|
1170
1973
|
*
|
|
1171
1974
|
* ```ts
|
|
1172
1975
|
* for await (const page of client.webhooks.paginateDeliveries(id)) {
|
|
@@ -1175,21 +1978,36 @@ var WebhooksAPI = class {
|
|
|
1175
1978
|
* ```
|
|
1176
1979
|
*/
|
|
1177
1980
|
async *paginateDeliveries(id, params = {}, options) {
|
|
1178
|
-
const
|
|
1179
|
-
|
|
1981
|
+
const start = startingPosition(params.offset, params.limit, 50);
|
|
1982
|
+
const limit = start.limit;
|
|
1983
|
+
let offset = start.offset;
|
|
1180
1984
|
const seen = /* @__PURE__ */ new Set();
|
|
1985
|
+
let repeats = 0;
|
|
1181
1986
|
for (; ; ) {
|
|
1182
1987
|
const page = await this.deliveries(id, { limit, offset }, options);
|
|
1183
|
-
const
|
|
1184
|
-
const
|
|
1988
|
+
const listed = page.deliveries;
|
|
1989
|
+
const deliveries = Array.isArray(listed) ? listed : [];
|
|
1990
|
+
const rows = deliveries.length;
|
|
1991
|
+
let readable = 0;
|
|
1992
|
+
let unseen = 0;
|
|
1993
|
+
const fresh = deliveries.filter((d) => {
|
|
1185
1994
|
if (typeof d.id !== "string") return true;
|
|
1995
|
+
readable++;
|
|
1186
1996
|
if (seen.has(d.id)) return false;
|
|
1187
1997
|
seen.add(d.id);
|
|
1998
|
+
unseen++;
|
|
1188
1999
|
return true;
|
|
1189
2000
|
});
|
|
2001
|
+
const total = count(page.total);
|
|
2002
|
+
if (total === void 0) {
|
|
2003
|
+
repeats = readable > 0 && unseen === 0 ? repeats + 1 : 0;
|
|
2004
|
+
if (repeats >= REPEATS_BEFORE_THROW) throw stalled("the server repeated the same deliveries", page);
|
|
2005
|
+
} else {
|
|
2006
|
+
repeats = 0;
|
|
2007
|
+
}
|
|
1190
2008
|
yield { ...page, deliveries: fresh };
|
|
1191
|
-
offset +=
|
|
1192
|
-
if (
|
|
2009
|
+
offset += rows;
|
|
2010
|
+
if (rows === 0 || total !== void 0 && offset >= total) return;
|
|
1193
2011
|
}
|
|
1194
2012
|
}
|
|
1195
2013
|
};
|
|
@@ -1204,11 +2022,16 @@ var LexAPI = class {
|
|
|
1204
2022
|
if (!apiKey) {
|
|
1205
2023
|
throw new Error("apiKey is required (or set LEXAPI_API_KEY)");
|
|
1206
2024
|
}
|
|
2025
|
+
if (options.fetch === void 0 && typeof globalThis.fetch !== "function") {
|
|
2026
|
+
throw new Error("This runtime has no global fetch; pass one with the `fetch` option");
|
|
2027
|
+
}
|
|
1207
2028
|
this.http = new HttpClient({
|
|
1208
2029
|
apiKey,
|
|
1209
2030
|
baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
|
|
1210
2031
|
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
1211
|
-
|
|
2032
|
+
// Looked up per call and invoked on the global object, which Cloudflare
|
|
2033
|
+
// Workers and browsers require.
|
|
2034
|
+
fetchFn: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
|
|
1212
2035
|
retry: {
|
|
1213
2036
|
maxRetries: options.retry?.maxRetries ?? 3,
|
|
1214
2037
|
baseDelayMs: options.retry?.baseDelayMs ?? 500,
|
|
@@ -1266,6 +2089,7 @@ var LexAPI = class {
|
|
|
1266
2089
|
return this.call({
|
|
1267
2090
|
method: "POST",
|
|
1268
2091
|
path: "/search",
|
|
2092
|
+
shape: { lists: ["results"], required: ["results"] },
|
|
1269
2093
|
body: request,
|
|
1270
2094
|
idempotent: true,
|
|
1271
2095
|
timeoutMs: options?.timeoutMs,
|
|
@@ -1290,6 +2114,7 @@ var LexAPI = class {
|
|
|
1290
2114
|
return this.call({
|
|
1291
2115
|
method: "POST",
|
|
1292
2116
|
path: "/documentContent",
|
|
2117
|
+
shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
|
|
1293
2118
|
body: request,
|
|
1294
2119
|
idempotent: true,
|
|
1295
2120
|
timeoutMs: options?.timeoutMs,
|
|
@@ -1311,6 +2136,7 @@ var LexAPI = class {
|
|
|
1311
2136
|
return this.call({
|
|
1312
2137
|
method: "POST",
|
|
1313
2138
|
path: "/documentContent/batch",
|
|
2139
|
+
shape: { lists: ["documents", "errors"] },
|
|
1314
2140
|
body: request,
|
|
1315
2141
|
idempotent: true,
|
|
1316
2142
|
timeoutMs: options?.timeoutMs,
|
|
@@ -1333,6 +2159,7 @@ var LexAPI = class {
|
|
|
1333
2159
|
return this.call({
|
|
1334
2160
|
method: "GET",
|
|
1335
2161
|
path: "/documents/recent",
|
|
2162
|
+
shape: { lists: ["results"] },
|
|
1336
2163
|
query: {
|
|
1337
2164
|
days: params.days,
|
|
1338
2165
|
documentType: params.documentType,
|
|
@@ -1355,6 +2182,7 @@ var LexAPI = class {
|
|
|
1355
2182
|
return this.call({
|
|
1356
2183
|
method: "POST",
|
|
1357
2184
|
path: "/documents/url",
|
|
2185
|
+
shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
|
|
1358
2186
|
body: request,
|
|
1359
2187
|
idempotent: true,
|
|
1360
2188
|
timeoutMs: options?.timeoutMs,
|
|
@@ -1393,18 +2221,20 @@ var LexAPI = class {
|
|
|
1393
2221
|
});
|
|
1394
2222
|
}
|
|
1395
2223
|
// ── Point-in-time versions ────────────────────────────────────────
|
|
1396
|
-
// Versions are LexAPI
|
|
1397
|
-
// fetches), NOT
|
|
1398
|
-
// ingestion. For the
|
|
1399
|
-
// semanticLegislationSearch({ asOf }).
|
|
2224
|
+
// Versions are LexAPI's fetch snapshots (content-hash changes between
|
|
2225
|
+
// fetches), NOT the law in force on a date; history begins at first
|
|
2226
|
+
// ingestion. For the version of an EU act for a date, use legislationAsOf.
|
|
1400
2227
|
/**
|
|
1401
2228
|
* `GET /documents/{celex}/versions` — version history, newest first,
|
|
1402
|
-
* current version included and flagged.
|
|
2229
|
+
* current version included and flagged. These are LexAPI's fetch
|
|
2230
|
+
* snapshots, not the law in force on a date; for the version of an EU act
|
|
2231
|
+
* for a date use `legislationAsOf`. 1 credit.
|
|
1403
2232
|
*/
|
|
1404
2233
|
async listDocumentVersions(celex, params = {}, options) {
|
|
1405
2234
|
return this.call({
|
|
1406
2235
|
method: "GET",
|
|
1407
2236
|
path: `/documents/${encodeURIComponent(celex)}/versions`,
|
|
2237
|
+
shape: { lists: ["versions"] },
|
|
1408
2238
|
query: { language: params.language },
|
|
1409
2239
|
timeoutMs: options?.timeoutMs,
|
|
1410
2240
|
signal: options?.signal
|
|
@@ -1413,27 +2243,41 @@ var LexAPI = class {
|
|
|
1413
2243
|
/**
|
|
1414
2244
|
* `GET /documents/{celex}/versions/{version}` — one immutable snapshot
|
|
1415
2245
|
* including `parsedContent`. `corpusVersion` mirrors the
|
|
1416
|
-
* `X-Corpus-Version` response header.
|
|
2246
|
+
* `X-Corpus-Version` response header. This is one of LexAPI's fetch
|
|
2247
|
+
* snapshots, not the law in force on a date; for the version of an EU act
|
|
2248
|
+
* for a date use `legislationAsOf`. 1 credit.
|
|
1417
2249
|
*/
|
|
1418
2250
|
async getDocumentVersion(celex, version, params = {}, options) {
|
|
1419
2251
|
return this.call({
|
|
1420
2252
|
method: "GET",
|
|
1421
2253
|
path: `/documents/${encodeURIComponent(celex)}/versions/${version}`,
|
|
2254
|
+
shape: { fields: [{ path: "document", kind: "object" }] },
|
|
1422
2255
|
query: { language: params.language },
|
|
1423
2256
|
timeoutMs: options?.timeoutMs,
|
|
1424
2257
|
signal: options?.signal
|
|
1425
2258
|
}, { corpusVersion: true });
|
|
1426
2259
|
}
|
|
1427
2260
|
/**
|
|
1428
|
-
* `GET /documents/{celex}/at/{date}` — the snapshot LexAPI
|
|
1429
|
-
*
|
|
1430
|
-
*
|
|
1431
|
-
*
|
|
2261
|
+
* `GET /documents/{celex}/at/{date}` — the snapshot LexAPI held as current
|
|
2262
|
+
* at the end of `date` (`YYYY-MM-DD`, UTC), from its own fetch history
|
|
2263
|
+
* (`kind: "observation_snapshot"`). This is not the law in force on that
|
|
2264
|
+
* date: for the version of an EU act for a date use `legislationAsOf`
|
|
2265
|
+
* (`inForceLookup` points to it). The snapshot was the current one from
|
|
2266
|
+
* `document.observedFrom` until `document.observedUntil` (`null` for the
|
|
2267
|
+
* current version). A future date returns the current version with
|
|
2268
|
+
* `dateInFuture: true`.
|
|
2269
|
+
*
|
|
2270
|
+
* A date before the document entered the corpus rejects with
|
|
2271
|
+
* `NotFoundError` where `beforeTracking` is `true` (`trackedSince`); a date
|
|
2272
|
+
* next to a version stored before API 2.28.0 whose start LexAPI has no
|
|
2273
|
+
* record of rejects with `boundaryUnknown` `true` and `candidates`
|
|
2274
|
+
* (refunded). 1 credit.
|
|
1432
2275
|
*/
|
|
1433
2276
|
async getDocumentAtDate(celex, date, params = {}, options) {
|
|
1434
2277
|
return this.call({
|
|
1435
2278
|
method: "GET",
|
|
1436
2279
|
path: `/documents/${encodeURIComponent(celex)}/at/${encodeURIComponent(date)}`,
|
|
2280
|
+
shape: { fields: [{ path: "document", kind: "object" }] },
|
|
1437
2281
|
query: { language: params.language },
|
|
1438
2282
|
timeoutMs: options?.timeoutMs,
|
|
1439
2283
|
signal: options?.signal
|
|
@@ -1450,6 +2294,7 @@ var LexAPI = class {
|
|
|
1450
2294
|
return this.call({
|
|
1451
2295
|
method: "POST",
|
|
1452
2296
|
path: "/citations/extract",
|
|
2297
|
+
shape: { lists: ["citations"] },
|
|
1453
2298
|
body: { celexNumber },
|
|
1454
2299
|
timeoutMs: options?.timeoutMs,
|
|
1455
2300
|
signal: options?.signal
|
|
@@ -1459,12 +2304,25 @@ var LexAPI = class {
|
|
|
1459
2304
|
* `GET /citations/cites/{celexNumber}` — documents this one cites
|
|
1460
2305
|
* (outbound edges), grouped by target. The document must first have been
|
|
1461
2306
|
* crawled via `extractCitations` to appear here. 1 credit.
|
|
2307
|
+
*
|
|
2308
|
+
* `celexNumber` may be a national document id (e.g. `AT-NOR-10001597`);
|
|
2309
|
+
* `params.includeNational` also pulls in national neighbours of live
|
|
2310
|
+
* jurisdictions — BUSINESS, SCALE and ENTERPRISE only (`403
|
|
2311
|
+
* TierForbiddenError` below that, refunded in full). A national id whose
|
|
2312
|
+
* jurisdiction is not live is `404 NotFoundError`.
|
|
2313
|
+
*
|
|
2314
|
+
* Filters (API 2.11.0): `citationType`, `provenance`, `jurisdictions` and
|
|
2315
|
+
* `resolution` each take one value or a list (sent comma-separated). On a
|
|
2316
|
+
* national id, `unresolved: true` also returns the references the
|
|
2317
|
+
* document records that could not be turned into an edge
|
|
2318
|
+
* (`unresolved` / `unresolvedTruncated`), at no extra cost.
|
|
1462
2319
|
*/
|
|
1463
2320
|
async getCites(celexNumber, params = {}, options) {
|
|
1464
2321
|
return this.call({
|
|
1465
2322
|
method: "GET",
|
|
1466
2323
|
path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
|
|
1467
|
-
|
|
2324
|
+
shape: { lists: ["cites", "unresolved"] },
|
|
2325
|
+
query: { ...edgeQuery(params), unresolved: params.unresolved },
|
|
1468
2326
|
timeoutMs: options?.timeoutMs,
|
|
1469
2327
|
signal: options?.signal
|
|
1470
2328
|
});
|
|
@@ -1474,11 +2332,16 @@ var LexAPI = class {
|
|
|
1474
2332
|
* (inbound edges), grouped by source. 1 credit. For legislation, inbound
|
|
1475
2333
|
* amendment / corrigendum / repeal edges are refreshed from Cellar when
|
|
1476
2334
|
* older than 7 days (waits ≤ ~2.5 s) — see `relationSync`.
|
|
2335
|
+
*
|
|
2336
|
+
* `celexNumber` may be a national document id; `params.includeNational`
|
|
2337
|
+
* also pulls in national neighbours of live jurisdictions — BUSINESS+
|
|
2338
|
+
* only (`403 TierForbiddenError` below that). Filters as on `getCites`.
|
|
1477
2339
|
*/
|
|
1478
2340
|
async getCitedBy(celexNumber, params = {}, options) {
|
|
1479
2341
|
return this.call({
|
|
1480
2342
|
method: "GET",
|
|
1481
2343
|
path: `/citations/cited-by/${encodeURIComponent(celexNumber)}`,
|
|
2344
|
+
shape: { lists: ["citedBy"] },
|
|
1482
2345
|
query: edgeQuery(params),
|
|
1483
2346
|
timeoutMs: options?.timeoutMs,
|
|
1484
2347
|
signal: options?.signal
|
|
@@ -1492,26 +2355,39 @@ var LexAPI = class {
|
|
|
1492
2355
|
* missed. A target's edges can straddle a page boundary, so the same
|
|
1493
2356
|
* `celexNumber` may appear in two consecutive pages — merge by
|
|
1494
2357
|
* `celexNumber` if you need one group per document.
|
|
2358
|
+
* The walk also ends once the offset reaches `totalEdges`, when that is a
|
|
2359
|
+
* non-negative integer. It throws `InvalidResponseError` when a page echoes
|
|
2360
|
+
* an `offset` other than the one requested, or, when the answers carry
|
|
2361
|
+
* neither `totalEdges` nor `offset`, after three pages in a row that each
|
|
2362
|
+
* repeat the one before (comparing the list only; a page with either
|
|
2363
|
+
* signal ends a run, and its list is still the one the next page is
|
|
2364
|
+
* compared with). When a walk throws, the pages already yielded stay
|
|
2365
|
+
* valid; the page that showed the stall is not yielded and is on the
|
|
2366
|
+
* error's `body`. A starting `offset` or `limit` that is not a non-negative
|
|
2367
|
+
* (positive) integer is a `RangeError` before any request. A group whose
|
|
2368
|
+
* `citationCount` is 0 but whose edge list is not empty counts its list.
|
|
1495
2369
|
*/
|
|
1496
2370
|
async *paginateCites(celexNumber, params = {}, options) {
|
|
1497
|
-
yield* paginateEdges(
|
|
1498
|
-
(p) => this.getCites(celexNumber, p, options),
|
|
1499
|
-
(page) => page.cites.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
|
|
1500
|
-
params
|
|
1501
|
-
);
|
|
2371
|
+
yield* paginateEdges((p) => this.getCites(celexNumber, p, options), (page) => page.cites, params);
|
|
1502
2372
|
}
|
|
1503
2373
|
/**
|
|
1504
2374
|
* Walk every page of `getCitedBy` (offset in edge rows) until a short or
|
|
1505
2375
|
* empty page (SDK contract §1.4). Each page is a billed call (1 credit);
|
|
1506
2376
|
* edges may repeat or be missed if extractions happen during the walk. A source's edges can straddle a page boundary, so the same
|
|
1507
2377
|
* `celexNumber` may appear in two consecutive pages.
|
|
2378
|
+
* The walk also ends once the offset reaches `totalEdges`, when that is a
|
|
2379
|
+
* non-negative integer. It throws `InvalidResponseError` when a page echoes
|
|
2380
|
+
* an `offset` other than the one requested, or, when the answers carry
|
|
2381
|
+
* neither `totalEdges` nor `offset`, after three pages in a row that each
|
|
2382
|
+
* repeat the one before (comparing the list only; a page with either
|
|
2383
|
+
* signal ends a run, and its list is still the one the next page is
|
|
2384
|
+
* compared with). When a walk throws, the pages already yielded stay
|
|
2385
|
+
* valid; the page that showed the stall is not yielded and is on the
|
|
2386
|
+
* error's `body`. A starting `offset` or `limit` that is not a non-negative
|
|
2387
|
+
* (positive) integer is a `RangeError` before any request.
|
|
1508
2388
|
*/
|
|
1509
2389
|
async *paginateCitedBy(celexNumber, params = {}, options) {
|
|
1510
|
-
yield* paginateEdges(
|
|
1511
|
-
(p) => this.getCitedBy(celexNumber, p, options),
|
|
1512
|
-
(page) => page.citedBy.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
|
|
1513
|
-
params
|
|
1514
|
-
);
|
|
2390
|
+
yield* paginateEdges((p) => this.getCitedBy(celexNumber, p, options), (page) => page.citedBy, params);
|
|
1515
2391
|
}
|
|
1516
2392
|
/**
|
|
1517
2393
|
* `GET /citations/network/{celexNumber}` — inbound and outbound
|
|
@@ -1520,16 +2396,23 @@ var LexAPI = class {
|
|
|
1520
2396
|
* If the server-side wall-clock budget expires the endpoint still
|
|
1521
2397
|
* returns 200 with `partial: true`, an EMPTY `network`, and `null`
|
|
1522
2398
|
* paging totals — check `partial` before treating the network as empty.
|
|
2399
|
+
*
|
|
2400
|
+
* `celexNumber` may be a national document id; `params.includeNational`
|
|
2401
|
+
* also pulls in national neighbours of live jurisdictions — BUSINESS+
|
|
2402
|
+
* only (`403 TierForbiddenError` below that). See `getCites`.
|
|
1523
2403
|
*/
|
|
1524
2404
|
async getCitationNetwork(celexNumber, params = {}, options) {
|
|
1525
2405
|
return this.call({
|
|
1526
2406
|
method: "GET",
|
|
1527
2407
|
path: `/citations/network/${encodeURIComponent(celexNumber)}`,
|
|
2408
|
+
shape: { lists: ["network.cites", "network.citedBy", "unresolved"] },
|
|
1528
2409
|
query: {
|
|
1529
|
-
|
|
2410
|
+
...filterQuery(params),
|
|
1530
2411
|
limit: params.limit,
|
|
1531
2412
|
offset: params.offset,
|
|
1532
|
-
language: params.language
|
|
2413
|
+
language: params.language,
|
|
2414
|
+
includeNational: params.includeNational,
|
|
2415
|
+
unresolved: params.unresolved
|
|
1533
2416
|
},
|
|
1534
2417
|
timeoutMs: options?.timeoutMs,
|
|
1535
2418
|
signal: options?.signal
|
|
@@ -1540,12 +2423,22 @@ var LexAPI = class {
|
|
|
1540
2423
|
* outbound edges). 20 credits. `found: false` is a graceful HTTP 200,
|
|
1541
2424
|
* not an error. Default `maxDepth` 3 (max 8); the visited set is bounded
|
|
1542
2425
|
* to 5000 nodes.
|
|
2426
|
+
*
|
|
2427
|
+
* `from`/`to` may be national document ids; `params.includeNational` also
|
|
2428
|
+
* follows national documents of live jurisdictions along the way —
|
|
2429
|
+
* BUSINESS+ only (`403 TierForbiddenError` below that). See `getCites`.
|
|
1543
2430
|
*/
|
|
1544
2431
|
async getCitationPath(from, to, params = {}, options) {
|
|
1545
2432
|
return this.call({
|
|
1546
2433
|
method: "GET",
|
|
1547
2434
|
path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
|
|
1548
|
-
|
|
2435
|
+
shape: { lists: ["path"] },
|
|
2436
|
+
query: {
|
|
2437
|
+
...filterQuery(params),
|
|
2438
|
+
maxDepth: params.maxDepth,
|
|
2439
|
+
language: params.language,
|
|
2440
|
+
includeNational: params.includeNational
|
|
2441
|
+
},
|
|
1549
2442
|
timeoutMs: options?.timeoutMs,
|
|
1550
2443
|
signal: options?.signal
|
|
1551
2444
|
});
|
|
@@ -1555,21 +2448,281 @@ var LexAPI = class {
|
|
|
1555
2448
|
* neighbours (documents sharing the most outbound citation targets with
|
|
1556
2449
|
* the seed). 20 credits. Returns a graceful empty list with `message`
|
|
1557
2450
|
* when the seed has no outbound citations to couple on.
|
|
2451
|
+
*
|
|
2452
|
+
* `celexNumber` may be a national document id; `params.includeNational`
|
|
2453
|
+
* also considers national documents of live jurisdictions — BUSINESS+
|
|
2454
|
+
* only (`403 TierForbiddenError` below that). See `getCites`.
|
|
1558
2455
|
*/
|
|
1559
2456
|
async getRelatedDocuments(celexNumber, params = {}, options) {
|
|
1560
2457
|
return this.call({
|
|
1561
2458
|
method: "GET",
|
|
1562
2459
|
path: `/citations/related/${encodeURIComponent(celexNumber)}`,
|
|
1563
|
-
|
|
2460
|
+
shape: { lists: ["related"] },
|
|
2461
|
+
query: {
|
|
2462
|
+
...filterQuery(params),
|
|
2463
|
+
limit: params.limit,
|
|
2464
|
+
language: params.language,
|
|
2465
|
+
includeNational: params.includeNational
|
|
2466
|
+
},
|
|
1564
2467
|
timeoutMs: options?.timeoutMs,
|
|
1565
2468
|
signal: options?.signal
|
|
1566
2469
|
});
|
|
1567
2470
|
}
|
|
1568
|
-
|
|
1569
|
-
|
|
2471
|
+
async getCitationStats(params, options) {
|
|
2472
|
+
let effectiveParams;
|
|
2473
|
+
let effectiveOptions;
|
|
2474
|
+
if (isLegacyCitationStatsCallOptions(params)) {
|
|
2475
|
+
effectiveOptions = params;
|
|
2476
|
+
} else {
|
|
2477
|
+
effectiveParams = params;
|
|
2478
|
+
effectiveOptions = options;
|
|
2479
|
+
}
|
|
1570
2480
|
return this.call({
|
|
1571
2481
|
method: "GET",
|
|
1572
2482
|
path: "/citations/stats",
|
|
2483
|
+
shape: { lists: ["stats.mostCited", "stats.mostCiting"] },
|
|
2484
|
+
query: { includeNational: effectiveParams?.includeNational },
|
|
2485
|
+
timeoutMs: effectiveOptions?.timeoutMs,
|
|
2486
|
+
signal: effectiveOptions?.signal
|
|
2487
|
+
});
|
|
2488
|
+
}
|
|
2489
|
+
/**
|
|
2490
|
+
* `GET /citations/transposition/{celexNumber}` — the measures the member
|
|
2491
|
+
* states notified to the Commission for an EU act (CELEX sector 3),
|
|
2492
|
+
* grouped by country, from the Publications Office's Cellar records of the
|
|
2493
|
+
* notifications (API 2.11.0). **A notification is not a finding that the
|
|
2494
|
+
* measure transposes the act, or transposes it completely** — `note` says
|
|
2495
|
+
* so on every answer. 5 credits, every plan; a 5xx is refunded.
|
|
2496
|
+
*
|
|
2497
|
+
* On BUSINESS, SCALE and ENTERPRISE, for live jurisdictions, the answer
|
|
2498
|
+
* also says which measures LexAPI holds (`id`, `resolved`, `resolution`,
|
|
2499
|
+
* `resolutionBasis`, `counts.resolved`, `source.lanes`) and adds the
|
|
2500
|
+
* documents whose national source records that they transpose or
|
|
2501
|
+
* implement the act (`provenance: "source"`); `resolvedOnly: true` keeps
|
|
2502
|
+
* only the held ones. Below BUSINESS, for a jurisdiction that is not live,
|
|
2503
|
+
* and while the national-source terms are not accepted (`termsRequired:
|
|
2504
|
+
* true` — never a 403) those fields are `null`.
|
|
2505
|
+
*
|
|
2506
|
+
* A CELEX that is not an EU act (sector 3) is `404 NotFoundError`.
|
|
2507
|
+
*/
|
|
2508
|
+
async getTransposition(celexNumber, params = {}, options) {
|
|
2509
|
+
return this.call({
|
|
2510
|
+
method: "GET",
|
|
2511
|
+
path: `/citations/transposition/${encodeURIComponent(celexNumber)}`,
|
|
2512
|
+
shape: { lists: ["jurisdictions"] },
|
|
2513
|
+
query: {
|
|
2514
|
+
jurisdictions: listParam(params.jurisdictions),
|
|
2515
|
+
resolvedOnly: params.resolvedOnly,
|
|
2516
|
+
language: params.language
|
|
2517
|
+
},
|
|
2518
|
+
timeoutMs: options?.timeoutMs,
|
|
2519
|
+
signal: options?.signal
|
|
2520
|
+
});
|
|
2521
|
+
}
|
|
2522
|
+
/**
|
|
2523
|
+
* `GET /citations/counterparts/{id}` — a national document's counterparts
|
|
2524
|
+
* in the other live jurisdictions, through the EU acts it transposes or
|
|
2525
|
+
* implements (API 2.11.0). Each `via[]` entry is one EU act, with the
|
|
2526
|
+
* other jurisdictions' measures for it ranked `1` (the national source
|
|
2527
|
+
* records the relation), `2` (a notified measure LexAPI holds) or `3` (a
|
|
2528
|
+
* notified Cellar record LexAPI does not hold, `id: null`). An EU act
|
|
2529
|
+
* CELEX as `id` lists its own measures the same way.
|
|
2530
|
+
*
|
|
2531
|
+
* **20 credits; BUSINESS, SCALE and ENTERPRISE only** (`403
|
|
2532
|
+
* TierForbiddenError` below that, refunded). A lookup past its 20-second
|
|
2533
|
+
* server-side budget throws `TimeoutError` (503, `err.partial === true`),
|
|
2534
|
+
* refunded. The SDK does not retry it (the same lookup would hit the same
|
|
2535
|
+
* budget); retry yourself, or narrow with `jurisdictions`.
|
|
2536
|
+
*/
|
|
2537
|
+
async getCounterparts(id, params = {}, options) {
|
|
2538
|
+
return this.call({
|
|
2539
|
+
method: "GET",
|
|
2540
|
+
path: `/citations/counterparts/${encodeURIComponent(id)}`,
|
|
2541
|
+
shape: { lists: ["via"] },
|
|
2542
|
+
query: {
|
|
2543
|
+
jurisdictions: listParam(params.jurisdictions),
|
|
2544
|
+
language: params.language
|
|
2545
|
+
},
|
|
2546
|
+
timeoutMs: options?.timeoutMs,
|
|
2547
|
+
signal: options?.signal
|
|
2548
|
+
});
|
|
2549
|
+
}
|
|
2550
|
+
// ── National law ──────────────────────────────────────────────────
|
|
2551
|
+
// Member-state (and non-EU) legal orders alongside EUR-Lex. BUSINESS and
|
|
2552
|
+
// above get full access; FREE/STARTER/PROFESSIONAL get it within a
|
|
2553
|
+
// monthly allowance of national calls (`X-National-Limit`/
|
|
2554
|
+
// `X-National-Remaining`/`X-National-Reset`, `result.headers.nationalAllowance`;
|
|
2555
|
+
// a used-up allowance is `NationalAllowanceExhaustedError`, 402). An
|
|
2556
|
+
// unlaunched or unknown jurisdiction answers 404 exactly like a path that
|
|
2557
|
+
// doesn't exist — call `getNationalCoverage()` first.
|
|
2558
|
+
/**
|
|
2559
|
+
* `GET /national/coverage` — which jurisdictions are live, what each one
|
|
2560
|
+
* covers (legislation / case law, semantic search, sources with their
|
|
2561
|
+
* attribution), and when each was last synced. Public: no API key or
|
|
2562
|
+
* allowance required, free.
|
|
2563
|
+
*/
|
|
2564
|
+
async getNationalCoverage(options) {
|
|
2565
|
+
return this.call({
|
|
2566
|
+
method: "GET",
|
|
2567
|
+
path: "/national/coverage",
|
|
2568
|
+
shape: { lists: ["jurisdictions"] },
|
|
2569
|
+
free: true,
|
|
2570
|
+
timeoutMs: options?.timeoutMs,
|
|
2571
|
+
signal: options?.signal
|
|
2572
|
+
});
|
|
2573
|
+
}
|
|
2574
|
+
/**
|
|
2575
|
+
* `GET /{jurisdiction}/documents/{id}` — one national document by its
|
|
2576
|
+
* corpus id (e.g. `"AT-NOR-12345"`), analogous to `getDocument`.
|
|
2577
|
+
*
|
|
2578
|
+
* **Cost: 1 credit** — every national read is a corpus read (there is no
|
|
2579
|
+
* live-fetch fallback), so the 5-credit upfront reservation always
|
|
2580
|
+
* settles to 1 (an unknown id too). Check
|
|
2581
|
+
* `document.textAvailability.available` before reading `content`, and
|
|
2582
|
+
* always show `document.attribution` to the user alongside the text.
|
|
2583
|
+
* The document has one shape for every jurisdiction (API 2.8.0):
|
|
2584
|
+
* `documentKind` (`act` | `decision`), `decision` (court, chamber,
|
|
2585
|
+
* caseNumbers, citedNorms — `null` for acts; see `isNationalDecision`)
|
|
2586
|
+
* and the closed `content` key set.
|
|
2587
|
+
*
|
|
2588
|
+
* A document its source withdrew (a takedown, a pseudonymisation fix)
|
|
2589
|
+
* throws `DocumentWithdrawnError` (410) instead of answering — nothing of
|
|
2590
|
+
* it is served, not even the title; drop any copy you hold.
|
|
2591
|
+
*/
|
|
2592
|
+
async getNationalDocument(jurisdiction, id, params = {}, options) {
|
|
2593
|
+
return this.call({
|
|
2594
|
+
method: "GET",
|
|
2595
|
+
path: `/${jurisdictionSegment(jurisdiction)}/documents/${encodeURIComponent(id)}`,
|
|
2596
|
+
shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
|
|
2597
|
+
query: { language: params.language },
|
|
2598
|
+
timeoutMs: options?.timeoutMs,
|
|
2599
|
+
signal: options?.signal
|
|
2600
|
+
});
|
|
2601
|
+
}
|
|
2602
|
+
/**
|
|
2603
|
+
* `GET /{jurisdiction}/documents` — browse a jurisdiction's corpus by
|
|
2604
|
+
* title (`q`), type, and in-force status. Newest-first by the document's
|
|
2605
|
+
* own date.
|
|
2606
|
+
*
|
|
2607
|
+
* **Cost: 3 credits per call** — flat; pagination does not multiply the
|
|
2608
|
+
* price, unlike `search`. **Paging:** `page` only reaches the first 1,000
|
|
2609
|
+
* rows (a 400 past that); page further with `cursor` (each response's
|
|
2610
|
+
* `nextCursor`), which works at any depth — see
|
|
2611
|
+
* `paginateNationalDocuments` for a ready-made walk. A slow page is a
|
|
2612
|
+
* retry-safe `TimeoutError` (504, refunded); the `total` count is capped
|
|
2613
|
+
* at 10,000 and flagged `totalExact: false` past that or on a slow count.
|
|
2614
|
+
*/
|
|
2615
|
+
async listNationalDocuments(jurisdiction, params = {}, options) {
|
|
2616
|
+
return this.call({
|
|
2617
|
+
method: "GET",
|
|
2618
|
+
path: `/${jurisdictionSegment(jurisdiction)}/documents`,
|
|
2619
|
+
shape: { lists: ["results"] },
|
|
2620
|
+
query: {
|
|
2621
|
+
page: params.page,
|
|
2622
|
+
cursor: params.cursor,
|
|
2623
|
+
limit: params.limit,
|
|
2624
|
+
q: params.q,
|
|
2625
|
+
type: params.documentType,
|
|
2626
|
+
includeRepealed: params.includeRepealed
|
|
2627
|
+
},
|
|
2628
|
+
timeoutMs: options?.timeoutMs,
|
|
2629
|
+
signal: options?.signal
|
|
2630
|
+
});
|
|
2631
|
+
}
|
|
2632
|
+
/**
|
|
2633
|
+
* Walk every page of `listNationalDocuments` via `cursor` (works past the
|
|
2634
|
+
* 1,000-row `page` ceiling, unlike passing `page` yourself). Each page is
|
|
2635
|
+
* a separate billed call. Stops after a page whose `hasMore` is not `true`,
|
|
2636
|
+
* whose `nextCursor` is absent, `null` or empty, or that is empty. A
|
|
2637
|
+
* `nextCursor` the walk already sent, or one that is not a string, throws
|
|
2638
|
+
* `InvalidResponseError`; the pages already yielded stay valid, and the
|
|
2639
|
+
* page that showed the stall is not yielded and is on the error's `body`.
|
|
2640
|
+
* Any `params.page` is ignored and never sent — pass
|
|
2641
|
+
* `params.cursor` only to resume a walk you saved partway through;
|
|
2642
|
+
* `page` together with `cursor` is a 400 ("Use either cursor or page,
|
|
2643
|
+
* not both"), so this strips `page` at runtime, not just in the type
|
|
2644
|
+
* (`Omit` alone only guards TypeScript callers — a JS caller, or one
|
|
2645
|
+
* using `as`, could otherwise still pass it through). A `limit` that is
|
|
2646
|
+
* not a positive integer is a `RangeError` before any request.
|
|
2647
|
+
*/
|
|
2648
|
+
async *paginateNationalDocuments(jurisdiction, params = {}, options) {
|
|
2649
|
+
const { page: _ignoredPage, ...rest } = params;
|
|
2650
|
+
startingPosition(void 0, rest.limit, 1);
|
|
2651
|
+
let cursor = rest.cursor;
|
|
2652
|
+
const sent = /* @__PURE__ */ new Set();
|
|
2653
|
+
for (; ; ) {
|
|
2654
|
+
if (typeof cursor === "string") sent.add(cursor);
|
|
2655
|
+
const page = await this.listNationalDocuments(
|
|
2656
|
+
jurisdiction,
|
|
2657
|
+
cursor !== void 0 ? { ...rest, cursor } : { ...rest },
|
|
2658
|
+
options
|
|
2659
|
+
);
|
|
2660
|
+
const results = page.results;
|
|
2661
|
+
const next = page.nextCursor;
|
|
2662
|
+
const ends = page.hasMore !== true || next === void 0 || next === null || next === "" || !Array.isArray(results) || results.length === 0;
|
|
2663
|
+
if (!ends) {
|
|
2664
|
+
if (typeof next !== "string") throw stalled("the server sent a page cursor that is not a string", page);
|
|
2665
|
+
if (sent.has(next)) throw stalled("the server repeated a page cursor", page);
|
|
2666
|
+
}
|
|
2667
|
+
yield page;
|
|
2668
|
+
if (ends) return;
|
|
2669
|
+
cursor = next;
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
/**
|
|
2673
|
+
* `POST /{jurisdiction}/search/semantic` — embedding-based semantic
|
|
2674
|
+
* search over a jurisdiction's case law. Same request/response shape as
|
|
2675
|
+
* `semanticSearch`, plus `jurisdiction`/`documentId`/`attribution` and
|
|
2676
|
+
* `document` (the matched decision as the listing returns it — the same
|
|
2677
|
+
* fields in every jurisdiction, API 2.8.0) on every hit.
|
|
2678
|
+
*
|
|
2679
|
+
* **Cost: a flat 5 credits** — `hyde` is accepted but never changes the
|
|
2680
|
+
* price or the billing tier here: the national index never rewrites, so
|
|
2681
|
+
* the response reports `hyde: false` (never `true`) when requested.
|
|
2682
|
+
*/
|
|
2683
|
+
async nationalSemanticSearch(jurisdiction, request, options) {
|
|
2684
|
+
return this.call({
|
|
2685
|
+
method: "POST",
|
|
2686
|
+
path: `/${jurisdictionSegment(jurisdiction)}/search/semantic`,
|
|
2687
|
+
shape: { lists: ["results"], required: ["results"] },
|
|
2688
|
+
body: nationalSemanticWireBody(request),
|
|
2689
|
+
idempotent: true,
|
|
2690
|
+
timeoutMs: options?.timeoutMs,
|
|
2691
|
+
signal: options?.signal
|
|
2692
|
+
});
|
|
2693
|
+
}
|
|
2694
|
+
/**
|
|
2695
|
+
* `POST /{jurisdiction}/legislation/semantic` — embedding-based semantic
|
|
2696
|
+
* search over a jurisdiction's legislation; article-level matches. Same
|
|
2697
|
+
* shape as `semanticLegislationSearch`, plus `jurisdiction`/`documentId`/
|
|
2698
|
+
* `attribution` and `document` (the matched act's listing summary) on
|
|
2699
|
+
* every hit; the index fields (`law_title`, `article_ref`, `section`,
|
|
2700
|
+
* `language`, `in_force`, `valid_from`, `valid_to`, `law_type`) are
|
|
2701
|
+
* always present, `null` when the index has nothing (API 2.8.0).
|
|
2702
|
+
*
|
|
2703
|
+
* **`asOf` (API 2.29.0)** labels each hit for a date (`asOfResolved`,
|
|
2704
|
+
* `asOfReason`, `asOfVersion`); the response adds `asOf` and
|
|
2705
|
+
* `asOfSummary`. The search runs over today's texts only. A hit is
|
|
2706
|
+
* resolved only when the publisher's dates, as of LexAPI's last recorded
|
|
2707
|
+
* read of the act (`asOfVersion.checkedAt`), show today's wording already
|
|
2708
|
+
* applied on the date; an unresolved hit keeps today's wording — it is not
|
|
2709
|
+
* established as the text for the date. LexAPI holds such dates for
|
|
2710
|
+
* Austria and Spain.
|
|
2711
|
+
*
|
|
2712
|
+
* `NationalSemanticLegislationOptions` has no `hyde` field, and this SDK
|
|
2713
|
+
* never forwards one on this call even if a caller bypasses the type
|
|
2714
|
+
* system — the server now validates `hyde` as a boolean on this route too
|
|
2715
|
+
* (400 otherwise), so a stray non-boolean value would 400 for nothing.
|
|
2716
|
+
*
|
|
2717
|
+
* **Cost: 5 credits.**
|
|
2718
|
+
*/
|
|
2719
|
+
async nationalLegislationSemanticSearch(jurisdiction, request, options) {
|
|
2720
|
+
return this.call({
|
|
2721
|
+
method: "POST",
|
|
2722
|
+
path: `/${jurisdictionSegment(jurisdiction)}/legislation/semantic`,
|
|
2723
|
+
shape: { lists: ["results"], required: ["results"] },
|
|
2724
|
+
body: nationalSemanticWireBody(request, { allowHyde: false, allowAsOf: true }),
|
|
2725
|
+
idempotent: true,
|
|
1573
2726
|
timeoutMs: options?.timeoutMs,
|
|
1574
2727
|
signal: options?.signal
|
|
1575
2728
|
});
|
|
@@ -1598,7 +2751,8 @@ var LexAPI = class {
|
|
|
1598
2751
|
return this.call({
|
|
1599
2752
|
method: "POST",
|
|
1600
2753
|
path: "/search/semantic",
|
|
1601
|
-
|
|
2754
|
+
shape: { lists: ["results"], required: ["results"] },
|
|
2755
|
+
body: semanticWireBody(request, { legislation: false }),
|
|
1602
2756
|
idempotent: true,
|
|
1603
2757
|
timeoutMs: options?.timeoutMs,
|
|
1604
2758
|
signal: options?.signal
|
|
@@ -1620,6 +2774,11 @@ var LexAPI = class {
|
|
|
1620
2774
|
* cannot be answered keeps its latest text with `asOfResolved: false` and
|
|
1621
2775
|
* an `asOfReason`. The response adds `asOf` and `asOfSummary`.
|
|
1622
2776
|
*
|
|
2777
|
+
* **In force today:** EU hits carry `inForce` (with `notInForceReason`,
|
|
2778
|
+
* `endOfValidity`, `entryIntoForce`) when the act's status is known;
|
|
2779
|
+
* `inForce: true` keeps only hits known to be in force today and reports
|
|
2780
|
+
* what it removed in `inForceFilter`.
|
|
2781
|
+
*
|
|
1623
2782
|
* **Cost:** 5 credits for the search; with `asOf`, each live fetch of a
|
|
1624
2783
|
* version the corpus does not hold reserves 5 and settles by outcome
|
|
1625
2784
|
* (Cellar 4, browser 5, no text 1, failed 0) — at most 3 per request by
|
|
@@ -1630,7 +2789,59 @@ var LexAPI = class {
|
|
|
1630
2789
|
return this.call({
|
|
1631
2790
|
method: "POST",
|
|
1632
2791
|
path: "/legislation/semantic",
|
|
1633
|
-
|
|
2792
|
+
shape: { lists: ["results"], required: ["results"] },
|
|
2793
|
+
body: semanticWireBody(request, { legislation: true }),
|
|
2794
|
+
idempotent: true,
|
|
2795
|
+
timeoutMs: options?.timeoutMs,
|
|
2796
|
+
signal: options?.signal
|
|
2797
|
+
});
|
|
2798
|
+
}
|
|
2799
|
+
/**
|
|
2800
|
+
* `POST /legislation/as-of` — the version of an EU regulation, directive
|
|
2801
|
+
* or decision listed for a date: the newest consolidated version dated on
|
|
2802
|
+
* or before it, or the act as published in the Official Journal when none
|
|
2803
|
+
* is. With `provision`, also that article, annex or recital range of the
|
|
2804
|
+
* version. Requires LexAPI API 2.26.0.
|
|
2805
|
+
*
|
|
2806
|
+
* **Unresolved is a normal return, not an error:** when the version or
|
|
2807
|
+
* the text cannot be established the call resolves with
|
|
2808
|
+
* `asOfResolved: false`, an `asOfReason` and no `provision`. Use
|
|
2809
|
+
* `provision.text` only when `asOfResolved` is `true`; `asOfVersion` can
|
|
2810
|
+
* also be present on an unresolved `provision` answer.
|
|
2811
|
+
* An unknown act throws `NotFoundError`; invalid input throws
|
|
2812
|
+
* `InvalidCelexError` / `InvalidParamsError`. An API older than 2.26.0
|
|
2813
|
+
* has no such endpoint and also answers 404 (`NotFoundError`).
|
|
2814
|
+
* `err.unknownEndpoint` is `false` there (the API sends it from 2.27.0):
|
|
2815
|
+
* check `err.message.includes("Unknown API endpoint")`.
|
|
2816
|
+
*
|
|
2817
|
+
* Consolidated versions have no legal force; only the act as published in
|
|
2818
|
+
* the Official Journal (`baseCelex`) is authentic. The answer does not say
|
|
2819
|
+
* whether an individual provision applied on that date, and
|
|
2820
|
+
* `act.inForceToday` is about today, not `asOf`. A retroactive amendment
|
|
2821
|
+
* counts from the date of the amending act.
|
|
2822
|
+
*
|
|
2823
|
+
* **Cost:** 1 credit when no text is fetched; when the provision's text
|
|
2824
|
+
* has to be fetched, 4 (5 when it is fetched live from EUR-Lex) whatever
|
|
2825
|
+
* the answer, and 1 if the fetch fails or finds no text. A fetch reserves
|
|
2826
|
+
* up to 5 credits: a pool holding fewer gets
|
|
2827
|
+
* `asOfReason: "insufficient_credits"`.
|
|
2828
|
+
*/
|
|
2829
|
+
async legislationAsOf(request, options) {
|
|
2830
|
+
const body = { document: request.document, asOf: request.asOf };
|
|
2831
|
+
if (request.provision !== void 0) body["provision"] = request.provision;
|
|
2832
|
+
if (request.language !== void 0) body["language"] = request.language;
|
|
2833
|
+
return this.call({
|
|
2834
|
+
method: "POST",
|
|
2835
|
+
path: "/legislation/as-of",
|
|
2836
|
+
shape: {
|
|
2837
|
+
fields: [
|
|
2838
|
+
{ path: "document", kind: "string" },
|
|
2839
|
+
{ path: "asOfResolved", kind: "boolean" },
|
|
2840
|
+
{ path: "act", kind: "object" },
|
|
2841
|
+
{ path: "provenance", kind: "object" }
|
|
2842
|
+
]
|
|
2843
|
+
},
|
|
2844
|
+
body,
|
|
1634
2845
|
idempotent: true,
|
|
1635
2846
|
timeoutMs: options?.timeoutMs,
|
|
1636
2847
|
signal: options?.signal
|
|
@@ -1695,7 +2906,7 @@ var LexAPI = class {
|
|
|
1695
2906
|
});
|
|
1696
2907
|
}
|
|
1697
2908
|
};
|
|
1698
|
-
function semanticWireBody(request) {
|
|
2909
|
+
function semanticWireBody(request, { legislation }) {
|
|
1699
2910
|
const body = { query: request.query };
|
|
1700
2911
|
if (request.limit !== void 0) body["limit"] = request.limit;
|
|
1701
2912
|
if (request.minScore !== void 0) body["min_score"] = request.minScore;
|
|
@@ -1703,15 +2914,44 @@ function semanticWireBody(request) {
|
|
|
1703
2914
|
if (request.includeText) body["include"] = ["text"];
|
|
1704
2915
|
if (request.filters !== void 0) body["filters"] = request.filters;
|
|
1705
2916
|
if (request.hyde !== void 0) body["hyde"] = request.hyde;
|
|
1706
|
-
if (request.asOf !== void 0) body["asOf"] = request.asOf;
|
|
2917
|
+
if (legislation && request.asOf !== void 0) body["asOf"] = request.asOf;
|
|
2918
|
+
if (legislation && request.inForce !== void 0) body["inForce"] = request.inForce;
|
|
2919
|
+
return body;
|
|
2920
|
+
}
|
|
2921
|
+
function nationalSemanticWireBody(request, { allowHyde = true, allowAsOf = false } = {}) {
|
|
2922
|
+
const body = { query: request.query };
|
|
2923
|
+
if (request.limit !== void 0) body["limit"] = request.limit;
|
|
2924
|
+
if (request.minScore !== void 0) body["min_score"] = request.minScore;
|
|
2925
|
+
if (request.language !== void 0) body["language"] = request.language;
|
|
2926
|
+
if (request.includeText) body["include"] = ["text"];
|
|
2927
|
+
if (request.filters !== void 0) body["filters"] = request.filters;
|
|
2928
|
+
if (allowHyde && request.hyde !== void 0) body["hyde"] = request.hyde;
|
|
2929
|
+
if (allowAsOf && request.asOf !== void 0) body["asOf"] = request.asOf;
|
|
1707
2930
|
return body;
|
|
1708
2931
|
}
|
|
2932
|
+
function jurisdictionSegment(jurisdiction) {
|
|
2933
|
+
return encodeURIComponent(jurisdiction.trim().toLowerCase());
|
|
2934
|
+
}
|
|
2935
|
+
function isLegacyCitationStatsCallOptions(value) {
|
|
2936
|
+
if (!value || typeof value !== "object") return false;
|
|
2937
|
+
if ("includeNational" in value) return false;
|
|
2938
|
+
return "timeoutMs" in value || "signal" in value;
|
|
2939
|
+
}
|
|
2940
|
+
function filterQuery(params) {
|
|
2941
|
+
return {
|
|
2942
|
+
citationType: listParam(params.citationType),
|
|
2943
|
+
provenance: listParam(params.provenance),
|
|
2944
|
+
jurisdictions: listParam(params.jurisdictions),
|
|
2945
|
+
resolution: listParam(params.resolution)
|
|
2946
|
+
};
|
|
2947
|
+
}
|
|
1709
2948
|
function edgeQuery(params) {
|
|
1710
2949
|
return {
|
|
1711
|
-
|
|
2950
|
+
...filterQuery(params),
|
|
1712
2951
|
limit: params.limit,
|
|
1713
2952
|
offset: params.offset,
|
|
1714
|
-
language: params.language
|
|
2953
|
+
language: params.language,
|
|
2954
|
+
includeNational: params.includeNational
|
|
1715
2955
|
};
|
|
1716
2956
|
}
|
|
1717
2957
|
function timestampParam(value) {
|
|
@@ -1721,16 +2961,40 @@ function listParam(value) {
|
|
|
1721
2961
|
if (value === void 0) return void 0;
|
|
1722
2962
|
return typeof value === "string" ? value : value.join(",");
|
|
1723
2963
|
}
|
|
1724
|
-
|
|
1725
|
-
const
|
|
1726
|
-
|
|
2964
|
+
function edgeRows(group) {
|
|
2965
|
+
const listed = Array.isArray(group.citations) ? group.citations.length : 0;
|
|
2966
|
+
const counted = count(group.citationCount);
|
|
2967
|
+
return counted === void 0 || counted === 0 ? listed : counted;
|
|
2968
|
+
}
|
|
2969
|
+
async function* paginateEdges(fetchPage, groupsIn, params) {
|
|
2970
|
+
const start = startingPosition(params.offset, params.limit, 100);
|
|
2971
|
+
const limit = start.limit;
|
|
2972
|
+
let offset = start.offset;
|
|
2973
|
+
let previous;
|
|
2974
|
+
let repeats = 0;
|
|
1727
2975
|
for (; ; ) {
|
|
1728
2976
|
const page = await fetchPage({ ...params, limit, offset });
|
|
2977
|
+
const listed = groupsIn(page);
|
|
2978
|
+
const groups = Array.isArray(listed) ? listed : [];
|
|
2979
|
+
const echoed = count(page.offset);
|
|
2980
|
+
const totalEdges = count(page.totalEdges);
|
|
2981
|
+
if (echoed !== void 0 && echoed !== offset) throw stalled("the server did not advance", page);
|
|
2982
|
+
if (echoed === void 0 && totalEdges === void 0) {
|
|
2983
|
+
const form = compactForm(groups);
|
|
2984
|
+
repeats = form === previous ? repeats + 1 : 0;
|
|
2985
|
+
previous = form;
|
|
2986
|
+
if (repeats >= REPEATS_BEFORE_THROW) throw stalled("the server repeated the same page", page);
|
|
2987
|
+
} else {
|
|
2988
|
+
repeats = 0;
|
|
2989
|
+
previous = compactForm(groups);
|
|
2990
|
+
}
|
|
1729
2991
|
yield page;
|
|
1730
|
-
const
|
|
1731
|
-
const
|
|
2992
|
+
const echoedLimit = count(page.limit);
|
|
2993
|
+
const pageLimit = echoedLimit !== void 0 && echoedLimit > 0 ? echoedLimit : limit;
|
|
2994
|
+
const rows = groups.reduce((n, g) => n + edgeRows(g), 0);
|
|
1732
2995
|
offset += rows;
|
|
1733
2996
|
if (rows === 0 || rows < pageLimit) return;
|
|
2997
|
+
if (totalEdges !== void 0 && offset >= totalEdges) return;
|
|
1734
2998
|
}
|
|
1735
2999
|
}
|
|
1736
3000
|
function withHeaders(data, response, corpusVersion) {
|
|
@@ -1745,11 +3009,20 @@ function withHeaders(data, response, corpusVersion) {
|
|
|
1745
3009
|
}
|
|
1746
3010
|
|
|
1747
3011
|
// src/credits.ts
|
|
3012
|
+
function figure(value) {
|
|
3013
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
3014
|
+
}
|
|
3015
|
+
function resetsAt(fromCredits, fromUsage) {
|
|
3016
|
+
if (typeof fromCredits === "string") return fromCredits;
|
|
3017
|
+
if (typeof fromUsage === "string") return fromUsage;
|
|
3018
|
+
return (fromCredits === null || fromCredits === void 0) && fromUsage === null ? null : void 0;
|
|
3019
|
+
}
|
|
1748
3020
|
function getCreditUsage(response) {
|
|
3021
|
+
if (typeof response !== "object" || response === null) response = {};
|
|
1749
3022
|
return {
|
|
1750
|
-
unitsCharged: response.credits?.operation_weight ?? 0,
|
|
1751
|
-
creditsRemaining: response.credits?.remaining ?? response.usage?.remaining,
|
|
1752
|
-
resetsAt: response.credits?.resetsAt
|
|
3023
|
+
unitsCharged: figure(response.credits?.operation_weight) ?? 0,
|
|
3024
|
+
creditsRemaining: figure(response.credits?.remaining) ?? figure(response.usage?.remaining),
|
|
3025
|
+
resetsAt: resetsAt(response.credits?.resetsAt, response.usage?.resetsAt)
|
|
1753
3026
|
};
|
|
1754
3027
|
}
|
|
1755
3028
|
|
|
@@ -1779,6 +3052,9 @@ function assertSecret(secret) {
|
|
|
1779
3052
|
"Webhook secret is empty \u2014 pass the secret returned when the webhook was created"
|
|
1780
3053
|
);
|
|
1781
3054
|
}
|
|
3055
|
+
if (!isWellFormed(secret)) {
|
|
3056
|
+
throw new WebhookSignatureError("missing_secret", "Webhook secret is not well-formed Unicode (lone surrogate)");
|
|
3057
|
+
}
|
|
1782
3058
|
}
|
|
1783
3059
|
async function getSubtle() {
|
|
1784
3060
|
const globalCrypto = globalThis.crypto;
|
|
@@ -1792,8 +3068,18 @@ async function getSubtle() {
|
|
|
1792
3068
|
if (nodeCrypto.webcrypto?.subtle) return nodeCrypto.webcrypto.subtle;
|
|
1793
3069
|
throw new Error("Web Crypto (crypto.subtle) is not available in this runtime");
|
|
1794
3070
|
}
|
|
3071
|
+
var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
|
3072
|
+
function isWellFormed(text2) {
|
|
3073
|
+
const native = String.prototype.isWellFormed;
|
|
3074
|
+
return typeof native === "function" ? native.call(text2) : !LONE_SURROGATE.test(text2);
|
|
3075
|
+
}
|
|
1795
3076
|
function toBytes(body) {
|
|
1796
|
-
if (typeof body === "string")
|
|
3077
|
+
if (typeof body === "string") {
|
|
3078
|
+
if (!isWellFormed(body)) {
|
|
3079
|
+
throw new WebhookSignatureError("malformed_body", "Webhook body string is not well-formed Unicode (lone surrogate)");
|
|
3080
|
+
}
|
|
3081
|
+
return new TextEncoder().encode(body);
|
|
3082
|
+
}
|
|
1797
3083
|
if (body instanceof Uint8Array) return body;
|
|
1798
3084
|
return new Uint8Array(body);
|
|
1799
3085
|
}
|
|
@@ -1802,6 +3088,37 @@ function toHex(buffer) {
|
|
|
1802
3088
|
for (const byte of new Uint8Array(buffer)) hex += byte.toString(16).padStart(2, "0");
|
|
1803
3089
|
return hex;
|
|
1804
3090
|
}
|
|
3091
|
+
function trimHeader(value) {
|
|
3092
|
+
const space = (code) => code === 32 || code === 9 || code === 13 || code === 10;
|
|
3093
|
+
let start = 0;
|
|
3094
|
+
let end = value.length;
|
|
3095
|
+
while (start < end && space(value.charCodeAt(start))) start++;
|
|
3096
|
+
while (end > start && space(value.charCodeAt(end - 1))) end--;
|
|
3097
|
+
return value.slice(start, end);
|
|
3098
|
+
}
|
|
3099
|
+
var TIMESTAMP = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?(?:Z|([+-])([0-9]{2}):([0-9]{2}))$/;
|
|
3100
|
+
function timestampMicros(value) {
|
|
3101
|
+
if (typeof value !== "string") return void 0;
|
|
3102
|
+
const match = TIMESTAMP.exec(value);
|
|
3103
|
+
if (!match) return void 0;
|
|
3104
|
+
const [y, mo, d, h, mi, sec] = match.slice(1, 7).map(Number);
|
|
3105
|
+
const fraction = match[7];
|
|
3106
|
+
const sign = match[8];
|
|
3107
|
+
const offH = sign === void 0 ? 0 : Number(match[9]);
|
|
3108
|
+
const offM = sign === void 0 ? 0 : Number(match[10]);
|
|
3109
|
+
const leap = y % 4 === 0 && y % 100 !== 0 || y % 400 === 0;
|
|
3110
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1];
|
|
3111
|
+
if (y < 1 || days === void 0 || d < 1 || d > days || h > 23 || mi > 59 || sec > 59 || offH > 23 || offM > 59) return void 0;
|
|
3112
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
3113
|
+
date.setUTCFullYear(y, mo - 1, d);
|
|
3114
|
+
date.setUTCHours(h, mi, sec, 0);
|
|
3115
|
+
const micros2 = fraction === void 0 ? 0 : Number(fraction.slice(0, 6).padEnd(6, "0"));
|
|
3116
|
+
const offset = (sign === "-" ? -1 : 1) * (offH * 60 + offM) * 6e7;
|
|
3117
|
+
return BigInt(date.getTime()) * BigInt(1e3) + BigInt(micros2) - BigInt(offset);
|
|
3118
|
+
}
|
|
3119
|
+
function micros(ms) {
|
|
3120
|
+
return BigInt(Math.round(ms * 1e3));
|
|
3121
|
+
}
|
|
1805
3122
|
function timingSafeEqual(a, b) {
|
|
1806
3123
|
if (a.length !== b.length) return false;
|
|
1807
3124
|
let diff = 0;
|
|
@@ -1821,31 +3138,49 @@ async function computeSignature(rawBody, secret) {
|
|
|
1821
3138
|
return toHex(await subtle.sign("HMAC", key, toBytes(rawBody)));
|
|
1822
3139
|
}
|
|
1823
3140
|
async function verifySignature(rawBody, signature, secret) {
|
|
1824
|
-
const candidate = typeof signature === "string" ? signature
|
|
3141
|
+
const candidate = typeof signature === "string" ? trimHeader(signature) : "";
|
|
3142
|
+
assertSecret(secret);
|
|
3143
|
+
if (typeof rawBody === "string" && !isWellFormed(rawBody)) return false;
|
|
1825
3144
|
const expected = await computeSignature(rawBody, secret);
|
|
1826
|
-
if (!/^[0-9a-
|
|
1827
|
-
return timingSafeEqual(expected, candidate);
|
|
3145
|
+
if (!/^[0-9a-fA-F]{64}$/.test(candidate)) return false;
|
|
3146
|
+
return timingSafeEqual(expected, candidate.toLowerCase());
|
|
1828
3147
|
}
|
|
1829
3148
|
async function verifyWebhook(rawBody, signature, secret, options = {}) {
|
|
1830
3149
|
assertSecret(secret);
|
|
3150
|
+
const toleranceMs = options.toleranceMs ?? 3e5;
|
|
3151
|
+
if (typeof toleranceMs !== "number" || Number.isNaN(toleranceMs)) {
|
|
3152
|
+
throw new RangeError(`toleranceMs must be a number, got ${String(toleranceMs)}`);
|
|
3153
|
+
}
|
|
1831
3154
|
if (!signature) {
|
|
1832
3155
|
throw new WebhookSignatureError("missing_signature", "Missing X-Webhook-Signature header");
|
|
1833
3156
|
}
|
|
1834
|
-
if (
|
|
3157
|
+
if (typeof rawBody === "string" && !isWellFormed(rawBody)) {
|
|
3158
|
+
throw new WebhookSignatureError("invalid_signature", "Webhook body string is not well-formed Unicode (lone surrogate)");
|
|
3159
|
+
}
|
|
3160
|
+
const bytes = toBytes(rawBody);
|
|
3161
|
+
if (!await verifySignature(bytes, signature, secret)) {
|
|
1835
3162
|
throw new WebhookSignatureError("invalid_signature", "X-Webhook-Signature does not match the body");
|
|
1836
3163
|
}
|
|
1837
3164
|
let payload;
|
|
1838
3165
|
try {
|
|
1839
|
-
const
|
|
1840
|
-
payload = JSON.parse(
|
|
3166
|
+
const text2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes);
|
|
3167
|
+
payload = JSON.parse(text2);
|
|
1841
3168
|
} catch {
|
|
1842
3169
|
throw new WebhookSignatureError("malformed_body", "Webhook body is not valid JSON");
|
|
1843
3170
|
}
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
3171
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
|
|
3172
|
+
throw new WebhookSignatureError("malformed_body", "Webhook body is not a JSON object");
|
|
3173
|
+
}
|
|
3174
|
+
if (toleranceMs !== 0) {
|
|
3175
|
+
const sentAt = timestampMicros(payload.timestamp);
|
|
1847
3176
|
const now = options.now ?? Date.now();
|
|
1848
|
-
|
|
3177
|
+
let fresh = sentAt !== void 0 && toleranceMs > 0;
|
|
3178
|
+
if (fresh && toleranceMs !== Infinity) {
|
|
3179
|
+
const distance = micros(now) - sentAt;
|
|
3180
|
+
const limit = micros(toleranceMs);
|
|
3181
|
+
fresh = distance <= limit && -distance <= limit;
|
|
3182
|
+
}
|
|
3183
|
+
if (!fresh) {
|
|
1849
3184
|
throw new WebhookSignatureError(
|
|
1850
3185
|
"stale_timestamp",
|
|
1851
3186
|
`Webhook timestamp is outside the ${toleranceMs} ms tolerance window`
|
|
@@ -1856,12 +3191,37 @@ async function verifyWebhook(rawBody, signature, secret, options = {}) {
|
|
|
1856
3191
|
}
|
|
1857
3192
|
|
|
1858
3193
|
// src/types.ts
|
|
3194
|
+
var CITATION_TYPES = [
|
|
3195
|
+
"reference",
|
|
3196
|
+
"amendment",
|
|
3197
|
+
"repeal",
|
|
3198
|
+
"corrigendum",
|
|
3199
|
+
"implementation",
|
|
3200
|
+
"legal-basis",
|
|
3201
|
+
"proposal",
|
|
3202
|
+
"transposition"
|
|
3203
|
+
];
|
|
3204
|
+
var CITATION_PROVENANCES = [
|
|
3205
|
+
"notice",
|
|
3206
|
+
"cellar",
|
|
3207
|
+
"notice+cellar",
|
|
3208
|
+
"cellar-nim",
|
|
3209
|
+
"source",
|
|
3210
|
+
"resolver"
|
|
3211
|
+
];
|
|
3212
|
+
var CITATION_RESOLUTIONS = [
|
|
3213
|
+
"id",
|
|
3214
|
+
"key",
|
|
3215
|
+
"abbreviation",
|
|
3216
|
+
"text-pattern"
|
|
3217
|
+
];
|
|
1859
3218
|
var AS_OF_REASONS = [
|
|
1860
3219
|
"not_yet_adopted",
|
|
1861
3220
|
"not_yet_in_force",
|
|
1862
3221
|
"no_longer_in_force",
|
|
1863
3222
|
"in_force_dates_unknown",
|
|
1864
3223
|
"not_in_language",
|
|
3224
|
+
"amendment_not_consolidated",
|
|
1865
3225
|
"text_unavailable",
|
|
1866
3226
|
"article_not_in_version",
|
|
1867
3227
|
"part_not_resolvable",
|
|
@@ -1877,13 +3237,53 @@ var AS_OF_REASONS = [
|
|
|
1877
3237
|
"insufficient_credits",
|
|
1878
3238
|
"credit_check_failed"
|
|
1879
3239
|
];
|
|
3240
|
+
var AS_OF_LOOKUP_REASONS = [
|
|
3241
|
+
"not_yet_adopted",
|
|
3242
|
+
"not_yet_in_force",
|
|
3243
|
+
"no_longer_in_force",
|
|
3244
|
+
"in_force_dates_unknown",
|
|
3245
|
+
"act_type_not_supported",
|
|
3246
|
+
"version_list_unavailable",
|
|
3247
|
+
"version_lookup_cap",
|
|
3248
|
+
"not_in_language",
|
|
3249
|
+
"amendment_not_consolidated",
|
|
3250
|
+
"text_unavailable",
|
|
3251
|
+
"article_not_in_version",
|
|
3252
|
+
"provision_ambiguous",
|
|
3253
|
+
"version_not_parsed",
|
|
3254
|
+
"fetch_budget_exhausted",
|
|
3255
|
+
"fetch_pending",
|
|
3256
|
+
"fetch_capacity",
|
|
3257
|
+
"fetch_failed",
|
|
3258
|
+
"fetch_timeout",
|
|
3259
|
+
"request_deadline",
|
|
3260
|
+
"insufficient_credits",
|
|
3261
|
+
"credit_check_failed"
|
|
3262
|
+
];
|
|
3263
|
+
function isNationalDecision(document2) {
|
|
3264
|
+
return document2.documentKind === "decision" && document2.decision != null;
|
|
3265
|
+
}
|
|
3266
|
+
var NATIONAL_AS_OF_REASONS = [
|
|
3267
|
+
"provision_amended_since",
|
|
3268
|
+
"no_longer_in_force",
|
|
3269
|
+
"provision_dates_unknown",
|
|
3270
|
+
"asof_not_available"
|
|
3271
|
+
];
|
|
3272
|
+
function isNationalAsOfVersion(version) {
|
|
3273
|
+
return typeof version === "object" && version !== null && version.kind === "current_unit";
|
|
3274
|
+
}
|
|
1880
3275
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1881
3276
|
0 && (module.exports = {
|
|
3277
|
+
AS_OF_LOOKUP_REASONS,
|
|
1882
3278
|
AS_OF_REASONS,
|
|
1883
3279
|
AuthenticationError,
|
|
3280
|
+
CITATION_PROVENANCES,
|
|
3281
|
+
CITATION_RESOLUTIONS,
|
|
3282
|
+
CITATION_TYPES,
|
|
1884
3283
|
CreditsExhaustedError,
|
|
1885
3284
|
DEFAULT_BASE_URL,
|
|
1886
3285
|
DEFAULT_TIMEOUT_MS,
|
|
3286
|
+
DocumentWithdrawnError,
|
|
1887
3287
|
IncompleteExportError,
|
|
1888
3288
|
InternalServerError,
|
|
1889
3289
|
InvalidCelexError,
|
|
@@ -1892,8 +3292,14 @@ var AS_OF_REASONS = [
|
|
|
1892
3292
|
InvalidUrlError,
|
|
1893
3293
|
LexAPI,
|
|
1894
3294
|
LexAPIError,
|
|
3295
|
+
NATIONAL_AS_OF_REASONS,
|
|
3296
|
+
NationalAllowanceExhaustedError,
|
|
3297
|
+
NationalSemanticFilterUnreachableError,
|
|
3298
|
+
NationalSemanticNotEnabledError,
|
|
3299
|
+
NationalSemanticUnavailableError,
|
|
1895
3300
|
NetworkError,
|
|
1896
3301
|
NotFoundError,
|
|
3302
|
+
PaymentPastDueError,
|
|
1897
3303
|
RateLimitedError,
|
|
1898
3304
|
RequestAbortedError,
|
|
1899
3305
|
ServiceUnavailableError,
|
|
@@ -1909,6 +3315,8 @@ var AS_OF_REASONS = [
|
|
|
1909
3315
|
computeSignature,
|
|
1910
3316
|
getCreditUsage,
|
|
1911
3317
|
isLexAPIError,
|
|
3318
|
+
isNationalAsOfVersion,
|
|
3319
|
+
isNationalDecision,
|
|
1912
3320
|
normalizeRetryAfterSeconds,
|
|
1913
3321
|
parseResponseHeaders,
|
|
1914
3322
|
verifySignature,
|