@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/dist/index.js CHANGED
@@ -1,3 +1,88 @@
1
+ // src/retryHints.ts
2
+ function normalizeRetryAfterSeconds(value) {
3
+ if (!Number.isFinite(value)) return 0;
4
+ if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
5
+ if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
6
+ return Math.max(0, value);
7
+ }
8
+ function trimSpaces(value) {
9
+ return value.replace(/^[ \t]+|[ \t]+$/g, "");
10
+ }
11
+ function decimalSeconds(raw) {
12
+ if (typeof raw !== "string") return void 0;
13
+ const value = trimSpaces(raw);
14
+ if (!/^[0-9]+(\.[0-9]+)?$/.test(value)) return void 0;
15
+ const seconds = Number(value);
16
+ return Number.isFinite(seconds) ? normalizeRetryAfterSeconds(seconds) : void 0;
17
+ }
18
+ function bodySeconds(value) {
19
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
20
+ return normalizeRetryAfterSeconds(value);
21
+ }
22
+ var DAYS = "Mon|Tue|Wed|Thu|Fri|Sat|Sun";
23
+ var LONG_DAYS = "Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday";
24
+ var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
25
+ var MONTH = MONTHS.join("|");
26
+ var TIME = "([0-9]{2}):([0-9]{2}):([0-9]{2})";
27
+ var ZONE = "(?:GMT|UTC|\\+0000)";
28
+ var IMF_FIXDATE = new RegExp(`^(?:${DAYS}), ([0-9]{2}) (${MONTH}) ([0-9]{4}) ${TIME} ${ZONE}$`, "i");
29
+ var RFC850_DATE = new RegExp(`^(?:${LONG_DAYS}), ([0-9]{2})-(${MONTH})-([0-9]{2}) ${TIME} ${ZONE}$`, "i");
30
+ var ASCTIME_DATE = new RegExp(`^(?:${DAYS}) (${MONTH}) ([0-9]{2}| [0-9]) ${TIME} ([0-9]{4})$`, "i");
31
+ function dateKey(year, month, day, h, m, s) {
32
+ return ((((year * 12 + month) * 31 + day) * 24 + h) * 60 + m) * 60 + s;
33
+ }
34
+ function fullYear(twoDigits, month, day, h, m, s, now) {
35
+ const at = new Date(now);
36
+ const limit = dateKey(at.getUTCFullYear() + 50, at.getUTCMonth(), at.getUTCDate(), at.getUTCHours(), at.getUTCMinutes(), at.getUTCSeconds());
37
+ const monthIndex = MONTHS.indexOf(month.toLowerCase());
38
+ let year = Math.floor(at.getUTCFullYear() / 100) * 100 + 100 + twoDigits;
39
+ while (dateKey(year, monthIndex, day, h, m, s) > limit) year -= 100;
40
+ return year;
41
+ }
42
+ function utcMs(year, month, day, h, m, s) {
43
+ const monthIndex = MONTHS.indexOf(month.toLowerCase());
44
+ if (monthIndex < 0 || h > 23 || m > 59 || s > 59 || day < 1) return void 0;
45
+ const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
46
+ const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][monthIndex];
47
+ if (day > daysInMonth) return void 0;
48
+ const date = /* @__PURE__ */ new Date(0);
49
+ date.setUTCFullYear(year, monthIndex, day);
50
+ date.setUTCHours(h, m, s, 0);
51
+ return date.getTime();
52
+ }
53
+ function httpDateMs(value, now = Date.now()) {
54
+ let match = IMF_FIXDATE.exec(value);
55
+ if (match) {
56
+ const [, day, month, year, h, m, s] = match;
57
+ return utcMs(Number(year), month, Number(day), Number(h), Number(m), Number(s));
58
+ }
59
+ match = RFC850_DATE.exec(value);
60
+ if (match) {
61
+ const [, day, month, year, h, m, s] = match;
62
+ const [d, hh, mm, ss] = [Number(day), Number(h), Number(m), Number(s)];
63
+ return utcMs(fullYear(Number(year), month, d, hh, mm, ss, now), month, d, hh, mm, ss);
64
+ }
65
+ match = ASCTIME_DATE.exec(value);
66
+ if (match) {
67
+ const [, month, day, h, m, s, year] = match;
68
+ return utcMs(Number(year), month, Number(day.trim()), Number(h), Number(m), Number(s));
69
+ }
70
+ return void 0;
71
+ }
72
+ function retryAfterHeaderSeconds(raw) {
73
+ if (typeof raw !== "string") return void 0;
74
+ const value = trimSpaces(raw);
75
+ if (/^[0-9]/.test(value)) return decimalSeconds(value);
76
+ const now = Date.now();
77
+ const date = httpDateMs(value, now);
78
+ return date === void 0 ? void 0 : Math.max(0, Math.round((date - now) / 1e3));
79
+ }
80
+ var MAX_TIMER_MS = 2 ** 31 - 1;
81
+ function timerDelay(ms) {
82
+ if (Number.isNaN(ms)) return 0;
83
+ return Math.min(Math.max(ms, 0), MAX_TIMER_MS);
84
+ }
85
+
1
86
  // src/errors.ts
