@simpleapps-com/augur-api 2026.11.3 → 2026.11.5

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.
Files changed (66) hide show
  1. package/README.md +40 -3
  2. package/dist/client.d.ts +31 -1
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/core/base-client.d.ts.map +1 -1
  5. package/dist/core/call-rules.d.ts +35 -0
  6. package/dist/core/call-rules.d.ts.map +1 -1
  7. package/dist/core/call.d.ts +2 -2
  8. package/dist/core/call.d.ts.map +1 -1
  9. package/dist/core/client-rules.d.ts +152 -0
  10. package/dist/core/client-rules.d.ts.map +1 -0
  11. package/dist/core/client.d.ts +36 -5
  12. package/dist/core/client.d.ts.map +1 -1
  13. package/dist/core/config.d.ts +24 -0
  14. package/dist/core/config.d.ts.map +1 -1
  15. package/dist/core/encoded-segment.d.ts +7 -1
  16. package/dist/core/encoded-segment.d.ts.map +1 -1
  17. package/dist/core/errors.d.ts.map +1 -1
  18. package/dist/core/http-rules.d.ts +0 -32
  19. package/dist/core/http-rules.d.ts.map +1 -1
  20. package/dist/core/proxy-rules.d.ts +53 -0
  21. package/dist/core/proxy-rules.d.ts.map +1 -1
  22. package/dist/core/registry-rules.d.ts +7 -0
  23. package/dist/core/registry-rules.d.ts.map +1 -1
  24. package/dist/core/registry.d.ts.map +1 -1
  25. package/dist/core/response-rules.d.ts +15 -0
  26. package/dist/core/response-rules.d.ts.map +1 -1
  27. package/dist/core/schemas.d.ts.map +1 -1
  28. package/dist/core/service-proxy.d.ts.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +774 -327
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +774 -327
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/services/goog-mc/generated/schemas.d.ts +8 -0
  36. package/dist/services/goog-mc/generated/schemas.d.ts.map +1 -1
  37. package/dist/services/goog-mc/generated/types.d.ts +8 -0
  38. package/dist/services/goog-mc/generated/types.d.ts.map +1 -1
  39. package/dist/services/items/client.d.ts +1 -1
  40. package/dist/services/items/generated/endpoints.d.ts.map +1 -1
  41. package/dist/services/items/generated/schemas.d.ts +8 -0
  42. package/dist/services/items/generated/schemas.d.ts.map +1 -1
  43. package/dist/services/items/generated/types.d.ts +13 -4
  44. package/dist/services/items/generated/types.d.ts.map +1 -1
  45. package/dist/services/joomla/generated/endpoints.d.ts.map +1 -1
  46. package/dist/services/joomla/generated/schemas.d.ts +5 -0
  47. package/dist/services/joomla/generated/schemas.d.ts.map +1 -1
  48. package/dist/services/joomla/generated/types.d.ts +18 -2
  49. package/dist/services/joomla/generated/types.d.ts.map +1 -1
  50. package/dist/services/legacy/generated/endpoints.d.ts.map +1 -1
  51. package/dist/services/legacy/generated/schemas.d.ts +2 -0
  52. package/dist/services/legacy/generated/schemas.d.ts.map +1 -1
  53. package/dist/services/legacy/generated/types.d.ts +4 -0
  54. package/dist/services/legacy/generated/types.d.ts.map +1 -1
  55. package/dist/services/open-search/generated/endpoints.d.ts.map +1 -1
  56. package/dist/services/open-search/generated/schemas.d.ts +2 -0
  57. package/dist/services/open-search/generated/schemas.d.ts.map +1 -1
  58. package/dist/services/open-search/generated/types.d.ts +4 -0
  59. package/dist/services/open-search/generated/types.d.ts.map +1 -1
  60. package/dist/testing.d.ts.map +1 -1
  61. package/dist/testing.js +22 -9
  62. package/dist/testing.js.map +1 -1
  63. package/dist/testing.mjs +20 -9
  64. package/dist/testing.mjs.map +1 -1
  65. package/dist/utils/cross-site-auth.d.ts.map +1 -1
  66. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -140,6 +140,9 @@ function joinFrom(xs, sep, i) {
140
140
  if (i >= xs.length) return "";
141
141
  return joinRange(xs, sep, i, xs.length);
142
142
  }
