@lexapi/client 0.4.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.cjs CHANGED
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ AS_OF_LOOKUP_REASONS: () => AS_OF_LOOKUP_REASONS,
23
24
  AS_OF_REASONS: () => AS_OF_REASONS,
24
25
  AuthenticationError: () => AuthenticationError,
25
26
  CITATION_PROVENANCES: () => CITATION_PROVENANCES,
@@ -37,12 +38,14 @@ __export(index_exports, {
37
38
  InvalidUrlError: () => InvalidUrlError,
38
39
  LexAPI: () => LexAPI,
39
40
  LexAPIError: () => LexAPIError,
41
+ NATIONAL_AS_OF_REASONS: () => NATIONAL_AS_OF_REASONS,
40
42
  NationalAllowanceExhaustedError: () => NationalAllowanceExhaustedError,
41
43
  NationalSemanticFilterUnreachableError: () => NationalSemanticFilterUnreachableError,
42
44
  NationalSemanticNotEnabledError: () => NationalSemanticNotEnabledError,
43
45
  NationalSemanticUnavailableError: () => NationalSemanticUnavailableError,
44
46
  NetworkError: () => NetworkError,
45
47
  NotFoundError: () => NotFoundError,
48
+ PaymentPastDueError: () => PaymentPastDueError,
46
49
  RateLimitedError: () => RateLimitedError,
47
50
  RequestAbortedError: () => RequestAbortedError,
48
51
  ServiceUnavailableError: () => ServiceUnavailableError,
@@ -58,6 +61,7 @@ __export(index_exports, {
58
61
  computeSignature: () => computeSignature,
59
62
  getCreditUsage: () => getCreditUsage,
60
63
  isLexAPIError: () => isLexAPIError,
64
+ isNationalAsOfVersion: () => isNationalAsOfVersion,
61
65
  isNationalDecision: () => isNationalDecision,
62
66
  normalizeRetryAfterSeconds: () => normalizeRetryAfterSeconds,
63
67
  parseResponseHeaders: () => parseResponseHeaders,
@@ -66,6 +70,91 @@ __export(index_exports, {
66
70
  });
67
71
  module.exports = __toCommonJS(index_exports);
68
72
 
73
+ // src/retryHints.ts
74
+ function normalizeRetryAfterSeconds(value) {
75
+ if (!Number.isFinite(value)) return 0;
76
+ if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
77
+ if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
78
+ return Math.max(0, value);
79
+ }
80
+ function trimSpaces(value) {
81
+ return value.replace(/^[ \t]+|[ \t]+$/g, "");
82
+ }
83
+ function decimalSeconds(raw) {
84
+ if (typeof raw !== "string") return void 0;
85
+ const value = trimSpaces(raw);
86
+ if (!/^[0-9]+(\.[0-9]+)?$/.test(value)) return void 0;
87
+ const seconds = Number(value);
88
+ return Number.isFinite(seconds) ? normalizeRetryAfterSeconds(seconds) : void 0;
89
+ }
90
+ function bodySeconds(value) {
91
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
92
+ return normalizeRetryAfterSeconds(value);
93
+ }
94
+ var DAYS = "Mon|Tue|Wed|Thu|Fri|Sat|Sun";
95
+ var LONG_DAYS = "Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday";
96
+ var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
97
+ var MONTH = MONTHS.join("|");
98
+ var TIME = "([0-9]{2}):([0-9]{2}):([0-9]{2})";
99
+ var ZONE = "(?:GMT|UTC|\\+0000)";
100
+ var IMF_FIXDATE = new RegExp(`^(?:${DAYS}), ([0-9]{2}) (${MONTH}) ([0-9]{4}) ${TIME} ${ZONE}$`, "i");
101
+ var RFC850_DATE = new RegExp(`^(?:${LONG_DAYS}), ([0-9]{2})-(${MONTH})-([0-9]{2}) ${TIME} ${ZONE}$`, "i");
102
+ var ASCTIME_DATE = new RegExp(`^(?:${DAYS}) (${MONTH}) ([0-9]{2}| [0-9]) ${TIME} ([0-9]{4})$`, "i");
103
+ function dateKey(year, month, day, h, m, s) {
104
+ return ((((year * 12 + month) * 31 + day) * 24 + h) * 60 + m) * 60 + s;
105
+ }
106
+ function fullYear(twoDigits, month, day, h, m, s, now) {
107
+ const at = new Date(now);
108
+ const limit = dateKey(at.getUTCFullYear() + 50, at.getUTCMonth(), at.getUTCDate(), at.getUTCHours(), at.getUTCMinutes(), at.getUTCSeconds());
109
+ const monthIndex = MONTHS.indexOf(month.toLowerCase());
110
+ let year = Math.floor(at.getUTCFullYear() / 100) * 100 + 100 + twoDigits;
111
+ while (dateKey(year, monthIndex, day, h, m, s) > limit) year -= 100;
112
+ return year;
113
+ }
114
+ function utcMs(year, month, day, h, m, s) {
115
+ const monthIndex = MONTHS.indexOf(month.toLowerCase());
116
+ if (monthIndex < 0 || h > 23 || m > 59 || s > 59 || day < 1) return void 0;
117
+ const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
118
+ const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][monthIndex];
119
+ if (day > daysInMonth) return void 0;
120
+ const date = /* @__PURE__ */ new Date(0);
121
+ date.setUTCFullYear(year, monthIndex, day);
122
+ date.setUTCHours(h, m, s, 0);
123
+ return date.getTime();
124
+ }
125
+ function httpDateMs(value, now = Date.now()) {
126
+ let match = IMF_FIXDATE.exec(value);
127
+ if (match) {
128
+ const [, day, month, year, h, m, s] = match;
129
+ return utcMs(Number(year), month, Number(day), Number(h), Number(m), Number(s));
130
+ }
131
+ match = RFC850_DATE.exec(value);
132
+ if (match) {
133
+ const [, day, month, year, h, m, s] = match;
134
+ const [d, hh, mm, ss] = [Number(day), Number(h), Number(m), Number(s)];
135
+ return utcMs(fullYear(Number(year), month, d, hh, mm, ss, now), month, d, hh, mm, ss);
136
+ }
137
+ match = ASCTIME_DATE.exec(value);
138
+ if (match) {
139
+ const [, month, day, h, m, s, year] = match;
140
+ return utcMs(Number(year), month, Number(day.trim()), Number(h), Number(m), Number(s));
141
+ }
142
+ return void 0;
143
+ }
144
+ function retryAfterHeaderSeconds(raw) {
145
+ if (typeof raw !== "string") return void 0;
146
+ const value = trimSpaces(raw);
147
+ if (/^[0-9]/.test(value)) return decimalSeconds(value);
148
+ const now = Date.now();
149
+ const date = httpDateMs(value, now);
150
+ return date === void 0 ? void 0 : Math.max(0, Math.round((date - now) / 1e3));
151
+ }
152
+ var MAX_TIMER_MS = 2 ** 31 - 1;
153
+ function timerDelay(ms) {
154
+ if (Number.isNaN(ms)) return 0;
155
+ return Math.min(Math.max(ms, 0), MAX_TIMER_MS);
156
+ }
157
+
69
158
  // src/errors.ts
70
159
  var STATUS_TO_CODE = {
71
160
  400: "INVALID_PARAMS",
@@ -86,6 +175,8 @@ var STATUS_TO_CODE = {
86
175
  524: "TIMEOUT"
87
176
  };
88
177
  var ERROR_KINDS = /* @__PURE__ */ Symbol.for("@lexapi/client.errorKinds");
178
+ var EXCERPTS = /* @__PURE__ */ new WeakMap();
179
+ var INVALID_BODIES = /* @__PURE__ */ new WeakMap();
89
180
  function collectKinds(ctor) {
90
181
  const kinds = [];
91
182
  let current = ctor;
@@ -121,8 +212,8 @@ var LexAPIError = class _LexAPIError extends Error {
121
212
  * Seconds to wait before retrying, when the server said so (429; also the
122
213
  * 503 of an incomplete national semantic search).
123
214
  * Sourced from the `Retry-After` response HEADER first; the JSON
124
- * `retryAfter` body field is only a fallback because it historically
125
- * carried buggy epoch-seconds values (epoch-looking values are
215
+ * `retryAfter` body field is only a fallback because it can carry
216
+ * epoch-seconds values (epoch-looking values are
126
217
  * normalized to a delta).
127
218
  */
128
219
  retryAfter;
@@ -143,64 +234,89 @@ var LexAPIError = class _LexAPIError extends Error {
143
234
  this.retryAfter = retryAfter;
144
235
  this.body = context?.body;
145
236
  this.headers = context?.headers;
237
+ if (context?.bodyExcerpt !== void 0) EXCERPTS.set(this, context.bodyExcerpt);
146
238
  Object.defineProperty(this, ERROR_KINDS, { value: collectKinds(new.target), enumerable: false });
147
239
  }
240
+ /**
241
+ * For a response body that is not JSON, its first 200 characters (code
242
+ * points); `undefined` otherwise. Raw response text; may contain document
243
+ * text; do not show to a model or log by default. Not an own property of
244
+ * the error, so `console.log` (also with `%o`), `util.inspect` with
245
+ * `showHidden` or with `getters`, `JSON.stringify`, spread and
246
+ * `structuredClone` leave it out (`util.inspect` with `showHidden` and
247
+ * `getters` together shows it); never part of `message`. Assigning to it
248
+ * replaces it (`undefined` clears it).
249
+ */
250
+ get bodyExcerpt() {
251
+ return EXCERPTS.get(this);
252
+ }
253
+ set bodyExcerpt(value) {
254
+ if (value === void 0) EXCERPTS.delete(this);
255
+ else EXCERPTS.set(this, value);
256
+ }
148
257
  /**
149
258
  * Build the most specific error subclass for a non-2xx response.
150
259
  * Accepts both the typed envelope and the legacy bare `{error, message}` shape.
260
+ * `code` and `message` are read only when they are non-empty strings.
151
261
  */
152
- static fromResponse(status, body, headerRetryAfter, headers) {
262
+ static fromResponse(status, body, headerRetryAfter, headers, bodyExcerpt) {
153
263
  const statusCode = STATUS_TO_CODE[status];
154
264
  let code = statusCode ?? "INTERNAL";
155
265
  let typedCode = false;
156
266
  let message = `HTTP ${status}`;
157
267
  let details;
158
268
  let retryAfter = headerRetryAfter;
159
- let resetsAt;
269
+ let resetsAt2;
160
270
  if (typeof body === "object" && body !== null) {
161
271
  const record = body;
162
272
  const err = record["error"];
163
- if (typeof err === "object" && err !== null) {
273
+ const topCode = nonEmptyString(record["code"]);
274
+ const topMessage = nonEmptyString(record["message"]);
275
+ if (typeof err === "object" && err !== null && !Array.isArray(err)) {
164
276
  const e = err;
165
- if (typeof e["code"] === "string") {
166
- code = e["code"];
277
+ const typed = nonEmptyString(e["code"]);
278
+ if (typed !== void 0) {
279
+ code = typed;
167
280
  typedCode = true;
168
281
  }
169
- if (typeof e["message"] === "string") message = e["message"];
282
+ message = nonEmptyString(e["message"]) ?? message;
170
283
  details = e["details"];
171
- } else if (typeof err === "string") {
172
- if (typeof record["code"] === "string" && record["code"] !== "") {
173
- code = record["code"];
284
+ } else if (typeof err === "string" && err !== "") {
285
+ if (topCode !== void 0) {
286
+ code = topCode;
174
287
  typedCode = true;
175
288
  }
176
- message = typeof record["message"] === "string" && record["message"] !== err ? `${err}: ${record["message"]}` : err;
289
+ message = topMessage !== void 0 && topMessage !== err ? `${err}: ${topMessage}` : err;
177
290
  details = record["details"];
178
291
  } else {
179
- if (typeof record["code"] === "string" && record["code"] !== "") {
180
- code = record["code"];
292
+ if (topCode !== void 0) {
293
+ code = topCode;
181
294
  typedCode = true;
182
295
  }
183
- if (typeof record["message"] === "string") message = record["message"];
296
+ message = topMessage ?? message;
184
297
  details = record["details"];
185
298
  }
186
299
  if (retryAfter === void 0 && (status === 429 || status === 503 && code === "NATIONAL_SEMANTIC_UNAVAILABLE")) {
187
- const jsonRetryAfter = readNumber(record["retryAfter"]) ?? readNumber(detailsField(details, "retryAfter"));
188
- if (jsonRetryAfter !== void 0) retryAfter = normalizeRetryAfterSeconds(jsonRetryAfter);
300
+ retryAfter = bodyWait(record, details);
189
301
  }
190
- resetsAt = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
302
+ resetsAt2 = readString(detailsField(details, "resetsAt")) ?? readString(usageField(record, "resetsAt"));
191
303
  }
192
- const context = { body, ...headers ? { headers } : {} };
304
+ const context = {
305
+ body,
306
+ ...headers ? { headers } : {},
307
+ ...bodyExcerpt !== void 0 ? { bodyExcerpt } : {}
308
+ };
193
309
  if (!typedCode && statusCode === void 0 && status < 500) {
194
310
  return new _LexAPIError(code, message, status, details, retryAfter, context);
195
311
  }
196
- if (code === "QUOTA_EXHAUSTED" || code === "RATE_LIMITED" && isQuota429(body, headers)) {
312
+ if (code === "QUOTA_EXHAUSTED" || status === 429 && hasQuotaCode(body) || status === 429 && code === "RATE_LIMITED" && isQuota429(body, headers)) {
197
313
  return new RateLimitedError(
198
314
  message,
199
315
  status,
200
316
  details,
201
- void 0,
317
+ status === 429 ? void 0 : retryAfter,
202
318
  context,
203
- code === "QUOTA_EXHAUSTED" ? "QUOTA_EXHAUSTED" : "RATE_LIMITED"
319
+ code === "RATE_LIMITED" ? "RATE_LIMITED" : "QUOTA_EXHAUSTED"
204
320
  );
205
321
  }
206
322
  switch (code) {
@@ -216,8 +332,10 @@ var LexAPIError = class _LexAPIError extends Error {
216
332
  return new RateLimitedError(message, status, details, retryAfter, context);
217
333
  case "TIER_FORBIDDEN":
218
334
  return new TierForbiddenError(message, status, details, retryAfter, context);
335
+ case "PAYMENT_PAST_DUE":
336
+ return new PaymentPastDueError(message, status, details, retryAfter, context);
219
337
  case "CREDITS_EXHAUSTED":
220
- return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt, context);
338
+ return new CreditsExhaustedError(message, status, details, retryAfter, resetsAt2, context);
221
339
  case "NATIONAL_ALLOWANCE_EXHAUSTED":
222
340
  return new NationalAllowanceExhaustedError(message, status, details, retryAfter, context);
223
341
  case "NATIONAL_SEMANTIC_NOT_ENABLED":
@@ -249,7 +367,107 @@ var NotFoundError = class extends LexAPIError {
249
367
  super("NOT_FOUND", message, status, details, retryAfter, context);
250
368
  this.name = "NotFoundError";
251
369
  }
370
+ /**
371
+ * `true` when the API (2.27.0 or later) has no such endpoint
372
+ * (`details.reason` is `"unknown_endpoint"`): a mistyped path, a method
373
+ * newer than the API, or a national route for a country that is not
374
+ * available. Always `false` on APIs before 2.27.0; there the message
375
+ * contains "Unknown API endpoint". Read from `details` only, never from
376
+ * the message.
377
+ */
378
+ get unknownEndpoint() {
379
+ return ownField(this.details, "reason") === "unknown_endpoint";
380
+ }
381
+ // The accessors below read `details` only when it is a plain JSON object,
382
+ // and only its own keys; anything else gives each accessor's default.
383
+ /**
384
+ * `details.reason` when it is a string: `unknown_endpoint`, or on
385
+ * `getDocumentAtDate` (API 2.28.0) `before_tracking` / `boundary_unknown`.
386
+ * `undefined` on a 404 without one (e.g. a document not in the corpus).
387
+ */
388
+ get reason() {
389
+ return readString(ownField(this.details, "reason"));
390
+ }
391
+ /**
392
+ * `true` when `getDocumentAtDate` was asked about a date before the
393
+ * document entered the corpus (`details.reason` is `"before_tracking"`);
394
+ * {@link trackedSince} says when that was.
395
+ */
396
+ get beforeTracking() {
397
+ return ownField(this.details, "reason") === "before_tracking";
398
+ }
399
+ /**
400
+ * `true` when LexAPI has no record of when a version stored before API
401
+ * 2.28.0 began, so it cannot say which snapshot it held on the date and
402
+ * does not guess (`details.reason` is `"boundary_unknown"`). Refunded.
403
+ * Read the {@link candidates} with `getDocumentVersion`.
404
+ */
405
+ get boundaryUnknown() {
406
+ return ownField(this.details, "reason") === "boundary_unknown";
407
+ }
408
+ /** `before_tracking` only: when the document entered the corpus (`details.trackedSince`). */
409
+ get trackedSince() {
410
+ return readString(ownField(this.details, "trackedSince"));
411
+ }
412
+ /**
413
+ * On `before_tracking` for an EU act: the request that answers which
414
+ * version is listed for a date (`legislationAsOf`).
415
+ */
416
+ get inForceLookup() {
417
+ const value = ownField(this.details, "inForceLookup");
418
+ if (!isPlainJsonObject(value)) return void 0;
419
+ const lookup2 = {};
420
+ const method = readString(ownField(value, "method"));
421
+ const path = readString(ownField(value, "path"));
422
+ if (method !== void 0) lookup2.method = method;
423
+ if (path !== void 0) lookup2.path = path;
424
+ return lookup2;
425
+ }
426
+ /**
427
+ * `boundary_unknown` only: the versions the date could fall in — the
428
+ * first 10 items of `details.candidates`
429
+ * that are objects with an integer `version` (`fetchedAt` / `observedFrom`
430
+ * are `null` when not strings). `[]` when there are none. For these
431
+ * versions `fetchedAt` can be the last fetch and later than the date.
432
+ */
433
+ get candidates() {
434
+ return readCandidates(this.details).kept;
435
+ }
436
+ /**
437
+ * `boundary_unknown` only: `true` when more versions matched than
438
+ * {@link candidates} lists (`details.candidatesTruncated` is `true`, or
439
+ * more than 10 usable candidates were sent).
440
+ */
441
+ get candidatesTruncated() {
442
+ return ownField(this.details, "candidatesTruncated") === true || readCandidates(this.details).more;
443
+ }
252
444
  };
445
+ var MAX_SNAPSHOT_CANDIDATES = 10;
446
+ function readCandidates(details) {
447
+ const list = ownField(details, "candidates");
448
+ const kept = [];
449
+ if (!Array.isArray(list)) return { kept, more: false };
450
+ for (const item of list) {
451
+ const version = ownField(item, "version");
452
+ if (typeof version !== "number" || !Number.isInteger(version)) continue;
453
+ if (kept.length === MAX_SNAPSHOT_CANDIDATES) return { kept, more: true };
454
+ const fetchedAt = ownField(item, "fetchedAt");
455
+ const observedFrom = ownField(item, "observedFrom");
456
+ kept.push({
457
+ version: version + 0,
458
+ // -0 → 0
459
+ fetchedAt: typeof fetchedAt === "string" ? fetchedAt : null,
460
+ observedFrom: typeof observedFrom === "string" ? observedFrom : null
461
+ });
462
+ }
463
+ return { kept, more: false };
464
+ }
465
+ function isPlainJsonObject(value) {
466
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
467
+ }
468
+ function ownField(value, key) {
469
+ return isPlainJsonObject(value) && Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
470
+ }
253
471
  var InvalidCelexError = class extends LexAPIError {
254
472
  static kind = "InvalidCelexError";
255
473
  constructor(message, status = 400, details, retryAfter, context) {
@@ -308,14 +526,14 @@ var RateLimitedError = class extends LexAPIError {
308
526
  /**
309
527
  * `true` for a legacy-plan quota 429 (daily call quota, or the monthly
310
528
  * semantic quota) rather than the per-minute limiter (SDK contract §1.2):
311
- * `code` is `QUOTA_EXHAUSTED`, or — servers before lex-api #304, which
529
+ * `code` is `QUOTA_EXHAUSTED`, or — servers before API 2.4.0, which
312
530
  * send no code — the body carries `usage.resetsAt` with neither a
313
531
  * `Retry-After` header nor a `retryAfter` body field. It cannot succeed
314
532
  * before `resetsAt`, so the SDK does not retry it and `retryAfter` is
315
533
  * `undefined`.
316
534
  */
317
535
  get quotaExhausted() {
318
- return this.code === "QUOTA_EXHAUSTED" || isQuota429(this.body, this.headers);
536
+ return this.code === "QUOTA_EXHAUSTED" || this.status === 429 && this.code === "RATE_LIMITED" && isQuota429(this.body, this.headers);
319
537
  }
320
538
  /** When a legacy quota resets: the body's `resetsAt`, else `usage.resetsAt`. */
321
539
  get resetsAt() {
@@ -324,19 +542,34 @@ var RateLimitedError = class extends LexAPIError {
324
542
  };
325
543
  var TierForbiddenError = class extends LexAPIError {
326
544
  static kind = "TierForbiddenError";
327
- constructor(message, status = 403, details, retryAfter, context) {
328
- super("TIER_FORBIDDEN", message, status, details, retryAfter, context);
545
+ constructor(message, status = 403, details, retryAfter, context, code = "TIER_FORBIDDEN") {
546
+ super(code, message, status, details, retryAfter, context);
329
547
  this.name = "TierForbiddenError";
330
548
  }
331
549
  };
550
+ var PaymentPastDueError = class extends TierForbiddenError {
551
+ static kind = "PaymentPastDueError";
552
+ constructor(message, status = 403, details, retryAfter, context) {
553
+ super(message, status, details, retryAfter, context, "PAYMENT_PAST_DUE");
554
+ this.name = "PaymentPastDueError";
555
+ }
556
+ /** When API access ended (ISO date-time); `undefined` when the server does not say. */
557
+ get accessEndedAt() {
558
+ return readString(detailsOrBodyField(this.details, this.body, "accessEndedAt"));
559
+ }
560
+ /** Where to pay the open invoice (absolute URL of the dashboard's billing page). */
561
+ get billingUrl() {
562
+ return readString(detailsOrBodyField(this.details, this.body, "billingUrl"));
563
+ }
564
+ };
332
565
  var CreditsExhaustedError = class extends LexAPIError {
333
566
  static kind = "CreditsExhaustedError";
334
567
  /** When the monthly credit allowance resets (ISO date-time), when the server said so. */
335
568
  resetsAt;
336
- constructor(message, status = 402, details, retryAfter, resetsAt, context) {
569
+ constructor(message, status = 402, details, retryAfter, resetsAt2, context) {
337
570
  super("CREDITS_EXHAUSTED", message, status, details, retryAfter, context);
338
571
  this.name = "CreditsExhaustedError";
339
- this.resetsAt = resetsAt;
572
+ this.resetsAt = resetsAt2;
340
573
  }
341
574
  /** The refused operation's credit weight (`details.weight`). */
342
575
  get weight() {
@@ -504,14 +737,25 @@ var RequestAbortedError = class extends LexAPIError {
504
737
  };
505
738
  var InvalidResponseError = class extends LexAPIError {
506
739
  static kind = "InvalidResponseError";
507
- constructor(message, status, rawText, context) {
508
- super("INVALID_RESPONSE", message, status, void 0, void 0, {
509
- ...context,
510
- body: rawText === void 0 ? void 0 : rawText.slice(0, 500)
511
- });
740
+ constructor(message, status, body, context) {
741
+ super("INVALID_RESPONSE", message, status, void 0, void 0, context);
742
+ delete this.body;
743
+ if (body !== void 0) INVALID_BODIES.set(this, body);
512
744
  this.name = "InvalidResponseError";
513
745
  }
514
746
  };
747
+ Object.defineProperty(InvalidResponseError.prototype, "body", {
748
+ get() {
749
+ return INVALID_BODIES.get(this);
750
+ },
751
+ // Assigning replaces the stored value (`undefined` clears it), as on 0.4.0.
752
+ set(value) {
753
+ if (value === void 0) INVALID_BODIES.delete(this);
754
+ else INVALID_BODIES.set(this, value);
755
+ },
756
+ enumerable: false,
757
+ configurable: true
758
+ });
515
759
  var IncompleteExportError = class extends LexAPIError {
516
760
  static kind = "IncompleteExportError";
517
761
  /** Rows yielded before the stream ended. */
@@ -529,15 +773,19 @@ var IncompleteExportError = class extends LexAPIError {
529
773
  function isLexAPIError(value, errorClass) {
530
774
  return value instanceof (errorClass ?? LexAPIError);
531
775
  }
532
- function normalizeRetryAfterSeconds(value) {
533
- if (!Number.isFinite(value)) return 0;
534
- if (value > 1e12) return Math.max(0, Math.round((value - Date.now()) / 1e3));
535
- if (value > 1e9) return Math.max(0, Math.round(value - Date.now() / 1e3));
536
- return Math.max(0, value);
537
- }
538
776
  function readNumber(value) {
539
777
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
540
778
  }
779
+ function bodyDetails(body) {
780
+ const err = detailsField(body, "error");
781
+ return typeof err === "object" && err !== null && !Array.isArray(err) ? detailsField(err, "details") : detailsField(body, "details");
782
+ }
783
+ function bodyWait(body, details) {
784
+ return bodySeconds(detailsField(body, "retryAfter")) ?? bodySeconds(detailsField(details, "retryAfter"));
785
+ }
786
+ function nonEmptyString(value) {
787
+ return typeof value === "string" && value !== "" ? value : void 0;
788
+ }
541
789
  function readString(value) {
542
790
  return typeof value === "string" ? value : void 0;
543
791
  }
@@ -547,12 +795,15 @@ function detailsField(details, key) {
547
795
  }
548
796
  return void 0;
549
797
  }
798
+ function hasQuotaCode(body) {
799
+ return detailsField(body, "code") === "QUOTA_EXHAUSTED" || detailsField(bodyField(body, "error"), "code") === "QUOTA_EXHAUSTED";
800
+ }
550
801
  function isQuota429(body, headers) {
551
- if (detailsField(body, "code") === "QUOTA_EXHAUSTED") return true;
552
- const resetsAt = detailsField(detailsField(body, "usage"), "resetsAt");
553
- if (typeof resetsAt !== "string") return false;
554
- if (headers?.retryAfter !== void 0 && headers.retryAfter.trim() !== "") return false;
555
- return detailsField(body, "retryAfter") === void 0;
802
+ if (hasQuotaCode(body)) return true;
803
+ const resetsAt2 = detailsField(detailsField(body, "usage"), "resetsAt");
804
+ if (typeof resetsAt2 !== "string") return false;
805
+ if (retryAfterHeaderSeconds(headers?.retryAfter) !== void 0) return false;
806
+ return bodyWait(body, bodyDetails(body)) === void 0;
556
807
  }
557
808
  function detailsOrBodyField(details, body, key) {
558
809
  const fromDetails = detailsField(details, key);
@@ -570,11 +821,15 @@ function str(headers, name) {
570
821
  const value = headers.get(name);
571
822
  return value === null ? void 0 : value;
572
823
  }
824
+ function parseHeaderInteger(value) {
825
+ if (typeof value !== "string") return void 0;
826
+ const text2 = value.replace(/^[ \t]+|[ \t]+$/g, "");
827
+ if (!/^[0-9]+$/.test(text2)) return void 0;
828
+ const parsed = Number(text2);
829
+ return Number.isSafeInteger(parsed) ? parsed : void 0;
830
+ }
573
831
  function int(headers, name) {
574
- const value = headers.get(name);
575
- if (value === null) return void 0;
576
- const parsed = Number.parseInt(value, 10);
577
- return Number.isNaN(parsed) ? void 0 : parsed;
832
+ return parseHeaderInteger(headers.get(name));
578
833
  }
579
834
  function compact(obj) {
580
835
  const out = {};
@@ -630,11 +885,12 @@ function parseResponseHeaders(source) {
630
885
  }
631
886
 
632
887
  // src/version.ts
633
- var VERSION = "0.4.0";
888
+ var VERSION = "0.5.0";
634
889
 
635
890
  // src/http.ts
636
891
  var DEFAULT_BASE_URL = "https://lex-api.com/api/v1";
637
892
  var DEFAULT_TIMEOUT_MS = 95e3;
893
+ var KIND_NAMES = { object: "an object", string: "a string", boolean: "a boolean" };
638
894
  var NEVER_REACHED_CODES = /* @__PURE__ */ new Set([
639
895
  // DNS
640
896
  "ENOTFOUND",
@@ -672,6 +928,33 @@ var CONNECT_SYSCALL_CODES = /* @__PURE__ */ new Set(["ETIMEDOUT"]);
672
928
  var NEVER_REACHED_STATUSES = /* @__PURE__ */ new Set([521, 522, 523]);
673
929
  var ORIGIN_DEPENDENT_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
674
930
  var PROXY_STATUSES = /* @__PURE__ */ new Set([520, 524]);
931
+ var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
932
+ var MAX_REDIRECTS = 5;
933
+ function redirectTarget(location, from) {
934
+ let to;
935
+ try {
936
+ to = new URL(location, from);
937
+ } catch {
938
+ throw new NetworkError("Refused to follow a redirect with an invalid Location header");
939
+ }
940
+ if (to.protocol !== "http:" && to.protocol !== "https:") {
941
+ throw new NetworkError("Refused to follow a redirect to a URL that is not http(s)");
942
+ }
943
+ if (to.username !== "" || to.password !== "") {
944
+ throw new NetworkError(`Refused to follow a redirect to a URL that carries credentials (${to.origin})`);
945
+ }
946
+ const httpsUpgrade = from.protocol === "http:" && to.protocol === "https:" && to.hostname === from.hostname && from.port === "" && to.port === "";
947
+ if (to.origin !== from.origin && !httpsUpgrade) {
948
+ throw new NetworkError(`Refused to follow a redirect to another origin (${to.origin})`);
949
+ }
950
+ return to;
951
+ }
952
+ function discardBody(response) {
953
+ try {
954
+ response.body?.cancel().catch(() => void 0);
955
+ } catch {
956
+ }
957
+ }
675
958
  function isNeverReachedError(error, depth = 0) {
676
959
  if (depth > 6 || typeof error !== "object" || error === null) return false;
677
960
  const { code, syscall, cause, errors } = error;
@@ -717,7 +1000,10 @@ var HttpClient = class {
717
1000
  [INSPECT]() {
718
1001
  return `HttpClient { baseUrl: '${this.opts.baseUrl}', apiKey: '[redacted]' }`;
719
1002
  }
720
- /** Perform a request and parse the JSON body (204 / empty body yields `{}`). */
1003
+ /**
1004
+ * Perform a request and parse the JSON body. A 2xx that is not the
1005
+ * documented shape (`options.shape`) throws `InvalidResponseError`.
1006
+ */
721
1007
  async requestJson(options) {
722
1008
  const { data } = await this.requestJsonWithResponse(options);
723
1009
  return data;
@@ -728,7 +1014,7 @@ var HttpClient = class {
728
1014
  */
729
1015
  async requestJsonWithResponse(options) {
730
1016
  return this.execute(options, async (response, ctx) => ({
731
- data: await readJsonBody(response, ctx.touch),
1017
+ data: await readJsonBody(response, options.shape ?? {}, ctx.touch),
732
1018
  response
733
1019
  }));
734
1020
  }
@@ -769,10 +1055,11 @@ var HttpClient = class {
769
1055
  let timer;
770
1056
  const touch = () => {
771
1057
  if (timer !== void 0) clearTimeout(timer);
1058
+ if (timeoutMs === Infinity) return;
772
1059
  timer = setTimeout(() => {
773
1060
  timedOut = true;
774
1061
  controller.abort();
775
- }, timeoutMs);
1062
+ }, timerDelay(timeoutMs));
776
1063
  };
777
1064
  touch();
778
1065
  const onAbort = () => controller.abort();
@@ -781,12 +1068,7 @@ var HttpClient = class {
781
1068
  let response;
782
1069
  let retryTransport = false;
783
1070
  try {
784
- response = await this.opts.fetchFn(url, {
785
- method,
786
- headers,
787
- ...serializedBody !== void 0 ? { body: serializedBody } : {},
788
- signal: controller.signal
789
- });
1071
+ response = await this.fetchWithinOrigin(url, method, headers, serializedBody, controller.signal);
790
1072
  touch();
791
1073
  if (response.ok) {
792
1074
  return await onSuccess(response, { signal: controller.signal, timeoutMs, touch });
@@ -823,9 +1105,59 @@ var HttpClient = class {
823
1105
  throw error;
824
1106
  }
825
1107
  }
1108
+ /**
1109
+ * `fetch` with redirects followed here rather than by the runtime, which
1110
+ * would repeat every request header to whichever host a redirect names.
1111
+ * Method and body change as `fetch` changes them: a 303, or a 301/302
1112
+ * answer to a POST, continues as a body-less GET; 307/308 repeat the request.
1113
+ * The body of a redirect response is cancelled, so its connection is released.
1114
+ * A response that says it was already redirected (a custom `fetch` that did
1115
+ * not honour `redirect: "manual"`) is refused.
1116
+ */
1117
+ async fetchWithinOrigin(url, method, headers, body, signal) {
1118
+ const fetchFn = this.opts.fetchFn;
1119
+ let target = url;
1120
+ for (let hop = 0; ; hop++) {
1121
+ const response = await fetchFn(target, {
1122
+ method,
1123
+ headers,
1124
+ ...body !== void 0 ? { body } : {},
1125
+ redirect: "manual",
1126
+ signal
1127
+ });
1128
+ if (response.redirected === true) {
1129
+ discardBody(response);
1130
+ throw new NetworkError('The custom fetch followed a redirect itself; it must honour redirect: "manual"');
1131
+ }
1132
+ if (response.type === "opaqueredirect") {
1133
+ throw new NetworkError("The API answered with a redirect, which this runtime does not expose");
1134
+ }
1135
+ const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null;
1136
+ if (location === null) return response;
1137
+ discardBody(response);
1138
+ let from;
1139
+ try {
1140
+ from = new URL(target);
1141
+ } catch {
1142
+ throw new NetworkError("Refused to follow a redirect from a request URL that is not absolute");
1143
+ }
1144
+ const next = redirectTarget(location, from);
1145
+ if (hop >= MAX_REDIRECTS) {
1146
+ throw new NetworkError(`Too many redirects (more than ${MAX_REDIRECTS})`);
1147
+ }
1148
+ if (response.status === 303 && method !== "GET" || (response.status === 301 || response.status === 302) && method === "POST") {
1149
+ method = "GET";
1150
+ body = void 0;
1151
+ headers = { ...headers };
1152
+ delete headers["content-type"];
1153
+ }
1154
+ target = next.href;
1155
+ }
1156
+ }
826
1157
  };
827
1158
  function shouldRetryStatus(error, call) {
828
1159
  const status = error.status;
1160
+ if (error.code === "PAYMENT_PAST_DUE") return false;
829
1161
  if (status === 503 && isBudgetTimeout(error.body)) return false;
830
1162
  if (status === 503 && isSearchIncomplete(error) && error.retryAfter === void 0) return false;
831
1163
  if (status === 429) return !(error instanceof RateLimitedError && error.quotaExhausted);
@@ -844,34 +1176,133 @@ function isSearchIncomplete(error) {
844
1176
  const field = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v["partialReason"] : void 0;
845
1177
  return (field(error.details) ?? field(error.body)) === "SEARCH_INCOMPLETE";
846
1178
  }
847
- async function readBodyText(response, touch) {
848
- if (response.body === null || touch === void 0) return response.text();
1179
+ async function readBodyBytes(response, touch) {
1180
+ if (response.body === null || touch === void 0) return new Uint8Array(await response.arrayBuffer());
849
1181
  const reader = response.body.getReader();
850
- const decoder = new TextDecoder();
851
- const parts = [];
1182
+ const chunks = [];
1183
+ let length = 0;
852
1184
  for (; ; ) {
853
1185
  const { done, value } = await reader.read();
854
1186
  if (done) break;
855
1187
  touch();
856
- parts.push(decoder.decode(value, { stream: true }));
1188
+ chunks.push(value);
1189
+ length += value.byteLength;
1190
+ }
1191
+ const bytes = new Uint8Array(length);
1192
+ let offset = 0;
1193
+ for (const chunk of chunks) {
1194
+ bytes.set(chunk, offset);
1195
+ offset += chunk.byteLength;
857
1196
  }
858
- parts.push(decoder.decode());
859
- return parts.join("");
1197
+ return bytes;
860
1198
  }
861
- async function readJsonBody(response, touch) {
862
- if (response.status === 204) return {};
863
- const text = await readBodyText(response, touch);
864
- if (text.trim() === "") return {};
1199
+ var EXCERPT_CHARS = 200;
1200
+ var EXCERPT_BYTES = EXCERPT_CHARS * 4;
1201
+ var NOT_JSON = /* @__PURE__ */ Symbol("not JSON");
1202
+ function parseJsonBytes(bytes) {
865
1203
  try {
866
- return JSON.parse(text);
1204
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
867
1205
  } catch {
868
- throw new InvalidResponseError(
869
- `Expected a JSON body (HTTP ${response.status}, content-type ${response.headers.get("content-type") ?? "none"})`,
870
- response.status,
871
- text,
872
- { headers: parseResponseHeaders(response) }
1206
+ return NOT_JSON;
1207
+ }
1208
+ }
1209
+ function excerptOf(bytes) {
1210
+ if (bytes.byteLength === 0) return void 0;
1211
+ const text2 = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(0, EXCERPT_BYTES));
1212
+ let out = "";
1213
+ let count2 = 0;
1214
+ for (const char of text2) {
1215
+ if (count2++ === EXCERPT_CHARS) break;
1216
+ out += char;
1217
+ }
1218
+ return out;
1219
+ }
1220
+ function mediaTypeOf(response) {
1221
+ const value = response.headers.get("content-type") ?? "";
1222
+ const media = Array.from(value.split(";", 1)[0].replace(/^[ \t]+|[ \t]+$/g, "")).slice(0, 100).join("");
1223
+ return media === "" ? "no content type" : media;
1224
+ }
1225
+ function jsonKind(value) {
1226
+ if (value === null) return "null";
1227
+ if (Array.isArray(value)) return "array";
1228
+ return typeof value;
1229
+ }
1230
+ function isJsonObject(value) {
1231
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1232
+ }
1233
+ var MISSING = /* @__PURE__ */ Symbol("missing");
1234
+ function lookup(body, path) {
1235
+ let value = body;
1236
+ for (const key of path.split(".")) {
1237
+ if (!isJsonObject(value) || !Object.prototype.hasOwnProperty.call(value, key)) return MISSING;
1238
+ value = value[key];
1239
+ }
1240
+ return value;
1241
+ }
1242
+ function shapeProblem(body, shape) {
1243
+ const missing = (path) => `Expected "${path}" in the response; it is missing`;
1244
+ const wrongKind = (path, expected, value) => `Expected "${path}" to be ${KIND_NAMES[expected]}, got ${jsonKind(value)}`;
1245
+ for (const path of shape.required ?? []) {
1246
+ const value = lookup(body, path);
1247
+ if (value === MISSING || value === null) return missing(path);
1248
+ }
1249
+ for (const { path, kind } of shape.fields ?? []) {
1250
+ const value = lookup(body, path);
1251
+ if (value === MISSING || value === null || kind === "string" && value === "") return missing(path);
1252
+ const ok = kind === "object" ? isJsonObject(value) : typeof value === kind;
1253
+ if (!ok) return wrongKind(path, kind, value);
1254
+ }
1255
+ for (const path of shape.optionalObjects ?? []) {
1256
+ const value = lookup(body, path);
1257
+ if (value !== MISSING && value !== null && !isJsonObject(value)) return wrongKind(path, "object", value);
1258
+ }
1259
+ for (const path of shape.lists ?? []) {
1260
+ const value = lookup(body, path);
1261
+ if (value === MISSING || value === null) continue;
1262
+ if (!Array.isArray(value)) return `Expected "${path}" to be a list, got ${jsonKind(value)}`;
1263
+ for (let index = 0; index < value.length; index++) {
1264
+ const item = value[index];
1265
+ if (!isJsonObject(item)) {
1266
+ return `Expected every item of "${path}" to be an object, got ${jsonKind(item)} at index ${index}`;
1267
+ }
1268
+ }
1269
+ }
1270
+ return void 0;
1271
+ }
1272
+ function hasErrorEnvelope(body) {
1273
+ const err = body["error"];
1274
+ return isJsonObject(err) || typeof err === "string" && err !== "";
1275
+ }
1276
+ async function readJsonBody(response, shape, touch) {
1277
+ const status = response.status;
1278
+ const headers = parseResponseHeaders(response);
1279
+ const invalid = (message, body2, bodyExcerpt) => new InvalidResponseError(message, status, body2, { headers, ...bodyExcerpt !== void 0 ? { bodyExcerpt } : {} });
1280
+ if (status === 204) {
1281
+ discardBody(response);
1282
+ if (shape.allowEmpty === true) return {};
1283
+ throw invalid("Expected JSON, got no body");
1284
+ }
1285
+ const bytes = await readBodyBytes(response, touch);
1286
+ if (bytes.byteLength === 0) {
1287
+ if (shape.allowEmpty === true) return {};
1288
+ throw invalid("Expected JSON, got no body");
1289
+ }
1290
+ const body = parseJsonBytes(bytes);
1291
+ if (body === NOT_JSON) {
1292
+ throw invalid(
1293
+ `Expected JSON, got ${mediaTypeOf(response)} that does not parse as JSON (${bytes.byteLength} bytes)`,
1294
+ void 0,
1295
+ excerptOf(bytes)
873
1296
  );
874
1297
  }
1298
+ if (!isJsonObject(body)) throw invalid(`Expected a JSON object, got ${jsonKind(body)}`, body);
1299
+ if (body["success"] === false && shape.successFalseOk !== true) {
1300
+ if (hasErrorEnvelope(body)) throw LexAPIError.fromResponse(status, body, void 0, headers);
1301
+ throw invalid("Response reported success: false without an error", body);
1302
+ }
1303
+ const problem = shapeProblem(body, shape);
1304
+ if (problem !== void 0) throw invalid(problem, body);
1305
+ return body;
875
1306
  }
876
1307
  function throwIfAborted(signal, method, path) {
877
1308
  if (signal?.aborted) {
@@ -879,39 +1310,24 @@ function throwIfAborted(signal, method, path) {
879
1310
  }
880
1311
  }
881
1312
  async function parseErrorResponse(response, touch) {
882
- let body;
883
- try {
884
- const text = await readBodyText(response, touch);
885
- body = text.trim() === "" ? void 0 : JSON.parse(text);
886
- } catch (cause) {
887
- if (!(cause instanceof SyntaxError)) throw cause;
888
- body = void 0;
889
- }
1313
+ const bytes = await readBodyBytes(response, touch);
1314
+ const parsed = bytes.byteLength === 0 ? NOT_JSON : parseJsonBytes(bytes);
1315
+ const body = parsed === NOT_JSON ? void 0 : parsed;
1316
+ const bodyExcerpt = parsed === NOT_JSON ? excerptOf(bytes) : void 0;
890
1317
  const hint = headerRetryAfterSeconds(response) ?? (response.status === 429 ? resetHeaderSeconds(response, "ratelimit-reset") : void 0);
891
- return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response));
1318
+ return LexAPIError.fromResponse(response.status, body, hint, parseResponseHeaders(response), bodyExcerpt);
892
1319
  }
893
1320
  function headerRetryAfterSeconds(response) {
894
- const raw = response.headers.get("retry-after");
895
- if (raw === null) return void 0;
896
- const header = raw.trim();
897
- if (header === "") return void 0;
898
- if (/^\d+(\.\d+)?$/.test(header)) return normalizeRetryAfterSeconds(Number(header));
899
- if (/^[-+]?\d/.test(header)) return void 0;
900
- const date = Date.parse(header);
901
- if (!Number.isNaN(date)) return Math.max(0, Math.round((date - Date.now()) / 1e3));
902
- return void 0;
1321
+ return retryAfterHeaderSeconds(response.headers.get("retry-after"));
903
1322
  }
904
1323
  function resetHeaderSeconds(response, name) {
905
- const raw = response.headers.get(name);
906
- if (raw === null || raw.trim() === "") return void 0;
907
- const seconds = Number(raw);
908
- if (!Number.isFinite(seconds) || seconds < 0) return void 0;
909
- return normalizeRetryAfterSeconds(seconds);
1324
+ return decimalSeconds(response.headers.get(name));
910
1325
  }
911
1326
  function fullJitterBackoff(attempt, baseDelayMs, maxDelayMs) {
912
1327
  return Math.random() * Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
913
1328
  }
914
1329
  function sleep(ms, signal, method, path) {
1330
+ ms = timerDelay(ms);
915
1331
  return new Promise((resolve, reject) => {
916
1332
  if (signal?.aborted) {
917
1333
  reject(new RequestAbortedError(`Request ${method} ${path} was aborted`, signal.reason));
@@ -946,6 +1362,39 @@ function buildQuery(query) {
946
1362
  }
947
1363
 
948
1364
  // src/export.ts
1365
+ var INVALID_LINE = /* @__PURE__ */ Symbol("invalid line");
1366
+ var NO_BYTES = new Uint8Array(0);
1367
+ function heldBytes(previous, chunk) {
1368
+ const n = chunk.length;
1369
+ if (n > 0 && chunk[n - 1] < 128) return NO_BYTES;
1370
+ const tail = n >= 3 ? chunk.subarray(n - 3) : new Uint8Array([...previous, ...chunk].slice(-3));
1371
+ for (let k = 1; k <= tail.length; k++) {
1372
+ const byte = tail[tail.length - k];
1373
+ if ((byte & 192) === 128) continue;
1374
+ const size = byte >= 240 ? 4 : byte >= 224 ? 3 : byte >= 192 ? 2 : 1;
1375
+ return size > k ? tail.slice(tail.length - k) : NO_BYTES;
1376
+ }
1377
+ return NO_BYTES;
1378
+ }
1379
+ function strictDecoder() {
1380
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1381
+ }
1382
+ function byteView(chunk) {
1383
+ if (chunk instanceof Uint8Array) return chunk;
1384
+ if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
1385
+ if (ArrayBuffer.isView(chunk)) return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
1386
+ return void 0;
1387
+ }
1388
+ function trimLine(line) {
1389
+ let start = 0;
1390
+ let end = line.length;
1391
+ while (start < end && isLineSpace(line.charCodeAt(start))) start++;
1392
+ while (end > start && isLineSpace(line.charCodeAt(end - 1))) end--;
1393
+ return start === 0 && end === line.length ? line : line.slice(start, end);
1394
+ }
1395
+ function isLineSpace(code) {
1396
+ return code === 32 || code === 9 || code === 13;
1397
+ }
949
1398
  var NdjsonReader = class {
950
1399
  constructor(body, options) {
951
1400
  this.options = options;
@@ -955,54 +1404,175 @@ var NdjsonReader = class {
955
1404
  else signal?.addEventListener("abort", this.onAbort, { once: true });
956
1405
  }
957
1406
  reader;
958
- decoder = new TextDecoder();
959
- /** Pieces of the line currently being received. */
1407
+ /** Decodes the line in progress; holds the bytes of a character split across chunks. */
1408
+ decoder = strictDecoder();
1409
+ /** A copy of the bytes the decoder holds (a character not yet complete), so it can be rebuilt. */
1410
+ carry = NO_BYTES;
1411
+ /** Text pieces of the line in progress. */
960
1412
  partial = [];
1413
+ /** The line in progress already holds bytes that are not UTF-8. */
1414
+ broken = false;
961
1415
  /** Complete lines not yet handed out. */
962
1416
  ready = [];
1417
+ /** No line has been completed yet. */
1418
+ atStart = true;
1419
+ /** The first line of the stream was blank (so the first line handed out is not the stream's first). */
1420
+ firstLineBlank = false;
963
1421
  eof = false;
964
1422
  released = false;
965
1423
  /** Data rows handed out so far (for error messages). */
966
1424
  rows = 0;
967
1425
  /** Releases the connection the moment the caller aborts — even while nobody is reading. */
968
1426
  onAbort = () => this.cancel();
969
- /** Next trimmed, non-empty line, or `undefined` at EOF. */
1427
+ /** Next non-blank line (trimmed), or `INVALID_LINE`, or `undefined` at EOF. */
970
1428
  async nextLine() {
971
1429
  const { signal } = this.options;
972
1430
  if (signal?.aborted) {
973
1431
  this.cancel();
974
1432
  throw new RequestAbortedError("Export stream was aborted", signal.reason);
975
1433
  }
976
- for (; ; ) {
977
- const line = this.ready.shift();
978
- if (line !== void 0) return line;
979
- if (this.eof) {
980
- const tail = this.partial.join("").trim();
981
- this.partial = [];
982
- return tail || void 0;
1434
+ try {
1435
+ for (; ; ) {
1436
+ const line = this.ready.shift();
1437
+ if (line !== void 0) return line;
1438
+ if (this.eof) return void 0;
1439
+ const result = await this.read();
1440
+ if (result.done) {
1441
+ this.finish();
1442
+ this.release();
1443
+ } else {
1444
+ this.ingest(result.value);
1445
+ }
983
1446
  }
984
- const chunk = await this.read();
985
- if (chunk === void 0) {
986
- this.eof = true;
987
- this.ingest(this.decoder.decode());
988
- this.release();
989
- } else {
990
- this.ingest(this.decoder.decode(chunk, { stream: true }));
1447
+ } catch (cause) {
1448
+ this.cancel();
1449
+ if (cause instanceof LexAPIError) throw cause;
1450
+ throw new NetworkError(`Export stream interrupted after ${this.rows} rows`, cause);
1451
+ }
1452
+ }
1453
+ ingest(value) {
1454
+ const chunk = byteView(value);
1455
+ if (chunk === void 0) throw new TypeError("Export stream yielded a chunk that is not bytes");
1456
+ if (!this.broken) {
1457
+ let text2;
1458
+ try {
1459
+ text2 = this.decoder.decode(chunk, { stream: true });
1460
+ } catch {
1461
+ this.decoder = strictDecoder();
1462
+ if (this.carry.length > 0) this.decoder.decode(this.carry, { stream: true });
1463
+ }
1464
+ if (text2 !== void 0) {
1465
+ this.carry = heldBytes(this.carry, chunk);
1466
+ let pos = 0;
1467
+ for (; ; ) {
1468
+ const newline = text2.indexOf("\n", pos);
1469
+ if (newline === -1) break;
1470
+ this.partial.push(text2.slice(pos, newline));
1471
+ const line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1472
+ this.partial = [];
1473
+ this.complete(line);
1474
+ pos = newline + 1;
1475
+ }
1476
+ if (pos < text2.length) this.partial.push(pos === 0 ? text2 : text2.slice(pos));
1477
+ return;
991
1478
  }
992
1479
  }
1480
+ this.ingestBytes(chunk);
993
1481
  }
994
- ingest(text) {
1482
+ /** A chunk that is not all UTF-8, or that continues a line that is not. */
1483
+ ingestBytes(chunk) {
1484
+ const first = chunk.indexOf(10);
1485
+ if (first === -1) {
1486
+ this.feed(chunk);
1487
+ return;
1488
+ }
1489
+ const last = chunk.lastIndexOf(10);
1490
+ let line = INVALID_LINE;
1491
+ if (!this.broken) {
1492
+ try {
1493
+ const text2 = this.decoder.decode(chunk.subarray(0, first + 1), { stream: true });
1494
+ this.partial.push(text2.slice(0, -1));
1495
+ line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1496
+ } catch {
1497
+ this.decoder = strictDecoder();
1498
+ }
1499
+ }
1500
+ this.partial = [];
1501
+ this.broken = false;
1502
+ this.carry = NO_BYTES;
1503
+ this.complete(line);
1504
+ if (first < last) this.completeRegion(chunk.subarray(first + 1, last + 1));
1505
+ if (last + 1 < chunk.length) this.feed(chunk.subarray(last + 1));
1506
+ }
1507
+ /** Whole lines, each ending with its line feed. */
1508
+ completeRegion(region) {
1509
+ let text2;
1510
+ try {
1511
+ text2 = this.decoder.decode(region, { stream: true });
1512
+ } catch {
1513
+ this.decoder = strictDecoder();
1514
+ }
1515
+ if (text2 !== void 0) {
1516
+ let pos2 = 0;
1517
+ for (; ; ) {
1518
+ const newline = text2.indexOf("\n", pos2);
1519
+ if (newline === -1) break;
1520
+ this.complete(text2.slice(pos2, newline));
1521
+ pos2 = newline + 1;
1522
+ }
1523
+ return;
1524
+ }
995
1525
  let pos = 0;
996
- for (; ; ) {
997
- const newline = text.indexOf("\n", pos);
998
- if (newline === -1) break;
999
- this.partial.push(text.slice(pos, newline));
1000
- const line = this.partial.join("").trim();
1001
- this.partial = [];
1002
- if (line) this.ready.push(line);
1526
+ while (pos < region.length) {
1527
+ const newline = region.indexOf(10, pos);
1528
+ try {
1529
+ this.complete(this.decoder.decode(region.subarray(pos, newline + 1), { stream: true }).slice(0, -1));
1530
+ } catch {
1531
+ this.decoder = strictDecoder();
1532
+ this.complete(INVALID_LINE);
1533
+ }
1003
1534
  pos = newline + 1;
1004
1535
  }
1005
- if (pos < text.length) this.partial.push(text.slice(pos));
1536
+ }
1537
+ /** Bytes of the line in progress (after a line feed, or continuing a line that is not UTF-8). */
1538
+ feed(bytes) {
1539
+ if (this.broken || bytes.length === 0) return;
1540
+ try {
1541
+ const text2 = this.decoder.decode(bytes, { stream: true });
1542
+ if (text2) this.partial.push(text2);
1543
+ this.carry = heldBytes(this.carry, bytes);
1544
+ } catch {
1545
+ this.broken = true;
1546
+ this.decoder = strictDecoder();
1547
+ this.carry = NO_BYTES;
1548
+ }
1549
+ }
1550
+ /** End of stream: the line in progress, if any. */
1551
+ finish() {
1552
+ this.eof = true;
1553
+ let line = INVALID_LINE;
1554
+ if (!this.broken) {
1555
+ try {
1556
+ this.partial.push(this.decoder.decode());
1557
+ line = this.partial.length === 1 ? this.partial[0] : this.partial.join("");
1558
+ } catch {
1559
+ }
1560
+ }
1561
+ this.partial = [];
1562
+ this.broken = false;
1563
+ this.complete(line);
1564
+ }
1565
+ /** Queue a complete line: a byte order mark leading the stream is dropped; blank lines are skipped. */
1566
+ complete(line) {
1567
+ const first = this.atStart;
1568
+ this.atStart = false;
1569
+ if (line === INVALID_LINE) {
1570
+ this.ready.push(line);
1571
+ return;
1572
+ }
1573
+ const text2 = trimLine(first && line.charCodeAt(0) === 65279 ? line.slice(1) : line);
1574
+ if (text2) this.ready.push(text2);
1575
+ else if (first) this.firstLineBlank = true;
1006
1576
  }
1007
1577
  async read() {
1008
1578
  const { idleTimeoutMs, signal } = this.options;
@@ -1013,12 +1583,12 @@ var NdjsonReader = class {
1013
1583
  let timer;
1014
1584
  let onAbort;
1015
1585
  const interruptions = new Promise((_, reject) => {
1016
- if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0) {
1586
+ if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0 && idleTimeoutMs !== Infinity) {
1017
1587
  timer = setTimeout(() => {
1018
1588
  reject(
1019
1589
  new TimeoutError(`Export stream received no data for ${idleTimeoutMs}ms (after ${this.rows} rows)`, 0)
1020
1590
  );
1021
- }, idleTimeoutMs);
1591
+ }, timerDelay(idleTimeoutMs));
1022
1592
  }
1023
1593
  if (signal) {
1024
1594
  onAbort = () => reject(new RequestAbortedError("Export stream was aborted", signal.reason));
@@ -1028,7 +1598,7 @@ var NdjsonReader = class {
1028
1598
  try {
1029
1599
  const result = await Promise.race([this.reader.read(), interruptions]);
1030
1600
  if (signal?.aborted) throw new RequestAbortedError("Export stream was aborted", signal.reason);
1031
- return result.done ? void 0 : result.value;
1601
+ return result;
1032
1602
  } catch (cause) {
1033
1603
  this.cancel();
1034
1604
  if (cause instanceof LexAPIError) throw cause;
@@ -1062,17 +1632,25 @@ var NdjsonReader = class {
1062
1632
  function liftEnvelope(parsed, key) {
1063
1633
  const inner = parsed[key];
1064
1634
  if (typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
1065
- return { ...inner, ...parsed };
1635
+ return { ...inner, [key]: inner };
1066
1636
  }
1067
1637
  return parsed;
1068
1638
  }
1639
+ function text(value) {
1640
+ try {
1641
+ return String(value);
1642
+ } catch {
1643
+ return Array.isArray(value) ? "array" : typeof value;
1644
+ }
1645
+ }
1069
1646
  function errorLine(parsed) {
1070
1647
  const keys = Object.keys(parsed);
1071
1648
  if (keys.length !== 1 || keys[0] !== "_error") return void 0;
1072
1649
  const value = parsed._error;
1073
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: String(value) };
1650
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : { message: text(value) };
1074
1651
  }
1075
1652
  function parseLine(line) {
1653
+ if (line === INVALID_LINE) return void 0;
1076
1654
  try {
1077
1655
  const value = JSON.parse(line);
1078
1656
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
@@ -1101,7 +1679,7 @@ var ExportStreamImpl = class {
1101
1679
  }
1102
1680
  failureReason() {
1103
1681
  if (this.error !== void 0) {
1104
- return `the server reported an error mid-stream (${String(this.error.code ?? "UNKNOWN")}: ${String(this.error.message ?? "")})`;
1682
+ return `the server reported an error mid-stream (${text(this.error.code ?? "UNKNOWN")}: ${text(this.error.message ?? "")})`;
1105
1683
  }
1106
1684
  return "its _done trailer says complete: false";
1107
1685
  }
@@ -1112,7 +1690,7 @@ var ExportStreamImpl = class {
1112
1690
  if (typeof this.done?.truncated === "boolean") return this.done.truncated;
1113
1691
  if (this.headers.truncated !== void 0) return this.headers.truncated;
1114
1692
  if (typeof this.meta?.truncated === "boolean") return this.meta.truncated;
1115
- return void 0;
1693
+ return false;
1116
1694
  }
1117
1695
  constructor(lines, headers) {
1118
1696
  this.lines = lines;
@@ -1124,21 +1702,20 @@ var ExportStreamImpl = class {
1124
1702
  }
1125
1703
  /** Read the leading line so `meta` is available before iteration starts. */
1126
1704
  async init() {
1127
- let parsed;
1128
- for (; ; ) {
1129
- const first = await this.lines.nextLine();
1130
- if (first === void 0) return;
1131
- parsed = parseLine(first);
1132
- if (parsed !== void 0) {
1133
- const error = errorLine(parsed);
1134
- if (error === void 0) break;
1135
- this.error = error;
1136
- continue;
1137
- }
1705
+ const first = await this.lines.nextLine();
1706
+ if (first === void 0) return;
1707
+ const parsed = parseLine(first);
1708
+ if (parsed === void 0) {
1138
1709
  this.invalidLines++;
1710
+ return;
1711
+ }
1712
+ const error = errorLine(parsed);
1713
+ if (error !== void 0) {
1714
+ this.error = error;
1715
+ return;
1139
1716
  }
1140
1717
  if ("_meta" in parsed) {
1141
- this.meta = liftEnvelope(parsed, "_meta");
1718
+ if (!this.lines.firstLineBlank) this.meta = liftEnvelope(parsed, "_meta");
1142
1719
  } else if ("_done" in parsed) {
1143
1720
  this.done = liftEnvelope(parsed, "_done");
1144
1721
  this.lines.cancel();
@@ -1181,12 +1758,12 @@ var ExportStreamImpl = class {
1181
1758
  this.invalidLines++;
1182
1759
  continue;
1183
1760
  }
1761
+ if ("_meta" in parsed) continue;
1184
1762
  if ("_done" in parsed) {
1185
1763
  this.done = liftEnvelope(parsed, "_done");
1186
1764
  if (!this.complete) throw this.incomplete(this.failureReason());
1187
1765
  return;
1188
1766
  }
1189
- if ("_meta" in parsed) continue;
1190
1767
  const error = errorLine(parsed);
1191
1768
  if (error !== void 0) {
1192
1769
  this.error = error;
@@ -1200,6 +1777,10 @@ var ExportStreamImpl = class {
1200
1777
  }
1201
1778
  }
1202
1779
  };
1780
+ function truncatedFlag(value) {
1781
+ const flag = value === null ? void 0 : trimSpaces(value);
1782
+ return flag === "1" ? true : flag === "0" ? false : void 0;
1783
+ }
1203
1784
  async function createExportStream(response, options = {}) {
1204
1785
  if (response.body === null) {
1205
1786
  throw new LexAPIError("INTERNAL", "Export response had no body stream", response.status);
@@ -1208,14 +1789,63 @@ async function createExportStream(response, options = {}) {
1208
1789
  const streamingHeader = response.headers.get("x-export-streaming");
1209
1790
  const truncatedHeader = response.headers.get("x-export-truncated");
1210
1791
  const stream = new ExportStreamImpl(new NdjsonReader(response.body, options), {
1211
- total: totalHeader !== null ? Number(totalHeader) : void 0,
1212
- streaming: streamingHeader !== null ? Number(streamingHeader) : void 0,
1213
- truncated: truncatedHeader !== null ? truncatedHeader === "1" : void 0
1792
+ total: parseHeaderInteger(totalHeader),
1793
+ streaming: parseHeaderInteger(streamingHeader),
1794
+ truncated: truncatedFlag(truncatedHeader)
1214
1795
  });
1215
1796
  await stream.init();
1216
1797
  return stream;
1217
1798
  }
1218
1799
 
1800
+ // src/paging.ts
1801
+ function count(value) {
1802
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1803
+ }
1804
+ var REPEATS_BEFORE_THROW = 3;
1805
+ function startingPosition(offset, limit, defaultLimit) {
1806
+ if (offset !== void 0 && count(offset) === void 0) {
1807
+ throw new RangeError(`offset must be a non-negative integer, got ${String(offset)}`);
1808
+ }
1809
+ if (limit !== void 0 && !(count(limit) !== void 0 && limit > 0)) {
1810
+ throw new RangeError(`limit must be a positive integer, got ${String(limit)}`);
1811
+ }
1812
+ return { offset: offset ?? 0, limit: limit ?? defaultLimit };
1813
+ }
1814
+ function stalled(reason, page) {
1815
+ return new InvalidResponseError(`Pagination stopped: ${reason}`, 200, page);
1816
+ }
1817
+ var Token = class {
1818
+ constructor(text2) {
1819
+ this.text = text2;
1820
+ }
1821
+ };
1822
+ function compactForm(value) {
1823
+ let out = "";
1824
+ const stack = [value];
1825
+ while (stack.length > 0) {
1826
+ const item = stack.pop();
1827
+ if (item instanceof Token) out += item.text;
1828
+ else if (typeof item === "string") out += JSON.stringify(item);
1829
+ else if (Array.isArray(item)) {
1830
+ out += "[";
1831
+ stack.push(new Token("]"));
1832
+ for (let i = item.length - 1; i >= 0; i--) {
1833
+ stack.push(item[i]);
1834
+ if (i > 0) stack.push(new Token(","));
1835
+ }
1836
+ } else if (typeof item === "object" && item !== null) {
1837
+ out += "{";
1838
+ stack.push(new Token("}"));
1839
+ const keys = Object.keys(item).sort();
1840
+ for (let i = keys.length - 1; i >= 0; i--) {
1841
+ stack.push(item[keys[i]]);
1842
+ stack.push(new Token(`${i > 0 ? "," : ""}${JSON.stringify(keys[i])}:`));
1843
+ }
1844
+ } else out += String(item);
1845
+ }
1846
+ return out;
1847
+ }
1848
+
1219
1849
  // src/webhooks.ts
1220
1850
  var WebhooksAPI = class {
1221
1851
  http;
@@ -1235,6 +1865,7 @@ var WebhooksAPI = class {
1235
1865
  return this.call({
1236
1866
  method: "GET",
1237
1867
  path: "/webhooks",
1868
+ shape: { lists: ["webhooks"] },
1238
1869
  free: true,
1239
1870
  timeoutMs: options?.timeoutMs,
1240
1871
  signal: options?.signal
@@ -1295,6 +1926,7 @@ var WebhooksAPI = class {
1295
1926
  return this.call({
1296
1927
  method: "DELETE",
1297
1928
  path: `/webhooks/${encodeURIComponent(id)}`,
1929
+ shape: { allowEmpty: true },
1298
1930
  timeoutMs: options?.timeoutMs,
1299
1931
  signal: options?.signal
1300
1932
  });
@@ -1309,6 +1941,7 @@ var WebhooksAPI = class {
1309
1941
  return this.call({
1310
1942
  method: "POST",
1311
1943
  path: `/webhooks/${encodeURIComponent(id)}/test`,
1944
+ shape: { successFalseOk: true },
1312
1945
  timeoutMs: options?.timeoutMs,
1313
1946
  signal: options?.signal
1314
1947
  });
@@ -1318,6 +1951,7 @@ var WebhooksAPI = class {
1318
1951
  return this.call({
1319
1952
  method: "GET",
1320
1953
  path: `/webhooks/${encodeURIComponent(id)}/deliveries`,
1954
+ shape: { lists: ["deliveries"] },
1321
1955
  free: true,
1322
1956
  query: { limit: params.limit, offset: params.offset },
1323
1957
  timeoutMs: options?.timeoutMs,
@@ -1329,7 +1963,13 @@ var WebhooksAPI = class {
1329
1963
  * 50), starting at `offset`, newest first (SDK contract §1.4). Each
1330
1964
  * delivery is yielded at most once (deduplicated on `id`): a delivery
1331
1965
  * created during the walk shifts later pages by one. Stops on an empty page
1332
- * or when the offset reaches `total`. Pages are free (0 credits).
1966
+ * or when the offset reaches `total`. Without a usable `total`, three pages
1967
+ * in a row that bring no unseen `id` throw `InvalidResponseError` (a page
1968
+ * with a usable `total` ends a run). When a walk throws, the pages already
1969
+ * yielded stay valid; the page that showed the stall is not yielded and is
1970
+ * on the error's `body`. A starting `offset` or `limit` that is not a
1971
+ * non-negative (positive) integer is a `RangeError` before any request.
1972
+ * Pages are free (0 credits).
1333
1973
  *
1334
1974
  * ```ts
1335
1975
  * for await (const page of client.webhooks.paginateDeliveries(id)) {
@@ -1338,21 +1978,36 @@ var WebhooksAPI = class {
1338
1978
  * ```
1339
1979
  */
1340
1980
  async *paginateDeliveries(id, params = {}, options) {
1341
- const limit = params.limit ?? 50;
1342
- let offset = params.offset ?? 0;
1981
+ const start = startingPosition(params.offset, params.limit, 50);
1982
+ const limit = start.limit;
1983
+ let offset = start.offset;
1343
1984
  const seen = /* @__PURE__ */ new Set();
1985
+ let repeats = 0;
1344
1986
  for (; ; ) {
1345
1987
  const page = await this.deliveries(id, { limit, offset }, options);
1346
- const count = page.deliveries.length;
1347
- const fresh = page.deliveries.filter((d) => {
1988
+ const listed = page.deliveries;
1989
+ const deliveries = Array.isArray(listed) ? listed : [];
1990
+ const rows = deliveries.length;
1991
+ let readable = 0;
1992
+ let unseen = 0;
1993
+ const fresh = deliveries.filter((d) => {
1348
1994
  if (typeof d.id !== "string") return true;
1995
+ readable++;
1349
1996
  if (seen.has(d.id)) return false;
1350
1997
  seen.add(d.id);
1998
+ unseen++;
1351
1999
  return true;
1352
2000
  });
2001
+ const total = count(page.total);
2002
+ if (total === void 0) {
2003
+ repeats = readable > 0 && unseen === 0 ? repeats + 1 : 0;
2004
+ if (repeats >= REPEATS_BEFORE_THROW) throw stalled("the server repeated the same deliveries", page);
2005
+ } else {
2006
+ repeats = 0;
2007
+ }
1353
2008
  yield { ...page, deliveries: fresh };
1354
- offset += count;
1355
- if (count === 0 || page.total !== void 0 && offset >= page.total) return;
2009
+ offset += rows;
2010
+ if (rows === 0 || total !== void 0 && offset >= total) return;
1356
2011
  }
1357
2012
  }
1358
2013
  };
@@ -1367,11 +2022,16 @@ var LexAPI = class {
1367
2022
  if (!apiKey) {
1368
2023
  throw new Error("apiKey is required (or set LEXAPI_API_KEY)");
1369
2024
  }
2025
+ if (options.fetch === void 0 && typeof globalThis.fetch !== "function") {
2026
+ throw new Error("This runtime has no global fetch; pass one with the `fetch` option");
2027
+ }
1370
2028
  this.http = new HttpClient({
1371
2029
  apiKey,
1372
2030
  baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
1373
2031
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1374
- fetchFn: options.fetch ?? fetch,
2032
+ // Looked up per call and invoked on the global object, which Cloudflare
2033
+ // Workers and browsers require.
2034
+ fetchFn: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
1375
2035
  retry: {
1376
2036
  maxRetries: options.retry?.maxRetries ?? 3,
1377
2037
  baseDelayMs: options.retry?.baseDelayMs ?? 500,
@@ -1429,6 +2089,7 @@ var LexAPI = class {
1429
2089
  return this.call({
1430
2090
  method: "POST",
1431
2091
  path: "/search",
2092
+ shape: { lists: ["results"], required: ["results"] },
1432
2093
  body: request,
1433
2094
  idempotent: true,
1434
2095
  timeoutMs: options?.timeoutMs,
@@ -1453,6 +2114,7 @@ var LexAPI = class {
1453
2114
  return this.call({
1454
2115
  method: "POST",
1455
2116
  path: "/documentContent",
2117
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
1456
2118
  body: request,
1457
2119
  idempotent: true,
1458
2120
  timeoutMs: options?.timeoutMs,
@@ -1474,6 +2136,7 @@ var LexAPI = class {
1474
2136
  return this.call({
1475
2137
  method: "POST",
1476
2138
  path: "/documentContent/batch",
2139
+ shape: { lists: ["documents", "errors"] },
1477
2140
  body: request,
1478
2141
  idempotent: true,
1479
2142
  timeoutMs: options?.timeoutMs,
@@ -1496,6 +2159,7 @@ var LexAPI = class {
1496
2159
  return this.call({
1497
2160
  method: "GET",
1498
2161
  path: "/documents/recent",
2162
+ shape: { lists: ["results"] },
1499
2163
  query: {
1500
2164
  days: params.days,
1501
2165
  documentType: params.documentType,
@@ -1518,6 +2182,7 @@ var LexAPI = class {
1518
2182
  return this.call({
1519
2183
  method: "POST",
1520
2184
  path: "/documents/url",
2185
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
1521
2186
  body: request,
1522
2187
  idempotent: true,
1523
2188
  timeoutMs: options?.timeoutMs,
@@ -1556,18 +2221,20 @@ var LexAPI = class {
1556
2221
  });
1557
2222
  }
1558
2223
  // ── Point-in-time versions ────────────────────────────────────────
1559
- // Versions are LexAPI observation snapshots (content-hash changes between
1560
- // fetches), NOT legal in-force reconstructions; history begins at first
1561
- // ingestion. For the text in force on a date, use a consolidated CELEX or
1562
- // semanticLegislationSearch({ asOf }).
2224
+ // Versions are LexAPI's fetch snapshots (content-hash changes between
2225
+ // fetches), NOT the law in force on a date; history begins at first
2226
+ // ingestion. For the version of an EU act for a date, use legislationAsOf.
1563
2227
  /**
1564
2228
  * `GET /documents/{celex}/versions` — version history, newest first,
1565
- * current version included and flagged. 1 credit.
2229
+ * current version included and flagged. These are LexAPI's fetch
2230
+ * snapshots, not the law in force on a date; for the version of an EU act
2231
+ * for a date use `legislationAsOf`. 1 credit.
1566
2232
  */
1567
2233
  async listDocumentVersions(celex, params = {}, options) {
1568
2234
  return this.call({
1569
2235
  method: "GET",
1570
2236
  path: `/documents/${encodeURIComponent(celex)}/versions`,
2237
+ shape: { lists: ["versions"] },
1571
2238
  query: { language: params.language },
1572
2239
  timeoutMs: options?.timeoutMs,
1573
2240
  signal: options?.signal
@@ -1576,27 +2243,41 @@ var LexAPI = class {
1576
2243
  /**
1577
2244
  * `GET /documents/{celex}/versions/{version}` — one immutable snapshot
1578
2245
  * including `parsedContent`. `corpusVersion` mirrors the
1579
- * `X-Corpus-Version` response header. 1 credit.
2246
+ * `X-Corpus-Version` response header. This is one of LexAPI's fetch
2247
+ * snapshots, not the law in force on a date; for the version of an EU act
2248
+ * for a date use `legislationAsOf`. 1 credit.
1580
2249
  */
1581
2250
  async getDocumentVersion(celex, version, params = {}, options) {
1582
2251
  return this.call({
1583
2252
  method: "GET",
1584
2253
  path: `/documents/${encodeURIComponent(celex)}/versions/${version}`,
2254
+ shape: { fields: [{ path: "document", kind: "object" }] },
1585
2255
  query: { language: params.language },
1586
2256
  timeoutMs: options?.timeoutMs,
1587
2257
  signal: options?.signal
1588
2258
  }, { corpusVersion: true });
1589
2259
  }
1590
2260
  /**
1591
- * `GET /documents/{celex}/at/{date}` — the snapshot LexAPI observed as
1592
- * current on `date` (`YYYY-MM-DD`, end-of-day UTC inclusive). Dates
1593
- * before the document entered the corpus reject with `NotFoundError`
1594
- * carrying the tracking start date. 1 credit.
2261
+ * `GET /documents/{celex}/at/{date}` — the snapshot LexAPI held as current
2262
+ * at the end of `date` (`YYYY-MM-DD`, UTC), from its own fetch history
2263
+ * (`kind: "observation_snapshot"`). This is not the law in force on that
2264
+ * date: for the version of an EU act for a date use `legislationAsOf`
2265
+ * (`inForceLookup` points to it). The snapshot was the current one from
2266
+ * `document.observedFrom` until `document.observedUntil` (`null` for the
2267
+ * current version). A future date returns the current version with
2268
+ * `dateInFuture: true`.
2269
+ *
2270
+ * A date before the document entered the corpus rejects with
2271
+ * `NotFoundError` where `beforeTracking` is `true` (`trackedSince`); a date
2272
+ * next to a version stored before API 2.28.0 whose start LexAPI has no
2273
+ * record of rejects with `boundaryUnknown` `true` and `candidates`
2274
+ * (refunded). 1 credit.
1595
2275
  */
1596
2276
  async getDocumentAtDate(celex, date, params = {}, options) {
1597
2277
  return this.call({
1598
2278
  method: "GET",
1599
2279
  path: `/documents/${encodeURIComponent(celex)}/at/${encodeURIComponent(date)}`,
2280
+ shape: { fields: [{ path: "document", kind: "object" }] },
1600
2281
  query: { language: params.language },
1601
2282
  timeoutMs: options?.timeoutMs,
1602
2283
  signal: options?.signal
@@ -1613,6 +2294,7 @@ var LexAPI = class {
1613
2294
  return this.call({
1614
2295
  method: "POST",
1615
2296
  path: "/citations/extract",
2297
+ shape: { lists: ["citations"] },
1616
2298
  body: { celexNumber },
1617
2299
  timeoutMs: options?.timeoutMs,
1618
2300
  signal: options?.signal
@@ -1639,6 +2321,7 @@ var LexAPI = class {
1639
2321
  return this.call({
1640
2322
  method: "GET",
1641
2323
  path: `/citations/cites/${encodeURIComponent(celexNumber)}`,
2324
+ shape: { lists: ["cites", "unresolved"] },
1642
2325
  query: { ...edgeQuery(params), unresolved: params.unresolved },
1643
2326
  timeoutMs: options?.timeoutMs,
1644
2327
  signal: options?.signal
@@ -1658,6 +2341,7 @@ var LexAPI = class {
1658
2341
  return this.call({
1659
2342
  method: "GET",
1660
2343
  path: `/citations/cited-by/${encodeURIComponent(celexNumber)}`,
2344
+ shape: { lists: ["citedBy"] },
1661
2345
  query: edgeQuery(params),
1662
2346
  timeoutMs: options?.timeoutMs,
1663
2347
  signal: options?.signal
@@ -1671,26 +2355,39 @@ var LexAPI = class {
1671
2355
  * missed. A target's edges can straddle a page boundary, so the same
1672
2356
  * `celexNumber` may appear in two consecutive pages — merge by
1673
2357
  * `celexNumber` if you need one group per document.
2358
+ * The walk also ends once the offset reaches `totalEdges`, when that is a
2359
+ * non-negative integer. It throws `InvalidResponseError` when a page echoes
2360
+ * an `offset` other than the one requested, or, when the answers carry
2361
+ * neither `totalEdges` nor `offset`, after three pages in a row that each
2362
+ * repeat the one before (comparing the list only; a page with either
2363
+ * signal ends a run, and its list is still the one the next page is
2364
+ * compared with). When a walk throws, the pages already yielded stay
2365
+ * valid; the page that showed the stall is not yielded and is on the
2366
+ * error's `body`. A starting `offset` or `limit` that is not a non-negative
2367
+ * (positive) integer is a `RangeError` before any request. A group whose
2368
+ * `citationCount` is 0 but whose edge list is not empty counts its list.
1674
2369
  */
1675
2370
  async *paginateCites(celexNumber, params = {}, options) {
1676
- yield* paginateEdges(
1677
- (p) => this.getCites(celexNumber, p, options),
1678
- (page) => page.cites.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
1679
- params
1680
- );
2371
+ yield* paginateEdges((p) => this.getCites(celexNumber, p, options), (page) => page.cites, params);
1681
2372
  }
1682
2373
  /**
1683
2374
  * Walk every page of `getCitedBy` (offset in edge rows) until a short or
1684
2375
  * empty page (SDK contract §1.4). Each page is a billed call (1 credit);
1685
2376
  * edges may repeat or be missed if extractions happen during the walk. A source's edges can straddle a page boundary, so the same
1686
2377
  * `celexNumber` may appear in two consecutive pages.
2378
+ * The walk also ends once the offset reaches `totalEdges`, when that is a
2379
+ * non-negative integer. It throws `InvalidResponseError` when a page echoes
2380
+ * an `offset` other than the one requested, or, when the answers carry
2381
+ * neither `totalEdges` nor `offset`, after three pages in a row that each
2382
+ * repeat the one before (comparing the list only; a page with either
2383
+ * signal ends a run, and its list is still the one the next page is
2384
+ * compared with). When a walk throws, the pages already yielded stay
2385
+ * valid; the page that showed the stall is not yielded and is on the
2386
+ * error's `body`. A starting `offset` or `limit` that is not a non-negative
2387
+ * (positive) integer is a `RangeError` before any request.
1687
2388
  */
1688
2389
  async *paginateCitedBy(celexNumber, params = {}, options) {
1689
- yield* paginateEdges(
1690
- (p) => this.getCitedBy(celexNumber, p, options),
1691
- (page) => page.citedBy.reduce((n, g) => n + (g.citationCount ?? g.citations?.length ?? 0), 0),
1692
- params
1693
- );
2390
+ yield* paginateEdges((p) => this.getCitedBy(celexNumber, p, options), (page) => page.citedBy, params);
1694
2391
  }
1695
2392
  /**
1696
2393
  * `GET /citations/network/{celexNumber}` — inbound and outbound
@@ -1708,6 +2405,7 @@ var LexAPI = class {
1708
2405
  return this.call({
1709
2406
  method: "GET",
1710
2407
  path: `/citations/network/${encodeURIComponent(celexNumber)}`,
2408
+ shape: { lists: ["network.cites", "network.citedBy", "unresolved"] },
1711
2409
  query: {
1712
2410
  ...filterQuery(params),
1713
2411
  limit: params.limit,
@@ -1734,6 +2432,7 @@ var LexAPI = class {
1734
2432
  return this.call({
1735
2433
  method: "GET",
1736
2434
  path: `/citations/path/${encodeURIComponent(from)}/${encodeURIComponent(to)}`,
2435
+ shape: { lists: ["path"] },
1737
2436
  query: {
1738
2437
  ...filterQuery(params),
1739
2438
  maxDepth: params.maxDepth,
@@ -1758,6 +2457,7 @@ var LexAPI = class {
1758
2457
  return this.call({
1759
2458
  method: "GET",
1760
2459
  path: `/citations/related/${encodeURIComponent(celexNumber)}`,
2460
+ shape: { lists: ["related"] },
1761
2461
  query: {
1762
2462
  ...filterQuery(params),
1763
2463
  limit: params.limit,
@@ -1780,6 +2480,7 @@ var LexAPI = class {
1780
2480
  return this.call({
1781
2481
  method: "GET",
1782
2482
  path: "/citations/stats",
2483
+ shape: { lists: ["stats.mostCited", "stats.mostCiting"] },
1783
2484
  query: { includeNational: effectiveParams?.includeNational },
1784
2485
  timeoutMs: effectiveOptions?.timeoutMs,
1785
2486
  signal: effectiveOptions?.signal
@@ -1808,6 +2509,7 @@ var LexAPI = class {
1808
2509
  return this.call({
1809
2510
  method: "GET",
1810
2511
  path: `/citations/transposition/${encodeURIComponent(celexNumber)}`,
2512
+ shape: { lists: ["jurisdictions"] },
1811
2513
  query: {
1812
2514
  jurisdictions: listParam(params.jurisdictions),
1813
2515
  resolvedOnly: params.resolvedOnly,
@@ -1836,6 +2538,7 @@ var LexAPI = class {
1836
2538
  return this.call({
1837
2539
  method: "GET",
1838
2540
  path: `/citations/counterparts/${encodeURIComponent(id)}`,
2541
+ shape: { lists: ["via"] },
1839
2542
  query: {
1840
2543
  jurisdictions: listParam(params.jurisdictions),
1841
2544
  language: params.language
@@ -1862,6 +2565,7 @@ var LexAPI = class {
1862
2565
  return this.call({
1863
2566
  method: "GET",
1864
2567
  path: "/national/coverage",
2568
+ shape: { lists: ["jurisdictions"] },
1865
2569
  free: true,
1866
2570
  timeoutMs: options?.timeoutMs,
1867
2571
  signal: options?.signal
@@ -1889,6 +2593,7 @@ var LexAPI = class {
1889
2593
  return this.call({
1890
2594
  method: "GET",
1891
2595
  path: `/${jurisdictionSegment(jurisdiction)}/documents/${encodeURIComponent(id)}`,
2596
+ shape: { fields: [{ path: "document", kind: "object" }], optionalObjects: ["document.content"], lists: ["document.content.articles"] },
1892
2597
  query: { language: params.language },
1893
2598
  timeoutMs: options?.timeoutMs,
1894
2599
  signal: options?.signal
@@ -1911,6 +2616,7 @@ var LexAPI = class {
1911
2616
  return this.call({
1912
2617
  method: "GET",
1913
2618
  path: `/${jurisdictionSegment(jurisdiction)}/documents`,
2619
+ shape: { lists: ["results"] },
1914
2620
  query: {
1915
2621
  page: params.page,
1916
2622
  cursor: params.cursor,
@@ -1926,26 +2632,41 @@ var LexAPI = class {
1926
2632
  /**
1927
2633
  * Walk every page of `listNationalDocuments` via `cursor` (works past the
1928
2634
  * 1,000-row `page` ceiling, unlike passing `page` yourself). Each page is
1929
- * a separate billed call. Stops after a page with `hasMore: false` (or an
1930
- * empty page). Any `params.page` is ignored and never sent — pass
2635
+ * a separate billed call. Stops after a page whose `hasMore` is not `true`,
2636
+ * whose `nextCursor` is absent, `null` or empty, or that is empty. A
2637
+ * `nextCursor` the walk already sent, or one that is not a string, throws
2638
+ * `InvalidResponseError`; the pages already yielded stay valid, and the
2639
+ * page that showed the stall is not yielded and is on the error's `body`.
2640
+ * Any `params.page` is ignored and never sent — pass
1931
2641
  * `params.cursor` only to resume a walk you saved partway through;
1932
2642
  * `page` together with `cursor` is a 400 ("Use either cursor or page,
1933
2643
  * not both"), so this strips `page` at runtime, not just in the type
1934
2644
  * (`Omit` alone only guards TypeScript callers — a JS caller, or one
1935
- * using `as`, could otherwise still pass it through).
2645
+ * using `as`, could otherwise still pass it through). A `limit` that is
2646
+ * not a positive integer is a `RangeError` before any request.
1936
2647
  */
1937
2648
  async *paginateNationalDocuments(jurisdiction, params = {}, options) {
1938
2649
  const { page: _ignoredPage, ...rest } = params;
2650
+ startingPosition(void 0, rest.limit, 1);
1939
2651
  let cursor = rest.cursor;
2652
+ const sent = /* @__PURE__ */ new Set();
1940
2653
  for (; ; ) {
2654
+ if (typeof cursor === "string") sent.add(cursor);
1941
2655
  const page = await this.listNationalDocuments(
1942
2656
  jurisdiction,
1943
2657
  cursor !== void 0 ? { ...rest, cursor } : { ...rest },
1944
2658
  options
1945
2659
  );
2660
+ const results = page.results;
2661
+ const next = page.nextCursor;
2662
+ const ends = page.hasMore !== true || next === void 0 || next === null || next === "" || !Array.isArray(results) || results.length === 0;
2663
+ if (!ends) {
2664
+ if (typeof next !== "string") throw stalled("the server sent a page cursor that is not a string", page);
2665
+ if (sent.has(next)) throw stalled("the server repeated a page cursor", page);
2666
+ }
1946
2667
  yield page;
1947
- if (!page.hasMore || !page.nextCursor || page.results.length === 0) return;
1948
- cursor = page.nextCursor;
2668
+ if (ends) return;
2669
+ cursor = next;
1949
2670
  }
1950
2671
  }
1951
2672
  /**
@@ -1963,6 +2684,7 @@ var LexAPI = class {
1963
2684
  return this.call({
1964
2685
  method: "POST",
1965
2686
  path: `/${jurisdictionSegment(jurisdiction)}/search/semantic`,
2687
+ shape: { lists: ["results"], required: ["results"] },
1966
2688
  body: nationalSemanticWireBody(request),
1967
2689
  idempotent: true,
1968
2690
  timeoutMs: options?.timeoutMs,
@@ -1976,7 +2698,17 @@ var LexAPI = class {
1976
2698
  * `attribution` and `document` (the matched act's listing summary) on
1977
2699
  * every hit; the index fields (`law_title`, `article_ref`, `section`,
1978
2700
  * `language`, `in_force`, `valid_from`, `valid_to`, `law_type`) are
1979
- * always present, `null` when the index has nothing (API 2.8.0). No `hyde`, no `asOf` — both are EU-only.
2701
+ * always present, `null` when the index has nothing (API 2.8.0).
2702
+ *
2703
+ * **`asOf` (API 2.29.0)** labels each hit for a date (`asOfResolved`,
2704
+ * `asOfReason`, `asOfVersion`); the response adds `asOf` and
2705
+ * `asOfSummary`. The search runs over today's texts only. A hit is
2706
+ * resolved only when the publisher's dates, as of LexAPI's last recorded
2707
+ * read of the act (`asOfVersion.checkedAt`), show today's wording already
2708
+ * applied on the date; an unresolved hit keeps today's wording — it is not
2709
+ * established as the text for the date. LexAPI holds such dates for
2710
+ * Austria and Spain.
2711
+ *
1980
2712
  * `NationalSemanticLegislationOptions` has no `hyde` field, and this SDK
1981
2713
  * never forwards one on this call even if a caller bypasses the type
1982
2714
  * system — the server now validates `hyde` as a boolean on this route too
@@ -1988,7 +2720,8 @@ var LexAPI = class {
1988
2720
  return this.call({
1989
2721
  method: "POST",
1990
2722
  path: `/${jurisdictionSegment(jurisdiction)}/legislation/semantic`,
1991
- body: nationalSemanticWireBody(request, { allowHyde: false }),
2723
+ shape: { lists: ["results"], required: ["results"] },
2724
+ body: nationalSemanticWireBody(request, { allowHyde: false, allowAsOf: true }),
1992
2725
  idempotent: true,
1993
2726
  timeoutMs: options?.timeoutMs,
1994
2727
  signal: options?.signal
@@ -2018,7 +2751,8 @@ var LexAPI = class {
2018
2751
  return this.call({
2019
2752
  method: "POST",
2020
2753
  path: "/search/semantic",
2021
- body: semanticWireBody(request),
2754
+ shape: { lists: ["results"], required: ["results"] },
2755
+ body: semanticWireBody(request, { legislation: false }),
2022
2756
  idempotent: true,
2023
2757
  timeoutMs: options?.timeoutMs,
2024
2758
  signal: options?.signal
@@ -2040,6 +2774,11 @@ var LexAPI = class {
2040
2774
  * cannot be answered keeps its latest text with `asOfResolved: false` and
2041
2775
  * an `asOfReason`. The response adds `asOf` and `asOfSummary`.
2042
2776
  *
2777
+ * **In force today:** EU hits carry `inForce` (with `notInForceReason`,
2778
+ * `endOfValidity`, `entryIntoForce`) when the act's status is known;
2779
+ * `inForce: true` keeps only hits known to be in force today and reports
2780
+ * what it removed in `inForceFilter`.
2781
+ *
2043
2782
  * **Cost:** 5 credits for the search; with `asOf`, each live fetch of a
2044
2783
  * version the corpus does not hold reserves 5 and settles by outcome
2045
2784
  * (Cellar 4, browser 5, no text 1, failed 0) — at most 3 per request by
@@ -2050,7 +2789,59 @@ var LexAPI = class {
2050
2789
  return this.call({
2051
2790
  method: "POST",
2052
2791
  path: "/legislation/semantic",
2053
- body: semanticWireBody(request),
2792
+ shape: { lists: ["results"], required: ["results"] },
2793
+ body: semanticWireBody(request, { legislation: true }),
2794
+ idempotent: true,
2795
+ timeoutMs: options?.timeoutMs,
2796
+ signal: options?.signal
2797
+ });
2798
+ }
2799
+ /**
2800
+ * `POST /legislation/as-of` — the version of an EU regulation, directive
2801
+ * or decision listed for a date: the newest consolidated version dated on
2802
+ * or before it, or the act as published in the Official Journal when none
2803
+ * is. With `provision`, also that article, annex or recital range of the
2804
+ * version. Requires LexAPI API 2.26.0.
2805
+ *
2806
+ * **Unresolved is a normal return, not an error:** when the version or
2807
+ * the text cannot be established the call resolves with
2808
+ * `asOfResolved: false`, an `asOfReason` and no `provision`. Use
2809
+ * `provision.text` only when `asOfResolved` is `true`; `asOfVersion` can
2810
+ * also be present on an unresolved `provision` answer.
2811
+ * An unknown act throws `NotFoundError`; invalid input throws
2812
+ * `InvalidCelexError` / `InvalidParamsError`. An API older than 2.26.0
2813
+ * has no such endpoint and also answers 404 (`NotFoundError`).
2814
+ * `err.unknownEndpoint` is `false` there (the API sends it from 2.27.0):
2815
+ * check `err.message.includes("Unknown API endpoint")`.
2816
+ *
2817
+ * Consolidated versions have no legal force; only the act as published in
2818
+ * the Official Journal (`baseCelex`) is authentic. The answer does not say
2819
+ * whether an individual provision applied on that date, and
2820
+ * `act.inForceToday` is about today, not `asOf`. A retroactive amendment
2821
+ * counts from the date of the amending act.
2822
+ *
2823
+ * **Cost:** 1 credit when no text is fetched; when the provision's text
2824
+ * has to be fetched, 4 (5 when it is fetched live from EUR-Lex) whatever
2825
+ * the answer, and 1 if the fetch fails or finds no text. A fetch reserves
2826
+ * up to 5 credits: a pool holding fewer gets
2827
+ * `asOfReason: "insufficient_credits"`.
2828
+ */
2829
+ async legislationAsOf(request, options) {
2830
+ const body = { document: request.document, asOf: request.asOf };
2831
+ if (request.provision !== void 0) body["provision"] = request.provision;
2832
+ if (request.language !== void 0) body["language"] = request.language;
2833
+ return this.call({
2834
+ method: "POST",
2835
+ path: "/legislation/as-of",
2836
+ shape: {
2837
+ fields: [
2838
+ { path: "document", kind: "string" },
2839
+ { path: "asOfResolved", kind: "boolean" },
2840
+ { path: "act", kind: "object" },
2841
+ { path: "provenance", kind: "object" }
2842
+ ]
2843
+ },
2844
+ body,
2054
2845
  idempotent: true,
2055
2846
  timeoutMs: options?.timeoutMs,
2056
2847
  signal: options?.signal
@@ -2115,7 +2906,7 @@ var LexAPI = class {
2115
2906
  });
2116
2907
  }
2117
2908
  };
2118
- function semanticWireBody(request) {
2909
+ function semanticWireBody(request, { legislation }) {
2119
2910
  const body = { query: request.query };
2120
2911
  if (request.limit !== void 0) body["limit"] = request.limit;
2121
2912
  if (request.minScore !== void 0) body["min_score"] = request.minScore;
@@ -2123,10 +2914,11 @@ function semanticWireBody(request) {
2123
2914
  if (request.includeText) body["include"] = ["text"];
2124
2915
  if (request.filters !== void 0) body["filters"] = request.filters;
2125
2916
  if (request.hyde !== void 0) body["hyde"] = request.hyde;
2126
- if (request.asOf !== void 0) body["asOf"] = request.asOf;
2917
+ if (legislation && request.asOf !== void 0) body["asOf"] = request.asOf;
2918
+ if (legislation && request.inForce !== void 0) body["inForce"] = request.inForce;
2127
2919
  return body;
2128
2920
  }
2129
- function nationalSemanticWireBody(request, { allowHyde = true } = {}) {
2921
+ function nationalSemanticWireBody(request, { allowHyde = true, allowAsOf = false } = {}) {
2130
2922
  const body = { query: request.query };
2131
2923
  if (request.limit !== void 0) body["limit"] = request.limit;
2132
2924
  if (request.minScore !== void 0) body["min_score"] = request.minScore;
@@ -2134,6 +2926,7 @@ function nationalSemanticWireBody(request, { allowHyde = true } = {}) {
2134
2926
  if (request.includeText) body["include"] = ["text"];
2135
2927
  if (request.filters !== void 0) body["filters"] = request.filters;
2136
2928
  if (allowHyde && request.hyde !== void 0) body["hyde"] = request.hyde;
2929
+ if (allowAsOf && request.asOf !== void 0) body["asOf"] = request.asOf;
2137
2930
  return body;
2138
2931
  }
2139
2932
  function jurisdictionSegment(jurisdiction) {
@@ -2168,16 +2961,40 @@ function listParam(value) {
2168
2961
  if (value === void 0) return void 0;
2169
2962
  return typeof value === "string" ? value : value.join(",");
2170
2963
  }
2171
- async function* paginateEdges(fetchPage, rawRowsIn, params) {
2172
- const limit = params.limit ?? 100;
2173
- let offset = params.offset ?? 0;
2964
+ function edgeRows(group) {
2965
+ const listed = Array.isArray(group.citations) ? group.citations.length : 0;
2966
+ const counted = count(group.citationCount);
2967
+ return counted === void 0 || counted === 0 ? listed : counted;
2968
+ }
2969
+ async function* paginateEdges(fetchPage, groupsIn, params) {
2970
+ const start = startingPosition(params.offset, params.limit, 100);
2971
+ const limit = start.limit;
2972
+ let offset = start.offset;
2973
+ let previous;
2974
+ let repeats = 0;
2174
2975
  for (; ; ) {
2175
2976
  const page = await fetchPage({ ...params, limit, offset });
2977
+ const listed = groupsIn(page);
2978
+ const groups = Array.isArray(listed) ? listed : [];
2979
+ const echoed = count(page.offset);
2980
+ const totalEdges = count(page.totalEdges);
2981
+ if (echoed !== void 0 && echoed !== offset) throw stalled("the server did not advance", page);
2982
+ if (echoed === void 0 && totalEdges === void 0) {
2983
+ const form = compactForm(groups);
2984
+ repeats = form === previous ? repeats + 1 : 0;
2985
+ previous = form;
2986
+ if (repeats >= REPEATS_BEFORE_THROW) throw stalled("the server repeated the same page", page);
2987
+ } else {
2988
+ repeats = 0;
2989
+ previous = compactForm(groups);
2990
+ }
2176
2991
  yield page;
2177
- const pageLimit = page.limit && page.limit > 0 ? page.limit : limit;
2178
- const rows = rawRowsIn(page);
2992
+ const echoedLimit = count(page.limit);
2993
+ const pageLimit = echoedLimit !== void 0 && echoedLimit > 0 ? echoedLimit : limit;
2994
+ const rows = groups.reduce((n, g) => n + edgeRows(g), 0);
2179
2995
  offset += rows;
2180
2996
  if (rows === 0 || rows < pageLimit) return;
2997
+ if (totalEdges !== void 0 && offset >= totalEdges) return;
2181
2998
  }
2182
2999
  }
2183
3000
  function withHeaders(data, response, corpusVersion) {
@@ -2192,11 +3009,20 @@ function withHeaders(data, response, corpusVersion) {
2192
3009
  }
2193
3010
 
2194
3011
  // src/credits.ts
3012
+ function figure(value) {
3013
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
3014
+ }
3015
+ function resetsAt(fromCredits, fromUsage) {
3016
+ if (typeof fromCredits === "string") return fromCredits;
3017
+ if (typeof fromUsage === "string") return fromUsage;
3018
+ return (fromCredits === null || fromCredits === void 0) && fromUsage === null ? null : void 0;
3019
+ }
2195
3020
  function getCreditUsage(response) {
3021
+ if (typeof response !== "object" || response === null) response = {};
2196
3022
  return {
2197
- unitsCharged: response.credits?.operation_weight ?? 0,
2198
- creditsRemaining: response.credits?.remaining ?? response.usage?.remaining,
2199
- resetsAt: response.credits?.resetsAt ?? response.usage?.resetsAt
3023
+ unitsCharged: figure(response.credits?.operation_weight) ?? 0,
3024
+ creditsRemaining: figure(response.credits?.remaining) ?? figure(response.usage?.remaining),
3025
+ resetsAt: resetsAt(response.credits?.resetsAt, response.usage?.resetsAt)
2200
3026
  };
2201
3027
  }
2202
3028
 
@@ -2226,6 +3052,9 @@ function assertSecret(secret) {
2226
3052
  "Webhook secret is empty \u2014 pass the secret returned when the webhook was created"
2227
3053
  );
2228
3054
  }
3055
+ if (!isWellFormed(secret)) {
3056
+ throw new WebhookSignatureError("missing_secret", "Webhook secret is not well-formed Unicode (lone surrogate)");
3057
+ }
2229
3058
  }
2230
3059
  async function getSubtle() {
2231
3060
  const globalCrypto = globalThis.crypto;
@@ -2239,8 +3068,18 @@ async function getSubtle() {
2239
3068
  if (nodeCrypto.webcrypto?.subtle) return nodeCrypto.webcrypto.subtle;
2240
3069
  throw new Error("Web Crypto (crypto.subtle) is not available in this runtime");
2241
3070
  }
3071
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
3072
+ function isWellFormed(text2) {
3073
+ const native = String.prototype.isWellFormed;
3074
+ return typeof native === "function" ? native.call(text2) : !LONE_SURROGATE.test(text2);
3075
+ }
2242
3076
  function toBytes(body) {
2243
- if (typeof body === "string") return new TextEncoder().encode(body);
3077
+ if (typeof body === "string") {
3078
+ if (!isWellFormed(body)) {
3079
+ throw new WebhookSignatureError("malformed_body", "Webhook body string is not well-formed Unicode (lone surrogate)");
3080
+ }
3081
+ return new TextEncoder().encode(body);
3082
+ }
2244
3083
  if (body instanceof Uint8Array) return body;
2245
3084
  return new Uint8Array(body);
2246
3085
  }
@@ -2249,6 +3088,37 @@ function toHex(buffer) {
2249
3088
  for (const byte of new Uint8Array(buffer)) hex += byte.toString(16).padStart(2, "0");
2250
3089
  return hex;
2251
3090
  }
3091
+ function trimHeader(value) {
3092
+ const space = (code) => code === 32 || code === 9 || code === 13 || code === 10;
3093
+ let start = 0;
3094
+ let end = value.length;
3095
+ while (start < end && space(value.charCodeAt(start))) start++;
3096
+ while (end > start && space(value.charCodeAt(end - 1))) end--;
3097
+ return value.slice(start, end);
3098
+ }
3099
+ var TIMESTAMP = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?(?:Z|([+-])([0-9]{2}):([0-9]{2}))$/;
3100
+ function timestampMicros(value) {
3101
+ if (typeof value !== "string") return void 0;
3102
+ const match = TIMESTAMP.exec(value);
3103
+ if (!match) return void 0;
3104
+ const [y, mo, d, h, mi, sec] = match.slice(1, 7).map(Number);
3105
+ const fraction = match[7];
3106
+ const sign = match[8];
3107
+ const offH = sign === void 0 ? 0 : Number(match[9]);
3108
+ const offM = sign === void 0 ? 0 : Number(match[10]);
3109
+ const leap = y % 4 === 0 && y % 100 !== 0 || y % 400 === 0;
3110
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1];
3111
+ if (y < 1 || days === void 0 || d < 1 || d > days || h > 23 || mi > 59 || sec > 59 || offH > 23 || offM > 59) return void 0;
3112
+ const date = /* @__PURE__ */ new Date(0);
3113
+ date.setUTCFullYear(y, mo - 1, d);
3114
+ date.setUTCHours(h, mi, sec, 0);
3115
+ const micros2 = fraction === void 0 ? 0 : Number(fraction.slice(0, 6).padEnd(6, "0"));
3116
+ const offset = (sign === "-" ? -1 : 1) * (offH * 60 + offM) * 6e7;
3117
+ return BigInt(date.getTime()) * BigInt(1e3) + BigInt(micros2) - BigInt(offset);
3118
+ }
3119
+ function micros(ms) {
3120
+ return BigInt(Math.round(ms * 1e3));
3121
+ }
2252
3122
  function timingSafeEqual(a, b) {
2253
3123
  if (a.length !== b.length) return false;
2254
3124
  let diff = 0;
@@ -2268,31 +3138,49 @@ async function computeSignature(rawBody, secret) {
2268
3138
  return toHex(await subtle.sign("HMAC", key, toBytes(rawBody)));
2269
3139
  }
2270
3140
  async function verifySignature(rawBody, signature, secret) {
2271
- const candidate = typeof signature === "string" ? signature.trim().toLowerCase() : "";
3141
+ const candidate = typeof signature === "string" ? trimHeader(signature) : "";
3142
+ assertSecret(secret);
3143
+ if (typeof rawBody === "string" && !isWellFormed(rawBody)) return false;
2272
3144
  const expected = await computeSignature(rawBody, secret);
2273
- if (!/^[0-9a-f]{64}$/.test(candidate)) return false;
2274
- return timingSafeEqual(expected, candidate);
3145
+ if (!/^[0-9a-fA-F]{64}$/.test(candidate)) return false;
3146
+ return timingSafeEqual(expected, candidate.toLowerCase());
2275
3147
  }
2276
3148
  async function verifyWebhook(rawBody, signature, secret, options = {}) {
2277
3149
  assertSecret(secret);
3150
+ const toleranceMs = options.toleranceMs ?? 3e5;
3151
+ if (typeof toleranceMs !== "number" || Number.isNaN(toleranceMs)) {
3152
+ throw new RangeError(`toleranceMs must be a number, got ${String(toleranceMs)}`);
3153
+ }
2278
3154
  if (!signature) {
2279
3155
  throw new WebhookSignatureError("missing_signature", "Missing X-Webhook-Signature header");
2280
3156
  }
2281
- if (!await verifySignature(rawBody, signature, secret)) {
3157
+ if (typeof rawBody === "string" && !isWellFormed(rawBody)) {
3158
+ throw new WebhookSignatureError("invalid_signature", "Webhook body string is not well-formed Unicode (lone surrogate)");
3159
+ }
3160
+ const bytes = toBytes(rawBody);
3161
+ if (!await verifySignature(bytes, signature, secret)) {
2282
3162
  throw new WebhookSignatureError("invalid_signature", "X-Webhook-Signature does not match the body");
2283
3163
  }
2284
3164
  let payload;
2285
3165
  try {
2286
- const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(toBytes(rawBody));
2287
- payload = JSON.parse(text);
3166
+ const text2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes);
3167
+ payload = JSON.parse(text2);
2288
3168
  } catch {
2289
3169
  throw new WebhookSignatureError("malformed_body", "Webhook body is not valid JSON");
2290
3170
  }
2291
- const toleranceMs = options.toleranceMs ?? 3e5;
2292
- if (toleranceMs > 0) {
2293
- const sentAt = Date.parse(String(payload.timestamp));
3171
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
3172
+ throw new WebhookSignatureError("malformed_body", "Webhook body is not a JSON object");
3173
+ }
3174
+ if (toleranceMs !== 0) {
3175
+ const sentAt = timestampMicros(payload.timestamp);
2294
3176
  const now = options.now ?? Date.now();
2295
- if (Number.isNaN(sentAt) || Math.abs(now - sentAt) > toleranceMs) {
3177
+ let fresh = sentAt !== void 0 && toleranceMs > 0;
3178
+ if (fresh && toleranceMs !== Infinity) {
3179
+ const distance = micros(now) - sentAt;
3180
+ const limit = micros(toleranceMs);
3181
+ fresh = distance <= limit && -distance <= limit;
3182
+ }
3183
+ if (!fresh) {
2296
3184
  throw new WebhookSignatureError(
2297
3185
  "stale_timestamp",
2298
3186
  `Webhook timestamp is outside the ${toleranceMs} ms tolerance window`
@@ -2333,6 +3221,7 @@ var AS_OF_REASONS = [
2333
3221
  "no_longer_in_force",
2334
3222
  "in_force_dates_unknown",
2335
3223
  "not_in_language",
3224
+ "amendment_not_consolidated",
2336
3225
  "text_unavailable",
2337
3226
  "article_not_in_version",
2338
3227
  "part_not_resolvable",
@@ -2348,11 +3237,44 @@ var AS_OF_REASONS = [
2348
3237
  "insufficient_credits",
2349
3238
  "credit_check_failed"
2350
3239
  ];
3240
+ var AS_OF_LOOKUP_REASONS = [
3241
+ "not_yet_adopted",
3242
+ "not_yet_in_force",
3243
+ "no_longer_in_force",
3244
+ "in_force_dates_unknown",
3245
+ "act_type_not_supported",
3246
+ "version_list_unavailable",
3247
+ "version_lookup_cap",
3248
+ "not_in_language",
3249
+ "amendment_not_consolidated",
3250
+ "text_unavailable",
3251
+ "article_not_in_version",
3252
+ "provision_ambiguous",
3253
+ "version_not_parsed",
3254
+ "fetch_budget_exhausted",
3255
+ "fetch_pending",
3256
+ "fetch_capacity",
3257
+ "fetch_failed",
3258
+ "fetch_timeout",
3259
+ "request_deadline",
3260
+ "insufficient_credits",
3261
+ "credit_check_failed"
3262
+ ];
2351
3263
  function isNationalDecision(document2) {
2352
3264
  return document2.documentKind === "decision" && document2.decision != null;
2353
3265
  }
3266
+ var NATIONAL_AS_OF_REASONS = [
3267
+ "provision_amended_since",
3268
+ "no_longer_in_force",
3269
+ "provision_dates_unknown",
3270
+ "asof_not_available"
3271
+ ];
3272
+ function isNationalAsOfVersion(version) {
3273
+ return typeof version === "object" && version !== null && version.kind === "current_unit";
3274
+ }
2354
3275
  // Annotate the CommonJS export names for ESM import in node:
2355
3276
  0 && (module.exports = {
3277
+ AS_OF_LOOKUP_REASONS,
2356
3278
  AS_OF_REASONS,
2357
3279
  AuthenticationError,
2358
3280
  CITATION_PROVENANCES,
@@ -2370,12 +3292,14 @@ function isNationalDecision(document2) {
2370
3292
  InvalidUrlError,
2371
3293
  LexAPI,
2372
3294
  LexAPIError,
3295
+ NATIONAL_AS_OF_REASONS,
2373
3296
  NationalAllowanceExhaustedError,
2374
3297
  NationalSemanticFilterUnreachableError,
2375
3298
  NationalSemanticNotEnabledError,
2376
3299
  NationalSemanticUnavailableError,
2377
3300
  NetworkError,
2378
3301
  NotFoundError,
3302
+ PaymentPastDueError,
2379
3303
  RateLimitedError,
2380
3304
  RequestAbortedError,
2381
3305
  ServiceUnavailableError,
@@ -2391,6 +3315,7 @@ function isNationalDecision(document2) {
2391
3315
  computeSignature,
2392
3316
  getCreditUsage,
2393
3317
  isLexAPIError,
3318
+ isNationalAsOfVersion,
2394
3319
  isNationalDecision,
2395
3320
  normalizeRetryAfterSeconds,
2396
3321
  parseResponseHeaders,