2
87
  var STATUS_TO_CODE = {
3
88
  400: "INVALID_PARAMS",
@@ -18,6 +103,8 @@ var STATUS_TO_CODE = {
18
103
  524: "TIMEOUT"
19
104
  };
20
105
  var ERROR_KINDS = /* @__PURE__ */ Symbol.for("@lexapi/client.errorKinds");
106
+ var EXCERPTS = /* @__PURE__ */ new WeakMap();
107
+ var INVALID_BODIES = /* @__PURE__ */ new WeakMap();
21
108
  function collectKinds(ctor) {
22
109
  const kinds = [];
23
110
  let current = ctor;
@@ -50,10 +137,11 @@ var LexAPIError = class _LexAPIError extends Error {
50
137
  /** The `error.details` object from the typed envelope, when present. */
51
138
  details;
52
139
  /**
53
- * Seconds to wait before retrying, when the server said so (429).
140
+ * Seconds to wait before retrying, when the server said so (429; also the
141
+ * 503 of an incomplete national semantic search).
54
142
  * Sourced from the `Retry-After` response HEADER first; the JSON
55
- * `retryAfter` body field is only a fallback because it historically
56
- * carried buggy epoch-seconds values (epoch-looking values are
143
+ * `retryAfter` body field is only a fallback because it can carry
144
+ * epoch-seconds values (epoch-looking values are
57
145
  * normalized to a delta).
58
146
  */
59
147
  retryAfter;
@@ -74,64 +162,89 @@ var LexAPIError = class _LexAPIError extends Error {
74
162
  this.retryAfter = retryAfter;
75
163
  this.body = context?.body;
76
164
  this.headers = context?.headers;
165
+ if (context?.bodyExcerpt !== void 0) EXCERPTS.set(this, context.bodyExcerpt);
77
166
  Object.defineProperty(this, ERROR_KINDS, { value: collectKinds(new.target), enumerable: false });
78
167
  }
168
+ /**
169
+ * For a response body that is not JSON, its first 200 characters (code
170
+ * points); `undefined` otherwise. Raw response text; may contain document
171
+ * text; do not show to a model or log by default. Not an own property of
172
+ * the error, so `console.log` (also with `%o`), `util.inspect` with
173
+ * `showHidden` or with `getters`, `JSON.stringify`, spread and
174
+ * `structuredClone` leave it out (`util.inspect` with `showHidden` and
175
+ * `getters` together shows it); never part of `message`. Assigning to it
176
+ * replaces it (`undefined` clears it).
177
+ */
178
+ get bodyExcerpt() {
179
+ return EXCERPTS.get(this);
180
+ }
181
+ set bodyExcerpt(value) {
182
+ if (value === void 0) EXCERPTS.delete(this);
183
+ else EXCERPTS.set(this, value);
184
+ }
79
185
  /**
80
186
  * Build the most specific error subclass for a non-2xx response.
81
187
  * Accepts both the typed envelope and the legacy bare `{error, message}` shape.
188
+ * `code` and `message` are read only when they are non-empty strings.
82
189
  */
83
- static fromResponse(status, body, headerRetryAfter, headers) {
190
+ static fromResponse(status, body, headerRetryAfter, headers, bodyExcerpt) {
84
191
  const statusCode = STATUS_TO_CODE[status];
85
192
  let code = statusCode ?? "INTERNAL";
86
193
  let typedCode = false;
87
194
  let message = `HTTP ${status}`;
88
195
  let details;
89
196
  let retryAfter = headerRetryAfter;
90
- let resetsAt;
197
+ let resetsAt2;
91
198
  if (typeof body === "object" && body !== null) {
92
199
  const record = body;
93
200
  const err = record["error"];
94
- if (typeof err === "object" && err !== null) {
201
+ const topCode = nonEmptyString(record["code"]);
202
+ const topMessage = nonEmptyString(record["message"]);
203
+ if (typeof err === "object" && err !== null && !Array.isArray(err)) {
95
204
  const e = err;
96
- if (typeof e["code"] === "string") {
97
- code = e["code"];
205
+ const typed = nonEmptyString(e["code"]);
206
+ if (typed !== void 0) {
207
+ code = typed;
98
208
  typedCode = true;
99
209
  }
100
- if (typeof e["message"] === "string") message = e["message"];
210
+ message = nonEmptyString(e["message"]) ?? message;
101
211
  details = e["details"];
102
- } else if (typeof err === "string") {
103
- if (typeof record["code"] === "string" && record["code"] !== "") {
104
- code = record["code"];
212
+ } else if (typeof err === "string" && err !== "") {
213
+ if (topCode !== void 0) {
214
+ code = topCode;
105
215
  typedCode = true;
106
216
  }
107
- message = typeof record["message"] === "string" && record["message"] !== err ? `${err}: ${record["message"]}` : err;
217
+ message = topMessage !== void 0 && topMessage !== err ? `${err}: ${topMessage}` : err;
108
218
  details = record["details"];
109
219
  } else {
110
- if (typeof record["code"] === "string" && record["code"] !== "") {
111
- code = record["code"];
220
+ if (topCode !== void 0) {
221
+ code = topCode;
112
222
  typedCode = true;
113
223
  }
114
- if (typeof record["message"] === "string") message = record["message"];
224
+ message = topMessage ?? message;
115
225
  details = record["details"];
116
226
  }
117
- if (retryAfter === void 0 && status === 429) {
118
- const jsonRetryAfter = readNumber(record["retryAfter"]) ?? readNumber(detailsField(details, "retryAfter"));
119
- if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
227
+ if (retryAfter === void 0 && (status === 429 || status === 503 && code === "NATIONAL_SEMANTIC_UNAVAILABLE")) {
228
+ retryAfter = bodyWait(record, details);
120
229
  }
121
- resetsAt = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
230
+ resetsAt2 = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
122
231
  }
123
- const context = { body, ...headers ? { headers } : {} };
232
+ const context = {
233
+ body,
234
+ ...headers ? { headers } : {},
235
+ ...bodyExcerpt !== void 0 ? { bodyExcerpt } : {}
236
+ };
124
237
  if (!typedCode && statusCode === void 0 && status < 500) {
125
238
  return new _LexAPIError(code, message, status, details, retryAfter, context);
126
239
  }
127
- if (code === "QUOTA_EXHAUSTED" || code === "RATE_LIMITED" && isQuota429(body, headers)) {
240
+ if (code === "QUOTA_EXHAUSTED" || status === 429 && hasQuotaCode(body) || status === 429 && code === "RATE_LIMITED" && isQuota429(body, headers)) {
128
241
  return new RateLimitedError(
129
242
  message,
130
243
  status,
131
244
  details,
132
- void 0,
245
+ status === 429 ? void 0 : retryAfter,
133
246
  context,
134
- code === "QUOTA_EXHAUSTED" ? "QUOTA_EXHAUSTED" : "RATE_LIMITED"
247
+ code === "RATE_LIMITED" ? "RATE_LIMITED" : "QUOTA_EXHAUSTED"
135
248
  );
136
249
  }
137
250
  switch (code) {
@@ -147,8 +260,20 @@ var LexAPIError = class _LexAPIError extends Error {
147
260
  return new RateLimitedError(message, status, details, retryAfter, context);
148
261
  case "TIER_FORBIDDEN":
149
262
  return new TierForbiddenError(message, status, details, retryAfter, context);
263
+ case "PAYMENT_PAST_DUE":
264
+ return new PaymentPastDueError(message, status, details, retryAfter, context);
150
265
  case "CREDITS_EXHAUSTED":
151
- return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt, context);
266
+ return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt2, context);
267
+ case "NATIONAL_ALLOWANCE_EXHAUSTED":
268
+ return new NationalAllowanceExhaustedError(message, status, details, retryAfter, context);
269
+ case "NATIONAL_SEMANTIC_NOT_ENABLED":
270
+ return new NationalSemanticNotEnabledError(message, status, details, retryAfter, context);
271
+ case "NATIONAL_SEMANTIC_UNAVAILABLE":
272
+ return new NationalSemanticUnavailableError(message, status, details, retryAfter, context);
273
+ case "NATIONAL_SEMANTIC_FILTER_UNREACHABLE":
274
+ return new NationalSemanticFilterUnreachableError(message, status, details, retryAfter, context);
275
+ case "DOCUMENT_WITHDRAWN":
276
+ return new DocumentWithdrawnError(message, status, details, retryAfter, context);
152
277
  case "UPSTREAM_ERROR":
153
278
  return new UpstreamError(message, status, details, retryAfter, context);
154
279
  case "TIMEOUT":
@@ -170,7 +295,107 @@ var NotFoundError = class extends LexAPIError {
170
295
  super("NOT_FOUND", message, status, details, retryAfter, context);
171
296
  this.name = "NotFoundError";
172
297
  }
298
+ /**
299
+ * `true` when the API (2.27.0 or later) has no such endpoint
300
+ * (`details.reason` is `"unknown_endpoint"`): a mistyped path, a method
301
+ * newer than the API, or a national route for a country that is not
302
+ * available. Always `false` on APIs before 2.27.0; there the message
303
+ * contains "Unknown API endpoint". Read from `details` only, never from
304
+ * the message.
305
+ */
306
+ get unknownEndpoint() {
307
+ return ownField(this.details, "reason") === "unknown_endpoint";
308
+ }
309
+ // The accessors below read `details` only when it is a plain JSON object,
310
+ // and only its own keys; anything else gives each accessor's default.
311
+ /**
312
+ * `details.reason` when it is a string: `unknown_endpoint`, or on
313
+ * `getDocumentAtDate` (API 2.28.0) `before_tracking` / `boundary_unknown`.
314
+ * `undefined` on a 404 without one (e.g. a document not in the corpus).
315
+ */
316
+ get reason() {
317
+ return readString(ownField(this.details, "reason"));
318
+ }
319
+ /**
320
+ * `true` when `getDocumentAtDate` was asked about a date before the
321
+ * document entered the corpus (`details.reason` is `"before_tracking"`);
322
+ * {@link trackedSince} says when that was.
323
+ */
324
+ get beforeTracking() {
325
+ return ownField(this.details, "reason") === "before_tracking";
326
+ }
327
+ /**
328
+ * `true` when LexAPI has no record of when a version stored before API
329
+ * 2.28.0 began, so it cannot say which snapshot it held on the date and
330
+ * does not guess (`details.reason` is `"boundary_unknown"`). Refunded.
331
+ * Read the {@link candidates} with `getDocumentVersion`.
332
+ */
333
+ get boundaryUnknown() {
334
+ return ownField(this.details, "reason") === "boundary_unknown";
335
+ }
336
+ /** `before_tracking` only: when the document entered the corpus (`details.trackedSince`). */
337
+ get trackedSince() {
338
+ return readString(ownField(this.details, "trackedSince"));
339
+ }
340
+ /**
341
+ * On `before_tracking` for an EU act: the request that answers which
342
+ * version is listed for a date (`legislationAsOf`).
343
+ */
344
+ get inForceLookup() {
345
+ const value = ownField(this.details, "inForceLookup");
346
+ if (!isPlainJsonObject(value)) return void 0;
347
+ const lookup2 = {};
348
+ const method = readString(ownField(value, "method"));
349
+ const path = readString(ownField(value, "path"));
350
+ if (method !== void 0) lookup2.method = method;
351
+ if (path !== void 0) lookup2.path = path;
352
+ return lookup2;
353
+ }
354
+ /**
355
+ * `boundary_unknown` only: the versions the date could fall in — the
356
+ * first 10 items of `details.candidates`
357
+ * that are objects with an integer `version` (`fetchedAt` / `observedFrom`
358
+ * are `null` when not strings). `[]` when there are none. For these
359
+ * versions `fetchedAt` can be the last fetch and later than the date.
360
+ */
361
+ get candidates() {
362
+ return readCandidates(this.details).kept;
363
+ }
364
+ /**
365
+ * `boundary_unknown` only: `true` when more versions matched than
366
+ * {@link candidates} lists (`details.candidatesTruncated` is `true`, or
367
+ * more than 10 usable candidates were sent).
368
+ */
369
+ get candidatesTruncated() {
370
+ return ownField(this.details, "candidatesTruncated") === true || readCandidates(this.details).more;
371
+ }
173
372
  };
373
+ var MAX_SNAPSHOT_CANDIDATES = 10;
374
+ function readCandidates(details) {
375
+ const list = ownField(details, "candidates");
376
+ const kept = [];
377
+ if (!Array.isArray(list)) return { kept, more: false };
378
+ for (const item of list) {
379
+ const version = ownField(item, "version");
380
+ if (typeof version !== "number" || !Number.isInteger(version)) continue;
381
+ if (kept.length === MAX_SNAPSHOT_CANDIDATES) return { kept, more: true };
382
+ const fetchedAt = ownField(item, "fetchedAt");
383
+ const observedFrom = ownField(item, "observedFrom");
384
+ kept.push({
385
+ version: version + 0,
386
+ // -0 → 0
387
+ fetchedAt: typeof fetchedAt === "string" ? fetchedAt : null,
388
+ observedFrom: typeof observedFrom === "string" ? observedFrom : null
389
+ });
390
+ }
391
+ return { kept, more: false };
392
+ }
393
+ function isPlainJsonObject(value) {
394
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
395
+ }
396
+ function ownField(value, key) {
397
+ return isPlainJsonObject(value) && Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
398
+ }
174
399
  var InvalidCelexError = class extends LexAPIError {
175
400
  static kind = "InvalidCelexError";
176
401
  constructor(message, status = 400, details, retryAfter, context) {
@@ -187,10 +412,27 @@ var InvalidUrlError = class extends LexAPIError {
187
412
  };
188
413
  var InvalidParamsError = class extends LexAPIError {
189
414
  static kind = "InvalidParamsError";
190
- constructor(message, status = 400, details, retryAfter, context) {
191
- super("INVALID_PARAMS", message, status, details, retryAfter, context);
415
+ constructor(message, status = 400, details, retryAfter, context, code = "INVALID_PARAMS") {
416
+ super(code, message, status, details, retryAfter, context);
192
417
  this.name = "InvalidParamsError";
193
418
  }
419
+ /**
420
+ * The parameter that was refused, when the server names it — e.g. an
421
+ * unknown citation-graph filter value (API 2.11.0). Read from `details`
422
+ * (typed envelope) or the top level of the body (legacy shape).
423
+ */
424
+ get param() {
425
+ return readString(detailsOrBodyField(this.details, this.body, "param"));
426
+ }
427
+ /** The refused value of {@link param}, when the server echoes it. */
428
+ get value() {
429
+ return detailsOrBodyField(this.details, this.body, "value");
430
+ }
431
+ /** The allowed values of {@link param}, when the server lists them (may be empty). */
432
+ get allowed() {
433
+ const value = detailsOrBodyField(this.details, this.body, "allowed");
434
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : void 0;
435
+ }
194
436
  };
195
437
  var AuthenticationError = class extends LexAPIError {
196
438
  static kind = "AuthenticationError";
@@ -212,14 +454,14 @@ var RateLimitedError = class extends LexAPIError {
212
454
  /**
213
455
  * `true` for a legacy-plan quota 429 (daily call quota, or the monthly
214
456
  * semantic quota) rather than the per-minute limiter (SDK contract §1.2):
215
- * `code` is `QUOTA_EXHAUSTED`, or — servers before lex-api #304, which
457
+ * `code` is `QUOTA_EXHAUSTED`, or — servers before API 2.4.0, which
216
458
  * send no code — the body carries `usage.resetsAt` with neither a
217
459
  * `Retry-After` header nor a `retryAfter` body field. It cannot succeed
218
460
  * before `resetsAt`, so the SDK does not retry it and `retryAfter` is
219
461
  * `undefined`.
220
462
  */
221
463
  get quotaExhausted() {
222
- return this.code === "QUOTA_EXHAUSTED" || isQuota429(this.body, this.headers);
464
+ return this.code === "QUOTA_EXHAUSTED" || this.status === 429 && this.code === "RATE_LIMITED" && isQuota429(this.body, this.headers);
223
465
  }
224
466
  /** When a legacy quota resets: the body's `resetsAt`, else `usage.resetsAt`. */
225
467
  get resetsAt() {
@@ -228,19 +470,34 @@ var RateLimitedError = class extends LexAPIError {
228
470
  };
229
471
  var TierForbiddenError = class extends LexAPIError {
230
472
  static kind = "TierForbiddenError";
231
- constructor(message, status = 403, details, retryAfter, context) {
232
- super("TIER_FORBIDDEN", message, status, details, retryAfter, context);
473
+ constructor(message, status = 403, details, retryAfter, context, code = "TIER_FORBIDDEN") {
474
+ super(code, message, status, details, retryAfter, context);
233
475
  this.name = "TierForbiddenError";
234
476
  }
235
477
  };
478
+ var PaymentPastDueError = class extends TierForbiddenError {
479
+ static kind = "PaymentPastDueError";
480
+ constructor(message, status = 403, details, retryAfter, context) {
481
+ super(message, status, details, retryAfter, context, "PAYMENT_PAST_DUE");
482
+ this.name = "PaymentPastDueError";
483
+ }
484
+ /** When API access ended (ISO date-time); `undefined` when the server does not say. */
485
+ get accessEndedAt() {
486
+ return readString(detailsOrBodyField(this.details, this.body, "accessEndedAt"));
487
+ }
488
+ /** Where to pay the open invoice (absolute URL of the dashboard's billing page). */
489
+ get billingUrl() {
490
+ return readString(detailsOrBodyField(this.details, this.body, "billingUrl"));
491
+ }
492
+ };
236
493
  var CreditsExhaustedError = class extends LexAPIError {
237
494
  static kind = "CreditsExhaustedError";
238
495
  /** When the monthly credit allowance resets (ISO date-time), when the server said so. */
239
496
  resetsAt;
240
- constructor(message, status = 402, details, retryAfter, resetsAt, context) {
497
+ constructor(message, status = 402, details, retryAfter, resetsAt2, context) {
241
498
  super("CREDITS_EXHAUSTED", message, status, details, retryAfter, context);
242
499
  this.name = "CreditsExhaustedError";
243
- this.resetsAt = resetsAt;
500
+ this.resetsAt = resetsAt2;
244
501
  }
245
502
  /** The refused operation's credit weight (`details.weight`). */
246
503
  get weight() {
@@ -255,6 +512,33 @@ var CreditsExhaustedError = class extends LexAPIError {
255
512
  return readString(this.details?.operation);
256
513
  }
257
514
  };
515
+ var NationalAllowanceExhaustedError = class extends LexAPIError {
516
+ static kind = "NationalAllowanceExhaustedError";
517
+ constructor(message, status = 402, details, retryAfter, context) {
518
+ super("NATIONAL_ALLOWANCE_EXHAUSTED", message, status, details, retryAfter, context);
519
+ this.name = "NationalAllowanceExhaustedError";
520
+ }
521
+ /** The jurisdiction code of the refused call (`details.jurisdiction`). */
522
+ get jurisdiction() {
523
+ return readString(this.details?.jurisdiction);
524
+ }
525
+ /** The tier's monthly allowance of national calls (`details.limit`). */
526
+ get limit() {
527
+ return readNumber(this.details?.limit);
528
+ }
529
+ /** Always `0` (`details.remaining`). */
530
+ get remaining() {
531
+ return readNumber(this.details?.remaining);
532
+ }
533
+ /** When the allowance resets (`details.resetsAt`, ISO date-time). */
534
+ get resetsAt() {
535
+ return readString(this.details?.resetsAt);
536
+ }
537
+ /** `/pricing` (`details.upgradeUrl`). */
538
+ get upgradeUrl() {
539
+ return readString(this.details?.upgradeUrl);
540
+ }
541
+ };
258
542
  var UpstreamError = class extends LexAPIError {
259
543
  static kind = "UpstreamError";
260
544
  constructor(message, status = 502, details, retryAfter, context) {
@@ -268,14 +552,92 @@ var TimeoutError = class extends LexAPIError {
268
552
  super(status === 0 ? "REQUEST_TIMEOUT" : "TIMEOUT", message, status, details, retryAfter, context);
269
553
  this.name = "TimeoutError";
270
554
  }
555
+ /** `true` when the server answered a budget timeout with `partial: true` (nothing else was returned). */
556
+ get partial() {
557
+ const value = bodyField(this.body, "partial");
558
+ return typeof value === "boolean" ? value : void 0;
559
+ }
560
+ /** The server-side budget that expired, in ms, when the body reports it. */
561
+ get serverTimeoutMs() {
562
+ return readNumber(bodyField(this.body, "timeoutMs"));
563
+ }
271
564
  };
272
565
  var ServiceUnavailableError = class extends LexAPIError {
273
566
  static kind = "ServiceUnavailableError";
274
- constructor(message, status = 503, details, retryAfter, context) {
275
- super("SERVICE_UNAVAILABLE", message, status, details, retryAfter, context);
567
+ constructor(message, status = 503, details, retryAfter, context, code = "SERVICE_UNAVAILABLE") {
568
+ super(code, message, status, details, retryAfter, context);
276
569
  this.name = "ServiceUnavailableError";
277
570
  }
278
571
  };
572
+ var NationalSemanticNotEnabledError = class extends LexAPIError {
573
+ static kind = "NationalSemanticNotEnabledError";
574
+ constructor(message, status = 409, details, retryAfter, context) {
575
+ super("NATIONAL_SEMANTIC_NOT_ENABLED", message, status, details, retryAfter, context);
576
+ this.name = "NationalSemanticNotEnabledError";
577
+ }
578
+ /** ISO 3166-1 alpha-2 jurisdiction code (top-level `jurisdiction` on the raw body). */
579
+ get jurisdiction() {
580
+ return readString(bodyField(this.body, "jurisdiction"));
581
+ }
582
+ };
583
+ var NationalSemanticUnavailableError = class extends ServiceUnavailableError {
584
+ static kind = "NationalSemanticUnavailableError";
585
+ constructor(message, status = 503, details, retryAfter, context) {
586
+ super(message, status, details, retryAfter, context, "NATIONAL_SEMANTIC_UNAVAILABLE");
587
+ this.name = "NationalSemanticUnavailableError";
588
+ }
589
+ get jurisdiction() {
590
+ return readString(bodyField(this.body, "jurisdiction"));
591
+ }
592
+ /**
593
+ * `"SEARCH_INCOMPLETE"` when the index could not complete this search for a
594
+ * temporary reason and there was nothing left to return (an empty answer
595
+ * would not have meant "no matches"). `retryAfter` is then the wait the
596
+ * server asked for — absent once the same search has repeatedly come back
597
+ * incomplete (try again later, or rephrase or narrow it). `undefined` on
598
+ * the plain "index unavailable" 503.
599
+ */
600
+ get partialReason() {
601
+ return readString(detailsOrBodyField(this.details, this.body, "partialReason"));
602
+ }
603
+ };
604
+ var NationalSemanticFilterUnreachableError = class extends InvalidParamsError {
605
+ static kind = "NationalSemanticFilterUnreachableError";
606
+ constructor(message, status = 422, details, retryAfter, context) {
607
+ super(message, status, details, retryAfter, context, "NATIONAL_SEMANTIC_FILTER_UNREACHABLE");
608
+ this.name = "NationalSemanticFilterUnreachableError";
609
+ }
610
+ get jurisdiction() {
611
+ return readString(bodyField(this.body, "jurisdiction"));
612
+ }
613
+ /** `"SEARCH_INCOMPLETE"`. */
614
+ get partialReason() {
615
+ return readString(detailsOrBodyField(this.details, this.body, "partialReason"));
616
+ }
617
+ };
618
+ var DocumentWithdrawnError = class extends LexAPIError {
619
+ static kind = "DocumentWithdrawnError";
620
+ constructor(message, status = 410, details, retryAfter, context) {
621
+ super("DOCUMENT_WITHDRAWN", message, status, details, retryAfter, context);
622
+ this.name = "DocumentWithdrawnError";
623
+ }
624
+ field(key) {
625
+ const fromDetails = detailsField(this.details, key);
626
+ return fromDetails !== void 0 ? fromDetails : bodyField(this.body, key);
627
+ }
628
+ /** The withdrawn document's id (e.g. `AT-NOR-10001597`). */
629
+ get id() {
630
+ return readString(this.field("id"));
631
+ }
632
+ /** Upper-case jurisdiction code. */
633
+ get jurisdiction() {
634
+ return readString(this.field("jurisdiction"));
635
+ }
636
+ /** ISO date-time the source withdrew the document; `undefined` when unknown. */
637
+ get withdrawnAt() {
638
+ return readString(this.field("withdrawnAt"));
639
+ }
640
+ };
279
641
  var InternalServerError = class extends LexAPIError {
280
642
  static kind = "InternalServerError";
281
643
  constructor(message, status = 500, details, retryAfter, context) {
@@ -303,14 +665,25 @@ var RequestAbortedError = class extends LexAPIError {
303
665
  };
304
666
  var InvalidResponseError = class extends LexAPIError {
305
667
  static kind = "InvalidResponseError";
306
- constructor(message, status, rawText, context) {
307
- super("INVALID_RESPONSE", message, status, void 0, void 0, {
308
- ...context,
309
- body: rawText === void 0 ? void 0 : rawText.slice(0, 500)
310
- });
668
+ constructor(message, status, body, context) {
669
+ super("INVALID_RESPONSE", message, status, void 0, void 0, context);
670
+ delete this.body;
671
+ if (body !== void 0) INVALID_BODIES.set(this, body);
311
672
  this.name = "InvalidResponseError";
312
673
  }
313
674
  };
675
+ Object.defineProperty(InvalidResponseError.prototype, "body", {
676
+ get() {
677
+ return INVALID_BODIES.get(this);
678
+ },
679
+ // Assigning replaces the stored value (`undefined` clears it), as on 0.4.0.
680
+ set(value) {
681
+ if (value === void 0) INVALID_BODIES.delete(this);
682
+ else INVALID_BODIES.set(this, value);
683
+ },
684
+ enumerable: false,
685
+ configurable: true
686
+ });
314
687
  var IncompleteExportError = class extends LexAPIError {
315
688
  static kind = "IncompleteExportError";
316
689
  /** Rows yielded before the stream ended. */
@@ -328,15 +701,19 @@ var IncompleteExportError = class extends LexAPIError {
328
701
  function isLexAPIError(value, errorClass) {
329
702
  return value instanceof (errorClass ?? LexAPIError);
330
703
  }
331
- function normalizeRetryAfterSeconds(value) {
332
- if (!Number.isFinite(value)) return 0;
333
- if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
334
- if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
335
- return Math.max(0, value);
336
- }
337
704
  function readNumber(value) {
338
705
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
339
706
  }
707
+ function bodyDetails(body) {
708
+ const err = detailsField(body, "error");
709
+ return typeof err === "object" && err !== null && !Array.isArray(err) ? detailsField(err, "details") : detailsField(body, "details");
710
+ }
711
+ function bodyWait(body, details) {
712
+ return bodySeconds(detailsField(body, "retryAfter")) ?? bodySeconds(detailsField(details, "retryAfter"));
713
+ }
714
+ function nonEmptyString(value) {
715
+ return typeof value === "string" && value !== "" ? value : void 0;
716
+ }
340
717
  function readString(value) {
341
718
  return typeof value === "string" ? value : void 0;
342
719
  }
@@ -346,12 +723,19 @@ function detailsField(details, key) {
346
723
  }
347
724
  return void 0;
348
725
  }
726
+ function hasQuotaCode(body) {
727
+ return detailsField(body, "code") === "QUOTA_EXHAUSTED" || detailsField(bodyField(body, "error"), "code") === "QUOTA_EXHAUSTED";
728
+ }
349
729
  function isQuota429(body, headers) {
350
- if (detailsField(body, "code") === "QUOTA_EXHAUSTED") return true;
351
- const resetsAt = detailsField(detailsField(body, "usage"), "resetsAt");
352
- if (typeof resetsAt !== "string") return false;
353
- if (headers?.retryAfter !== void 0 && headers.retryAfter.trim() !== "") return false;
354
- return detailsField(body, "retryAfter") === void 0;
730
+ if (hasQuotaCode(body)) return true;
731
+ const resetsAt2 = detailsField(detailsField(body, "usage"), "resetsAt");
732
+ if (typeof resetsAt2 !== "string") return false;
733
+ if (retryAfterHeaderSeconds(headers?.retryAfter) !== void 0) return false;
734
+ return bodyWait(body, bodyDetails(body)) === void 0;
735
+ }
736
+ function detailsOrBodyField(details, body, key) {
737
+ const fromDetails = detailsField(details, key);
738
+ return fromDetails !== void 0 ? fromDetails : bodyField(body, key);
355
739
  }
356
740
  function bodyField(body, key) {
357
741
  return detailsField(body, key);
@@ -365,11 +749,15 @@ function str(headers, name) {
365
749
  const value = headers.get(name);
366
750
  return value === null ? void 0 : value;
367
751
  }
752
+ function parseHeaderInteger(value) {
753
+ if (typeof value !== "string") return void 0;
754
+ const text2 = value.replace(/^[ \t]+|[ \t]+$/g, "");
755
+ if (!/^[0-9]+$/.test(text2)) return void 0;
756
+ const parsed = Number(text2);
757
+ return Number.isSafeInteger(parsed) ? parsed : void 0;
758
+ }
368
759
  function int(headers, name) {
369
- const value = headers.get(name);
370
- if (value === null) return void 0;
371
- const parsed = Number.parseInt(value, 10);
372
- return Number.isNaN(parsed) ? void 0 : parsed;
760
+ return parseHeaderInteger(headers.get(name));
373
761
  }
374
762
  function compact(obj) {
375
763
  const out = {};
@@ -414,17 +802,23 @@ function parseResponseHeaders(source) {
414
802
  remaining: int(h, "ratelimit-remaining"),
415
803
  reset: int(h, "ratelimit-reset"),
416
804
  policy: str(h, "ratelimit-policy")
805
+ }),
806
+ nationalAllowance: compact({
807
+ limit: int(h, "x-national-limit"),
808
+ remaining: int(h, "x-national-remaining"),
809
+ resetsAt: str(h, "x-national-reset")
417
810
  })
418
811
  };
419
812
  return compact(parsed) ?? {};
420
813
  }
421
814
 
422
815
  // src/version.ts
423
- var VERSION = "0.2.0";
816
+ var VERSION = "0.5.0";
424
817
 
425
818
  // src/http.ts
426
819
  var DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
427
820
  var DEFAULT_TIMEOUT_MS = 95e3;
821
+ var KIND_NAMES = { object: "an object", string: "a string", boolean: "a boolean" };
428
822
  var NEVER_REACHED_CODES = /* @__PURE__ */ new Set([
429
823
  // DNS
430
824
  "ENOTFOUND",
@@ -462,6 +856,33 @@ var CONNECT_SYSCALL_CODES = /* @__PURE__ */ new Set(["ETIMEDOUT"]);
462
856
  var NEVER_REACHED_STATUSES = /* @__PURE__ */ new Set([521, 522, 523]);
463
857
  var ORIGIN_DEPENDENT_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
464
858
  var PROXY_STATUSES = /* @__PURE__ */ new Set([520, 524]);
859
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
860
+ var MAX_REDIRECTS = 5;
861
+ function redirectTarget(location, from) {
862
+ let to;
863
+ try {
864
+ to = new URL(location, from);
865
+ } catch {
866
+ throw new NetworkError("Refused to follow a redirect with an invalid Location header");
867
+ }
868
+ if (to.protocol !== "http:" && to.protocol !== "https:") {
869
+ throw new NetworkError("Refused to follow a redirect to a URL that is not http(s)");
870
+ }
871
+ if (to.username !== "" || to.password !== "") {
872
+ throw new NetworkError(`Refused to follow a redirect to a URL that carries credentials (${to.origin})`);
873
+ }
874
+ const httpsUpgrade = from.protocol === "http:" && to.protocol === "https:" && to.hostname === from.hostname && from.port === "" && to.port === "";
875
+ if (to.origin !== from.origin && !httpsUpgrade) {
876
+ throw new NetworkError(`Refused to follow a redirect to another origin (${to.origin})`);
877
+ }
878
+ return to;
879
+ }
880
+ function discardBody(response) {
881
+ try {
882
+ response.body?.cancel().catch(() => void 0);
883
+ } catch {
884
+ }
885
+ }
465
886
  function isNeverReachedError(error, depth = 0) {
466
887
  if (depth > 6 || typeof error !== "object" || error === null) return false;
467
888
  const { code, syscall, cause, errors } = error;
@@ -507,7 +928,10 @@ var HttpClient = class {
507
928
  [INSPECT]() {
508
929
  return `HttpClient { baseUrl: '${this.opts.baseUrl}', apiKey: '[redacted]' }`;
509
930
  }
510
- /** Perform a request and parse the JSON body (204 / empty body yields `{}`). */
931
+ /**
932
+ * Perform a request and parse the JSON body. A 2xx that is not the
933
+ * documented shape (`options.shape`) throws `InvalidResponseError`.
934
+ */
511
935
  async requestJson(options) {
512
936
  const { data } = await this.requestJsonWithResponse(options);
513
937
  return data;
@@ -518,7 +942,7 @@ var HttpClient = class {
518
942
  */
519
943
  async requestJsonWithResponse(options) {
520
944
  return this.execute(options, async (response, ctx) => ({
521
- data: await readJsonBody(response, ctx.touch),
945
+ data: await readJsonBody(response, options.shape ?? {}, ctx.touch),
522
946
  response
523
947
  }));
524
948
  }
@@ -551,6 +975,7 @@ var HttpClient = class {
551
975
  headers["content-type"] = "application/json";
552
976
  serializedBody = JSON.stringify(body);
553
977
  }
978
+ let incompleteRetried = false;
554
979
  for (let attempt = 0; ; attempt++) {
555
980
  throwIfAborted(signal, method, path);
556
981
  const controller = new AbortController();
@@ -558,10 +983,11 @@ var HttpClient = class {
558
983
  let timer;
559
984
  const touch = () => {
560
985
  if (timer !== void 0) clearTimeout(timer);
986
+ if (timeoutMs === Infinity) return;
561
987
  timer = setTimeout(() => {
562
988
  timedOut = true;
563
989
  controller.abort();
564
- }, timeoutMs);
990
+ }, timerDelay(timeoutMs));
565
991
  };
566
992
  touch();
567
993
  const onAbort = () => controller.abort();
@@ -570,12 +996,7 @@ var HttpClient = class {
570
996
  let response;
571
997
  let retryTransport = false;
572
998
  try {
573
- response = await this.opts.fetchFn(url, {
574
- method,
575
- headers,
576
- ...serializedBody !== void 0 ? { body: serializedBody } : {},
577
- signal: controller.signal
578
- });
999
+ response = await this.fetchWithinOrigin(url, method, headers, serializedBody, controller.signal);
579
1000
  touch();
580
1001
  if (response.ok) {
581
1002
  return await onSuccess(response, { signal: controller.signal, timeoutMs, touch });
@@ -602,7 +1023,9 @@ var HttpClient = class {
602
1023
  await sleep(fullJitterBackoff(attempt, baseDelayMs, maxDelayMs), signal, method, path);
603
1024
  continue;
604
1025
  }
605
- if (attempt < maxRetries && shouldRetryStatus(error, { isGet, free, readOnly: options.idempotent === true && retryReadOnlyPosts })) {
1026
+ const incomplete = error.status === 503 && isSearchIncomplete(error);
1027
+ if (attempt < maxRetries && !(incomplete && incompleteRetried) && shouldRetryStatus(error, { isGet, free, readOnly: options.idempotent === true && retryReadOnlyPosts })) {
1028
+ if (incomplete) incompleteRetried = true;
606
1029
  const waitMs = error.retryAfter !== void 0 ? Math.min(error.retryAfter * 1e3, maxDelayMs) : fullJitterBackoff(attempt, baseDelayMs, maxDelayMs);
607
1030
  await sleep(waitMs, signal, method, path);
608
1031
  continue;
@@ -610,9 +1033,61 @@ var HttpClient = class {
610
1033
  throw error;
611
1034
  }
612
1035
  }
1036
+ /**
1037
+ * `fetch` with redirects followed here rather than by the runtime, which
1038
+ * would repeat every request header to whichever host a redirect names.
1039
+ * Method and body change as `fetch` changes them: a 303, or a 301/302
1040
+ * answer to a POST, continues as a body-less GET; 307/308 repeat the request.
1041
+ * The body of a redirect response is cancelled, so its connection is released.
1042
+ * A response that says it was already redirected (a custom `fetch` that did
1043
+ * not honour `redirect: "manual"`) is refused.
1044
+ */
1045
+ async fetchWithinOrigin(url, method, headers, body, signal) {
1046
+ const fetchFn = this.opts.fetchFn;
1047
+ let target = url;
1048
+ for (let hop = 0; ; hop++) {
1049
+ const response = await fetchFn(target, {
1050
+ method,
1051
+ headers,
1052
+ ...body !== void 0 ? { body } : {},
1053
+ redirect: "manual",
1054
+ signal
1055
+ });
1056
+ if (response.redirected === true) {
1057
+ discardBody(response);
1058
+ throw new NetworkError('The custom fetch followed a redirect itself; it must honour redirect: "manual"');
1059
+ }
1060
+ if (response.type === "opaqueredirect") {
1061
+ throw new NetworkError("The API answered with a redirect, which this runtime does not expose");
1062
+ }
1063
+ const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null;
1064
+ if (location === null) return response;
1065
+ discardBody(response);
1066
+ let from;
1067
+ try {
1068
+ from = new URL(target);
1069
+ } catch {
1070
+ throw new NetworkError("Refused to follow a redirect from a request URL that is not absolute");
1071
+ }
1072
+ const next = redirectTarget(location, from);
1073
+ if (hop >= MAX_REDIRECTS) {
1074
+ throw new NetworkError(`Too many redirects (more than ${MAX_REDIRECTS})`);
1075
+ }
1076
+ if (response.status === 303 && method !== "GET" || (response.status === 301 || response.status === 302) && method === "POST") {
1077
+ method = "GET";
1078
+ body = void 0;
1079
+ headers = { ...headers };
1080
+ delete headers["content-type"];
1081
+ }
1082
+ target = next.href;
1083
+ }
1084
+ }
613
1085
  };
614
1086
  function shouldRetryStatus(error, call) {
615
1087
  const status = error.status;
1088
+ if (error.code === "PAYMENT_PAST_DUE") return false;
1089
+ if (status === 503 && isBudgetTimeout(error.body)) return false;
1090
+ if (status === 503 && isSearchIncomplete(error) && error.retryAfter === void 0) return false;
616
1091
  if (status === 429) return !(error instanceof RateLimitedError && error.quotaExhausted);
617
1092
  if (NEVER_REACHED_STATUSES.has(status)) return true;
618
1093
  if (ORIGIN_DEPENDENT_STATUSES.has(status)) {
@@ -622,34 +1097,140 @@ function shouldRetryStatus(error, call) {
622
1097
  if (PROXY_STATUSES.has(status)) return call.free;
623
1098
  return false;
624
1099
  }
625
- async function readBodyText(response, touch) {
626
- if (response.body === null || touch === void 0) return response.text();
1100
+ function isBudgetTimeout(body) {
1101
+ return typeof body === "object" && body !== null && body["partialReason"] === "TIMEOUT";
1102
+ }
1103
+ function isSearchIncomplete(error) {
1104
+ const field = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v["partialReason"] : void 0;
1105
+ return (field(error.details) ?? field(error.body)) === "SEARCH_INCOMPLETE";
1106
+ }
1107
+ async function readBodyBytes(response, touch) {
1108
+ if (response.body === null || touch === void 0) return new Uint8Array(await response.arrayBuffer());
627
1109
  const reader = response.body.getReader();
628
- const decoder = new TextDecoder();
629
- const parts = [];
1110
+ const chunks = [];
1111
+ let length = 0;
630
1112
  for (; ; ) {
631
1113
  const { done, value } = await reader.read();
632
1114
  if (done) break;
633
1115
  touch();
634
- parts.push(decoder.decode(value, { stream: true }));
1116
+ chunks.push(value);
1117
+ length += value.byteLength;
635
1118
  }
636
- parts.push(decoder.decode());
637
- return parts.join("");
1119
+ const bytes = new Uint8Array(length);
1120
+ let offset = 0;
1121
+ for (const chunk of chunks) {
1122
+ bytes.set(chunk, offset);
1123
+ offset += chunk.byteLength;
1124
+ }
1125
+ return bytes;
638
1126
  }
639
- async function readJsonBody(response, touch) {
640
- if (response.status === 204) return {};
641
- const text = await readBodyText(response, touch);
642
- if (text.trim() === "") return {};
1127
+ var EXCERPT_CHARS = 200;
1128
+ var EXCERPT_BYTES = EXCERPT_CHARS * 4;
1129
+ var NOT_JSON = /* @__PURE__ */ Symbol("not JSON");
1130
+ function parseJsonBytes(bytes) {
643
1131
  try {
644
- return JSON.parse(text);
1132
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
645
1133
  } catch {
646
- throw new InvalidResponseError(
647
- `Expected a JSON body (HTTP ${response.status}, content-type ${response.headers.get("content-type") ?? "none"})`,
648
- response.status,
649
- text,
650
- { headers: parseResponseHeaders(response) }
1134
+ return NOT_JSON;
1135
+ }
1136
+ }
1137
+ function excerptOf(bytes) {
1138
+ if (bytes.byteLength === 0) return void 0;
1139
+ const text2 = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(0, EXCERPT_BYTES));
1140
+ let out = "";
1141
+ let count2 = 0;
1142
+ for (const char of text2) {
1143
+ if (count2++ === EXCERPT_CHARS) break;
1144
+ out += char;
1145
+ }
1146
+ return out;
1147
+ }
1148
+ function mediaTypeOf(response) {
1149
+ const value = response.headers.get("content-type") ?? "";
1150
+ const media = Array.from(value.split(";", 1)[0].replace(/^[ \t]+|[ \t]+$/g, "")).slice(0, 100).join("");
1151
+ return media === "" ? "no content type" : media;
1152
+ }
1153
+ function jsonKind(value) {
1154
+ if (value === null) return "null";
1155
+ if (Array.isArray(value)) return "array";
1156
+ return typeof value;
1157
+ }
1158
+ function isJsonObject(value) {
1159
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1160
+ }
1161
+ var MISSING = /* @__PURE__ */ Symbol("missing");
1162
+ function lookup(body, path) {
1163
+ let value = body;
1164
+ for (const key of path.split(".")) {
1165
+ if (!isJsonObject(value) || !Object.prototype.hasOwnProperty.call(value, key)) return MISSING;
1166
+ value = value[key];
1167
+ }
1168
+ return value;
1169
+ }
1170
+ function shapeProblem(body, shape) {
1171
+ const missing = (path) => `Expected "${path}" in the response; it is missing`;
1172
+ const wrongKind = (path, expected, value) => `Expected "${path}" to be ${KIND_NAMES[expected]}, got ${jsonKind(value)}`;
1173
+ for (const path of shape.required ?? []) {
1174
+ const value = lookup(body, path);
1175
+ if (value === MISSING || value === null) return missing(path);
1176
+ }
1177
+ for (const { path, kind } of shape.fields ?? []) {
1178
+ const value = lookup(body, path);
1179
+ if (value === MISSING || value === null || kind === "string" && value === "") return missing(path);
1180
+ const ok = kind === "object" ? isJsonObject(value) : typeof value === kind;
1181
+ if (!ok) return wrongKind(path, kind, value);
1182
+ }
1183
+ for (const path of shape.optionalObjects ?? []) {
1184
+ const value = lookup(body, path);
1185
+ if (value !== MISSING && value !== null && !isJsonObject(value)) return wrongKind(path, "object", value);
1186
+ }
1187
+ for (const path of shape.lists ?? []) {
1188
+ const value = lookup(body, path);
1189
+ if (value === MISSING || value === null) continue;
1190
+ if (!Array.isArray(value)) return `Expected "${path}" to be a list, got ${jsonKind(value)}`;
1191
+ for (let index = 0; index < value.length; index++) {
1192
+ const item = value[index];
1193
+ if (!isJsonObject(item)) {
1194
+ return `Expected every item of "${path}" to be an object, got ${jsonKind(item)} at index ${index}`;
1195
+ }
1196
+ }
1197
+ }
1198
+ return void 0;
1199
+ }
1200
+ function hasErrorEnvelope(body) {
1201
+ const err = body["error"];
1202
+ return isJsonObject(err) || typeof err === "string" && err !== "";
1203
+ }
1204
+ async function readJsonBody(response, shape, touch) {
1205
+ const status = response.status;
1206
+ const headers = parseResponseHeaders(response);
1207
+ const invalid = (message, body2, bodyExcerpt) => new InvalidResponseError(message, status, body2, { headers, ...bodyExcerpt !== void 0 ? { bodyExcerpt } : {} });
1208
+ if (status === 204) {
1209
+ discardBody(response);
1210
+ if (shape.allowEmpty === true) return {};
1211
+ throw invalid("Expected JSON, got no body");
1212
+ }
1213
+ const bytes = await readBodyBytes(response, touch);
1214
+ if (bytes.byteLength === 0) {
1215
+ if (shape.allowEmpty === true) return {};
1216
+ throw invalid("Expected JSON, got no body");
1217
+ }
1218
+ const body = parseJsonBytes(bytes);
1219
+ if (body === NOT_JSON) {
1220
+ throw invalid(
1221
+ `Expected JSON, got ${mediaTypeOf(response)} that does not parse as JSON (${bytes.byteLength} bytes)`,
1222
+ void 0,
1223
+ excerptOf(bytes)
651
1224
  );
652
1225
  }
1226
+ if (!isJsonObject(body)) throw invalid(`Expected a JSON object, got ${jsonKind(body)}`, body);
1227
+ if (body["success"] === false && shape.successFalseOk !== true) {
1228
+ if (hasErrorEnvelope(body)) throw LexAPIError.fromResponse(status, body, void 0, headers);
1229
+ throw invalid("Response reported success: false without an error", body);
1230
+ }
1231
+ const problem = shapeProblem(body, shape);
1232
+ if (problem !== void 0) throw invalid(problem, body);
1233
+ return body;
653
1234
  }
654
1235
  function throwIfAborted(signal, method, path) {
655
1236
  if (signal?.aborted) {
@@ -657,39 +1238,24 @@ function throwIfAborted(signal, method, path) {
657
1238
  }
658
1239
  }
659
1240
  async function parseErrorResponse(response, touch) {
660
- let body;
661
- try {
662
- const text = await readBodyText(response, touch);
663
- body = text.trim() === "" ? void 0 : JSON.parse(text);
664
- } catch (cause) {
665
- if (!(cause instanceof SyntaxError)) throw cause;
666
- body = void 0;
667
- }
1241
+ const bytes = await readBodyBytes(response, touch);
1242
+ const parsed = bytes.byteLength === 0 ? NOT_JSON : parseJsonBytes(bytes);
1243
+ const body = parsed === NOT_JSON ? void 0 : parsed;
1244
+ const bodyExcerpt = parsed === NOT_JSON ? excerptOf(bytes) : void 0;
668
1245
  const hint = headerRetryAfterSeconds(response) ?? (response.status === 429 ? resetHeaderSeconds(response, "ratelimit-reset") : void 0);
669
- return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response));
1246
+ return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response), bodyExcerpt);
670
1247
  }
671
1248
  function headerRetryAfterSeconds(response) {
672
- const raw = response.headers.get("retry-after");
673
- if (raw === null) return void 0;
674
- const header = raw.trim();
675
- if (header === "") return void 0;
676
- if (/^\d+(\.\d+)?$/.test(header)) return normalizeRetryAfterSeconds(Number(header));
677
- if (/^[-+]?\d/.test(header)) return void 0;
678
- const date = Date.parse(header);
679
- if (!Number.isNaN(date)) return Math.max(0, Math.round((date - Date.now()) / 1e3));
680
- return void 0;
1249
+ return retryAfterHeaderSeconds(response.headers.get("retry-after"));
681
1250
  }
682
1251
  function resetHeaderSeconds(response, name) {
683
- const raw = response.headers.get(name);
684
- if (raw === null || raw.trim() === "") return void 0;
685
- const seconds = Number(raw);
686
- if (!Number.isFinite(seconds) || seconds < 0) return void 0;
687
- return normalizeRetryAfterSeconds(seconds);
1252
+ return decimalSeconds(response.headers.get(name));
688
1253
  }
689
1254
  function fullJitterBackoff(attempt, baseDelayMs, maxDelayMs) {
690
1255
  return Math.random() * Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
691
1256
  }
692
1257
  function sleep(ms, signal, method, path) {
1258
+ ms = timerDelay(ms);
693
1259
  return new Promise((resolve, reject) => {
694
1260
  if (signal?.aborted) {
695
1261
  reject(new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason));
@@ -724,6 +1290,39 @@ function buildQuery(query) {
724
1290
  }
725
1291
 
726
1292
  // src/export.ts
1293
+ var INVALID_LINE = /* @__PURE__ */ Symbol("invalid line");
1294
+ var NO_BYTES = new Uint8Array(0);
1295
+ function heldBytes(previous, chunk) {
1296
+ const n = chunk.length;
1297
+ if (n > 0 && chunk[n - 1] < 128) return NO_BYTES;
1298
+ const tail = n >= 3 ? chunk.subarray(n - 3) : new Uint8Array([...previous, ...chunk].slice(-3));
1299
+ for (let k = 1; k <= tail.length; k++) {
1300
+ const byte = tail[tail.length - k];
1301
+ if ((byte & 192) === 128) continue;
1302
+ const size = byte >= 240 ? 4 : byte >= 224 ? 3 : byte >= 192 ? 2 : 1;
1303
+ return size > k ? tail.slice(tail.length - k) : NO_BYTES;
1304
+ }
1305
+ return NO_BYTES;
1306
+ }
1307
+ function strictDecoder() {
1308
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1309
+ }
1310
+ function byteView(chunk) {
1311
+ if (chunk instanceof Uint8Array) return chunk;
1312
+ if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
1313
+ if (ArrayBuffer.isView(chunk)) return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
1314
+ return void 0;
1315
+ }
1316
+ function trimLine(line) {
1317
+ let start = 0;
1318
+ let end = line.length;
1319
+ while (start < end && isLineSpace(line.charCodeAt(start))) start++;
1320
+ while (end > start && isLineSpace(line.charCodeAt(end - 1))) end--;
1321
+ return start === 0 && end === line.length ? line : line.slice(start, end);
1322
+ }
1323
+ function isLineSpace(code) {
1324
+ return code === 32 || code === 9 || code === 13;
1325
+ }
727
1326
  var NdjsonReader = class {
728
1327
  constructor(body, options) {
729
1328
  this.options = options;
@@ -733,54 +1332,175 @@ var NdjsonReader = class {
733
1332
  else signal?.addEventListener("abort", this.onAbort, { once: true });
734
1333
  }
735
1334
  reader;
736
- decoder = new TextDecoder();
737
- /** Pieces of the line currently being received. */
1335
+ /** Decodes the line in progress; holds the bytes of a character split across chunks. */
1336
+ decoder = strictDecoder();
1337
+ /** A copy of the bytes the decoder holds (a character not yet complete), so it can be rebuilt. */
1338
+ carry = NO_BYTES;
1339
+ /** Text pieces of the line in progress. */
738
1340
  partial = [];
1341
+ /** The line in progress already holds bytes that are not UTF-8. */
1342
+ broken = false;
739
1343
  /** Complete lines not yet handed out. */
740
1344
  ready = [];
1345
+ /** No line has been completed yet. */
1346
+ atStart = true;
1347
+ /** The first line of the stream was blank (so the first line handed out is not the stream's first). */
1348
+ firstLineBlank = false;
741
1349
  eof = false;
742
1350
  released = false;
743
1351
  /** Data rows handed out so far (for error messages). */
744
1352
  rows = 0;
745
1353
  /** Releases the connection the moment the caller aborts — even while nobody is reading. */
746
1354
  onAbort = () => this.cancel();
747
- /** Next trimmed, non-empty line, or `undefined` at EOF. */
1355
+ /** Next non-blank line (trimmed), or `INVALID_LINE`, or `undefined` at EOF. */
748
1356
  async nextLine() {
749
1357
  const { signal } = this.options;
750
1358
  if (signal?.aborted) {
751
1359
  this.cancel();
752
1360
  throw new RequestAbortedError("Export stream was aborted", signal.reason);
753
1361
  }
754
- for (; ; ) {
755
- const line = this.ready.shift();
756
- if (line !== void 0) return line;
757
- if (this.eof) {
758
- const tail = this.partial.join("").trim();
759
- this.partial = [];
760
- return tail || void 0;
1362
+ try {
1363
+ for (; ; ) {
1364
+ const line = this.ready.shift();
1365
+ if (line !== void 0) return line;
1366
+ if (this.eof) return void 0;
1367
+ const result = await this.read();
1368
+ if (result.done) {
1369
+ this.finish();
1370
+ this.release();
1371
+ } else {
1372
+ this.ingest(result.value);
1373
+ }
761
1374
  }
762
- const chunk = await this.read();
763
- if (chunk === void 0) {
764
- this.eof = true;
765
- this.ingest(this.decoder.decode());
766
- this.release();
767
- } else {
768
- this.ingest(this.decoder.decode(chunk, { stream: true }));
1375
+ } catch (cause) {
1376
+ this.cancel();
1377
+ if (cause instanceof LexAPIError) throw cause;
1378
+ throw new NetworkError(`Export stream interrupted after ${this.rows} rows`, cause);
1379
+ }
1380
+ }
1381
+ ingest(value) {
1382
+ const chunk = byteView(value);
1383
+ if (chunk === void 0) throw new TypeError("Export stream yielded a chunk that is not bytes");
1384
+ if (!this.broken) {
1385
+ let text2;
1386
+ try {
1387
+ text2 = this.decoder.decode(chunk, { stream: true });
1388
+ } catch {
1389
+ this.decoder = strictDecoder();
1390
+ if (this.carry.length > 0) this.decoder.decode(this.carry, { stream: true });
1391
+ }
1392
+ if (text2 !== void 0) {
1393
+ this.carry = heldBytes(this.carry, chunk);
1394
+ let pos = 0;
1395
+ for (; ; ) {
1396
+ const newline = text2.indexOf("\n", pos);
1397
+ if (newline === -1) break;
1398
+ this.partial.push(text2.slice(pos, newline));
1399
+ const line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1400
+ this.partial = [];
1401
+ this.complete(line);
1402
+ pos = newline + 1;
1403
+ }
1404
+ if (pos < text2.length) this.partial.push(pos === 0 ? text2 : text2.slice(pos));
1405
+ return;
769
1406
  }
770
1407
  }
1408
+ this.ingestBytes(chunk);
771
1409
  }
772
- ingest(text) {
1410
+ /** A chunk that is not all UTF-8, or that continues a line that is not. */
1411
+ ingestBytes(chunk) {
1412
+ const first = chunk.indexOf(10);
1413
+ if (first === -1) {
1414
+ this.feed(chunk);
1415
+ return;
1416
+ }
1417
+ const last = chunk.lastIndexOf(10);
1418
+ let line = INVALID_LINE;
1419
+ if (!this.broken) {
1420
+ try {
1421
+ const text2 = this.decoder.decode(chunk.subarray(0, first + 1), { stream: true });
1422
+ this.partial.push(text2.slice(0, -1));
1423
+ line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1424
+ } catch {
1425
+ this.decoder = strictDecoder();
1426
+ }
1427
+ }
1428
+ this.partial = [];
1429
+ this.broken = false;
1430
+ this.carry = NO_BYTES;
1431
+ this.complete(line);
1432
+ if (first < last) this.completeRegion(chunk.subarray(first + 1, last + 1));
1433
+ if (last + 1 < chunk.length) this.feed(chunk.subarray(last + 1));
1434
+ }
1435
+ /** Whole lines, each ending with its line feed. */
1436
+ completeRegion(region) {
1437
+ let text2;
1438
+ try {
1439
+ text2 = this.decoder.decode(region, { stream: true });
1440
+ } catch {
1441
+ this.decoder = strictDecoder();
1442
+ }
1443
+ if (text2 !== void 0) {
1444
+ let pos2 = 0;
1445
+ for (; ; ) {
1446
+ const newline = text2.indexOf("\n", pos2);
1447
+ if (newline === -1) break;
1448
+ this.complete(text2.slice(pos2, newline));
1449
+ pos2 = newline + 1;
1450
+ }
1451
+ return;
1452
+ }
773
1453
  let pos = 0;
774
- for (; ; ) {
775
- const newline = text.indexOf("\n", pos);
776
- if (newline === -1) break;
777
- this.partial.push(text.slice(pos, newline));
778
- const line = this.partial.join("").trim();
779
- this.partial = [];
780
- if (line) this.ready.push(line);
1454
+ while (pos < region.length) {
1455
+ const newline = region.indexOf(10, pos);
1456
+ try {
1457
+ this.complete(this.decoder.decode(region.subarray(pos, newline + 1), { stream: true }).slice(0, -1));
1458
+ } catch {
1459
+ this.decoder = strictDecoder();
1460
+ this.complete(INVALID_LINE);
1461
+ }
781
1462
  pos = newline + 1;
782
1463
  }
783
- if (pos < text.length) this.partial.push(text.slice(pos));
1464
+ }
1465
+ /** Bytes of the line in progress (after a line feed, or continuing a line that is not UTF-8). */
1466
+ feed(bytes) {
1467
+ if (this.broken || bytes.length === 0) return;
1468
+ try {
1469
+ const text2 = this.decoder.decode(bytes, { stream: true });
1470
+ if (text2) this.partial.push(text2);
1471
+ this.carry = heldBytes(this.carry, bytes);
1472
+ } catch {
1473
+ this.broken = true;
1474
+ this.decoder = strictDecoder();
1475
+ this.carry = NO_BYTES;
1476
+ }
1477
+ }
1478
+ /** End of stream: the line in progress, if any. */
1479
+ finish() {
1480
+ this.eof = true;
1481
+ let line = INVALID_LINE;
1482
+ if (!this.broken) {
1483
+ try {
1484
+ this.partial.push(this.decoder.decode());
1485
+ line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1486
+ } catch {
1487
+ }
1488
+ }
1489
+ this.partial = [];
1490
+ this.broken = false;
1491
+ this.complete(line);
1492
+ }
1493
+ /** Queue a complete line: a byte order mark leading the stream is dropped; blank lines are skipped. */
1494
+ complete(line) {
1495
+ const first = this.atStart;
1496
+ this.atStart = false;
1497
+ if (line === INVALID_LINE) {
1498
+ this.ready.push(line);
1499
+ return;
1500
+ }
1501
+ const text2 = trimLine(first && line.charCodeAt(0) === 65279 ? line.slice(1) : line);
1502
+ if (text2) this.ready.push(text2);
1503
+ else if (first) this.firstLineBlank = true;
784
1504
  }
785
1505
  async read() {
786
1506
  const { idleTimeoutMs, signal } = this.options;
@@ -791,12 +1511,12 @@ var NdjsonReader = class {
791
1511
  let timer;
792
1512
  let onAbort;
793
1513
  const interruptions = new Promise((_, reject) => {
794
- if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0) {
1514
+ if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0 && idleTimeoutMs !== Infinity) {
795
1515
  timer = setTimeout(() => {
796
1516
  reject(
797
1517
  new TimeoutError(`Export stream received no data for ${idleTimeoutMs}ms (after ${this.rows} rows)`, 0)
798
1518
  );
799
- }, idleTimeoutMs);
1519
+ }, timerDelay(idleTimeoutMs));
800
1520
  }
801
1521
  if (signal) {
802
1522
  onAbort = () => reject(new RequestAbortedError("Export stream was aborted", signal.reason));
@@ -806,7 +1526,7 @@ var NdjsonReader = class {
806
1526
  try {
807
1527
  const result = await Promise.race([this.reader.read(), interruptions]);
808
1528
  if (signal?.aborted) throw new RequestAbortedError("Export stream was aborted", signal.reason);
809
- return result.done ? void 0 : result.value;
1529
+ return result;
810
1530
  } catch (cause) {
811
1531
  this.cancel();
812
1532
  if (cause instanceof LexAPIError) throw cause;
@@ -840,17 +1560,25 @@ var NdjsonReader = class {
840
1560
  function liftEnvelope(parsed, key) {
841
1561
  const inner = parsed[key];
842
1562
  if (typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
843
- return { ...inner, ...parsed };
1563
+ return { ...inner, [key]: inner };
844
1564
  }
845
1565
  return parsed;
846
1566
  }
1567
+ function text(value) {
1568
+ try {
1569
+ return String(value);
1570
+ } catch {
1571
+ return Array.isArray(value) ? "array" : typeof value;
1572
+ }
1573
+ }
847
1574
  function errorLine(parsed) {
848
1575
  const keys = Object.keys(parsed);
849
1576
  if (keys.length !== 1 || keys[0] !== "_error") return void 0;
850
1577
  const value = parsed._error;
851
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: String(value) };
1578
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: text(value) };
852
1579
  }
853
1580
  function parseLine(line) {
1581
+ if (line === INVALID_LINE) return void 0;
854
1582
  try {
855
1583
  const value = JSON.parse(line);
856
1584
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
@@ -879,7 +1607,7 @@ var ExportStreamImpl = class {
879
1607
  }
880
1608
  failureReason() {
881
1609
  if (this.error !== void 0) {
882
- return `the server reported an error mid-stream (${String(this.error.code ?? "UNKNOWN")}: ${String(this.error.message ?? "")})`;
1610
+ return `the server reported an error mid-stream (${text(this.error.code ?? "UNKNOWN")}: ${text(this.error.message ?? "")})`;
883
1611
  }
884
1612
  return "its _done trailer says complete: false";
885
1613
  }
@@ -890,7 +1618,7 @@ var ExportStreamImpl = class {
890
1618
  if (typeof this.done?.truncated === "boolean") return this.done.truncated;
891
1619
  if (this.headers.truncated !== void 0) return this.headers.truncated;
892
1620
  if (typeof this.meta?.truncated === "boolean") return this.meta.truncated;
893
- return void 0;
1621
+ return false;
894
1622
  }
895
1623
  constructor(lines, headers) {
896
1624
  this.lines = lines;
@@ -902,21 +1630,20 @@ var ExportStreamImpl = class {
902
1630
  }
903
1631
  /** Read the leading line so `meta` is available before iteration starts. */
904
1632
  async init() {
905
- let parsed;
906
- for (; ; ) {
907
- const first = await this.lines.nextLine();
908
- if (first === void 0) return;
909
- parsed = parseLine(first);
910
- if (parsed !== void 0) {
911
- const error = errorLine(parsed);
912
- if (error === void 0) break;
913
- this.error = error;
914
- continue;
915
- }
1633
+ const first = await this.lines.nextLine();
1634
+ if (first === void 0) return;
1635
+ const parsed = parseLine(first);
1636
+ if (parsed === void 0) {
916
1637
  this.invalidLines++;
1638
+ return;
1639
+ }
1640
+ const error = errorLine(parsed);
1641
+ if (error !== void 0) {
1642
+ this.error = error;
1643
+ return;
917
1644
  }
918
1645
  if ("_meta" in parsed) {
919
- this.meta = liftEnvelope(parsed, "_meta");
1646
+ if (!this.lines.firstLineBlank) this.meta = liftEnvelope(parsed, "_meta");
920
1647
  } else if ("_done" in parsed) {
921
1648
  this.done = liftEnvelope(parsed, "_done");
922
1649
  this.lines.cancel();
@@ -959,12 +1686,12 @@ var ExportStreamImpl = class {
959
1686
  this.invalidLines++;
960
1687
  continue;
961
1688
  }
1689
+ if ("_meta" in parsed) continue;
962
1690
  if ("_done" in parsed) {
963
1691
  this.done = liftEnvelope(parsed, "_done");
964
1692
  if (!this.complete) throw this.incomplete(this.failureReason());
965
1693
  return;
966
1694
  }
967
- if ("_meta" in parsed) continue;
968
1695
  const error = errorLine(parsed);
969
1696
  if (error !== void 0) {
970
1697
  this.error = error;
@@ -978,6 +1705,10 @@ var ExportStreamImpl = class {
978
1705
  }
979
1706
  }
980
1707
  };
1708
+ function truncatedFlag(value) {
1709
+ const flag = value === null ? void 0 : trimSpaces(value);
1710
+ return flag === "1" ? true : flag === "0" ? false : void 0;
1711
+ }
981
1712
  async function createExportStream(response, options = {}) {
982
1713
  if (response.body === null) {
983
1714
  throw new LexAPIError("INTERNAL", "Export response had no body stream", response.status);
@@ -986,14 +1717,63 @@ async function createExportStream(response, options = {}) {
986
1717
  const streamingHeader = response.headers.get("x-export-streaming");
987
1718
  const truncatedHeader = response.headers.get("x-export-truncated");
988
1719
  const stream = new ExportStreamImpl(new NdjsonReader(response.body, options), {
989
- total: totalHeader !== null ? Number(totalHeader) : void 0,
990
- streaming: streamingHeader !== null ? Number(streamingHeader) : void 0,
991
- truncated: truncatedHeader !== null ? truncatedHeader === "1" : void 0
1720
+ total: parseHeaderInteger(totalHeader),
1721
+ streaming: parseHeaderInteger(streamingHeader),
1722
+ truncated: truncatedFlag(truncatedHeader)
992
1723
  });
993
1724
  await stream.init();
994
1725
  return stream;
995
1726
  }
996
1727
 
1728
+ // src/paging.ts
1729
+ function count(value) {
1730
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1731
+ }
1732
+ var REPEATS_BEFORE_THROW = 3;
1733
+ function startingPosition(offset, limit, defaultLimit) {
1734
+ if (offset !== void 0 && count(offset) === void 0) {
1735
+ throw new RangeError(`offset must be a non-negative integer, got ${String(offset)}`);
1736
+ }
1737
+ if (limit !== void 0 && !(count(limit) !== void 0 && limit > 0)) {
1738
+ throw new RangeError(`limit must be a positive integer, got ${String(limit)}`);
1739
+ }
1740
+ return { offset: offset ?? 0, limit: limit ?? defaultLimit };
1741
+ }
1742
+ function stalled(reason, page) {
1743
+ return new InvalidResponseError(`Pagination stopped: ${reason}`, 200, page);
1744
+ }
1745
+ var Token = class {
1746
+ constructor(text2) {
1747
+ this.text = text2;
1748
+ }
1749
+ };
1750
+ function compactForm(value) {
1751
+ let out = "";
1752
+ const stack = [value];
1753
+ while (stack.length > 0) {
1754
+ const item = stack.pop();
1755
+ if (item instanceof Token) out += item.text;
1756
+ else if (typeof item === "string") out += JSON.stringify(item);
1757
+ else if (Array.isArray(item)) {
1758
+ out += "[";
1759
+ stack.push(new Token("]"));
1760
+ for (let i = item.length - 1; i >= 0; i--) {
1761
+ stack.push(item[i]);
1762
+ if (i > 0) stack.push(new Token(","));
1763
+ }
1764
+ } else if (typeof item === "object" && item !== null) {
1765
+ out += "{";
1766
+ stack.push(new Token("}"));
1767
+ const keys = Object.keys(item).sort();
1768
+ for (let i = keys.length - 1; i >= 0; i--) {
1769
+ stack.push(item[keys[i]]);
1770
+ stack.push(new Token(`${i > 0 ? "," : ""}${JSON.stringify(keys[i])}:`));
1771
+ }
1772
+ } else out += String(item);
1773
+ }
1774
+ return out;
1775
+ }
1776
+
997
1777
  // src/webhooks.ts
998
1778
  var WebhooksAPI = class {
999
1779
  http;
@@ -1013,6 +1793,7 @@ var WebhooksAPI = class {
1013
1793
  return this.call({
1014
1794
  method: "GET",
1015
1795
  path: "/webhooks",
1796
+ shape: { lists: ["webhooks"] },
1016
1797
  free: true,
1017
1798
  timeoutMs: options?.timeoutMs,
1018
1799
  signal: options?.signal
@@ -1073,6 +1854,7 @@ var WebhooksAPI = class {
1073
1854
  return this.call({
1074
1855
  method: "DELETE",
1075
1856
  path: `/webhooks/${encodeURIComponent(id)}`,
1857
+ shape: { allowEmpty: true },
1076
1858
  timeoutMs: options?.timeoutMs,
1077
1859
  signal: options?.signal
1078
1860
  });
@@ -1087,6 +1869,7 @@ var WebhooksAPI = class {
1087
1869
  return this.call({
1088
1870
  method: "POST",
1089
1871
  path: `/webhooks/${encodeURIComponent(id)}/test`,
1872
+ shape: { successFalseOk: true },
1090
1873
  timeoutMs: options?.timeoutMs,
1091
1874
  signal: options?.signal
1092
1875
  });
@@ -1096,6 +1879,7 @@ var WebhooksAPI = class {
1096
1879
  return this.call({
1097
1880
  method: "GET",
1098
1881
  path: `/webhooks/${encodeURIComponent(id)}/deliveries`,
1882
+ shape: { lists: ["deliveries"] },
1099
1883
  free: true,
1100
1884
  query: { limit: params.limit, offset: params.offset },
1101
1885
  timeoutMs: options?.timeoutMs,
@@ -1107,7 +1891,13 @@ var WebhooksAPI = class {
1107
1891
  * 50), starting at `offset`, newest first (SDK contract §1.4). Each
1108
1892
  * delivery is yielded at most once (deduplicated on `id`): a delivery
1109
1893
  * created during the walk shifts later pages by one. Stops on an empty page
1110
- * or when the offset reaches `total`. Pages are free (0 credits).
1894
+ * or when the offset reaches `total`. Without a usable `total`, three pages
1895
+ * in a row that bring no unseen `id` throw `InvalidResponseError` (a page
1896
+ * with a usable `total` ends a run). When a walk throws, the pages already
1897
+ * yielded stay valid; the page that showed the stall is not yielded and is
1898
+ * on the error's `body`. A starting `offset` or `limit` that is not a
1899
+ * non-negative (positive) integer is a `RangeError` before any request.
1900
+ * Pages are free (0 credits).
1111
1901
  *
1112
1902
  * ```ts
1113
1903
  * for await (const page of client.webhooks.paginateDeliveries(id)) {
@@ -1116,21 +1906,36 @@ var WebhooksAPI = class {
1116
1906
  * ```
1117
1907
  */
1118
1908
  async *paginateDeliveries(id, params = {}, options) {
1119
- const limit = params.limit ?? 50;
1120
- let offset = params.offset ?? 0;
1909
+ const start = startingPosition(params.offset, params.limit, 50);
1910
+ const limit = start.limit;
1911
+ let offset = start.offset;
1121
1912
  const seen = /* @__PURE__ */ new Set();
1913
+ let repeats = 0;
1122
1914
  for (; ; ) {
1123
1915
  const page = await this.deliveries(id, { limit, offset }, options);
1124
- const count = page.deliveries.length;
1125
- const fresh = page.deliveries.filter((d) => {
1916
+ const listed = page.deliveries;
1917
+ const deliveries = Array.isArray(listed) ? listed : [];
1918
+ const rows = deliveries.length;
1919
+ let readable = 0;
1920
+ let unseen = 0;
1921
+ const fresh = deliveries.filter((d) => {
1126
1922
  if (typeof d.id !== "string") return true;
1923
+ readable++;
1127
1924
  if (seen.has(d.id)) return false;
1128
1925
  seen.add(d.id);
1926
+ unseen++;
1129
1927
  return true;
1130
1928
  });
1929
+ const total = count(page.total);
1930
+ if (total === void 0) {
1931
+ repeats = readable > 0 && unseen === 0 ? repeats + 1 : 0;
1932
+ if (repeats >= REPEATS_BEFORE_THROW) throw stalled("the server repeated the same deliveries", page);
1933
+ } else {
1934
+ repeats = 0;
1935
+ }
1131
1936
  yield { ...page, deliveries: fresh };
1132
- offset += count;
1133
- if (count === 0 || page.total !== void 0 && offset >= page.total) return;
1937
+ offset += rows;
1938
+ if (rows === 0 || total !== void 0 && offset >= total) return;
1134
1939
  }
1135
1940
  }
1136
1941
  };
@@ -1145,11 +1950,16 @@ var LexAPI = class {
1145
1950
  if (!apiKey) {
1146
1951
  throw new Error("apiKey is required (or set LEXAPI_API_KEY)");
1147
1952
  }
1953
+ if (options.fetch === void 0 && typeof globalThis.fetch !== "function") {
1954
+ throw new Error("This runtime has no global fetch; pass one with the `fetch` option");
1955
+ }
1148
1956
  this.http = new HttpClient({
1149
1957
  apiKey,
1150
1958
  baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
1151
1959
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1152
- fetchFn: options.fetch ?? fetch,
1960
+ // Looked up per call and invoked on the global object, which Cloudflare
1961
+ // Workers and browsers require.
1962
+ fetchFn: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
1153
1963
  retry: {
1154
1964
  maxRetries: options.retry?.maxRetries ?? 3,
1155
1965
  baseDelayMs: options.retry?.baseDelayMs ?? 500,
@@ -1207,6 +2017,7 @@ var LexAPI = class {
1207
2017
  return this.call({
1208
2018
  method: "POST",
1209
2019
  path: "/search",
2020
+ shape: { lists: ["results"], required: ["results"] },
1210
2021
  body: request,
1211
2022
  idempotent: true,
1212
2023
  timeoutMs: options?.timeoutMs,
@@ -1231,6 +2042,7 @@ var LexAPI = class {
1231
2042
  return this.call({
1232
2043
  method: "POST",
1233
2044
  path: "/documentContent",
2045
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
1234
2046
  body: request,
1235
2047
  idempotent: true,
1236
2048
  timeoutMs: options?.timeoutMs,
@@ -1252,6 +2064,7 @@ var LexAPI = class {
1252
2064
  return this.call({
1253
2065
  method: "POST",
1254
2066
  path: "/documentContent/batch",
2067
+ shape: { lists: ["documents", "errors"] },
1255
2068
  body: request,
1256
2069
  idempotent: true,
1257
2070
  timeoutMs: options?.timeoutMs,
@@ -1274,6 +2087,7 @@ var LexAPI = class {
1274
2087
  return this.call({
1275
2088
  method: "GET",
1276
2089
  path: "/documents/recent",
2090
+ shape: { lists: ["results"] },
1277
2091
  query: {
1278
2092
  days: params.days,
1279
2093
  documentType: params.documentType,
@@ -1296,6 +2110,7 @@ var LexAPI = class {
1296
2110
  return this.call({
1297
2111
  method: "POST",
1298
2112
  path: "/documents/url",
2113
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
1299
2114
  body: request,
1300
2115
  idempotent: true,
1301
2116
  timeoutMs: options?.timeoutMs,
@@ -1334,18 +2149,20 @@ var LexAPI = class {
1334
2149
  });
1335
2150
  }
1336
2151
  // ── Point-in-time versions ────────────────────────────────────────
1337
- // Versions are LexAPI observation snapshots (content-hash changes between
1338
- // fetches), NOT legal in-force reconstructions; history begins at first
1339
- // ingestion. For the text in force on a date, use a consolidated CELEX or
1340
- // semanticLegislationSearch({ asOf }).
2152
+ // Versions are LexAPI's fetch snapshots (content-hash changes between
2153
+ // fetches), NOT the law in force on a date; history begins at first
2154
+ // ingestion. For the version of an EU act for a date, use legislationAsOf.
1341
2155
  /**
1342
2156
  * `GET /documents/{celex}/versions` — version history, newest first,
1343
- * current version included and flagged. 1 credit.
2157
+ * current version included and flagged. These are LexAPI's fetch
2158
+ * snapshots, not the law in force on a date; for the version of an EU act
2159
+ * for a date use `legislationAsOf`. 1 credit.
1344
2160
  */
1345
2161
  async listDocumentVersions(celex, params = {}, options) {
1346
2162
  return this.call({
1347
2163
  method: "GET",
1348
2164
  path: `/documents/${encodeURIComponent(celex)}/versions`,
2165
+ shape: { lists: ["versions"] },
1349
2166
  query: { language: params.language },
1350
2167
  timeoutMs: options?.timeoutMs,
1351
2168
  signal: options?.signal
@@ -1354,27 +2171,41 @@ var LexAPI = class {
1354
2171
  /**
1355
2172
  * `GET /documents/{celex}/versions/{version}` — one immutable snapshot
1356
2173
  * including `parsedContent`. `corpusVersion` mirrors the
1357
- * `X-Corpus-Version` response header. 1 credit.
2174
+ * `X-Corpus-Version` response header. This is one of LexAPI's fetch
2175
+ * snapshots, not the law in force on a date; for the version of an EU act
2176
+ * for a date use `legislationAsOf`. 1 credit.
1358
2177
  */
1359
2178
  async getDocumentVersion(celex, version, params = {}, options) {
1360
2179
  return this.call({
1361
2180
  method: "GET",
1362
2181
  path: `/documents/${encodeURIComponent(celex)}/versions/${version}`,
2182
+ shape: { fields: [{ path: "document", kind: "object" }] },
1363
2183
  query: { language: params.language },
1364
2184
  timeoutMs: options?.timeoutMs,
1365
2185
  signal: options?.signal
1366
2186
  }, { corpusVersion: true });
1367
2187
  }
1368
2188
  /**
1369
- * `GET /documents/{celex}/at/{date}` — the snapshot LexAPI observed as
1370
- * current on `date` (`YYYY-MM-DD`, end-of-day UTC inclusive). Dates
1371
- * before the document entered the corpus reject with `NotFoundError`
1372
- * carrying the tracking start date. 1 credit.
2189
+ * `GET /documents/{celex}/at/{date}` — the snapshot LexAPI held as current
2190
+ * at the end of `date` (`YYYY-MM-DD`, UTC), from its own fetch history
2191
+ * (`kind: "observation_snapshot"`). This is not the law in force on that
2192
+ * date: for the version of an EU act for a date use `legislationAsOf`
2193
+ * (`inForceLookup` points to it). The snapshot was the current one from
2194
+ * `document.observedFrom` until `document.observedUntil` (`null` for the
2195
+ * current version). A future date returns the current version with
2196
+ * `dateInFuture: true`.
2197
+ *
2198
+ * A date before the document entered the corpus rejects with
2199
+ * `NotFoundError` where `beforeTracking` is `true` (`trackedSince`); a date
2200
+ * next to a version stored before API 2.28.0 whose start LexAPI has no
2201
+ * record of rejects with `boundaryUnknown` `true` and `candidates`
2202
+ * (refunded). 1 credit.
1373
2203
  */
1374
2204
  async getDocumentAtDate(celex, date, params = {}, options) {
1375
2205
  return this.call({
1376
2206
  method: "GET",
1377
2207
  path: `/documents/${encodeURIComponent(celex)}/at/${encodeURIComponent(date)}`,
2208
+ shape: { fields: [{ path: "document", kind: "object" }] },
1378
2209
  query: { language: params.language },
1379
2210
  timeoutMs: options?.timeoutMs,
1380
2211
  signal: options?.signal
@@ -1391,6 +2222,7 @@ var LexAPI = class {
1391
2222
  return this.call({
1392
2223
  method: "POST",
1393
2224
  path: "/citations/extract",
2225
+ shape: { lists: ["citations"] },
1394
2226
  body: { celexNumber },
1395
2227
  timeoutMs: options?.timeoutMs,
1396
2228
  signal: options?.signal
@@ -1400,12 +2232,25 @@ var LexAPI = class {
1400
2232
  * `GET /citations/cites/{celexNumber}` — documents this one cites
1401
2233
  * (outbound edges), grouped by target. The document must first have been
1402
2234
  * crawled via `extractCitations` to appear here. 1 credit.
2235
+ *
2236
+ * `celexNumber` may be a national document id (e.g. `AT-NOR-10001597`);
2237
+ * `params.includeNational` also pulls in national neighbours of live
2238
+ * jurisdictions — BUSINESS, SCALE and ENTERPRISE only (`403
2239
+ * TierForbiddenError` below that, refunded in full). A national id whose
2240
+ * jurisdiction is not live is `404 NotFoundError`.
2241
+ *
2242
+ * Filters (API 2.11.0): `citationType`, `provenance`, `jurisdictions` and
2243
+ * `resolution` each take one value or a list (sent comma-separated). On a
2244
+ * national id, `unresolved: true` also returns the references the
2245
+ * document records that could not be turned into an edge
2246
+ * (`unresolved` / `unresolvedTruncated`), at no extra cost.
1403
2247
  */
1404
2248
  async getCites(celexNumber, params = {}, options) {
1405
2249
  return this.call({
1406
2250
  method: "GET",
1407
2251
  path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
1408
- query: edgeQuery(params),
2252
+ shape: { lists: ["cites", "unresolved"] },
2253
+ query: { ...edgeQuery(params), unresolved: params.unresolved },
1409
2254
  timeoutMs: options?.timeoutMs,
1410
2255
  signal: options?.signal
1411
2256
  });
@@ -1415,11 +2260,16 @@ var LexAPI = class {
1415
2260
  * (inbound edges), grouped by source. 1 credit. For legislation, inbound
1416
2261
  * amendment / corrigendum / repeal edges are refreshed from Cellar when
1417
2262
  * older than 7 days (waits ≤ ~2.5 s) — see `relationSync`.
2263
+ *
2264
+ * `celexNumber` may be a national document id; `params.includeNational`
2265
+ * also pulls in national neighbours of live jurisdictions — BUSINESS+
2266
+ * only (`403 TierForbiddenError` below that). Filters as on `getCites`.
1418
2267
  */
1419
2268
  async getCitedBy(celexNumber, params = {}, options) {
1420
2269
  return this.call({
1421
2270
  method: "GET",
1422
2271
  path: `/citations/cited-by/${encodeURIComponent(celexNumber)}`,
2272
+ shape: { lists: ["citedBy"] },
1423
2273
  query: edgeQuery(params),
1424
2274
  timeoutMs: options?.timeoutMs,
1425
2275
  signal: options?.signal
@@ -1433,26 +2283,39 @@ var LexAPI = class {
1433
2283
  * missed. A target's edges can straddle a page boundary, so the same
1434
2284
  * `celexNumber` may appear in two consecutive pages — merge by
1435
2285
  * `celexNumber` if you need one group per document.
2286
+ * The walk also ends once the offset reaches `totalEdges`, when that is a
2287
+ * non-negative integer. It throws `InvalidResponseError` when a page echoes
2288
+ * an `offset` other than the one requested, or, when the answers carry
2289
+ * neither `totalEdges` nor `offset`, after three pages in a row that each
2290
+ * repeat the one before (comparing the list only; a page with either
2291
+ * signal ends a run, and its list is still the one the next page is
2292
+ * compared with). When a walk throws, the pages already yielded stay
2293
+ * valid; the page that showed the stall is not yielded and is on the
2294
+ * error's `body`. A starting `offset` or `limit` that is not a non-negative
2295
+ * (positive) integer is a `RangeError` before any request. A group whose
2296
+ * `citationCount` is 0 but whose edge list is not empty counts its list.
1436
2297
  */
1437
2298
  async *paginateCites(celexNumber, params = {}, options) {
1438
- yield* paginateEdges(
1439
- (p) => this.getCites(celexNumber, p, options),
1440
- (page) => page.cites.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
1441
- params
1442
- );
2299
+ yield* paginateEdges((p) => this.getCites(celexNumber, p, options), (page) => page.cites, params);
1443
2300
  }
1444
2301
  /**
1445
2302
  * Walk every page of `getCitedBy` (offset in edge rows) until a short or
1446
2303
  * empty page (SDK contract §1.4). Each page is a billed call (1 credit);
1447
2304
  * edges may repeat or be missed if extractions happen during the walk. A source's edges can straddle a page boundary, so the same
1448
2305
  * `celexNumber` may appear in two consecutive pages.
2306
+ * The walk also ends once the offset reaches `totalEdges`, when that is a
2307
+ * non-negative integer. It throws `InvalidResponseError` when a page echoes
2308
+ * an `offset` other than the one requested, or, when the answers carry
2309
+ * neither `totalEdges` nor `offset`, after three pages in a row that each
2310
+ * repeat the one before (comparing the list only; a page with either
2311
+ * signal ends a run, and its list is still the one the next page is
2312
+ * compared with). When a walk throws, the pages already yielded stay
2313
+ * valid; the page that showed the stall is not yielded and is on the
2314
+ * error's `body`. A starting `offset` or `limit` that is not a non-negative
2315
+ * (positive) integer is a `RangeError` before any request.
1449
2316
  */
1450
2317
  async *paginateCitedBy(celexNumber, params = {}, options) {
1451
- yield* paginateEdges(
1452
- (p) => this.getCitedBy(celexNumber, p, options),
1453
- (page) => page.citedBy.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
1454
- params
1455
- );
2318
+ yield* paginateEdges((p) => this.getCitedBy(celexNumber, p, options), (page) => page.citedBy, params);
1456
2319
  }
1457
2320
  /**
1458
2321
  * `GET /citations/network/{celexNumber}` — inbound and outbound
@@ -1461,16 +2324,23 @@ var LexAPI = class {
1461
2324
  * If the server-side wall-clock budget expires the endpoint still
1462
2325
  * returns 200 with `partial: true`, an EMPTY `network`, and `null`
1463
2326
  * paging totals — check `partial` before treating the network as empty.
2327
+ *
2328
+ * `celexNumber` may be a national document id; `params.includeNational`
2329
+ * also pulls in national neighbours of live jurisdictions — BUSINESS+
2330
+ * only (`403 TierForbiddenError` below that). See `getCites`.
1464
2331
  */
1465
2332
  async getCitationNetwork(celexNumber, params = {}, options) {
1466
2333
  return this.call({
1467
2334
  method: "GET",
1468
2335
  path: `/citations/network/${encodeURIComponent(celexNumber)}`,
2336
+ shape: { lists: ["network.cites", "network.citedBy", "unresolved"] },
1469
2337
  query: {
1470
- citationType: params.citationType,
2338
+ ...filterQuery(params),
1471
2339
  limit: params.limit,
1472
2340
  offset: params.offset,
1473
- language: params.language
2341
+ language: params.language,
2342
+ includeNational: params.includeNational,
2343
+ unresolved: params.unresolved
1474
2344
  },
1475
2345
  timeoutMs: options?.timeoutMs,
1476
2346
  signal: options?.signal
@@ -1481,12 +2351,22 @@ var LexAPI = class {
1481
2351
  * outbound edges). 20 credits. `found: false` is a graceful HTTP 200,
1482
2352
  * not an error. Default `maxDepth` 3 (max 8); the visited set is bounded
1483
2353
  * to 5000 nodes.
2354
+ *
2355
+ * `from`/`to` may be national document ids; `params.includeNational` also
2356
+ * follows national documents of live jurisdictions along the way —
2357
+ * BUSINESS+ only (`403 TierForbiddenError` below that). See `getCites`.
1484
2358
  */
1485
2359
  async getCitationPath(from, to, params = {}, options) {
1486
2360
  return this.call({
1487
2361
  method: "GET",
1488
2362
  path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
1489
- query: { maxDepth: params.maxDepth, language: params.language },
2363
+ shape: { lists: ["path"] },
2364
+ query: {
2365
+ ...filterQuery(params),
2366
+ maxDepth: params.maxDepth,
2367
+ language: params.language,
2368
+ includeNational: params.includeNational
2369
+ },
1490
2370
  timeoutMs: options?.timeoutMs,
1491
2371
  signal: options?.signal
1492
2372
  });
@@ -1496,21 +2376,281 @@ var LexAPI = class {
1496
2376
  * neighbours (documents sharing the most outbound citation targets with
1497
2377
  * the seed). 20 credits. Returns a graceful empty list with `message`
1498
2378
  * when the seed has no outbound citations to couple on.
2379
+ *
2380
+ * `celexNumber` may be a national document id; `params.includeNational`
2381
+ * also considers national documents of live jurisdictions — BUSINESS+
2382
+ * only (`403 TierForbiddenError` below that). See `getCites`.
1499
2383
  */
1500
2384
  async getRelatedDocuments(celexNumber, params = {}, options) {
1501
2385
  return this.call({
1502
2386
  method: "GET",
1503
2387
  path: `/citations/related/${encodeURIComponent(celexNumber)}`,
1504
- query: { limit: params.limit, language: params.language },
2388
+ shape: { lists: ["related"] },
2389
+ query: {
2390
+ ...filterQuery(params),
2391
+ limit: params.limit,
2392
+ language: params.language,
2393
+ includeNational: params.includeNational
2394
+ },
1505
2395
  timeoutMs: options?.timeoutMs,
1506
2396
  signal: options?.signal
1507
2397
  });
1508
2398
  }
1509
- /** `GET /citations/stats` — global citation graph statistics. 20 credits. */
1510
- async getCitationStats(options) {
2399
+ async getCitationStats(params, options) {
2400
+ let effectiveParams;
2401
+ let effectiveOptions;
2402
+ if (isLegacyCitationStatsCallOptions(params)) {
2403
+ effectiveOptions = params;
2404
+ } else {
2405
+ effectiveParams = params;
2406
+ effectiveOptions = options;
2407
+ }
1511
2408
  return this.call({
1512
2409
  method: "GET",
1513
2410
  path: "/citations/stats",
2411
+ shape: { lists: ["stats.mostCited", "stats.mostCiting"] },
2412
+ query: { includeNational: effectiveParams?.includeNational },
2413
+ timeoutMs: effectiveOptions?.timeoutMs,
2414
+ signal: effectiveOptions?.signal
2415
+ });
2416
+ }
2417
+ /**
2418
+ * `GET /citations/transposition/{celexNumber}` — the measures the member
2419
+ * states notified to the Commission for an EU act (CELEX sector 3),
2420
+ * grouped by country, from the Publications Office's Cellar records of the
2421
+ * notifications (API 2.11.0). **A notification is not a finding that the
2422
+ * measure transposes the act, or transposes it completely** — `note` says
2423
+ * so on every answer. 5 credits, every plan; a 5xx is refunded.
2424
+ *
2425
+ * On BUSINESS, SCALE and ENTERPRISE, for live jurisdictions, the answer
2426
+ * also says which measures LexAPI holds (`id`, `resolved`, `resolution`,
2427
+ * `resolutionBasis`, `counts.resolved`, `source.lanes`) and adds the
2428
+ * documents whose national source records that they transpose or
2429
+ * implement the act (`provenance: "source"`); `resolvedOnly: true` keeps
2430
+ * only the held ones. Below BUSINESS, for a jurisdiction that is not live,
2431
+ * and while the national-source terms are not accepted (`termsRequired:
2432
+ * true` — never a 403) those fields are `null`.
2433
+ *
2434
+ * A CELEX that is not an EU act (sector 3) is `404 NotFoundError`.
2435
+ */
2436
+ async getTransposition(celexNumber, params = {}, options) {
2437
+ return this.call({
2438
+ method: "GET",
2439
+ path: `/citations/transposition/${encodeURIComponent(celexNumber)}`,
2440
+ shape: { lists: ["jurisdictions"] },
2441
+ query: {
2442
+ jurisdictions: listParam(params.jurisdictions),
2443
+ resolvedOnly: params.resolvedOnly,
2444
+ language: params.language
2445
+ },
2446
+ timeoutMs: options?.timeoutMs,
2447
+ signal: options?.signal
2448
+ });
2449
+ }
2450
+ /**
2451
+ * `GET /citations/counterparts/{id}` — a national document's counterparts
2452
+ * in the other live jurisdictions, through the EU acts it transposes or
2453
+ * implements (API 2.11.0). Each `via[]` entry is one EU act, with the
2454
+ * other jurisdictions' measures for it ranked `1` (the national source
2455
+ * records the relation), `2` (a notified measure LexAPI holds) or `3` (a
2456
+ * notified Cellar record LexAPI does not hold, `id: null`). An EU act
2457
+ * CELEX as `id` lists its own measures the same way.
2458
+ *
2459
+ * **20 credits; BUSINESS, SCALE and ENTERPRISE only** (`403
2460
+ * TierForbiddenError` below that, refunded). A lookup past its 20-second
2461
+ * server-side budget throws `TimeoutError` (503, `err.partial === true`),
2462
+ * refunded. The SDK does not retry it (the same lookup would hit the same
2463
+ * budget); retry yourself, or narrow with `jurisdictions`.
2464
+ */
2465
+ async getCounterparts(id, params = {}, options) {
2466
+ return this.call({
2467
+ method: "GET",
2468
+ path: `/citations/counterparts/${encodeURIComponent(id)}`,
2469
+ shape: { lists: ["via"] },
2470
+ query: {
2471
+ jurisdictions: listParam(params.jurisdictions),
2472
+ language: params.language
2473
+ },
2474
+ timeoutMs: options?.timeoutMs,
2475
+ signal: options?.signal
2476
+ });
2477
+ }
2478
+ // ── National law ──────────────────────────────────────────────────
2479
+ // Member-state (and non-EU) legal orders alongside EUR-Lex. BUSINESS and
2480
+ // above get full access; FREE/STARTER/PROFESSIONAL get it within a
2481
+ // monthly allowance of national calls (`X-National-Limit`/
2482
+ // `X-National-Remaining`/`X-National-Reset`, `result.headers.nationalAllowance`;
2483
+ // a used-up allowance is `NationalAllowanceExhaustedError`, 402). An
2484
+ // unlaunched or unknown jurisdiction answers 404 exactly like a path that
2485
+ // doesn't exist — call `getNationalCoverage()` first.
2486
+ /**
2487
+ * `GET /national/coverage` — which jurisdictions are live, what each one
2488
+ * covers (legislation / case law, semantic search, sources with their
2489
+ * attribution), and when each was last synced. Public: no API key or
2490
+ * allowance required, free.
2491
+ */
2492
+ async getNationalCoverage(options) {
2493
+ return this.call({
2494
+ method: "GET",
2495
+ path: "/national/coverage",
2496
+ shape: { lists: ["jurisdictions"] },
2497
+ free: true,
2498
+ timeoutMs: options?.timeoutMs,
2499
+ signal: options?.signal
2500
+ });
2501
+ }
2502
+ /**
2503
+ * `GET /{jurisdiction}/documents/{id}` — one national document by its
2504
+ * corpus id (e.g. `"AT-NOR-12345"`), analogous to `getDocument`.
2505
+ *
2506
+ * **Cost: 1 credit** — every national read is a corpus read (there is no
2507
+ * live-fetch fallback), so the 5-credit upfront reservation always
2508
+ * settles to 1 (an unknown id too). Check
2509
+ * `document.textAvailability.available` before reading `content`, and
2510
+ * always show `document.attribution` to the user alongside the text.
2511
+ * The document has one shape for every jurisdiction (API 2.8.0):
2512
+ * `documentKind` (`act` | `decision`), `decision` (court, chamber,
2513
+ * caseNumbers, citedNorms — `null` for acts; see `isNationalDecision`)
2514
+ * and the closed `content` key set.
2515
+ *
2516
+ * A document its source withdrew (a takedown, a pseudonymisation fix)
2517
+ * throws `DocumentWithdrawnError` (410) instead of answering — nothing of
2518
+ * it is served, not even the title; drop any copy you hold.
2519
+ */
2520
+ async getNationalDocument(jurisdiction, id, params = {}, options) {
2521
+ return this.call({
2522
+ method: "GET",
2523
+ path: `/${jurisdictionSegment(jurisdiction)}/documents/${encodeURIComponent(id)}`,
2524
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
2525
+ query: { language: params.language },
2526
+ timeoutMs: options?.timeoutMs,
2527
+ signal: options?.signal
2528
+ });
2529
+ }
2530
+ /**
2531
+ * `GET /{jurisdiction}/documents` — browse a jurisdiction's corpus by
2532
+ * title (`q`), type, and in-force status. Newest-first by the document's
2533
+ * own date.
2534
+ *
2535
+ * **Cost: 3 credits per call** — flat; pagination does not multiply the
2536
+ * price, unlike `search`. **Paging:** `page` only reaches the first 1,000
2537
+ * rows (a 400 past that); page further with `cursor` (each response's
2538
+ * `nextCursor`), which works at any depth — see
2539
+ * `paginateNationalDocuments` for a ready-made walk. A slow page is a
2540
+ * retry-safe `TimeoutError` (504, refunded); the `total` count is capped
2541
+ * at 10,000 and flagged `totalExact: false` past that or on a slow count.
2542
+ */
2543
+ async listNationalDocuments(jurisdiction, params = {}, options) {
2544
+ return this.call({
2545
+ method: "GET",
2546
+ path: `/${jurisdictionSegment(jurisdiction)}/documents`,
2547
+ shape: { lists: ["results"] },
2548
+ query: {
2549
+ page: params.page,
2550
+ cursor: params.cursor,
2551
+ limit: params.limit,
2552
+ q: params.q,
2553
+ type: params.documentType,
2554
+ includeRepealed: params.includeRepealed
2555
+ },
2556
+ timeoutMs: options?.timeoutMs,
2557
+ signal: options?.signal
2558
+ });
2559
+ }
2560
+ /**
2561
+ * Walk every page of `listNationalDocuments` via `cursor` (works past the
2562
+ * 1,000-row `page` ceiling, unlike passing `page` yourself). Each page is
2563
+ * a separate billed call. Stops after a page whose `hasMore` is not `true`,
2564
+ * whose `nextCursor` is absent, `null` or empty, or that is empty. A
2565
+ * `nextCursor` the walk already sent, or one that is not a string, throws
2566
+ * `InvalidResponseError`; the pages already yielded stay valid, and the
2567
+ * page that showed the stall is not yielded and is on the error's `body`.
2568
+ * Any `params.page` is ignored and never sent — pass
2569
+ * `params.cursor` only to resume a walk you saved partway through;
2570
+ * `page` together with `cursor` is a 400 ("Use either cursor or page,
2571
+ * not both"), so this strips `page` at runtime, not just in the type
2572
+ * (`Omit` alone only guards TypeScript callers — a JS caller, or one
2573
+ * using `as`, could otherwise still pass it through). A `limit` that is
2574
+ * not a positive integer is a `RangeError` before any request.
2575
+ */
2576
+ async *paginateNationalDocuments(jurisdiction, params = {}, options) {
2577
+ const { page: _ignoredPage, ...rest } = params;
2578
+ startingPosition(void 0, rest.limit, 1);
2579
+ let cursor = rest.cursor;
2580
+ const sent = /* @__PURE__ */ new Set();
2581
+ for (; ; ) {
2582
+ if (typeof cursor === "string") sent.add(cursor);
2583
+ const page = await this.listNationalDocuments(
2584
+ jurisdiction,
2585
+ cursor !== void 0 ? { ...rest, cursor } : { ...rest },
2586
+ options
2587
+ );
2588
+ const results = page.results;
2589
+ const next = page.nextCursor;
2590
+ const ends = page.hasMore !== true || next === void 0 || next === null || next === "" || !Array.isArray(results) || results.length === 0;
2591
+ if (!ends) {
2592
+ if (typeof next !== "string") throw stalled("the server sent a page cursor that is not a string", page);
2593
+ if (sent.has(next)) throw stalled("the server repeated a page cursor", page);
2594
+ }
2595
+ yield page;
2596
+ if (ends) return;
2597
+ cursor = next;
2598
+ }
2599
+ }
2600
+ /**
2601
+ * `POST /{jurisdiction}/search/semantic` — embedding-based semantic
2602
+ * search over a jurisdiction's case law. Same request/response shape as
2603
+ * `semanticSearch`, plus `jurisdiction`/`documentId`/`attribution` and
2604
+ * `document` (the matched decision as the listing returns it — the same
2605
+ * fields in every jurisdiction, API 2.8.0) on every hit.
2606
+ *
2607
+ * **Cost: a flat 5 credits** — `hyde` is accepted but never changes the
2608
+ * price or the billing tier here: the national index never rewrites, so
2609
+ * the response reports `hyde: false` (never `true`) when requested.
2610
+ */
2611
+ async nationalSemanticSearch(jurisdiction, request, options) {
2612
+ return this.call({
2613
+ method: "POST",
2614
+ path: `/${jurisdictionSegment(jurisdiction)}/search/semantic`,
2615
+ shape: { lists: ["results"], required: ["results"] },
2616
+ body: nationalSemanticWireBody(request),
2617
+ idempotent: true,
2618
+ timeoutMs: options?.timeoutMs,
2619
+ signal: options?.signal
2620
+ });
2621
+ }
2622
+ /**
2623
+ * `POST /{jurisdiction}/legislation/semantic` — embedding-based semantic
2624
+ * search over a jurisdiction's legislation; article-level matches. Same
2625
+ * shape as `semanticLegislationSearch`, plus `jurisdiction`/`documentId`/
2626
+ * `attribution` and `document` (the matched act's listing summary) on
2627
+ * every hit; the index fields (`law_title`, `article_ref`, `section`,
2628
+ * `language`, `in_force`, `valid_from`, `valid_to`, `law_type`) are
2629
+ * always present, `null` when the index has nothing (API 2.8.0).
2630
+ *
2631
+ * **`asOf` (API 2.29.0)** labels each hit for a date (`asOfResolved`,
2632
+ * `asOfReason`, `asOfVersion`); the response adds `asOf` and
2633
+ * `asOfSummary`. The search runs over today's texts only. A hit is
2634
+ * resolved only when the publisher's dates, as of LexAPI's last recorded
2635
+ * read of the act (`asOfVersion.checkedAt`), show today's wording already
2636
+ * applied on the date; an unresolved hit keeps today's wording — it is not
2637
+ * established as the text for the date. LexAPI holds such dates for
2638
+ * Austria and Spain.
2639
+ *
2640
+ * `NationalSemanticLegislationOptions` has no `hyde` field, and this SDK
2641
+ * never forwards one on this call even if a caller bypasses the type
2642
+ * system — the server now validates `hyde` as a boolean on this route too
2643
+ * (400 otherwise), so a stray non-boolean value would 400 for nothing.
2644
+ *
2645
+ * **Cost: 5 credits.**
2646
+ */
2647
+ async nationalLegislationSemanticSearch(jurisdiction, request, options) {
2648
+ return this.call({
2649
+ method: "POST",
2650
+ path: `/${jurisdictionSegment(jurisdiction)}/legislation/semantic`,
2651
+ shape: { lists: ["results"], required: ["results"] },
2652
+ body: nationalSemanticWireBody(request, { allowHyde: false, allowAsOf: true }),
2653
+ idempotent: true,
1514
2654
  timeoutMs: options?.timeoutMs,
1515
2655
  signal: options?.signal
1516
2656
  });
@@ -1539,7 +2679,8 @@ var LexAPI = class {
1539
2679
  return this.call({
1540
2680
  method: "POST",
1541
2681
  path: "/search/semantic",
1542
- body: semanticWireBody(request),
2682
+ shape: { lists: ["results"], required: ["results"] },
2683
+ body: semanticWireBody(request, { legislation: false }),
1543
2684
  idempotent: true,
1544
2685
  timeoutMs: options?.timeoutMs,
1545
2686
  signal: options?.signal
@@ -1561,6 +2702,11 @@ var LexAPI = class {
1561
2702
  * cannot be answered keeps its latest text with `asOfResolved: false` and
1562
2703
  * an `asOfReason`. The response adds `asOf` and `asOfSummary`.
1563
2704
  *
2705
+ * **In force today:** EU hits carry `inForce` (with `notInForceReason`,
2706
+ * `endOfValidity`, `entryIntoForce`) when the act's status is known;
2707
+ * `inForce: true` keeps only hits known to be in force today and reports
2708
+ * what it removed in `inForceFilter`.
2709
+ *
1564
2710
  * **Cost:** 5 credits for the search; with `asOf`, each live fetch of a
1565
2711
  * version the corpus does not hold reserves 5 and settles by outcome
1566
2712
  * (Cellar 4, browser 5, no text 1, failed 0) — at most 3 per request by
@@ -1571,7 +2717,59 @@ var LexAPI = class {
1571
2717
  return this.call({
1572
2718
  method: "POST",
1573
2719
  path: "/legislation/semantic",
1574
- body: semanticWireBody(request),
2720
+ shape: { lists: ["results"], required: ["results"] },
2721
+ body: semanticWireBody(request, { legislation: true }),
2722
+ idempotent: true,
2723
+ timeoutMs: options?.timeoutMs,
2724
+ signal: options?.signal
2725
+ });
2726
+ }
2727
+ /**
2728
+ * `POST /legislation/as-of` — the version of an EU regulation, directive
2729
+ * or decision listed for a date: the newest consolidated version dated on
2730
+ * or before it, or the act as published in the Official Journal when none
2731
+ * is. With `provision`, also that article, annex or recital range of the
2732
+ * version. Requires LexAPI API 2.26.0.
2733
+ *
2734
+ * **Unresolved is a normal return, not an error:** when the version or
2735
+ * the text cannot be established the call resolves with
2736
+ * `asOfResolved: false`, an `asOfReason` and no `provision`. Use
2737
+ * `provision.text` only when `asOfResolved` is `true`; `asOfVersion` can
2738
+ * also be present on an unresolved `provision` answer.
2739
+ * An unknown act throws `NotFoundError`; invalid input throws
2740
+ * `InvalidCelexError` / `InvalidParamsError`. An API older than 2.26.0
2741
+ * has no such endpoint and also answers 404 (`NotFoundError`).
2742
+ * `err.unknownEndpoint` is `false` there (the API sends it from 2.27.0):
2743
+ * check `err.message.includes("Unknown API endpoint")`.
2744
+ *
2745
+ * Consolidated versions have no legal force; only the act as published in
2746
+ * the Official Journal (`baseCelex`) is authentic. The answer does not say
2747
+ * whether an individual provision applied on that date, and
2748
+ * `act.inForceToday` is about today, not `asOf`. A retroactive amendment
2749
+ * counts from the date of the amending act.
2750
+ *
2751
+ * **Cost:** 1 credit when no text is fetched; when the provision's text
2752
+ * has to be fetched, 4 (5 when it is fetched live from EUR-Lex) whatever
2753
+ * the answer, and 1 if the fetch fails or finds no text. A fetch reserves
2754
+ * up to 5 credits: a pool holding fewer gets
2755
+ * `asOfReason: "insufficient_credits"`.
2756
+ */
2757
+ async legislationAsOf(request, options) {
2758
+ const body = { document: request.document, asOf: request.asOf };
2759
+ if (request.provision !== void 0) body["provision"] = request.provision;
2760
+ if (request.language !== void 0) body["language"] = request.language;
2761
+ return this.call({
2762
+ method: "POST",
2763
+ path: "/legislation/as-of",
2764
+ shape: {
2765
+ fields: [
2766
+ { path: "document", kind: "string" },
2767
+ { path: "asOfResolved", kind: "boolean" },
2768
+ { path: "act", kind: "object" },
2769
+ { path: "provenance", kind: "object" }
2770
+ ]
2771
+ },
2772
+ body,
1575
2773
  idempotent: true,
1576
2774
  timeoutMs: options?.timeoutMs,
1577
2775
  signal: options?.signal
@@ -1636,7 +2834,7 @@ var LexAPI = class {
1636
2834
  });
1637
2835
  }
1638
2836
  };
1639
- function semanticWireBody(request) {
2837
+ function semanticWireBody(request, { legislation }) {
1640
2838
  const body = { query: request.query };
1641
2839
  if (request.limit !== void 0) body["limit"] = request.limit;
1642
2840
  if (request.minScore !== void 0) body["min_score"] = request.minScore;
@@ -1644,15 +2842,44 @@ function semanticWireBody(request) {
1644
2842
  if (request.includeText) body["include"] = ["text"];
1645
2843
  if (request.filters !== void 0) body["filters"] = request.filters;
1646
2844
  if (request.hyde !== void 0) body["hyde"] = request.hyde;
1647
- if (request.asOf !== void 0) body["asOf"] = request.asOf;
2845
+ if (legislation && request.asOf !== void 0) body["asOf"] = request.asOf;
2846
+ if (legislation && request.inForce !== void 0) body["inForce"] = request.inForce;
1648
2847
  return body;
1649
2848
  }
2849
+ function nationalSemanticWireBody(request, { allowHyde = true, allowAsOf = false } = {}) {
2850
+ const body = { query: request.query };
2851
+ if (request.limit !== void 0) body["limit"] = request.limit;
2852
+ if (request.minScore !== void 0) body["min_score"] = request.minScore;
2853
+ if (request.language !== void 0) body["language"] = request.language;
2854
+ if (request.includeText) body["include"] = ["text"];
2855
+ if (request.filters !== void 0) body["filters"] = request.filters;
2856
+ if (allowHyde && request.hyde !== void 0) body["hyde"] = request.hyde;
2857
+ if (allowAsOf && request.asOf !== void 0) body["asOf"] = request.asOf;
2858
+ return body;
2859
+ }
2860
+ function jurisdictionSegment(jurisdiction) {
2861
+ return encodeURIComponent(jurisdiction.trim().toLowerCase());
2862
+ }
2863
+ function isLegacyCitationStatsCallOptions(value) {
2864
+ if (!value || typeof value !== "object") return false;
2865
+ if ("includeNational" in value) return false;
2866
+ return "timeoutMs" in value || "signal" in value;
2867
+ }
2868
+ function filterQuery(params) {
2869
+ return {
2870
+ citationType: listParam(params.citationType),
2871
+ provenance: listParam(params.provenance),
2872
+ jurisdictions: listParam(params.jurisdictions),
2873
+ resolution: listParam(params.resolution)
2874
+ };
2875
+ }
1650
2876
  function edgeQuery(params) {
1651
2877
  return {
1652
- citationType: params.citationType,
2878
+ ...filterQuery(params),
1653
2879
  limit: params.limit,
1654
2880
  offset: params.offset,
1655
- language: params.language
2881
+ language: params.language,
2882
+ includeNational: params.includeNational
1656
2883
  };
1657
2884
  }
1658
2885
  function timestampParam(value) {
@@ -1662,16 +2889,40 @@ function listParam(value) {
1662
2889
  if (value === void 0) return void 0;
1663
2890
  return typeof value === "string" ? value : value.join(",");
1664
2891
  }
1665
- async function* paginateEdges(fetchPage, rawRowsIn, params) {
1666
- const limit = params.limit ?? 100;
1667
- let offset = params.offset ?? 0;
2892
+ function edgeRows(group) {
2893
+ const listed = Array.isArray(group.citations) ? group.citations.length : 0;
2894
+ const counted = count(group.citationCount);
2895
+ return counted === void 0 || counted === 0 ? listed : counted;
2896
+ }
2897
+ async function* paginateEdges(fetchPage, groupsIn, params) {
2898
+ const start = startingPosition(params.offset, params.limit, 100);
2899
+ const limit = start.limit;
2900
+ let offset = start.offset;
2901
+ let previous;
2902
+ let repeats = 0;
1668
2903
  for (; ; ) {
1669
2904
  const page = await fetchPage({ ...params, limit, offset });
2905
+ const listed = groupsIn(page);
2906
+ const groups = Array.isArray(listed) ? listed : [];
2907
+ const echoed = count(page.offset);
2908
+ const totalEdges = count(page.totalEdges);
2909
+ if (echoed !== void 0 && echoed !== offset) throw stalled("the server did not advance", page);
2910
+ if (echoed === void 0 && totalEdges === void 0) {
2911
+ const form = compactForm(groups);
2912
+ repeats = form === previous ? repeats + 1 : 0;
2913
+ previous = form;
2914
+ if (repeats >= REPEATS_BEFORE_THROW) throw stalled("the server repeated the same page", page);
2915
+ } else {
2916
+ repeats = 0;
2917
+ previous = compactForm(groups);
2918
+ }
1670
2919
  yield page;
1671
- const pageLimit = page.limit && page.limit > 0 ? page.limit : limit;
1672
- const rows = rawRowsIn(page);
2920
+ const echoedLimit = count(page.limit);
2921
+ const pageLimit = echoedLimit !== void 0 && echoedLimit > 0 ? echoedLimit : limit;
2922
+ const rows = groups.reduce((n, g) => n + edgeRows(g), 0);
1673
2923
  offset += rows;
1674
2924
  if (rows === 0 || rows < pageLimit) return;
2925
+ if (totalEdges !== void 0 && offset >= totalEdges) return;
1675
2926
  }
1676
2927
  }
1677
2928
  function withHeaders(data, response, corpusVersion) {
@@ -1686,11 +2937,20 @@ function withHeaders(data, response, corpusVersion) {
1686
2937
  }
1687
2938
 
1688
2939
  // src/credits.ts
2940
+ function figure(value) {
2941
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2942
+ }
2943
+ function resetsAt(fromCredits, fromUsage) {
2944
+ if (typeof fromCredits === "string") return fromCredits;
2945
+ if (typeof fromUsage === "string") return fromUsage;
2946
+ return (fromCredits === null || fromCredits === void 0) && fromUsage === null ? null : void 0;
2947
+ }
1689
2948
  function getCreditUsage(response) {
2949
+ if (typeof response !== "object" || response === null) response = {};
1690
2950
  return {
1691
- unitsCharged: response.credits?.operation_weight ?? 0,
1692
- creditsRemaining: response.credits?.remaining ?? response.usage?.remaining,
1693
- resetsAt: response.credits?.resetsAt ?? response.usage?.resetsAt
2951
+ unitsCharged: figure(response.credits?.operation_weight) ?? 0,
2952
+ creditsRemaining: figure(response.credits?.remaining) ?? figure(response.usage?.remaining),
2953
+ resetsAt: resetsAt(response.credits?.resetsAt, response.usage?.resetsAt)
1694
2954
  };
1695
2955
  }
1696
2956
 
@@ -1720,6 +2980,9 @@ function assertSecret(secret) {
1720
2980
  "Webhook secret is empty \u2014 pass the secret returned when the webhook was created"
1721
2981
  );
1722
2982
  }
2983
+ if (!isWellFormed(secret)) {
2984
+ throw new WebhookSignatureError("missing_secret", "Webhook secret is not well-formed Unicode (lone surrogate)");
2985
+ }
1723
2986
  }
1724
2987
  async function getSubtle() {
1725
2988
  const globalCrypto = globalThis.crypto;
@@ -1733,8 +2996,18 @@ async function getSubtle() {
1733
2996
  if (nodeCrypto.webcrypto?.subtle) return nodeCrypto.webcrypto.subtle;
1734
2997
  throw new Error("Web Crypto (crypto.subtle) is not available in this runtime");
1735
2998
  }
2999
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
3000
+ function isWellFormed(text2) {
3001
+ const native = String.prototype.isWellFormed;
3002
+ return typeof native === "function" ? native.call(text2) : !LONE_SURROGATE.test(text2);
3003
+ }
1736
3004
  function toBytes(body) {
1737
- if (typeof body === "string") return new TextEncoder().encode(body);
3005
+ if (typeof body === "string") {
3006
+ if (!isWellFormed(body)) {
3007
+ throw new WebhookSignatureError("malformed_body", "Webhook body string is not well-formed Unicode (lone surrogate)");
3008
+ }
3009
+ return new TextEncoder().encode(body);
3010
+ }
1738
3011
  if (body instanceof Uint8Array) return body;
1739
3012
  return new Uint8Array(body);
1740
3013
  }
@@ -1743,6 +3016,37 @@ function toHex(buffer) {
1743
3016
  for (const byte of new Uint8Array(buffer)) hex += byte.toString(16).padStart(2, "0");
1744
3017
  return hex;
1745
3018
  }
3019
+ function trimHeader(value) {
3020
+ const space = (code) => code === 32 || code === 9 || code === 13 || code === 10;
3021
+ let start = 0;
3022
+ let end = value.length;
3023
+ while (start < end && space(value.charCodeAt(start))) start++;
3024
+ while (end > start && space(value.charCodeAt(end - 1))) end--;
3025
+ return value.slice(start, end);
3026
+ }
3027
+ 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}))$/;
3028
+ function timestampMicros(value) {
3029
+ if (typeof value !== "string") return void 0;
3030
+ const match = TIMESTAMP.exec(value);
3031
+ if (!match) return void 0;
3032
+ const [y, mo, d, h, mi, sec] = match.slice(1, 7).map(Number);
3033
+ const fraction = match[7];
3034
+ const sign = match[8];
3035
+ const offH = sign === void 0 ? 0 : Number(match[9]);
3036
+ const offM = sign === void 0 ? 0 : Number(match[10]);
3037
+ const leap = y % 4 === 0 && y % 100 !== 0 || y % 400 === 0;
3038
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1];
3039
+ if (y < 1 || days === void 0 || d < 1 || d > days || h > 23 || mi > 59 || sec > 59 || offH > 23 || offM > 59) return void 0;
3040
+ const date = /* @__PURE__ */ new Date(0);
3041
+ date.setUTCFullYear(y, mo - 1, d);
3042
+ date.setUTCHours(h, mi, sec, 0);
3043
+ const micros2 = fraction === void 0 ? 0 : Number(fraction.slice(0, 6).padEnd(6, "0"));
3044
+ const offset = (sign === "-" ? -1 : 1) * (offH * 60 + offM) * 6e7;
3045
+ return BigInt(date.getTime()) * BigInt(1e3) + BigInt(micros2) - BigInt(offset);
3046
+ }
3047
+ function micros(ms) {
3048
+ return BigInt(Math.round(ms * 1e3));
3049
+ }
1746
3050
  function timingSafeEqual(a, b) {
1747
3051
  if (a.length !== b.length) return false;
1748
3052
  let diff = 0;
@@ -1762,31 +3066,49 @@ async function computeSignature(rawBody, secret) {
1762
3066
  return toHex(await subtle.sign("HMAC", key, toBytes(rawBody)));
1763
3067
  }
1764
3068
  async function verifySignature(rawBody, signature, secret) {
1765
- const candidate = typeof signature === "string" ? signature.trim().toLowerCase() : "";
3069
+ const candidate = typeof signature === "string" ? trimHeader(signature) : "";
3070
+ assertSecret(secret);
3071
+ if (typeof rawBody === "string" && !isWellFormed(rawBody)) return false;
1766
3072
  const expected = await computeSignature(rawBody, secret);
1767
- if (!/^[0-9a-f]{64}$/.test(candidate)) return false;
1768
- return timingSafeEqual(expected, candidate);
3073
+ if (!/^[0-9a-fA-F]{64}$/.test(candidate)) return false;
3074
+ return timingSafeEqual(expected, candidate.toLowerCase());
1769
3075
  }
1770
3076
  async function verifyWebhook(rawBody, signature, secret, options = {}) {
1771
3077
  assertSecret(secret);
3078
+ const toleranceMs = options.toleranceMs ?? 3e5;
3079
+ if (typeof toleranceMs !== "number" || Number.isNaN(toleranceMs)) {
3080
+ throw new RangeError(`toleranceMs must be a number, got ${String(toleranceMs)}`);
3081
+ }
1772
3082
  if (!signature) {
1773
3083
  throw new WebhookSignatureError("missing_signature", "Missing X-Webhook-Signature header");
1774
3084
  }
1775
- if (!await verifySignature(rawBody, signature, secret)) {
3085
+ if (typeof rawBody === "string" && !isWellFormed(rawBody)) {
3086
+ throw new WebhookSignatureError("invalid_signature", "Webhook body string is not well-formed Unicode (lone surrogate)");
3087
+ }
3088
+ const bytes = toBytes(rawBody);
3089
+ if (!await verifySignature(bytes, signature, secret)) {
1776
3090
  throw new WebhookSignatureError("invalid_signature", "X-Webhook-Signature does not match the body");
1777
3091
  }
1778
3092
  let payload;
1779
3093
  try {
1780
- const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(toBytes(rawBody));
1781
- payload = JSON.parse(text);
3094
+ const text2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes);
3095
+ payload = JSON.parse(text2);
1782
3096
  } catch {
1783
3097
  throw new WebhookSignatureError("malformed_body", "Webhook body is not valid JSON");
1784
3098
  }
1785
- const toleranceMs = options.toleranceMs ?? 3e5;
1786
- if (toleranceMs > 0) {
1787
- const sentAt = Date.parse(String(payload.timestamp));
3099
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
3100
+ throw new WebhookSignatureError("malformed_body", "Webhook body is not a JSON object");
3101
+ }
3102
+ if (toleranceMs !== 0) {
3103
+ const sentAt = timestampMicros(payload.timestamp);
1788
3104
  const now = options.now ?? Date.now();
1789
- if (Number.isNaN(sentAt) || Math.abs(now - sentAt) > toleranceMs) {
3105
+ let fresh = sentAt !== void 0 && toleranceMs > 0;
3106
+ if (fresh && toleranceMs !== Infinity) {
3107
+ const distance = micros(now) - sentAt;
3108
+ const limit = micros(toleranceMs);
3109
+ fresh = distance <= limit && -distance <= limit;
3110
+ }
3111
+ if (!fresh) {
1790
3112
  throw new WebhookSignatureError(
1791
3113
  "stale_timestamp",
1792
3114
  `Webhook timestamp is outside the ${toleranceMs} ms tolerance window`
@@ -1797,12 +3119,37 @@ async function verifyWebhook(rawBody, signature, secret, options = {}) {
1797
3119
  }
1798
3120
 
1799
3121
  // src/types.ts
3122
+ var CITATION_TYPES = [
3123
+ "reference",
3124
+ "amendment",
3125
+ "repeal",
3126
+ "corrigendum",
3127
+ "implementation",
3128
+ "legal-basis",
3129
+ "proposal",
3130
+ "transposition"
3131
+ ];
3132
+ var CITATION_PROVENANCES = [
3133
+ "notice",
3134
+ "cellar",
3135
+ "notice+cellar",
3136
+ "cellar-nim",
3137
+ "source",
3138
+ "resolver"
3139
+ ];
3140
+ var CITATION_RESOLUTIONS = [
3141
+ "id",
3142
+ "key",
3143
+ "abbreviation",
3144
+ "text-pattern"
3145
+ ];
1800
3146
  var AS_OF_REASONS = [
1801
3147
  "not_yet_adopted",
1802
3148
  "not_yet_in_force",
1803
3149
  "no_longer_in_force",
1804
3150
  "in_force_dates_unknown",
1805
3151
  "not_in_language",
3152
+ "amendment_not_consolidated",
1806
3153
  "text_unavailable",
1807
3154
  "article_not_in_version",
1808
3155
  "part_not_resolvable",
@@ -1818,12 +3165,52 @@ var AS_OF_REASONS = [
1818
3165
  "insufficient_credits",
1819
3166
  "credit_check_failed"
1820
3167
  ];
3168
+ var AS_OF_LOOKUP_REASONS = [
3169
+ "not_yet_adopted",
3170
+ "not_yet_in_force",
3171
+ "no_longer_in_force",
3172
+ "in_force_dates_unknown",
3173
+ "act_type_not_supported",
3174
+ "version_list_unavailable",
3175
+ "version_lookup_cap",
3176
+ "not_in_language",
3177
+ "amendment_not_consolidated",
3178
+ "text_unavailable",
3179
+ "article_not_in_version",
3180
+ "provision_ambiguous",
3181
+ "version_not_parsed",
3182
+ "fetch_budget_exhausted",
3183
+ "fetch_pending",
3184
+ "fetch_capacity",
3185
+ "fetch_failed",
3186
+ "fetch_timeout",
3187
+ "request_deadline",
3188
+ "insufficient_credits",
3189
+ "credit_check_failed"
3190
+ ];
3191
+ function isNationalDecision(document2) {
3192
+ return document2.documentKind === "decision" && document2.decision != null;
3193
+ }
3194
+ var NATIONAL_AS_OF_REASONS = [
3195
+ "provision_amended_since",
3196
+ "no_longer_in_force",
3197
+ "provision_dates_unknown",
3198
+ "asof_not_available"
3199
+ ];
3200
+ function isNationalAsOfVersion(version) {
3201
+ return typeof version === "object" && version !== null && version.kind === "current_unit";
3202
+ }
1821
3203
  export {
3204
+ AS_OF_LOOKUP_REASONS,
1822
3205
  AS_OF_REASONS,
1823
3206
  AuthenticationError,
3207
+ CITATION_PROVENANCES,
3208
+ CITATION_RESOLUTIONS,
3209
+ CITATION_TYPES,
1824
3210
  CreditsExhaustedError,
1825
3211
  DEFAULT_BASE_URL,
1826
3212
  DEFAULT_TIMEOUT_MS,
3213
+ DocumentWithdrawnError,
1827
3214
  IncompleteExportError,
1828
3215
  InternalServerError,
1829
3216
  InvalidCelexError,
@@ -1832,8 +3219,14 @@ export {
1832
3219
  InvalidUrlError,
1833
3220
  LexAPI,
1834
3221
  LexAPIError,
3222
+ NATIONAL_AS_OF_REASONS,
3223
+ NationalAllowanceExhaustedError,
3224
+ NationalSemanticFilterUnreachableError,
3225
+ NationalSemanticNotEnabledError,
3226
+ NationalSemanticUnavailableError,
1835
3227
  NetworkError,
1836
3228
  NotFoundError,
3229
+ PaymentPastDueError,
1837
3230
  RateLimitedError,
1838
3231
  RequestAbortedError,
1839
3232
  ServiceUnavailableError,
@@ -1849,6 +3242,8 @@ export {
1849
3242
  computeSignature,
1850
3243
  getCreditUsage,
1851
3244
  isLexAPIError,
3245
+ isNationalAsOfVersion,
3246
+ isNationalDecision,
1852
3247
  normalizeRetryAfterSeconds,
1853
3248
  parseResponseHeaders,
1854
3249
  verifySignature,