143
+ function joinOr(xs, sep, fallback) {
144
+ return xs.length === 0 ? fallback : joinFrom(xs, sep, 0);
145
+ }
143
146
  function joinRange(xs, sep, lo, hi) {
144
147
  if (hi - lo === 1) return xs[lo];
145
148
  const mid = lo + Math.floor((hi - lo) / 2);
@@ -156,6 +159,13 @@ function notInFrom(xs, allowed, i) {
156
159
  return hasItemFrom(allowed, xs[i], 0) ? rest : [xs[i], ...rest];
157
160
  }
158
161
 
162
+ // ../utils/src/pairs.ts
163
+ function allFrom(xs, i) {
164
+ if (i === xs.length) return true;
165
+ if (!xs[i]) return false;
166
+ return allFrom(xs, i + 1);
167
+ }
168
+
159
169
  // ../utils/src/uri.ts
160
170
  function isHigh(c) {
161
171
  return c >= 55296 && c <= 56319;
@@ -204,6 +214,25 @@ function isEncoded(s) {
204
214
  }
205
215
  return true;
206
216
  }
217
+ function pcharOf(hex) {
218
+ if (hex === "24") return "$";
219
+ if (hex === "26") return "&";
220
+ if (hex === "2B") return "+";
221
+ if (hex === "2C") return ",";
222
+ if (hex === "3B") return ";";
223
+ if (hex === "3D") return "=";
224
+ if (hex === "3A") return ":";
225
+ if (hex === "40") return "@";
226
+ return "";
227
+ }
228
+ function restorePcharFrom(s, i) {
229
+ if (i >= s.length) return "";
230
+ if (s.slice(i, i + 1) === "%" && i + 3 <= s.length) {
231
+ const ch = pcharOf(s.slice(i + 1, i + 3));
232
+ if (ch !== "") return ch + restorePcharFrom(s, i + 3);
233
+ }
234
+ return s.slice(i, i + 1) + restorePcharFrom(s, i + 1);
235
+ }
207
236
 
208
237
  // ../utils/src/replace.ts
209
238
  function replaceText(s, find, put) {
@@ -215,6 +244,21 @@ function replaceText(s, find, put) {
215
244
  }
216
245
 
217
246
  // src/core/call-rules.ts
247
+ function isEnvelopeBody(isPlainObject, allKeys) {
248
+ return isPlainObject && allKeys;
249
+ }
250
+ function callBodyKind(isJson) {
251
+ return isJson ? "json" : "text";
252
+ }
253
+ function validationMessageOf(kind) {
254
+ return kind === "params" ? "Invalid request parameters" : "Invalid API response structure\nThis appears to be a response validation error. The API returned data in an unexpected format.";
255
+ }
256
+ function issueCodeOf(type) {
257
+ return type !== void 0 ? type : "unknown";
258
+ }
259
+ function appendsIssues(count) {
260
+ return count > 0;
261
+ }
218
262
  function isQueryKeyAllowed(declared, edgeCache, key) {
219
263
  return declared || edgeCache && key === "edgeCache";
220
264
  }
@@ -253,11 +297,6 @@ function placeholderFilled(path, placeholder, segment) {
253
297
  return replaceText(path, "{" + placeholder + "}", segment);
254
298
  }
255
299
 
256
- // ../json-values/src/index.ts
257
- function isRecord(value) {
258
- return typeof value === "object" && value !== null && !Array.isArray(value);
259
- }
260
-
261
300
  // ../foundation/src/duration.ts
262
301
  function seconds(n) {
263
302
  return n;
@@ -267,6 +306,7 @@ function toMillis(d) {
267
306
  }
268
307
 
269
308
  // src/core/config.ts
309
+ var NO_BOUNDS = { signals: [] };
270
310
  var DEFAULT_CONFIG = {
271
311
  timeout: toMillis(seconds(30)),
272
312
  retries: 3,
@@ -281,7 +321,145 @@ var ContextCreationError = class extends Error {
281
321
  field;
282
322
  };
283
323
 
324
+ // ../foundation/src/optional.ts
325
+ function nonEmptyOr(s, fallback) {
326
+ return s !== "" ? s : fallback;
327
+ }
328
+
329
+ // ../foundation/src/decimal.ts
330
+ function decimal(n) {
331
+ const last = "0123456789".slice(n % 10, n % 10 + 1);
332
+ return n < 10 ? last : decimal(Math.floor(n / 10)) + last;
333
+ }
334
+
335
+ // ../json-values/src/index.ts
336
+ function isRecord(value) {
337
+ return typeof value === "object" && value !== null && !Array.isArray(value);
338
+ }
339
+
340
+ // ../utils/src/http.ts
341
+ function isPostOrPut(method) {
342
+ return method === "POST" || method === "PUT";
343
+ }
344
+ function querySeparator(url) {
345
+ return includesFrom(url, "?", 0) ? "&" : "?";
346
+ }
347
+ function queryValueSent(isUndefined, isNull) {
348
+ return !isUndefined && !isNull;
349
+ }
350
+ function urlWithQuery(url, query) {
351
+ return query === "" ? url : url + querySeparator(url) + query;
352
+ }
353
+ function isRetryableStatus(status) {
354
+ return !(status >= 400 && status < 500 && status !== 429);
355
+ }
356
+ function exponentialDelay(base, attempt) {
357
+ if (attempt === 0) return base;
358
+ return 2 * exponentialDelay(base, attempt - 1);
359
+ }
360
+ function cappedAt(d, cap) {
361
+ return Math.min(d, cap);
362
+ }
363
+ function firstGiven(hasA, a, hasB, b, fallback) {
364
+ if (hasA) return a;
365
+ return hasB ? b : fallback;
366
+ }
367
+ function isAbortName(name) {
368
+ return name === "AbortError" || name === "TimeoutError";
369
+ }
370
+ function remainingOf(deadline, elapsed) {
371
+ return elapsed < deadline ? deadline - elapsed : 0;
372
+ }
373
+ function cutToRemaining(value, hasDeadline, remaining) {
374
+ return hasDeadline && remaining < value ? remaining : value;
375
+ }
376
+ function startsAttempt(hasDeadline, remaining) {
377
+ return !hasDeadline || remaining > 0;
378
+ }
379
+
380
+ // src/core/client-rules.ts
381
+ function contextRefusalOf(hasContext, siteIdTruthy, contextTokenTruthy, finalTokenTruthy) {
382
+ if (!hasContext) return "context";
383
+ if (!siteIdTruthy) return "site-id";
384
+ if (!contextTokenTruthy) return "token";
385
+ return finalTokenTruthy ? "ok" : "token-removed";
386
+ }
387
+ function retryableError(isAugurError, status) {
388
+ return !isAugurError || isRetryableStatus(status);
389
+ }
390
+ function retryAfterCall(attempt, retries, retryable, callAborted) {
391
+ return !callAborted && attempt < retries && retryable;
392
+ }
393
+ function needsAttemptTimer(perAttempt, hasDeadline, remaining) {
394
+ return !(hasDeadline && remaining <= perAttempt);
395
+ }
396
+ function boundedCall(hasSignal, hasDeadline) {
397
+ return hasSignal || hasDeadline;
398
+ }
399
+ function deadlineInRange(deadline) {
400
+ return 0 <= deadline && deadline <= 2147483647;
401
+ }
402
+ function callOptionsAccepted(hasSignal, isAbortSignal, hasDeadline, inRange) {
403
+ return (!hasSignal || isAbortSignal) && (!hasDeadline || inRange);
404
+ }
405
+ function sharesInFlight(hasRequestSignal) {
406
+ return !hasRequestSignal;
407
+ }
408
+ function mergedDeadlineOf(hasOuter, outer, hasInner, inner) {
409
+ if (!hasOuter) return inner;
410
+ if (!hasInner) return outer;
411
+ return inner < outer ? inner : outer;
412
+ }
413
+ function hasMergedDeadline(hasOuter, hasInner) {
414
+ return hasOuter || hasInner;
415
+ }
416
+ function edgeCacheKindOf(text) {
417
+ if (text === "30s" || text === "1m" || text === "5m") return "sub-hour";
418
+ const hourly = text === "1" || text === "2" || text === "3" || text === "4" || text === "5" || text === "8";
419
+ return hourly ? "hourly" : "invalid";
420
+ }
421
+ function edgeCacheKeyOf(kind, text) {
422
+ return kind === "invalid" ? "" : "cacheSiteId" + text;
423
+ }
424
+ function errorClassOf(status) {
425
+ if (status === 400) return "validation";
426
+ if (status === 401) return "authentication";
427
+ if (status === 404) return "notFound";
428
+ if (status === 429) return "rateLimit";
429
+ return "augur";
430
+ }
431
+ function detailMessageOf(isJson, isObject, isText, message) {
432
+ if (isJson && isObject && isText && message !== "") return message;
433
+ return void 0;
434
+ }
435
+ function defaultMessageOf(kind, status) {
436
+ if (kind === "validation") return "Validation failed";
437
+ if (kind === "authentication") return "Authentication failed";
438
+ if (kind === "notFound") return "Resource not found";
439
+ if (kind === "rateLimit") return "Rate limit exceeded";
440
+ return "Request failed with status " + decimal(status);
441
+ }
442
+ function errorMessageOf(given, kind, status) {
443
+ return given !== void 0 ? given : defaultMessageOf(kind, status);
444
+ }
445
+ function crossSiteUserIdOf(isId, id) {
446
+ return isId ? decimal(id) : void 0;
447
+ }
448
+ function responseHookOf(ok, hasOnError, hasOnResponse) {
449
+ if (ok) return hasOnResponse ? "onResponse" : "noHook";
450
+ return hasOnError ? "onError" : "noHook";
451
+ }
452
+ function crossSiteOutcomeOf(isVerified, tokenIsText, token) {
453
+ if (!isVerified) return "notVerified";
454
+ if (!tokenIsText || token === "") return "noToken";
455
+ return "signedIn";
456
+ }
457
+ function rawRetries(method) {
458
+ return method === "GET";
459
+ }
460
+
284
461
  // src/core/errors.ts
462
+ var ROOT_PATH = "root";
285
463
  var AugurError = class _AugurError extends Error {
286
464
  code;
287
465
  statusCode;
@@ -320,8 +498,7 @@ var ValidationError = class extends AugurError {
320
498
  return [];
321
499
  }
322
500
  return this.validationErrors.map((error) => {
323
- const path = error.path.length > 0 ? error.path.join(".") : "root";
324
- return `${path}: ${error.message}`;
501
+ return `${joinOr(error.path.map(String), ".", ROOT_PATH)}: ${error.message}`;
325
502
  });
326
503
  }
327
504
  /**
@@ -333,7 +510,7 @@ var ValidationError = class extends AugurError {
333
510
  return [];
334
511
  }
335
512
  return this.validationErrors.map((error) => ({
336
- path: error.path.length > 0 ? error.path.join(".") : "root",
513
+ path: joinOr(error.path.map(String), ".", ROOT_PATH),
337
514
  message: error.message,
338
515
  code: error.code,
339
516
  received: "received" in error ? error.received : void 0,
@@ -347,7 +524,7 @@ var ValidationError = class extends AugurError {
347
524
  toString() {
348
525
  const baseMessage = super.toString();
349
526
  const formattedErrors = this.getFormattedErrors();
350
- if (formattedErrors.length > 0) {
527
+ if (appendsIssues(formattedErrors.length)) {
351
528
  return `${baseMessage}
352
529
  Validation errors:
353
530
  ${formattedErrors.map((err) => ` - ${err}`).join("\n")}`;
@@ -392,21 +569,39 @@ var InvalidArgumentError = class extends AugurError {
392
569
  }
393
570
  };
394
571
 
395
- // src/core/http-rules.ts
396
- function isRetryableStatus(status) {
397
- return !(status >= 400 && status < 500 && status !== 429);
572
+ // ../auth-core/src/site.ts
573
+ function isSiteChar(c) {
574
+ return c >= 97 && c <= 122 || c >= 48 && c <= 57 || c === 95 || c === 45;
398
575
  }
399
- function exponentialDelay(base, attempt) {
400
- if (attempt === 0) return base;
401
- return 2 * exponentialDelay(base, attempt - 1);
576
+ function siteCharsFrom(s, i) {
577
+ return i >= s.length || isSiteChar(s.charCodeAt(i)) && siteCharsFrom(s, i + 1);
402
578
  }
403
- function cappedDelay(d) {
404
- return Math.min(d, 3e4);
579
+ function isSiteId(s) {
580
+ return s.length > 0 && siteCharsFrom(s, 0);
581
+ }
582
+
583
+ // src/core/site-id-check.ts
584
+ function isSiteId2(s) {
585
+ return isSiteId(s);
586
+ }
587
+
588
+ // src/core/site-id.ts
589
+ function parseSiteId(value) {
590
+ return isSiteId2(value) ? value : void 0;
405
591
  }
406
- function timeoutOf(hasRequest, request, hasClient, client, fallback) {
407
- if (hasRequest) return request;
408
- return hasClient ? client : fallback;
592
+ function assertSiteId(value) {
593
+ const site = parseSiteId(value);
594
+ if (site === void 0) {
595
+ throw new InvalidArgumentError({
596
+ message: "Invalid siteId: expected lowercase letters, digits, '_' and '-' (e.g. example-site)",
597
+ service: "",
598
+ endpoint: ""
599
+ });
600
+ }
601
+ return site;
409
602
  }
603
+
604
+ // src/core/http-rules.ts
410
605
  function isPublicEndpoint(url) {
411
606
  return endsWith(url, "/health-check") || endsWith(url, "/ping");
412
607
  }
@@ -416,9 +611,6 @@ function sendsBearer(url, hasToken) {
416
611
  function sendsJsonBody(hasData, method) {
417
612
  return hasData && method !== "GET";
418
613
  }
419
- function querySeparator(url) {
420
- return includesFrom(url, "?", 0) ? "&" : "?";
421
- }
422
614
  function requestKey(method, url, params) {
423
615
  return method + ":" + url + ":" + params;
424
616
  }
@@ -427,6 +619,7 @@ function isEdgeCacheParam(key) {
427
619
  }
428
620
 
429
621
  // src/core/client.ts
622
+ var MAX_RETRY_DELAY_MS = 3e4;
430
623
  function parseJson(text) {
431
624
  try {
432
625
  return { json: true, value: JSON.parse(String(text)) };
@@ -440,16 +633,29 @@ function errorDetail(text) {
440
633
  return { detail: {} };
441
634
  }
442
635
  const body = parsed.value;
443
- const detail = typeof body === "object" && body !== null ? body : {};
444
- const message = typeof detail.message === "string" && detail.message !== "" ? detail.message : void 0;
636
+ const isObject = typeof body === "object" && body !== null;
637
+ const detail = isObject ? body : {};
638
+ const given = detail.message;
639
+ const isText = typeof given === "string";
640
+ const message = detailMessageOf(true, isObject, isText, isText ? given : "");
445
641
  return { detail, message };
446
642
  }
447
- var STATUS_ERRORS = {
448
- 400: (message, ctx) => new ValidationError({ message: message ?? "Validation failed", ...ctx, validationErrors: [] }),
449
- 401: (message, ctx) => new AuthenticationError({ message: message ?? "Authentication failed", ...ctx }),
450
- 404: (message, ctx) => new NotFoundError({ message: message ?? "Resource not found", ...ctx }),
451
- 429: (message, ctx) => new RateLimitError({ message: message ?? "Rate limit exceeded", ...ctx })
452
- };
643
+ function statusError(status, message, ctx, detail) {
644
+ const kind = errorClassOf(status);
645
+ const text = errorMessageOf(message, kind, status);
646
+ if (kind === "validation")
647
+ return new ValidationError({ message: text, ...ctx, validationErrors: [] });
648
+ if (kind === "authentication") return new AuthenticationError({ message: text, ...ctx });
649
+ if (kind === "notFound") return new NotFoundError({ message: text, ...ctx });
650
+ if (kind === "rateLimit") return new RateLimitError({ message: text, ...ctx });
651
+ return new AugurError({
652
+ message: text,
653
+ code: nonEmptyOr(detail.code ?? "", "API_ERROR"),
654
+ statusCode: status,
655
+ ...ctx,
656
+ requestId: detail.requestId
657
+ });
658
+ }
453
659
  function generateRequestKey(method, url, params) {
454
660
  const paramsStr = params ? JSON.stringify(params, Object.keys(params).sort()) : "";
455
661
  return requestKey(method, url, paramsStr);
@@ -457,13 +663,62 @@ function generateRequestKey(method, url, params) {
457
663
  function calculateBackoffDelay(attempt, baseDelay) {
458
664
  const exponential = exponentialDelay(baseDelay, attempt);
459
665
  const jitter = Math.random() * 0.3 * exponential;
460
- return cappedDelay(exponential + jitter);
666
+ return cappedAt(exponential + jitter, MAX_RETRY_DELAY_MS);
461
667
  }
462
668
  function isRetryableError(error) {
463
- return !(error instanceof AugurError) || isRetryableStatus(error.statusCode);
669
+ const isAugurError = error instanceof AugurError;
670
+ return retryableError(isAugurError, isAugurError ? error.statusCode : 0);
671
+ }
672
+ function delay(ms, signal) {
673
+ return new Promise((resolve, reject) => {
674
+ const onAbort = () => {
675
+ clearTimeout(timer);
676
+ reject(signal.reason);
677
+ };
678
+ const timer = setTimeout(() => {
679
+ signal?.removeEventListener("abort", onAbort);
680
+ resolve();
681
+ }, ms);
682
+ signal?.addEventListener("abort", onAbort, { once: true });
683
+ });
684
+ }
685
+ var UNBOUNDED = {
686
+ signal: void 0,
687
+ hasDeadline: false,
688
+ remaining: () => 0,
689
+ dispose: () => {
690
+ }
691
+ };
692
+ function throwIfEnded(call) {
693
+ if (call.signal?.aborted) throw call.signal.reason;
464
694
  }
465
- function delay(ms) {
466
- return new Promise((resolve) => setTimeout(resolve, ms));
695
+ function startCall(bounds, requestSignal) {
696
+ const sources = requestSignal === void 0 ? [...bounds.signals] : [...bounds.signals, requestSignal];
697
+ const deadline = bounds.deadline;
698
+ if (!boundedCall(sources.length > 0, deadline !== void 0)) return UNBOUNDED;
699
+ const controller = new AbortController();
700
+ const started = Date.now();
701
+ const listeners = sources.map((source) => {
702
+ const onAbort = () => controller.abort(source.reason);
703
+ source.addEventListener("abort", onAbort, { once: true });
704
+ return { source, onAbort };
705
+ });
706
+ for (const source of sources) {
707
+ if (source.aborted) controller.abort(source.reason);
708
+ }
709
+ const timer = deadline === void 0 ? void 0 : setTimeout(
710
+ () => controller.abort(new DOMException("Call deadline exceeded", "TimeoutError")),
711
+ deadline
712
+ );
713
+ return {
714
+ signal: controller.signal,
715
+ hasDeadline: deadline !== void 0,
716
+ remaining: () => remainingOf(deadline ?? 0, Date.now() - started),
717
+ dispose: () => {
718
+ clearTimeout(timer);
719
+ for (const { source, onAbort } of listeners) source.removeEventListener("abort", onAbort);
720
+ }
721
+ };
467
722
  }
468
723
  function withoutEdgeCache(params) {
469
724
  return Object.fromEntries(Object.entries(params).filter(([key]) => !isEdgeCacheParam(key)));
@@ -486,15 +741,11 @@ function buildUrlWithParams(url, params) {
486
741
  const searchParams = new URLSearchParams();
487
742
  const paramsObj = params;
488
743
  for (const [key, value] of Object.entries(paramsObj)) {
489
- if (value !== void 0 && value !== null) {
744
+ if (queryValueSent(value === void 0, value === null)) {
490
745
  searchParams.append(key, String(value));
491
746
  }
492
747
  }
493
- const queryString = searchParams.toString();
494
- if (!queryString) {
495
- return url;
496
- }
497
- return `${url}${querySeparator(url)}${queryString}`;
748
+ return urlWithQuery(url, searchParams.toString());
498
749
  }
499
750
  function headersToRecord(headers) {
500
751
  const record32 = {};
@@ -507,18 +758,33 @@ var HTTPClient = class {
507
758
  config;
508
759
  serviceName;
509
760
  inflightRequests = /* @__PURE__ */ new Map();
510
- constructor(serviceName, config) {
761
+ bounds;
762
+ /**
763
+ * The siteId this client sends (`x-site-id`, and the value of every `cacheSiteId` edge
764
+ * directive): a `SiteId`, so only a proved `isSiteId` string reaches the header or Cloudflare's
765
+ * cache key (AugurApiClient.EdgeDirectiveCarriesASiteId; owner 2026-11-10).
766
+ */
767
+ siteId;
768
+ /**
769
+ * `bounds` bound every call this client makes (a view's, from `AugurAPI.withRequest`).
770
+ *
771
+ * @throws InvalidArgumentError when `config.siteId` is not a siteId (as `AugurAPI` does)
772
+ */
773
+ constructor(serviceName, config, bounds = NO_BOUNDS) {
511
774
  this.serviceName = serviceName;
512
775
  this.config = { ...DEFAULT_CONFIG, ...config };
776
+ this.siteId = assertSiteId(this.config.siteId);
777
+ this.bounds = bounds;
513
778
  }
514
779
  /**
515
- * Build request headers with auth
780
+ * Build request headers with auth. A request's own headers come before `x-site-id` and
781
+ * `Authorization`, so neither can be replaced by one (AugurApiClient.SiteIdHeaderIsTheClients).
516
782
  */
517
783
  buildRequestHeaders(url, requestConfig) {
518
784
  const headers = {
519
785
  "Content-Type": "application/json",
520
- "x-site-id": this.config.siteId,
521
- ...requestConfig?.headers
786
+ ...requestConfig?.headers,
787
+ "x-site-id": this.siteId
522
788
  };
523
789
  if (sendsBearer(url, Boolean(this.config.bearerToken))) {
524
790
  headers["Authorization"] = `Bearer ${this.config.bearerToken}`;
@@ -535,9 +801,10 @@ var HTTPClient = class {
535
801
  } catch {
536
802
  }
537
803
  const { detail, message } = errorDetail(text);
538
- if (this.config.onError) {
804
+ const { onError, onResponse } = this.config;
805
+ if (responseHookOf(response.ok, onError !== void 0, onResponse !== void 0) === "onError") {
539
806
  const augurError = {
540
- message: message ?? `Request failed with status ${response.status}`,
807
+ message: errorMessageOf(message, "augur", response.status),
541
808
  config: augurConfig,
542
809
  response: {
543
810
  data: detail,
@@ -547,7 +814,7 @@ var HTTPClient = class {
547
814
  config: augurConfig
548
815
  }
549
816
  };
550
- await this.config.onError(augurError);
817
+ await onError(augurError);
551
818
  }
552
819
  this.handleHttpError(response.status, { ...detail, message }, endpoint);
553
820
  }
@@ -563,8 +830,9 @@ var HTTPClient = class {
563
830
  headers: headersToRecord(response.headers),
564
831
  config: augurConfig
565
832
  };
566
- if (this.config.onResponse) {
567
- const modified = await this.config.onResponse(augurResponse);
833
+ const { onError, onResponse } = this.config;
834
+ if (responseHookOf(response.ok, onError !== void 0, onResponse !== void 0) === "onResponse") {
835
+ const modified = await onResponse(augurResponse);
568
836
  return modified.data;
569
837
  }
570
838
  return responseData;
@@ -574,8 +842,9 @@ var HTTPClient = class {
574
842
  */
575
843
  async readRaw(response, augurConfig) {
576
844
  let text = await response.text();
577
- if (this.config.onResponse) {
578
- const modified = await this.config.onResponse({
845
+ const { onError, onResponse } = this.config;
846
+ if (responseHookOf(response.ok, onError !== void 0, onResponse !== void 0) === "onResponse") {
847
+ const modified = await onResponse({
579
848
  data: text,
580
849
  status: response.status,
581
850
  statusText: response.statusText,
@@ -594,35 +863,63 @@ var HTTPClient = class {
594
863
  * Core request method using native fetch. `read` turns a 2xx response into
595
864
  * the result, inside the same error handling and timeout as the fetch.
596
865
  */
597
- async request(method, url, options, read = (r, c) => this.handleFetchSuccess(r, c)) {
866
+ async request(method, url, options, call, read = (r, c) => this.handleFetchSuccess(r, c)) {
598
867
  const { config: requestConfig } = options;
599
868
  const endpoint = requestConfig?.endpoint ?? url;
600
- const timeout = this.timeoutFor(requestConfig);
601
- let augurConfig = this.baseRequest(method, url, options, timeout);
869
+ const bounds = this.attemptBounds(requestConfig, call);
870
+ let augurConfig = this.baseRequest(method, url, options, bounds.timeout);
602
871
  if (this.config.onRequest) {
603
872
  augurConfig = await this.config.onRequest(augurConfig);
604
873
  }
605
874
  const fullUrl = buildUrlWithParams(augurConfig.url, augurConfig.params);
606
- const controller = new AbortController();
607
- const timeoutId = setTimeout(() => controller.abort(), timeout);
608
- const signal = requestConfig?.signal ? this.mergeSignals(requestConfig.signal, controller.signal) : controller.signal;
875
+ throwIfEnded(call);
876
+ const attempt = this.attemptSignal(call, bounds);
609
877
  try {
610
- const response = await fetch(fullUrl, fetchOptionsFor(augurConfig, method, signal));
878
+ const response = await fetch(fullUrl, fetchOptionsFor(augurConfig, method, attempt.signal));
611
879
  if (!response.ok) {
612
880
  await this.handleFetchError(response, augurConfig, endpoint);
613
881
  }
614
882
  return await read(response, augurConfig);
615
883
  } catch (error) {
884
+ throwIfEnded(call);
616
885
  this.rethrowOrWrapError(error, endpoint);
617
886
  } finally {
618
- clearTimeout(timeoutId);
887
+ attempt.dispose();
619
888
  }
620
889
  }
621
- /** The request's timeout: per request, else the client's, else the default (timeoutOf). */
890
+ /**
891
+ * An attempt's timeout (the per-attempt one, cut to what is left of the call's deadline: what
892
+ * the onRequest hook sees) and whether it sets its own timer: only when it ends before the
893
+ * deadline; otherwise the call's one deadline timer cuts it, with a TimeoutError
894
+ * (client-rules.ts; AugurApiClient.OneTimerCutsEachAttempt).
895
+ */
896
+ attemptBounds(requestConfig, call) {
897
+ const perAttempt = this.timeoutFor(requestConfig);
898
+ const remaining = call.remaining();
899
+ return {
900
+ timeout: cutToRemaining(perAttempt, call.hasDeadline, remaining),
901
+ ownTimer: needsAttemptTimer(perAttempt, call.hasDeadline, remaining)
902
+ };
903
+ }
904
+ /** The signal one attempt is sent with, and how to clear its timer and listeners after. */
905
+ attemptSignal(call, bounds) {
906
+ const controller = new AbortController();
907
+ const timeoutId = bounds.ownTimer ? setTimeout(() => controller.abort(), bounds.timeout) : void 0;
908
+ const merged = call.signal ? this.mergeSignals(call.signal, controller.signal) : { signal: controller.signal, dispose: () => {
909
+ } };
910
+ return {
911
+ signal: merged.signal,
912
+ dispose: () => {
913
+ clearTimeout(timeoutId);
914
+ merged.dispose();
915
+ }
916
+ };
917
+ }
918
+ /** The request's timeout: per request, else the client's, else the default (firstGiven). */
622
919
  timeoutFor(requestConfig) {
623
920
  const request = requestConfig?.timeout;
624
921
  const client = this.config.timeout;
625
- return timeoutOf(
922
+ return firstGiven(
626
923
  request !== void 0,
627
924
  request ?? 0,
628
925
  client !== void 0,
@@ -642,17 +939,20 @@ var HTTPClient = class {
642
939
  };
643
940
  }
644
941
  /**
645
- * Merge two AbortSignals — aborts when either fires
942
+ * Merge the call's signal and an attempt's timer: aborts when either fires, with that one's
943
+ * reason. `dispose` removes the listener from the call's signal, which outlives the attempt
944
+ * (one per attempt would pile up on a long-lived caller signal).
646
945
  */
647
- mergeSignals(userSignal, timeoutSignal) {
946
+ mergeSignals(callSignal, timeoutSignal) {
648
947
  const controller = new AbortController();
649
- const onAbort = () => controller.abort();
650
- userSignal.addEventListener("abort", onAbort, { once: true });
651
- timeoutSignal.addEventListener("abort", onAbort, { once: true });
652
- if (userSignal.aborted) {
653
- controller.abort();
654
- }
655
- return controller.signal;
948
+ const onCallAbort = () => controller.abort(callSignal.reason);
949
+ const onTimeout = () => controller.abort(timeoutSignal.reason);
950
+ callSignal.addEventListener("abort", onCallAbort, { once: true });
951
+ timeoutSignal.addEventListener("abort", onTimeout, { once: true });
952
+ return {
953
+ signal: controller.signal,
954
+ dispose: () => callSignal.removeEventListener("abort", onCallAbort)
955
+ };
656
956
  }
657
957
  /**
658
958
  * The one status-to-error switch, shared by typed methods and `call()`.
@@ -662,18 +962,7 @@ var HTTPClient = class {
662
962
  * @ensures thrown.endpoint = endpoint (callers pass the path template, so no param values leak)
663
963
  */
664
964
  handleHttpError(status, data, endpoint) {
665
- const ctx = { service: this.serviceName, endpoint };
666
- const specific = STATUS_ERRORS[status];
667
- if (specific) {
668
- throw specific(data.message, ctx);
669
- }
670
- throw new AugurError({
671
- message: data.message ?? `Request failed with status ${status}`,
672
- code: data.code || "API_ERROR",
673
- statusCode: status,
674
- ...ctx,
675
- requestId: data.requestId
676
- });
965
+ throw statusError(status, data.message, { service: this.serviceName, endpoint }, data);
677
966
  }
678
967
  /**
679
968
  * Re-throw known error types or wrap as network error
@@ -682,14 +971,14 @@ var HTTPClient = class {
682
971
  if (error instanceof AugurError) {
683
972
  throw error;
684
973
  }
685
- if (error instanceof DOMException && error.name === "AbortError") {
974
+ if (error instanceof DOMException && isAbortName(error.name)) {
686
975
  throw error;
687
976
  }
688
977
  this.handleNetworkError(error, endpoint);
689
978
  }
690
979
  handleNetworkError(error, endpoint) {
691
980
  throw new AugurError({
692
- message: error.message || "Network error",
981
+ message: nonEmptyOr(error.message ?? "", "Network error"),
693
982
  code: "NETWORK_ERROR",
694
983
  statusCode: 0,
695
984
  service: this.serviceName,
@@ -699,25 +988,48 @@ var HTTPClient = class {
699
988
  /**
700
989
  * Executes a single request attempt
701
990
  */
702
- async executeAttempt(requestFn, attempt, maxRetries, baseDelay) {
991
+ async executeAttempt(requestFn, attempt, maxRetries, baseDelay, call) {
703
992
  try {
704
- return await requestFn();
993
+ return await this.attemptWithin(call, requestFn);
705
994
  } catch (error) {
706
- if (attempt >= maxRetries || !isRetryableError(error)) {
995
+ if (!retryAfterCall(attempt, maxRetries, isRetryableError(error), call.signal?.aborted === true)) {
707
996
  throw error;
708
997
  }
709
- const backoffDelay = calculateBackoffDelay(attempt, baseDelay);
710
- await delay(backoffDelay);
711
- return this.executeAttempt(requestFn, attempt + 1, maxRetries, baseDelay);
998
+ const backoffDelay = cutToRemaining(
999
+ calculateBackoffDelay(attempt, baseDelay),
1000
+ call.hasDeadline,
1001
+ call.remaining()
1002
+ );
1003
+ await delay(backoffDelay, call.signal);
1004
+ return this.executeAttempt(requestFn, attempt + 1, maxRetries, baseDelay, call);
712
1005
  }
713
1006
  }
1007
+ /**
1008
+ * One attempt, started only while the call's deadline has time left (client-rules.ts
1009
+ * startsAttempt); past it the call rejects with a TimeoutError.
1010
+ */
1011
+ attemptWithin(call, requestFn) {
1012
+ if (!startsAttempt(call.hasDeadline, call.remaining())) {
1013
+ return Promise.reject(new DOMException("Call deadline exceeded", "TimeoutError"));
1014
+ }
1015
+ return requestFn();
1016
+ }
714
1017
  /**
715
1018
  * Executes a request with retry logic
716
1019
  */
717
- async executeWithRetry(requestFn) {
1020
+ async executeWithRetry(requestFn, call) {
718
1021
  const maxRetries = this.config.retries ?? DEFAULT_CONFIG.retries;
719
1022
  const baseDelay = this.config.retryDelay ?? DEFAULT_CONFIG.retryDelay;
720
- return this.executeAttempt(requestFn, 0, maxRetries, baseDelay);
1023
+ return this.executeAttempt(requestFn, 0, maxRetries, baseDelay, call);
1024
+ }
1025
+ /** Runs `fn` in a fresh call scope and disposes it, however `fn` settles. */
1026
+ async withinCall(requestSignal, fn) {
1027
+ const call = startCall(this.bounds, requestSignal);
1028
+ try {
1029
+ return await fn(call);
1030
+ } finally {
1031
+ call.dispose();
1032
+ }
721
1033
  }
722
1034
  /**
723
1035
  * Transform edgeCache parameter to Cloudflare's cacheSiteId format
@@ -745,64 +1057,64 @@ var HTTPClient = class {
745
1057
  if (edgeCache == null) {
746
1058
  return params;
747
1059
  }
748
- const validSubHourValues = ["30s", "1m", "5m"];
749
- const validHourlyValues = [1, 2, 3, 4, 5, 8];
750
- let cacheSuffix;
751
1060
  const edgeCacheStr = String(edgeCache);
752
- if (validSubHourValues.includes(edgeCacheStr)) {
753
- cacheSuffix = edgeCacheStr;
754
- } else {
755
- const cacheHours = parseInt(edgeCacheStr, 10);
756
- if (!validHourlyValues.includes(cacheHours)) {
757
- return withoutEdgeCache(paramsObj);
758
- }
759
- cacheSuffix = String(cacheHours);
1061
+ const kind = edgeCacheKindOf(edgeCacheStr);
1062
+ if (kind === "invalid") {
1063
+ return withoutEdgeCache(paramsObj);
760
1064
  }
761
- const restParams = withoutEdgeCache(paramsObj);
762
- const cacheKey = `cacheSiteId${cacheSuffix}`;
1065
+ const cacheKey = edgeCacheKeyOf(kind, edgeCacheStr);
763
1066
  return {
764
- ...restParams,
765
- [cacheKey]: this.config.siteId
1067
+ ...withoutEdgeCache(paramsObj),
1068
+ [cacheKey]: this.siteId
766
1069
  };
767
1070
  }
768
1071
  async get(url, params, config) {
769
1072
  const transformedParams = this.transformEdgeCacheParams(params);
770
1073
  const method = "GET";
771
1074
  const requestKey2 = generateRequestKey(method, url, transformedParams);
772
- const inflight = this.inflightRequests.get(requestKey2);
1075
+ const shares = sharesInFlight(config?.signal !== void 0);
1076
+ const inflight = shares ? this.inflightRequests.get(requestKey2) : void 0;
773
1077
  if (inflight) {
774
1078
  return inflight;
775
1079
  }
776
- const requestPromise = this.executeWithRetry(
777
- () => this.request(method, url, { params: transformedParams, config })
778
- ).finally(() => {
1080
+ const requestPromise = this.withinCall(
1081
+ config?.signal,
1082
+ (call) => this.executeWithRetry(
1083
+ () => this.request(method, url, { params: transformedParams, config }, call),
1084
+ call
1085
+ )
1086
+ );
1087
+ if (!shares) return requestPromise;
1088
+ const shared = requestPromise.finally(() => {
779
1089
  this.inflightRequests.delete(requestKey2);
780
1090
  });
781
- this.inflightRequests.set(requestKey2, requestPromise);
782
- return requestPromise;
1091
+ this.inflightRequests.set(requestKey2, shared);
1092
+ return shared;
783
1093
  }
784
1094
  // The API declares query params on POST/PUT/DELETE as well as GET. `request`
785
1095
  // already carries both a body and a query slot; these wrappers simply never
786
1096
  // exposed the latter, leaving those params unreachable from the clients.
1097
+ // Writes make one attempt (never retried), bounded by the call's scope like a GET.
787
1098
  async post(url, data, params, config) {
788
- return this.request("POST", url, {
789
- data,
790
- params: this.transformEdgeCacheParams(params),
791
- config
792
- });
1099
+ const options = { data, params: this.transformEdgeCacheParams(params), config };
1100
+ return this.withinCall(
1101
+ config?.signal,
1102
+ (call) => this.attemptWithin(call, () => this.request("POST", url, options, call))
1103
+ );
793
1104
  }
794
1105
  async put(url, data, params, config) {
795
- return this.request("PUT", url, {
796
- data,
797
- params: this.transformEdgeCacheParams(params),
798
- config
799
- });
1106
+ const options = { data, params: this.transformEdgeCacheParams(params), config };
1107
+ return this.withinCall(
1108
+ config?.signal,
1109
+ (call) => this.attemptWithin(call, () => this.request("PUT", url, options, call))
1110
+ );
800
1111
  }
801
1112
  async delete(url, params, config) {
802
- return this.request("DELETE", url, {
803
- params: this.transformEdgeCacheParams(params),
804
- config
805
- });
1113
+ const options = { params: this.transformEdgeCacheParams(params), config };
1114
+ return this.withinCall(
1115
+ config?.signal,
1116
+ (call) => this.attemptWithin(call, () => this.request("DELETE", url, options, call))
1117
+ );
806
1118
  }
807
1119
  /**
808
1120
  * Send a request and return the 2xx response as text, with no schema
@@ -811,20 +1123,23 @@ var HTTPClient = class {
811
1123
  * in-flight deduplication); other methods make one attempt, like `post()`.
812
1124
  */
813
1125
  async raw(method, url, options = {}) {
814
- const send = () => this.request(
815
- method,
816
- url,
817
- { ...options, params: this.transformEdgeCacheParams(options.params) },
818
- (response, augurConfig) => this.readRaw(response, augurConfig)
819
- );
820
- return method === "GET" ? this.executeWithRetry(send) : send();
1126
+ const requestOptions = { ...options, params: this.transformEdgeCacheParams(options.params) };
1127
+ return this.withinCall(options.config?.signal, (call) => {
1128
+ const send = () => this.request(
1129
+ method,
1130
+ url,
1131
+ requestOptions,
1132
+ call,
1133
+ (response, augurConfig) => this.readRaw(response, augurConfig)
1134
+ );
1135
+ return rawRetries(method) ? this.executeWithRetry(send, call) : this.attemptWithin(call, send);
1136
+ });
821
1137
  }
822
1138
  };
823
1139
 
824
1140
  // src/core/encoded-segment.ts
825
- var PCHAR_RESTORE_RE = /%(?:24|26|2B|2C|3B|3D|3A|40)/g;
826
1141
  function encodePathSegment(value) {
827
- const encoded = encodeURIComponent(value).replace(PCHAR_RESTORE_RE, decodeURIComponent);
1142
+ const encoded = restorePcharFrom(encodeURIComponent(value), 0);
828
1143
  if (!isEncoded(encoded)) {
829
1144
  throw new InvalidArgumentError({
830
1145
  message: "Encoded path segment has an unexpected shape",
@@ -838,17 +1153,20 @@ function fillPlaceholder(path, placeholder, segment) {
838
1153
  return placeholderFilled(path, placeholder, segment);
839
1154
  }
840
1155
  function renderPath(template, segments) {
841
- return template.replace(/\{([^}]+)\}/g, (_, name) => {
842
- const segment = segments[name];
843
- if (segment === void 0) {
844
- throw new InvalidArgumentError({
845
- message: `No path value for {${name}}`,
846
- service: "",
847
- endpoint: template
848
- });
849
- }
850
- return segment;
851
- });
1156
+ const names = templateNames(template, 0);
1157
+ const missing = notInFrom(names, Object.keys(segments), 0);
1158
+ if (missing.length > 0) {
1159
+ throw new InvalidArgumentError({
1160
+ message: `No path value for {${missing[0]}}`,
1161
+ service: "",
1162
+ endpoint: template
1163
+ });
1164
+ }
1165
+ let path = template;
1166
+ for (const name of names) {
1167
+ path = fillPlaceholder(path, name, segments[name]);
1168
+ }
1169
+ return path;
852
1170
  }
853
1171
 
854
1172
  // src/core/path-validation.ts
@@ -865,6 +1183,17 @@ var validatePathSegment = (pathTemplate, name, value, pattern, service = "http-c
865
1183
  }
866
1184
  };
867
1185
 
1186
+ // ../utils/src/slices.ts
1187
+ function beforeLastCode(s, code) {
1188
+ return s.slice(0, endBefore(lastIndexOfCode(s, code, s.length), s.length));
1189
+ }
1190
+ function withLastSegment(id, segment) {
1191
+ return beforeLastCode(id, 46) + "." + segment;
1192
+ }
1193
+ function endBefore(k, len) {
1194
+ return k >= 0 ? k : Math.max(len - 1, 0);
1195
+ }
1196
+
868
1197
  // ../utils/src/case-spec.ts
869
1198
  var UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
870
1199
  function upperFirst(s) {
@@ -886,6 +1215,13 @@ function foldName(s) {
886
1215
  if (c === 45 || c === 95) return foldName(s.slice(1));
887
1216
  return lowerAscii(s.slice(0, 1)) + foldName(s.slice(1));
888
1217
  }
1218
+ function foldMatchesFrom(names, key, k) {
1219
+ if (k === names.length) return [];
1220
+ const name = names[k];
1221
+ const rest = foldMatchesFrom(names, key, k + 1);
1222
+ if (foldName(name) !== foldName(key)) return rest;
1223
+ return [name, ...rest];
1224
+ }
889
1225
  function snakeCamel(s) {
890
1226
  if (codeAt(s, 0) === 95) {
891
1227
  const c = codeAt(s, 1);
@@ -899,20 +1235,10 @@ function kebabCamel(s) {
899
1235
  return kebabCamelFrom(s, false);
900
1236
  }
901
1237
 
902
- // ../utils/src/slices.ts
903
- function beforeLastCode(s, code) {
904
- return s.slice(0, endBefore(lastIndexOfCode(s, code, s.length), s.length));
905
- }
906
- function endBefore(k, len) {
907
- return k >= 0 ? k : Math.max(len - 1, 0);
908
- }
909
-
910
- // ../utils/src/http.ts
911
- function isPostOrPut(method) {
912
- return method === "POST" || method === "PUT";
913
- }
914
-
915
1238
  // src/core/registry-rules.ts
1239
+ function endpointIdOf(service, chain, action) {
1240
+ return kebabCamel(service) + "." + chain + "." + action;
1241
+ }
916
1242
  function hasBodyFor(method) {
917
1243
  return isPostOrPut(method);
918
1244
  }
@@ -936,6 +1262,14 @@ function syncedTotal(total, totalResults) {
936
1262
  function syncedTotalResults(total, totalResults) {
937
1263
  return totalResults === 0 ? Math.max(total, 0) : totalResults;
938
1264
  }
1265
+ function countChanged(count, dataLength) {
1266
+ return normalCount(count, dataLength) !== count;
1267
+ }
1268
+ function totalsChangeOf(total, totalResults) {
1269
+ if (syncedTotal(total, totalResults) !== total) return "total";
1270
+ if (syncedTotalResults(total, totalResults) !== totalResults) return "totalResults";
1271
+ return "kept";
1272
+ }
939
1273
  function warnsOnNormalization(hasEnv, env) {
940
1274
  return hasEnv && env !== "production";
941
1275
  }
@@ -949,23 +1283,23 @@ var logNormalizationWarning = (message) => {
949
1283
  }
950
1284
  };
951
1285
  var normalizeCount = (count, actualDataLength) => {
952
- const normal = normalCount(count, actualDataLength);
953
- if (normal !== count) {
1286
+ if (countChanged(count, actualDataLength)) {
954
1287
  logNormalizationWarning(`'count' was 0 but data has ${actualDataLength} items`);
955
1288
  }
956
- return normal;
1289
+ return normalCount(count, actualDataLength);
957
1290
  };
958
1291
  var normalizeTotals = (total, totalResults) => {
959
- const synced = {
960
- total: syncedTotal(total, totalResults),
961
- totalResults: syncedTotalResults(total, totalResults)
962
- };
963
- if (synced.total !== total) {
1292
+ const change = totalsChangeOf(total, totalResults);
1293
+ if (change === "total") {
964
1294
  logNormalizationWarning(`'total' was 0 but 'totalResults' is ${totalResults}`);
965
- } else if (synced.totalResults !== totalResults) {
1295
+ }
1296
+ if (change === "totalResults") {
966
1297
  logNormalizationWarning(`'totalResults' was 0 but 'total' is ${total}`);
967
1298
  }
968
- return synced;
1299
+ return {
1300
+ total: syncedTotal(total, totalResults),
1301
+ totalResults: syncedTotalResults(total, totalResults)
1302
+ };
969
1303
  };
970
1304
  var BaseResponseSchema = (dataSchema) => v.pipe(
971
1305
  v.looseObject({
@@ -8791,7 +9125,11 @@ var ProductsListDataSchema = v11.array(
8791
9125
  dateLastBuilt: v11.nullable(v11.string()),
8792
9126
  checkoutLinkTemplate: v11.nullable(v11.string()),
8793
9127
  dateLastStatus: v11.nullable(v11.string()),
8794
- dateLastChanged: v11.nullable(v11.string())
9128
+ dateLastChanged: v11.nullable(v11.string()),
9129
+ imageWidth: v11.nullable(v11.number()),
9130
+ imageHeight: v11.nullable(v11.number()),
9131
+ additionalImageWidth: v11.nullable(v11.number()),
9132
+ additionalImageHeight: v11.nullable(v11.number())
8795
9133
  })
8796
9134
  );
8797
9135
  var ProductsGetDataSchema = v11.looseObject({
@@ -8842,7 +9180,11 @@ var ProductsGetDataSchema = v11.looseObject({
8842
9180
  dateLastBuilt: v11.nullable(v11.string()),
8843
9181
  checkoutLinkTemplate: v11.nullable(v11.string()),
8844
9182
  dateLastStatus: v11.nullable(v11.string()),
8845
- dateLastChanged: v11.nullable(v11.string())
9183
+ dateLastChanged: v11.nullable(v11.string()),
9184
+ imageWidth: v11.nullable(v11.number()),
9185
+ imageHeight: v11.nullable(v11.number()),
9186
+ additionalImageWidth: v11.nullable(v11.number()),
9187
+ additionalImageHeight: v11.nullable(v11.number())
8846
9188
  });
8847
9189
  var SitemapsItemsListDataSchema = v11.array(
8848
9190
  v11.looseObject({ id: v11.string(), link: v11.string(), lastModified: v11.nullable(v11.string()) })
@@ -9455,6 +9797,8 @@ var InvMastFaqListParamsSchema = v13.looseObject({
9455
9797
  });
9456
9798
  var InvMastInvAccessoryListParamsSchema = v13.looseObject({
9457
9799
  ...EdgeCacheParamsSchema.entries,
9800
+ classId5ExcludeList: v13.optional(v13.string()),
9801
+ classId5List: v13.optional(v13.string()),
9458
9802
  limit: v13.optional(v13.pipe(v13.unknown(), v13.transform(Number))),
9459
9803
  offset: v13.optional(v13.pipe(v13.unknown(), v13.transform(Number))),
9460
9804
  orderBy: v13.optional(v13.string()),
@@ -9491,6 +9835,11 @@ var InvMastPromotionalGroupsListParamsSchema = v13.looseObject({
9491
9835
  ])
9492
9836
  )
9493
9837
  });
9838
+ var InvMastSimilarListParamsSchema = v13.looseObject({
9839
+ ...EdgeCacheParamsSchema.entries,
9840
+ classId5ExcludeList: v13.optional(v13.string()),
9841
+ classId5List: v13.optional(v13.string())
9842
+ });
9494
9843
  var InvPeriodUsageListParamsSchema = v13.looseObject({
9495
9844
  ...EdgeCacheParamsSchema.entries,
9496
9845
  demandPeriodUid: v13.optional(v13.pipe(v13.unknown(), v13.transform(Number))),
@@ -15209,11 +15558,13 @@ var endpoints12 = [
15209
15558
  aliases: [],
15210
15559
  pathParams: ["invMastUid"],
15211
15560
  pathPatterns: { invMastUid: "^\\d+$" },
15212
- queryParams: ["limit", "offset", "orderBy", "statusCd"],
15561
+ queryParams: ["classId5ExcludeList", "classId5List", "limit", "offset", "orderBy", "statusCd"],
15213
15562
  edgeCache: true,
15214
15563
  summary: "List accessory items",
15215
15564
  params: {
15216
15565
  invMastUid: { in: "path", type: "integer", required: true },
15566
+ classId5ExcludeList: { in: "query", type: "string", required: false },
15567
+ classId5List: { in: "query", type: "string", required: false },
15217
15568
  limit: { in: "query", type: "integer", required: false },
15218
15569
  offset: { in: "query", type: "integer", required: false },
15219
15570
  orderBy: { in: "query", type: "string", required: false },
@@ -15313,10 +15664,14 @@ var endpoints12 = [
15313
15664
  aliases: [],
15314
15665
  pathParams: ["invMastUid"],
15315
15666
  pathPatterns: { invMastUid: "^\\d+$" },
15316
- queryParams: [],
15667
+ queryParams: ["classId5ExcludeList", "classId5List"],
15317
15668
  edgeCache: true,
15318
15669
  summary: "List similar items",
15319
- params: { invMastUid: { in: "path", type: "integer", required: true } },
15670
+ params: {
15671
+ invMastUid: { in: "path", type: "integer", required: true },
15672
+ classId5ExcludeList: { in: "query", type: "string", required: false },
15673
+ classId5List: { in: "query", type: "string", required: false }
15674
+ },
15320
15675
  responseSchema: InvMastSimilarListDataSchema,
15321
15676
  responseType: "array"
15322
15677
  },
@@ -16876,12 +17231,14 @@ var ContentListParamsSchema = v14.looseObject({
16876
17231
  var ContentGetParamsSchema = v14.looseObject({
16877
17232
  ...EdgeCacheParamsSchema.entries,
16878
17233
  alias: v14.optional(v14.string()),
16879
- catid: v14.optional(v14.pipe(v14.unknown(), v14.transform(Number)))
17234
+ catid: v14.optional(v14.pipe(v14.unknown(), v14.transform(Number))),
17235
+ includeUnpublished: v14.optional(v14.string())
16880
17236
  });
16881
17237
  var ContentDocListParamsSchema = v14.looseObject({
16882
17238
  ...EdgeCacheParamsSchema.entries,
16883
17239
  alias: v14.optional(v14.string()),
16884
- catid: v14.optional(v14.pipe(v14.unknown(), v14.transform(Number)))
17240
+ catid: v14.optional(v14.pipe(v14.unknown(), v14.transform(Number))),
17241
+ includeUnpublished: v14.optional(v14.string())
16885
17242
  });
16886
17243
  var MenuListParamsSchema = v14.looseObject({
16887
17244
  ...EdgeCacheParamsSchema.entries,
@@ -17046,7 +17403,8 @@ var ContentListDataSchema = v14.array(
17046
17403
  images: v14.union([v14.record(v14.string(), v14.unknown()), v14.array(v14.unknown())]),
17047
17404
  fields: v14.array(
17048
17405
  v14.looseObject({ value: v14.string(), title: v14.string(), name: v14.string(), label: v14.string() })
17049
- )
17406
+ ),
17407
+ state: v14.number()
17050
17408
  })
17051
17409
  );
17052
17410
  var ContentGetDataSchema = v14.looseObject({
@@ -17055,7 +17413,8 @@ var ContentGetDataSchema = v14.looseObject({
17055
17413
  alias: v14.string(),
17056
17414
  introtext: v14.nullable(v14.string()),
17057
17415
  fulltext: v14.nullable(v14.string()),
17058
- catid: v14.number()
17416
+ catid: v14.number(),
17417
+ state: v14.number()
17059
17418
  });
17060
17419
  var ContentDocListDataSchema = v14.looseObject({
17061
17420
  id: v14.number(),
@@ -17068,7 +17427,8 @@ var ContentDocListDataSchema = v14.looseObject({
17068
17427
  images: v14.union([v14.record(v14.string(), v14.unknown()), v14.array(v14.unknown())]),
17069
17428
  fields: v14.array(
17070
17429
  v14.looseObject({ value: v14.string(), title: v14.string(), name: v14.string(), label: v14.string() })
17071
- )
17430
+ ),
17431
+ state: v14.number()
17072
17432
  });
17073
17433
  var MenuListDataSchema = v14.array(
17074
17434
  v14.looseObject({
@@ -17479,13 +17839,14 @@ var endpoints13 = [
17479
17839
  aliases: [],
17480
17840
  pathParams: ["id"],
17481
17841
  pathPatterns: { id: "^\\d+$" },
17482
- queryParams: ["alias", "catid"],
17842
+ queryParams: ["alias", "catid", "includeUnpublished"],
17483
17843
  edgeCache: true,
17484
17844
  summary: "Get Content Detail",
17485
17845
  params: {
17486
17846
  id: { in: "path", type: "integer", required: true },
17487
17847
  alias: { in: "query", type: "string", required: false },
17488
- catid: { in: "query", type: "integer", required: false }
17848
+ catid: { in: "query", type: "integer", required: false },
17849
+ includeUnpublished: { in: "query", type: "string", required: false }
17489
17850
  },
17490
17851
  responseSchema: ContentGetDataSchema,
17491
17852
  responseType: "object"
@@ -17498,13 +17859,14 @@ var endpoints13 = [
17498
17859
  aliases: ["get"],
17499
17860
  pathParams: ["id"],
17500
17861
  pathPatterns: { id: "^\\d+$" },
17501
- queryParams: ["alias", "catid"],
17862
+ queryParams: ["alias", "catid", "includeUnpublished"],
17502
17863
  edgeCache: true,
17503
17864
  summary: "Get Content Doc",
17504
17865
  params: {
17505
17866
  id: { in: "path", type: "integer", required: true },
17506
17867
  alias: { in: "query", type: "string", required: false },
17507
- catid: { in: "query", type: "integer", required: false }
17868
+ catid: { in: "query", type: "integer", required: false },
17869
+ includeUnpublished: { in: "query", type: "string", required: false }
17508
17870
  },
17509
17871
  responseSchema: ContentDocListDataSchema,
17510
17872
  responseType: "object"
@@ -17857,6 +18219,8 @@ var endpoints13 = [
17857
18219
  var v15 = __toESM(require("valibot"));
17858
18220
  var InvMastAlsoBoughtListParamsSchema = v15.looseObject({
17859
18221
  ...EdgeCacheParamsSchema.entries,
18222
+ classId5ExcludeList: v15.optional(v15.string()),
18223
+ classId5List: v15.optional(v15.string()),
17860
18224
  statusCd: v15.optional(
17861
18225
  v15.union([
17862
18226
  v15.array(v15.pipe(v15.unknown(), v15.transform(Number))),
@@ -18360,11 +18724,13 @@ var endpoints14 = [
18360
18724
  aliases: [],
18361
18725
  pathParams: ["invMastUid"],
18362
18726
  pathPatterns: { invMastUid: "^\\d+$" },
18363
- queryParams: ["statusCd"],
18727
+ queryParams: ["classId5ExcludeList", "classId5List", "statusCd"],
18364
18728
  edgeCache: true,
18365
18729
  summary: "List item Also Bought",
18366
18730
  params: {
18367
18731
  invMastUid: { in: "path", type: "integer", required: true },
18732
+ classId5ExcludeList: { in: "query", type: "string", required: false },
18733
+ classId5List: { in: "query", type: "string", required: false },
18368
18734
  statusCd: { in: "query", type: "integer|integer[]", required: false }
18369
18735
  },
18370
18736
  responseSchema: InvMastAlsoBoughtListDataSchema,
@@ -20150,6 +20516,7 @@ var ItemSearchListParamsSchema = v19.looseObject({
20150
20516
  jobNumbers: v19.optional(v19.string()),
20151
20517
  operator: v19.optional(v19.string()),
20152
20518
  parentCategoryUid: v19.optional(v19.pipe(v19.unknown(), v19.transform(Number))),
20519
+ productGroupIdList: v19.optional(v19.string()),
20153
20520
  q: v19.string(),
20154
20521
  searchType: v19.string(),
20155
20522
  size: v19.optional(v19.pipe(v19.unknown(), v19.transform(Number))),
@@ -20172,6 +20539,7 @@ var ItemSearchFacetsListParamsSchema = v19.looseObject({
20172
20539
  jobNumbers: v19.optional(v19.string()),
20173
20540
  operator: v19.optional(v19.string()),
20174
20541
  parentCategoryUid: v19.optional(v19.pipe(v19.unknown(), v19.transform(Number))),
20542
+ productGroupIdList: v19.optional(v19.string()),
20175
20543
  q: v19.string(),
20176
20544
  searchType: v19.optional(v19.string()),
20177
20545
  size: v19.optional(v19.pipe(v19.unknown(), v19.transform(Number))),
@@ -20487,6 +20855,7 @@ var endpoints18 = [
20487
20855
  "jobNumbers",
20488
20856
  "operator",
20489
20857
  "parentCategoryUid",
20858
+ "productGroupIdList",
20490
20859
  "q",
20491
20860
  "searchType",
20492
20861
  "size",
@@ -20510,6 +20879,7 @@ var endpoints18 = [
20510
20879
  jobNumbers: { in: "query", type: "string", required: false },
20511
20880
  operator: { in: "query", type: "string", required: false },
20512
20881
  parentCategoryUid: { in: "query", type: "integer", required: false },
20882
+ productGroupIdList: { in: "query", type: "string", required: false },
20513
20883
  q: { in: "query", type: "string", required: true },
20514
20884
  searchType: { in: "query", type: "string", required: true },
20515
20885
  size: { in: "query", type: "integer", required: false },
@@ -20542,6 +20912,7 @@ var endpoints18 = [
20542
20912
  "jobNumbers",
20543
20913
  "operator",
20544
20914
  "parentCategoryUid",
20915
+ "productGroupIdList",
20545
20916
  "q",
20546
20917
  "searchType",
20547
20918
  "size",
@@ -20565,6 +20936,7 @@ var endpoints18 = [
20565
20936
  jobNumbers: { in: "query", type: "string", required: false },
20566
20937
  operator: { in: "query", type: "string", required: false },
20567
20938
  parentCategoryUid: { in: "query", type: "integer", required: false },
20939
+ productGroupIdList: { in: "query", type: "string", required: false },
20568
20940
  q: { in: "query", type: "string", required: true },
20569
20941
  searchType: { in: "query", type: "string", required: false },
20570
20942
  size: { in: "query", type: "integer", required: false },
@@ -39631,9 +40003,9 @@ function frozenParams(params) {
39631
40003
  }
39632
40004
  function fromRow(service, row) {
39633
40005
  return Object.freeze({
39634
- // the id root is the generator's rule too (utils kebabCamel, the model's ServiceId), so an
39635
- // id is the same whichever side built it: open-search → openSearch
39636
- id: `${kebabCamel(service)}.${row.chain}.${row.action}`,
40006
+ // the generator's rule too (proved endpointIdOf, the model's EndpointId), so an id is the
40007
+ // same whichever side built it: open-search → openSearch
40008
+ id: endpointIdOf(service, row.chain, row.action),
39637
40009
  service,
39638
40010
  method: row.method,
39639
40011
  path: row.path,
@@ -39652,7 +40024,7 @@ function fromRow(service, row) {
39652
40024
  function baseEntries(service) {
39653
40025
  return BASE_ENDPOINTS.map(
39654
40026
  ([chain, path, auth, summary]) => Object.freeze({
39655
- id: `${kebabCamel(service)}.${chain}.get`,
40027
+ id: endpointIdOf(service, chain, "get"),
39656
40028
  service,
39657
40029
  method: "GET",
39658
40030
  path,
@@ -39686,9 +40058,8 @@ function buildIndex() {
39686
40058
  const map = /* @__PURE__ */ new Map();
39687
40059
  for (const entry of registryEntries()) {
39688
40060
  map.set(entry.id, entry);
39689
- const chain = beforeLastCode(entry.id, 46);
39690
40061
  for (const alias of entry.aliases) {
39691
- map.set(`${chain}.${alias}`, entry);
40062
+ map.set(withLastSegment(entry.id, alias), entry);
39692
40063
  }
39693
40064
  }
39694
40065
  return map;
@@ -39727,7 +40098,7 @@ function rejectUnknown(entry, kind, keys, allowed) {
39727
40098
  }
39728
40099
  function checkArgs(entry, args) {
39729
40100
  const pathKeys = Object.keys(args.pathParams ?? {});
39730
- const missing = entry.pathParams.filter((name) => !pathKeys.includes(name));
40101
+ const missing = notInFrom([...entry.pathParams], pathKeys, 0);
39731
40102
  if (missing.length > 0) {
39732
40103
  throw invalid(missingPathMessage(entry.id, joinFrom(missing, ", ", 0)), entry);
39733
40104
  }
@@ -39751,62 +40122,62 @@ function fillPath(entry, pathParams) {
39751
40122
  return renderPath(entry.path, segments);
39752
40123
  }
39753
40124
  function toEnvelope(body) {
39754
- if (typeof body !== "object" || body === null || Array.isArray(body)) {
39755
- return null;
39756
- }
39757
- const record32 = body;
39758
- if (!ENVELOPE_KEYS.every((key) => key in record32)) {
40125
+ const isPlainObject = typeof body === "object" && body !== null && !Array.isArray(body);
40126
+ const record32 = isPlainObject ? body : {};
40127
+ const present = ENVELOPE_KEYS.map((key) => key in record32);
40128
+ if (!isEnvelopeBody(isPlainObject, allFrom(present, 0))) {
39759
40129
  return null;
39760
40130
  }
39761
40131
  return Object.fromEntries(ENVELOPE_KEYS.map((key) => [key, record32[key]]));
39762
40132
  }
39763
- async function callEndpoint(config, id, args = {}) {
40133
+ async function callEndpoint(config, id, args = {}, bounds = NO_BOUNDS) {
39764
40134
  const entry = resolveEndpoint(id);
39765
40135
  if (!entry) {
39766
40136
  throw invalid(unknownIdMessage(id));
39767
40137
  }
39768
40138
  checkArgs(entry, args);
39769
40139
  const url = serviceUrl(entry.service, fillPath(entry, args.pathParams ?? {}));
39770
- const raw = await new HTTPClient(entry.service, config).raw(entry.method, url, {
40140
+ const raw = await new HTTPClient(entry.service, config, bounds).raw(entry.method, url, {
39771
40141
  params: args.query,
39772
40142
  data: args.body ?? void 0,
39773
40143
  config: { endpoint: entry.path }
39774
40144
  });
39775
40145
  const parsed = parseJson(raw.text);
39776
- const body = parsed.json ? parsed.value : raw.text;
40146
+ const body = callBodyKind(parsed.json) === "json" ? parsed.value : raw.text;
39777
40147
  return { httpStatus: raw.status, envelope: toEnvelope(body), body };
39778
40148
  }
39779
40149
 
39780
- // ../auth-core/src/site.ts
39781
- function isSiteChar(c) {
39782
- return c >= 97 && c <= 122 || c >= 48 && c <= 57 || c === 95 || c === 45;
40150
+ // src/core/proxy-rules.ts
40151
+ function renamesWireParams(method) {
40152
+ return method === "GET";
39783
40153
  }
39784
- function siteCharsFrom(s, i) {
39785
- return i >= s.length || isSiteChar(s.charCodeAt(i)) && siteCharsFrom(s, i + 1);
40154
+ function defaultsEmptyBody(hasQueryParams, hasBody) {
40155
+ return !hasQueryParams && !hasBody;
39786
40156
  }
39787
- function isSiteId(s) {
39788
- return s.length > 0 && siteCharsFrom(s, 0);
40157
+ function dataProxyRoute(isFunction, isObject) {
40158
+ if (isFunction) return "unwrap";
40159
+ return isObject ? "nest" : "copy";
39789
40160
  }
39790
-
39791
- // src/core/site-id-check.ts
39792
- function isSiteId2(s) {
39793
- return isSiteId(s);
40161
+ function requestShapeOf(hasPathParams, hasQueryParams, hasBody) {
40162
+ if (hasPathParams) return "withPathParams";
40163
+ return hasQueryParams || hasBody ? "paramsOnly" : "noParams";
39794
40164
  }
39795
-
39796
- // src/core/site-id.ts
39797
- function parseSiteId(value) {
39798
- return isSiteId2(value) ? value : void 0;
40165
+ function copiesLegacyValue(camelGiven) {
40166
+ return !camelGiven;
39799
40167
  }
39800
- function assertSiteId(value) {
39801
- const site = parseSiteId(value);
39802
- if (site === void 0) {
39803
- throw new InvalidArgumentError({
39804
- message: "Invalid siteId: expected lowercase letters, digits, '_' and '-' (e.g. example-site)",
39805
- service: "",
39806
- endpoint: ""
39807
- });
39808
- }
39809
- return site;
40168
+ function pathParamTargets(path, key) {
40169
+ if (includesFrom(path, braced(key), 0)) return [key];
40170
+ return foldMatchesFrom(templateNames(path, 0), key, 0);
40171
+ }
40172
+ function bodySlot(method) {
40173
+ return method === "DELETE" ? -1 : 0;
40174
+ }
40175
+ function querySlot(method) {
40176
+ if (method === "POST" || method === "PUT") return 1;
40177
+ return method === "DELETE" ? 0 : -1;
40178
+ }
40179
+ function isLegacyAlias(changed, declared) {
40180
+ return changed && declared;
39810
40181
  }
39811
40182
 
39812
40183
  // src/core/common-schemas.ts
@@ -39941,16 +40312,15 @@ var BaseServiceClient = class {
39941
40312
  * describe the expected type, and `received` is not copied)
39942
40313
  */
39943
40314
  createValidationError(valibotError, config, errorType) {
39944
- const message = errorType === "params" ? "Invalid request parameters" : "Invalid API response structure\nThis appears to be a response validation error. The API returned data in an unexpected format.";
39945
40315
  return new ValidationError({
39946
- message,
40316
+ message: validationMessageOf(errorType),
39947
40317
  service: this.serviceName,
39948
40318
  endpoint: config.path,
39949
40319
  validationErrors: valibotError.issues.map((issue) => ({
39950
40320
  path: (issue.path ?? []).map((segment) => segment.key),
39951
40321
  message: issue.message,
39952
40322
  // Typed as always present, but issues built outside valibot can lack it
39953
- code: issue.type ?? "unknown"
40323
+ code: issueCodeOf(issue.type)
39954
40324
  }))
39955
40325
  });
39956
40326
  }
@@ -39978,45 +40348,28 @@ var BaseServiceClient = class {
39978
40348
  let path = pathTemplate;
39979
40349
  for (const [key, value] of Object.entries(pathParams)) {
39980
40350
  const stringValue = String(value);
39981
- if (includesFrom(path, braced(key), 0)) {
39982
- validatePathSegment(pathTemplate, key, stringValue, pathPatterns[key], this.serviceName);
39983
- path = fillPlaceholder(path, key, encodePathSegment(stringValue));
39984
- } else {
39985
- const folded = foldName(key);
39986
- for (const placeholder of new Set(templateNames(path, 0))) {
39987
- if (foldName(placeholder) === folded) {
39988
- validatePathSegment(
39989
- pathTemplate,
39990
- placeholder,
39991
- stringValue,
39992
- pathPatterns[placeholder],
39993
- this.serviceName
39994
- );
39995
- path = fillPlaceholder(path, placeholder, encodePathSegment(stringValue));
39996
- }
39997
- }
40351
+ for (const placeholder of pathParamTargets(path, key)) {
40352
+ validatePathSegment(
40353
+ pathTemplate,
40354
+ placeholder,
40355
+ stringValue,
40356
+ pathPatterns[placeholder],
40357
+ this.serviceName
40358
+ );
40359
+ path = fillPlaceholder(path, placeholder, encodePathSegment(stringValue));
39998
40360
  }
39999
40361
  }
40000
40362
  return path;
40001
40363
  }
40002
40364
  };
40003
40365
 
40004
- // src/core/service-proxy.ts
40005
- var v33 = __toESM(require("valibot"));
40006
-
40007
- // src/core/proxy-rules.ts
40008
- function bodySlot(method) {
40009
- return method === "DELETE" ? -1 : 0;
40010
- }
40011
- function querySlot(method) {
40012
- if (method === "POST" || method === "PUT") return 1;
40013
- return method === "DELETE" ? 0 : -1;
40014
- }
40015
- function isLegacyAlias(changed, declared) {
40016
- return changed && declared;
40366
+ // ../utils/src/distance.ts
40367
+ function min2(x, y) {
40368
+ return Math.min(x, y);
40017
40369
  }
40018
40370
 
40019
40371
  // src/core/service-proxy.ts
40372
+ var v33 = __toESM(require("valibot"));
40020
40373
  var PassthroughResponseSchema = v33.looseObject({
40021
40374
  count: v33.number(),
40022
40375
  data: v33.unknown(),
@@ -40061,16 +40414,12 @@ function createNodeObject(serviceName, executeRequest, node) {
40061
40414
  return obj;
40062
40415
  }
40063
40416
  function splitPathArgs(pathParams, args) {
40417
+ const taken = min2(pathParams.length, args.length);
40064
40418
  const pathParamMap = {};
40065
- let index2 = 0;
40066
- for (const name of pathParams) {
40067
- if (index2 >= args.length) {
40068
- break;
40069
- }
40070
- pathParamMap[name] = String(args[index2]);
40071
- index2++;
40419
+ for (let index2 = 0; index2 < taken; index2++) {
40420
+ pathParamMap[pathParams[index2]] = String(args[index2]);
40072
40421
  }
40073
- return { pathParamMap, rest: args.slice(index2) };
40422
+ return { pathParamMap, rest: args.slice(taken) };
40074
40423
  }
40075
40424
  function splitBodyAndQuery(method, rest) {
40076
40425
  const at = (slot) => rest[slot];
@@ -40091,7 +40440,7 @@ function normaliseLegacyParamCase(params, declared) {
40091
40440
  }
40092
40441
  renamed = true;
40093
40442
  delete out[key];
40094
- if (!(camel in source)) {
40443
+ if (copiesLegacyValue(camel in source)) {
40095
40444
  out[camel] = value;
40096
40445
  }
40097
40446
  }
@@ -40108,7 +40457,7 @@ function createActionFunction(_serviceName, executeRequest, endpoint) {
40108
40457
  hasQueryParams ? trailing : void 0,
40109
40458
  endpoint.queryParams
40110
40459
  );
40111
- const wireParams = (value) => method === "GET" ? normaliseLegacyParamCase(value, endpoint.queryParams) : value;
40460
+ const wireParams = (value) => renamesWireParams(method) ? normaliseLegacyParamCase(value, endpoint.queryParams) : value;
40112
40461
  const config = {
40113
40462
  method,
40114
40463
  path,
@@ -40116,11 +40465,17 @@ function createActionFunction(_serviceName, executeRequest, endpoint) {
40116
40465
  ...hasQueryParams ? { paramsSchema: PassthroughParamsSchema } : {},
40117
40466
  responseSchema: PassthroughResponseSchema
40118
40467
  };
40119
- if (Object.keys(pathParamMap).length > 0) {
40120
- const params = wireParams(hasQueryParams ? body : body ?? {});
40468
+ const shape = requestShapeOf(
40469
+ Object.keys(pathParamMap).length > 0,
40470
+ hasQueryParams,
40471
+ body !== void 0
40472
+ );
40473
+ if (shape === "withPathParams") {
40474
+ const hasBody = body !== void 0 && body !== null;
40475
+ const params = wireParams(defaultsEmptyBody(hasQueryParams, hasBody) ? {} : body);
40121
40476
  return query === void 0 ? executeRequest(config, params, pathParamMap) : executeRequest(config, params, pathParamMap, query);
40122
40477
  }
40123
- if (hasQueryParams || body !== void 0) {
40478
+ if (shape === "paramsOnly") {
40124
40479
  return query === void 0 ? executeRequest(config, wireParams(body)) : executeRequest(config, wireParams(body), void 0, query);
40125
40480
  }
40126
40481
  return executeRequest(config);
@@ -40131,14 +40486,18 @@ function createDataProxy(resource) {
40131
40486
  const src = resource;
40132
40487
  for (const key of Object.keys(src)) {
40133
40488
  const value = src[key];
40134
- if (typeof value === "function") {
40489
+ const route = dataProxyRoute(
40490
+ typeof value === "function",
40491
+ typeof value === "object" && value !== null
40492
+ );
40493
+ if (route === "unwrap") {
40135
40494
  const propKey = key;
40136
40495
  obj[key] = async (...args) => {
40137
40496
  const fn = src[propKey];
40138
40497
  const response = await fn(...args);
40139
40498
  return response?.data;
40140
40499
  };
40141
- } else if (value && typeof value === "object") {
40500
+ } else if (route === "nest") {
40142
40501
  obj[key] = createDataProxy(value);
40143
40502
  } else {
40144
40503
  obj[key] = value;
@@ -41821,8 +42180,32 @@ var Basecamp2Client = class extends BaseServiceClient {
41821
42180
  };
41822
42181
 
41823
42182
  // src/client.ts
42183
+ function mergedBounds(outer, signal, deadline) {
42184
+ const signals = signal === void 0 ? outer.signals : [...outer.signals, signal];
42185
+ const hasOuter = outer.deadline !== void 0;
42186
+ const hasInner = deadline !== void 0;
42187
+ if (!hasMergedDeadline(hasOuter, hasInner)) return { signals };
42188
+ return {
42189
+ signals,
42190
+ deadline: mergedDeadlineOf(hasOuter, outer.deadline ?? 0, hasInner, deadline ?? 0)
42191
+ };
42192
+ }
42193
+ var CONTEXT_REFUSALS = {
42194
+ context: () => new ContextCreationError("Context is required", "context"),
42195
+ "site-id": () => new ContextCreationError("Context must contain siteId", "siteId"),
42196
+ token: () => new ContextCreationError(
42197
+ "Context must contain jwt or bearerToken for authentication",
42198
+ "bearerToken"
42199
+ ),
42200
+ "token-removed": () => new ContextCreationError(
42201
+ "fromContext options must not remove the context's bearer token",
42202
+ "bearerToken"
42203
+ )
42204
+ };
41824
42205
  var AugurAPI = class _AugurAPI {
41825
42206
  config;
42207
+ /** This client's call bounds: none, unless it is a view from `withRequest`. */
42208
+ bounds = NO_BOUNDS;
41826
42209
  _joomla;
41827
42210
  _commerce;
41828
42211
  _pricing;
@@ -41885,7 +42268,52 @@ var AugurAPI = class _AugurAPI {
41885
42268
  * ```
41886
42269
  */
41887
42270
  call(id, args) {
41888
- return callEndpoint(this.config, id, args);
42271
+ return callEndpoint(this.config, id, args, this.bounds);
42272
+ }
42273
+ /**
42274
+ * A view of this client whose every call is bounded by `options` (atlas#106): the caller's
42275
+ * `signal`, and a `deadline` in milliseconds for the whole call, retries and the waits between
42276
+ * them included. The view has this client's siteId, token, timeouts, retries and hooks, sends
42277
+ * the same headers, and builds its own service clients (sharing no in-flight request with this
42278
+ * one). Building a view and its first service costs about what building this client did, so
42279
+ * make one per bounded call, not per request inside a loop.
42280
+ *
42281
+ * @example
42282
+ * ```typescript
42283
+ * const items = await api.withRequest({ deadline: 5000 }).items.categories.items.list(uid, params);
42284
+ * ```
42285
+ *
42286
+ * @throws InvalidArgumentError when `signal` is given but not an AbortSignal, or `deadline` is
42287
+ * given but not a number from 0 to 2147483647 (NaN, Infinity or larger would fire at once).
42288
+ * Options can come from a browser through a server action, so their shape is checked.
42289
+ */
42290
+ withRequest(options) {
42291
+ const signal = options?.signal;
42292
+ const deadline = options?.deadline;
42293
+ const accepted = callOptionsAccepted(
42294
+ signal !== void 0,
42295
+ signal instanceof AbortSignal,
42296
+ deadline !== void 0,
42297
+ typeof deadline === "number" && deadlineInRange(deadline)
42298
+ );
42299
+ if (!accepted) {
42300
+ throw new InvalidArgumentError({
42301
+ message: "Invalid call options: signal must be an AbortSignal, deadline a number of milliseconds from 0 to 2147483647",
42302
+ service: "",
42303
+ endpoint: ""
42304
+ });
42305
+ }
42306
+ const view = new _AugurAPI(this.config);
42307
+ view.bounds = mergedBounds(
42308
+ this.bounds,
42309
+ signal,
42310
+ deadline
42311
+ );
42312
+ return view;
42313
+ }
42314
+ /** The HTTP client a service is built with: this client's config and call bounds. */
42315
+ httpFor(service) {
42316
+ return new HTTPClient(service, this.config, this.bounds);
41889
42317
  }
41890
42318
  /**
41891
42319
  * Create AugurAPI client from context object
@@ -41913,25 +42341,19 @@ var AugurAPI = class _AugurAPI {
41913
42341
  * @throws {ContextCreationError} When context is invalid or missing required fields
41914
42342
  */
41915
42343
  static fromContext(context, options = {}) {
41916
- if (!context) {
41917
- throw new ContextCreationError("Context is required", "context");
41918
- }
41919
- if (!context.siteId) {
41920
- throw new ContextCreationError("Context must contain siteId", "siteId");
41921
- }
41922
- const bearerToken = context.jwt || context.bearerToken;
41923
- if (!bearerToken) {
41924
- throw new ContextCreationError(
41925
- "Context must contain jwt or bearerToken for authentication",
41926
- "bearerToken"
41927
- );
41928
- }
42344
+ const bearerToken = context?.jwt || context?.bearerToken;
41929
42345
  const config = {
41930
- siteId: context.siteId,
42346
+ siteId: context?.siteId ?? "",
41931
42347
  bearerToken,
41932
42348
  ...options
41933
- // Allow overrides
41934
42349
  };
42350
+ const refusal = contextRefusalOf(
42351
+ Boolean(context),
42352
+ Boolean(context?.siteId),
42353
+ Boolean(bearerToken),
42354
+ Boolean(config.bearerToken)
42355
+ );
42356
+ if (refusal !== "ok") throw CONTEXT_REFUSALS[refusal]();
41935
42357
  return new _AugurAPI(config);
41936
42358
  }
41937
42359
  /**
@@ -41939,7 +42361,7 @@ var AugurAPI = class _AugurAPI {
41939
42361
  */
41940
42362
  get joomla() {
41941
42363
  if (!this._joomla) {
41942
- const httpClient = new HTTPClient("joomla", this.config);
42364
+ const httpClient = this.httpFor("joomla");
41943
42365
  this._joomla = new JoomlaClient(httpClient);
41944
42366
  }
41945
42367
  return this._joomla;
@@ -41949,7 +42371,7 @@ var AugurAPI = class _AugurAPI {
41949
42371
  */
41950
42372
  get commerce() {
41951
42373
  if (!this._commerce) {
41952
- const httpClient = new HTTPClient("commerce", this.config);
42374
+ const httpClient = this.httpFor("commerce");
41953
42375
  this._commerce = new CommerceClient(httpClient);
41954
42376
  }
41955
42377
  return this._commerce;
@@ -41959,7 +42381,7 @@ var AugurAPI = class _AugurAPI {
41959
42381
  */
41960
42382
  get pricing() {
41961
42383
  if (!this._pricing) {
41962
- const httpClient = new HTTPClient("pricing", this.config);
42384
+ const httpClient = this.httpFor("pricing");
41963
42385
  this._pricing = new PricingClient(httpClient);
41964
42386
  }
41965
42387
  return this._pricing;
@@ -41969,7 +42391,7 @@ var AugurAPI = class _AugurAPI {
41969
42391
  */
41970
42392
  get vmi() {
41971
42393
  if (!this._vmi) {
41972
- const httpClient = new HTTPClient("vmi", this.config);
42394
+ const httpClient = this.httpFor("vmi");
41973
42395
  this._vmi = new VMIClient(httpClient);
41974
42396
  }
41975
42397
  return this._vmi;
@@ -41979,7 +42401,7 @@ var AugurAPI = class _AugurAPI {
41979
42401
  */
41980
42402
  get openSearch() {
41981
42403
  if (!this._openSearch) {
41982
- const httpClient = new HTTPClient("open-search", this.config);
42404
+ const httpClient = this.httpFor("open-search");
41983
42405
  this._openSearch = new OpenSearchClient(httpClient);
41984
42406
  }
41985
42407
  return this._openSearch;
@@ -41989,7 +42411,7 @@ var AugurAPI = class _AugurAPI {
41989
42411
  */
41990
42412
  get items() {
41991
42413
  if (!this._items) {
41992
- const httpClient = new HTTPClient("items", this.config);
42414
+ const httpClient = this.httpFor("items");
41993
42415
  this._items = new ItemsClient(httpClient);
41994
42416
  }
41995
42417
  return this._items;
@@ -41999,7 +42421,7 @@ var AugurAPI = class _AugurAPI {
41999
42421
  */
42000
42422
  get legacy() {
42001
42423
  if (!this._legacy) {
42002
- const httpClient = new HTTPClient("legacy", this.config);
42424
+ const httpClient = this.httpFor("legacy");
42003
42425
  this._legacy = new LegacyClient(httpClient);
42004
42426
  }
42005
42427
  return this._legacy;
@@ -42009,7 +42431,7 @@ var AugurAPI = class _AugurAPI {
42009
42431
  */
42010
42432
  get agrSite() {
42011
42433
  if (!this._agrSite) {
42012
- const httpClient = new HTTPClient("agr-site", this.config);
42434
+ const httpClient = this.httpFor("agr-site");
42013
42435
  this._agrSite = new AgrSiteClient(httpClient);
42014
42436
  }
42015
42437
  return this._agrSite;
@@ -42019,7 +42441,7 @@ var AugurAPI = class _AugurAPI {
42019
42441
  */
42020
42442
  get customers() {
42021
42443
  if (!this._customers) {
42022
- const httpClient = new HTTPClient("customers", this.config);
42444
+ const httpClient = this.httpFor("customers");
42023
42445
  this._customers = new CustomersClient(httpClient);
42024
42446
  }
42025
42447
  return this._customers;
@@ -42029,7 +42451,7 @@ var AugurAPI = class _AugurAPI {
42029
42451
  */
42030
42452
  get orders() {
42031
42453
  if (!this._orders) {
42032
- const httpClient = new HTTPClient("orders", this.config);
42454
+ const httpClient = this.httpFor("orders");
42033
42455
  this._orders = new OrdersClient(httpClient);
42034
42456
  }
42035
42457
  return this._orders;
@@ -42039,7 +42461,7 @@ var AugurAPI = class _AugurAPI {
42039
42461
  */
42040
42462
  get p21Pim() {
42041
42463
  if (!this._p21Pim) {
42042
- const httpClient = new HTTPClient("p21-pim", this.config);
42464
+ const httpClient = this.httpFor("p21-pim");
42043
42465
  this._p21Pim = new P21PimClient(httpClient);
42044
42466
  }
42045
42467
  return this._p21Pim;
@@ -42049,7 +42471,7 @@ var AugurAPI = class _AugurAPI {
42049
42471
  */
42050
42472
  get payments() {
42051
42473
  if (!this._payments) {
42052
- const httpClient = new HTTPClient("payments", this.config);
42474
+ const httpClient = this.httpFor("payments");
42053
42475
  this._payments = new PaymentsClient(httpClient);
42054
42476
  }
42055
42477
  return this._payments;
@@ -42059,7 +42481,7 @@ var AugurAPI = class _AugurAPI {
42059
42481
  */
42060
42482
  get agrInfo() {
42061
42483
  if (!this._agrInfo) {
42062
- const httpClient = new HTTPClient("agr-info", this.config);
42484
+ const httpClient = this.httpFor("agr-info");
42063
42485
  this._agrInfo = new AgrInfoClient(httpClient);
42064
42486
  }
42065
42487
  return this._agrInfo;
@@ -42069,7 +42491,7 @@ var AugurAPI = class _AugurAPI {
42069
42491
  */
42070
42492
  get agrInt() {
42071
42493
  if (!this._agrInt) {
42072
- const httpClient = new HTTPClient("agr-int", this.config);
42494
+ const httpClient = this.httpFor("agr-int");
42073
42495
  this._agrInt = new AgrIntClient(httpClient);
42074
42496
  }
42075
42497
  return this._agrInt;
@@ -42079,7 +42501,7 @@ var AugurAPI = class _AugurAPI {
42079
42501
  */
42080
42502
  get agrWork() {
42081
42503
  if (!this._agrWork) {
42082
- const httpClient = new HTTPClient("agr-work", this.config);
42504
+ const httpClient = this.httpFor("agr-work");
42083
42505
  this._agrWork = new AgrWorkClient(httpClient);
42084
42506
  }
42085
42507
  return this._agrWork;
@@ -42089,7 +42511,7 @@ var AugurAPI = class _AugurAPI {
42089
42511
  */
42090
42512
  get avalara() {
42091
42513
  if (!this._avalara) {
42092
- const httpClient = new HTTPClient("avalara", this.config);
42514
+ const httpClient = this.httpFor("avalara");
42093
42515
  this._avalara = new AvalaraClient(httpClient);
42094
42516
  }
42095
42517
  return this._avalara;
@@ -42099,7 +42521,7 @@ var AugurAPI = class _AugurAPI {
42099
42521
  */
42100
42522
  get brandFolder() {
42101
42523
  if (!this._brandFolder) {
42102
- const httpClient = new HTTPClient("brand-folder", this.config);
42524
+ const httpClient = this.httpFor("brand-folder");
42103
42525
  this._brandFolder = new BrandFolderClient(httpClient);
42104
42526
  }
42105
42527
  return this._brandFolder;
@@ -42109,7 +42531,7 @@ var AugurAPI = class _AugurAPI {
42109
42531
  */
42110
42532
  get googMc() {
42111
42533
  if (!this._googMc) {
42112
- const httpClient = new HTTPClient("goog-mc", this.config);
42534
+ const httpClient = this.httpFor("goog-mc");
42113
42535
  this._googMc = new GoogMcClient(httpClient);
42114
42536
  }
42115
42537
  return this._googMc;
@@ -42119,7 +42541,7 @@ var AugurAPI = class _AugurAPI {
42119
42541
  */
42120
42542
  get gregorovich() {
42121
42543
  if (!this._gregorovich) {
42122
- const httpClient = new HTTPClient("gregorovich", this.config);
42544
+ const httpClient = this.httpFor("gregorovich");
42123
42545
  this._gregorovich = new GregorovichClient(httpClient);
42124
42546
  }
42125
42547
  return this._gregorovich;
@@ -42129,7 +42551,7 @@ var AugurAPI = class _AugurAPI {
42129
42551
  */
42130
42552
  get logistics() {
42131
42553
  if (!this._logistics) {
42132
- const httpClient = new HTTPClient("logistics", this.config);
42554
+ const httpClient = this.httpFor("logistics");
42133
42555
  this._logistics = new LogisticsClient(httpClient);
42134
42556
  }
42135
42557
  return this._logistics;
@@ -42139,7 +42561,7 @@ var AugurAPI = class _AugurAPI {
42139
42561
  */
42140
42562
  get markets() {
42141
42563
  if (!this._markets) {
42142
- const httpClient = new HTTPClient("markets", this.config);
42564
+ const httpClient = this.httpFor("markets");
42143
42565
  this._markets = new MarketsClient(httpClient);
42144
42566
  }
42145
42567
  return this._markets;
@@ -42149,7 +42571,7 @@ var AugurAPI = class _AugurAPI {
42149
42571
  */
42150
42572
  get notifications() {
42151
42573
  if (!this._notifications) {
42152
- const httpClient = new HTTPClient("notifications", this.config);
42574
+ const httpClient = this.httpFor("notifications");
42153
42575
  this._notifications = new NotificationsClient(httpClient);
42154
42576
  }
42155
42577
  return this._notifications;
@@ -42159,7 +42581,7 @@ var AugurAPI = class _AugurAPI {
42159
42581
  */
42160
42582
  get p21Apis() {
42161
42583
  if (!this._p21Apis) {
42162
- const httpClient = new HTTPClient("p21-apis", this.config);
42584
+ const httpClient = this.httpFor("p21-apis");
42163
42585
  this._p21Apis = new P21ApisClient(httpClient);
42164
42586
  }
42165
42587
  return this._p21Apis;
@@ -42169,7 +42591,7 @@ var AugurAPI = class _AugurAPI {
42169
42591
  */
42170
42592
  get p21Core() {
42171
42593
  if (!this._p21Core) {
42172
- const httpClient = new HTTPClient("p21-core", this.config);
42594
+ const httpClient = this.httpFor("p21-core");
42173
42595
  this._p21Core = new P21CoreClient(httpClient);
42174
42596
  }
42175
42597
  return this._p21Core;
@@ -42179,7 +42601,7 @@ var AugurAPI = class _AugurAPI {
42179
42601
  */
42180
42602
  get p21Sism() {
42181
42603
  if (!this._p21Sism) {
42182
- const httpClient = new HTTPClient("p21-sism", this.config);
42604
+ const httpClient = this.httpFor("p21-sism");
42183
42605
  this._p21Sism = new P21SismClient(httpClient);
42184
42606
  }
42185
42607
  return this._p21Sism;
@@ -42189,7 +42611,7 @@ var AugurAPI = class _AugurAPI {
42189
42611
  */
42190
42612
  get shipping() {
42191
42613
  if (!this._shipping) {
42192
- const httpClient = new HTTPClient("shipping", this.config);
42614
+ const httpClient = this.httpFor("shipping");
42193
42615
  this._shipping = new ShippingClient(httpClient);
42194
42616
  }
42195
42617
  return this._shipping;
@@ -42199,7 +42621,7 @@ var AugurAPI = class _AugurAPI {
42199
42621
  */
42200
42622
  get smartyStreets() {
42201
42623
  if (!this._smartyStreets) {
42202
- const httpClient = new HTTPClient("smarty-streets", this.config);
42624
+ const httpClient = this.httpFor("smarty-streets");
42203
42625
  this._smartyStreets = new SmartyStreetsClient(httpClient);
42204
42626
  }
42205
42627
  return this._smartyStreets;
@@ -42209,7 +42631,7 @@ var AugurAPI = class _AugurAPI {
42209
42631
  */
42210
42632
  get ups() {
42211
42633
  if (!this._ups) {
42212
- const httpClient = new HTTPClient("ups", this.config);
42634
+ const httpClient = this.httpFor("ups");
42213
42635
  this._ups = new UPSClient(httpClient);
42214
42636
  }
42215
42637
  return this._ups;
@@ -42219,7 +42641,7 @@ var AugurAPI = class _AugurAPI {
42219
42641
  */
42220
42642
  get vendors() {
42221
42643
  if (!this._vendors) {
42222
- const httpClient = new HTTPClient("vendors", this.config);
42644
+ const httpClient = this.httpFor("vendors");
42223
42645
  this._vendors = new VendorsClient(httpClient);
42224
42646
  }
42225
42647
  return this._vendors;
@@ -42229,13 +42651,18 @@ var AugurAPI = class _AugurAPI {
42229
42651
  */
42230
42652
  get basecamp2() {
42231
42653
  if (!this._basecamp2) {
42232
- const httpClient = new HTTPClient("basecamp2", this.config);
42654
+ const httpClient = this.httpFor("basecamp2");
42233
42655
  this._basecamp2 = new Basecamp2Client(httpClient);
42234
42656
  }
42235
42657
  return this._basecamp2;
42236
42658
  }
42237
42659
  /**
42238
42660
  * Update authentication token
42661
+ *
42662
+ * Every service read from this client afterwards (`api.items`, …) sends the new token. A
42663
+ * service object read BEFORE the change keeps the token it was built with: read services from
42664
+ * the client after a change, don't hold them across it (AugurApiClient.BuiltClientKeepsItsSnapshot).
42665
+ *
42239
42666
  * @param bearerToken New bearer token
42240
42667
  */
42241
42668
  setAuthToken(bearerToken) {
@@ -42244,6 +42671,9 @@ var AugurAPI = class _AugurAPI {
42244
42671
  }
42245
42672
  /**
42246
42673
  * Update site ID
42674
+ *
42675
+ * As with `setAuthToken`: a service object read before the change keeps the old siteId.
42676
+ *
42247
42677
  * @param siteId New site ID
42248
42678
  * @throws InvalidArgumentError when it is not a siteId (see the constructor)
42249
42679
  */
@@ -42286,6 +42716,11 @@ var AugurAPI = class _AugurAPI {
42286
42716
  }
42287
42717
  };
42288
42718
 
42719
+ // ../foundation/src/pos-int.ts
42720
+ function posIntOf(n) {
42721
+ return Math.floor(n) === n && n >= 1 && n <= 9007199254740991 ? n : null;
42722
+ }
42723
+
42289
42724
  // src/utils/cross-site-auth.ts
42290
42725
  async function authenticateUserForSite(params) {
42291
42726
  const { targetSiteId, username, password, augurInfoToken } = params;
@@ -42300,23 +42735,35 @@ async function authenticateUserForSite(params) {
42300
42735
  siteId: targetSiteId
42301
42736
  // This tells the API to authenticate against the target site
42302
42737
  });
42303
- if (!data.isVerified) {
42738
+ const token = data.token;
42739
+ const tokenIsText = typeof token === "string";
42740
+ const outcome = crossSiteOutcomeOf(
42741
+ Boolean(data.isVerified),
42742
+ tokenIsText,
42743
+ tokenIsText ? token : ""
42744
+ );
42745
+ if (outcome === "notVerified") {
42304
42746
  return { success: false, targetSiteId, error: "Invalid username or password" };
42305
42747
  }
42306
- if (typeof data.token !== "string" || data.token === "") {
42748
+ if (outcome === "noToken") {
42307
42749
  return { success: false, targetSiteId, error: "Password verified, but no token was issued" };
42308
42750
  }
42751
+ const bearer = token;
42752
+ const rawId = data.id;
42753
+ const userId = posIntOf(typeof rawId === "number" ? rawId : Number.NaN);
42309
42754
  const targetSiteAPI = new AugurAPI({
42310
42755
  siteId: targetSiteId,
42311
- bearerToken: data.token
42756
+ bearerToken: bearer
42312
42757
  });
42313
42758
  return {
42314
42759
  success: true,
42315
- // `data` is typed, not validated at runtime: a missing id stays undefined, never "undefined"
42316
- userId: typeof data.id === "number" ? String(data.id) : void 0,
42760
+ // `data` is typed, not validated at runtime. A user id is an integer at least 1: it enters
42761
+ // as a PosInt (foundation's posIntOf; not a number reads as NaN, which it refuses) and the
42762
+ // proved crossSiteUserIdOf writes it, so 0, -1, 1.5 or a missing id report no id
42763
+ userId: crossSiteUserIdOf(userId !== null, userId ?? 0),
42317
42764
  username: data.username,
42318
42765
  email: data.email,
42319
- token: data.token,
42766
+ token: bearer,
42320
42767
  targetSiteId,
42321
42768
  targetSiteAPI
42322
42769
  };
@@ -42340,7 +42787,7 @@ function createCrossSiteAuthenticator(augurInfoToken) {
42340
42787
  }
42341
42788
 
42342
42789
  // src/index.ts
42343
- var VERSION = "2026.11.3";
42790
+ var VERSION = "2026.11.5";
42344
42791
  // Annotate the CommonJS export names for ESM import in node:
42345
42792
  0 && (module.exports = {
42346
42793
  AgrInfoClient,