node-autotask 0.68.1 → 0.69.1

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 (38) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/MCP_TOOL_CATALOG.json +2 -2
  3. package/README.md +51 -10
  4. package/capabilities.json +7 -7
  5. package/dist/capabilities-data.js +6 -6
  6. package/dist/capabilities.cjs +4 -4
  7. package/dist/capabilities.js +1 -1
  8. package/dist/{chunk-LOLWHPTJ.js → chunk-64BMSXWT.js} +3 -30
  9. package/dist/{chunk-XKIRTR37.cjs → chunk-CLHDTYWO.cjs} +1405 -488
  10. package/dist/{chunk-2D2KJOX2.cjs → chunk-EWXRFHPP.cjs} +236 -222
  11. package/dist/{chunk-YYHCZRUH.js → chunk-FK37JXSJ.js} +1398 -483
  12. package/dist/{chunk-SGH7F2CH.cjs → chunk-KAZE4WC7.cjs} +3 -3
  13. package/dist/{chunk-S6HEIGGM.js → chunk-MMGO3SFL.js} +80 -66
  14. package/dist/{chunk-JCMXQUIC.js → chunk-SCFB5MF3.js} +3 -3
  15. package/dist/{chunk-KRQONGLD.cjs → chunk-WFVLF7EW.cjs} +30 -57
  16. package/dist/{index-mIsdpO5d.d.cts → index-BT_0tTPS.d.cts} +19 -12
  17. package/dist/{index-DQ08uOH0.d.ts → index-Coe7LFLY.d.ts} +19 -12
  18. package/dist/index.cjs +92 -85
  19. package/dist/index.d.cts +3 -3
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +14 -7
  22. package/dist/operations/index.cjs +50 -50
  23. package/dist/operations/index.d.cts +2 -2
  24. package/dist/operations/index.d.ts +2 -2
  25. package/dist/operations/index.js +2 -2
  26. package/dist/pool.cjs +12 -12
  27. package/dist/pool.js +4 -4
  28. package/dist/resources/index.cjs +27 -27
  29. package/dist/resources/index.d.cts +1 -1
  30. package/dist/resources/index.d.ts +1 -1
  31. package/dist/resources/index.js +3 -3
  32. package/docs/API.md +85 -16
  33. package/docs/LIVE-TESTING.md +16 -2
  34. package/docs/VENDOR-QUIRKS.md +39 -0
  35. package/docs/performance-finance.md +35 -0
  36. package/docs/performance-reads.md +63 -0
  37. package/examples/mcp-env-config.ts +3 -4
  38. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkSGH7F2CH_cjs = require('./chunk-SGH7F2CH.cjs');
3
+ var chunkKAZE4WC7_cjs = require('./chunk-KAZE4WC7.cjs');
4
4
  var chunkBD4AUGCJ_cjs = require('./chunk-BD4AUGCJ.cjs');
5
5
  var crypto = require('crypto');
6
6
  var async_hooks = require('async_hooks');
@@ -116,7 +116,7 @@ var ConflictError = class extends AutotaskError {
116
116
  var RateLimitError = class extends AutotaskError {
117
117
  /** Seconds the server asked the client to wait (`Retry-After`), when present. */
118
118
  retryAfter;
119
- /** True when the call was refused locally (the tenant cooldown gate) and never sent. */
119
+ /** True when the call was refused locally (cooldown or hourly admission) and never sent. */
120
120
  notSent;
121
121
  constructor(message, options = {}) {
122
122
  super(message, { code: "RATE_LIMITED", category: "rate_limit", retryable: true, ...options });
@@ -636,6 +636,7 @@ var TtlCache = class {
636
636
  ttlFor;
637
637
  store = /* @__PURE__ */ new Map();
638
638
  inflightMap = /* @__PURE__ */ new Map();
639
+ loads = /* @__PURE__ */ new Map();
639
640
  epochCounter = 0;
640
641
  constructor(ttlMs, options = {}) {
641
642
  if (!Number.isInteger(ttlMs) || ttlMs <= 0) {
@@ -659,6 +660,86 @@ var TtlCache = class {
659
660
  }
660
661
  return structuredClone(entry.value);
661
662
  }
663
+ /**
664
+ * Load one record once for concurrent callers. Each subscriber owns its
665
+ * cancellation and receives a copy. The wire read is cancelled only when
666
+ * its last subscriber leaves. A fresh load starts a new flight and prevents
667
+ * an older flight from replacing its result; invalidation detaches flights
668
+ * without changing the answer owed to their existing subscribers.
669
+ * `shouldStore` controls retention, never the result returned to subscribers.
670
+ * @internal
671
+ */
672
+ async load(key, loader, opts) {
673
+ const { signal } = opts;
674
+ if (signal?.aborted) throw opts.abortError();
675
+ if (!opts.fresh) {
676
+ const hit = this.get(key);
677
+ if (hit !== void 0) return hit;
678
+ }
679
+ let flight = opts.fresh ? void 0 : this.loads.get(key);
680
+ let start;
681
+ if (flight === void 0) {
682
+ const epoch = this.epoch;
683
+ const controller = new AbortController();
684
+ const created = { controller, promise: Promise.resolve(), subscribers: 0, settled: false };
685
+ created.promise = new Promise((resolve, reject) => {
686
+ start = () => {
687
+ try {
688
+ resolve(loader(controller.signal));
689
+ } catch (error) {
690
+ if (this.loads.get(key) === created) this.loads.delete(key);
691
+ reject(error);
692
+ }
693
+ };
694
+ }).then((value) => {
695
+ if (this.loads.get(key) === created && !controller.signal.aborted && (opts.shouldStore?.(value) ?? true)) this.set(key, value, epoch);
696
+ return value;
697
+ });
698
+ const settled = () => {
699
+ created.settled = true;
700
+ if (this.loads.get(key) === created) this.loads.delete(key);
701
+ };
702
+ created.promise.then(settled, settled);
703
+ this.loads.set(key, created);
704
+ flight = created;
705
+ }
706
+ const shared = flight;
707
+ shared.subscribers += 1;
708
+ const result = new Promise((resolve, reject) => {
709
+ let active = true;
710
+ const leave = () => {
711
+ if (!active) return false;
712
+ active = false;
713
+ signal?.removeEventListener("abort", aborted);
714
+ shared.subscribers -= 1;
715
+ if (shared.subscribers === 0 && !shared.settled) {
716
+ if (this.loads.get(key) === shared) this.loads.delete(key);
717
+ shared.controller.abort();
718
+ }
719
+ return true;
720
+ };
721
+ const aborted = () => {
722
+ if (leave()) reject(opts.abortError());
723
+ };
724
+ signal?.addEventListener("abort", aborted, { once: true });
725
+ shared.promise.then(
726
+ (value) => {
727
+ if (leave()) {
728
+ try {
729
+ resolve(structuredClone(value));
730
+ } catch (error) {
731
+ reject(error);
732
+ }
733
+ }
734
+ },
735
+ (error) => {
736
+ if (leave()) reject(error);
737
+ }
738
+ );
739
+ });
740
+ start?.();
741
+ return result;
742
+ }
662
743
  /** Store `value` under `key`. `epoch` is the value the caller read BEFORE its
663
744
  * wire request: a read that straddled a `clear()` (a write) is dropped. */
664
745
  set(key, value, epoch = this.epochCounter) {
@@ -693,12 +774,14 @@ var TtlCache = class {
693
774
  /** Drop one key. */
694
775
  delete(key) {
695
776
  this.inflightMap.delete(key);
777
+ this.loads.delete(key);
696
778
  return this.store.delete(key);
697
779
  }
698
780
  /** Drop every stored and in-flight key that starts with `prefix`. */
699
781
  invalidate(prefix) {
700
782
  for (const key of [...this.store.keys()]) if (key.startsWith(prefix)) this.store.delete(key);
701
783
  for (const key of [...this.inflightMap.keys()]) if (key.startsWith(prefix)) this.inflightMap.delete(key);
784
+ for (const key of [...this.loads.keys()]) if (key.startsWith(prefix)) this.loads.delete(key);
702
785
  }
703
786
  /** Drop every expired entry (returns the number removed). */
704
787
  purgeExpired() {
@@ -725,6 +808,7 @@ var TtlCache = class {
725
808
  this.epochCounter += 1;
726
809
  this.store.clear();
727
810
  this.inflightMap.clear();
811
+ this.loads.clear();
728
812
  }
729
813
  };
730
814
 
@@ -803,9 +887,10 @@ function cooldownDurationMs(retryAfterSecs, opts) {
803
887
  }
804
888
  return Math.min(retryAfterSecs !== void 0 ? retryAfterSecs * 1e3 : opts.defaultMs, opts.maxMs);
805
889
  }
806
- function admitMaintenance(host, ctx) {
890
+ function admitMaintenance(host, ctx, owned) {
807
891
  const gate = maintenance.get(host);
808
892
  if (gate === void 0) return "send";
893
+ if (gate === owned && gate.probing) return gate;
809
894
  const now = Date.now();
810
895
  if (!gate.probing && now >= gate.nextProbeAt) {
811
896
  gate.probing = true;
@@ -1447,8 +1532,8 @@ function buildFilter(conditions) {
1447
1532
  if (list.length === 0) {
1448
1533
  throw new AutotaskConfigError("buildFilter requires at least one condition");
1449
1534
  }
1450
- const root = list.length === 1 ? list[0] : { op: "and", items: list };
1451
- const filter = { filter: [root] };
1535
+ const root3 = list.length === 1 ? list[0] : { op: "and", items: list };
1536
+ const filter = { filter: [root3] };
1452
1537
  validateFilter(filter);
1453
1538
  return filter;
1454
1539
  }
@@ -1717,41 +1802,48 @@ function bodySnippet(text, redactPersonalData) {
1717
1802
 
1718
1803
  // src/http/limits.ts
1719
1804
  var HourlyBudget = class {
1720
- constructor(perHour, profile) {
1805
+ constructor(perHour, profile, scope = "local", stamps = []) {
1721
1806
  this.perHour = perHour;
1722
1807
  this.profile = profile;
1808
+ this.scope = scope;
1809
+ this.stamps = stamps;
1723
1810
  }
1724
1811
  perHour;
1725
1812
  profile;
1726
- /** Request timestamps inside the trailing hour. */
1727
- stamps = [];
1813
+ scope;
1814
+ stamps;
1728
1815
  prune(now) {
1729
- while (this.stamps.length > 0 && this.stamps[0] <= now - HOUR_MS) this.stamps.shift();
1816
+ let expired = 0;
1817
+ while (expired < this.stamps.length && this.stamps[expired] <= now - HOUR_MS) expired += 1;
1818
+ if (expired > 0) this.stamps.splice(0, expired);
1730
1819
  }
1731
1820
  snapshot() {
1732
1821
  this.prune(Date.now());
1733
1822
  return { perHour: this.perHour, used: this.stamps.length, remaining: Math.max(0, this.perHour - this.stamps.length) };
1734
1823
  }
1735
- /** Waits for a slot within the call budget, else throws. */
1736
- async take(deadlineAt, signal, ctx) {
1737
- for (; ; ) {
1738
- const now = Date.now();
1739
- this.prune(now);
1740
- if (this.stamps.length < this.perHour) {
1741
- this.stamps.push(now);
1742
- return;
1743
- }
1744
- const waitMs = this.stamps[0] + HOUR_MS - now;
1745
- if (waitMs >= deadlineAt - now) {
1746
- const err = new RateLimitError(`Client-side rateLimit.perHour (${this.perHour}) exhausted; next slot in ${Math.ceil(waitMs / 1e3)}s`, {
1747
- ...ctx,
1748
- suggestedAction: this.profile === "agent" ? "Stop or narrow the query \u2014 the LOCAL hourly budget is exhausted (per-process: it cannot see other instances or integrations on the tenant). Do NOT raise rateLimit.perHour; the window frees in about an hour." : "Back off until the hourly window frees a slot, or raise rateLimit.perHour."
1749
- });
1750
- err.retryAfter = Math.ceil(waitMs / 1e3);
1751
- throw err;
1824
+ /** Non-mutating admission check (apart from pruning); callers can inspect several quotas atomically. */
1825
+ waitMs(now) {
1826
+ this.prune(now);
1827
+ return this.stamps.length < this.perHour ? 0 : Math.max(0, this.stamps[0] + HOUR_MS - now);
1828
+ }
1829
+ /** Record an actual attempt immediately after every applicable quota was checked, without awaiting. */
1830
+ record(now) {
1831
+ this.stamps.push(now);
1832
+ }
1833
+ /** The typed local refusal. Its scope determines advice; the shared ceiling cannot be raised. */
1834
+ exhausted(waitMs, ctx) {
1835
+ const shared = this.scope === "origin";
1836
+ const err = new RateLimitError(
1837
+ shared ? `Shared origin hourly ceiling (${this.perHour}) exhausted; next slot in ${Math.ceil(waitMs / 1e3)}s` : `Client-side rateLimit.perHour (${this.perHour}) exhausted; next slot in ${Math.ceil(waitMs / 1e3)}s`,
1838
+ {
1839
+ ...ctx,
1840
+ details: { budgetScope: shared ? "process_origin" : "client" },
1841
+ suggestedAction: shared ? "Stop or narrow the query and coordinate traffic sharing this origin; retry after the hourly window frees a slot. The shared SDK ceiling cannot be raised and cannot account for external traffic." : this.profile === "agent" ? "Stop or narrow the query \u2014 the LOCAL hourly budget is exhausted (per-process: it cannot see other instances or integrations on the tenant). Do NOT raise rateLimit.perHour; the window frees in about an hour." : "Back off until the hourly window frees a slot, or raise rateLimit.perHour."
1752
1842
  }
1753
- await sleep(waitMs, signal);
1754
- }
1843
+ );
1844
+ err.retryAfter = Math.ceil(waitMs / 1e3);
1845
+ err.notSent = true;
1846
+ return err;
1755
1847
  }
1756
1848
  };
1757
1849
  var Semaphore = class {
@@ -1760,65 +1852,99 @@ var Semaphore = class {
1760
1852
  }
1761
1853
  maxConcurrent;
1762
1854
  inFlight = 0;
1763
- waitQueue = [];
1764
- acquire() {
1855
+ waitQueue = /* @__PURE__ */ new Set();
1856
+ /** Synchronous eligibility check; acquisition must follow without an await. @internal */
1857
+ canAcquire() {
1858
+ return this.inFlight < this.maxConcurrent && this.waitQueue.size === 0;
1859
+ }
1860
+ acquire(signal) {
1861
+ if (signal?.aborted) return Promise.reject(signal.reason);
1765
1862
  if (this.inFlight < this.maxConcurrent) {
1766
1863
  this.inFlight += 1;
1767
1864
  return Promise.resolve();
1768
1865
  }
1769
- return new Promise((resolve) => {
1770
- this.waitQueue.push(() => {
1866
+ return new Promise((resolve, reject) => {
1867
+ const aborted = () => {
1868
+ this.waitQueue.delete(grant);
1869
+ signal?.removeEventListener("abort", aborted);
1870
+ reject(signal?.reason);
1871
+ };
1872
+ const grant = () => {
1873
+ signal?.removeEventListener("abort", aborted);
1771
1874
  this.inFlight += 1;
1772
1875
  resolve();
1773
- });
1876
+ };
1877
+ this.waitQueue.add(grant);
1878
+ signal?.addEventListener("abort", aborted, { once: true });
1774
1879
  });
1775
1880
  }
1776
1881
  release() {
1777
1882
  this.inFlight -= 1;
1778
- const next = this.waitQueue.shift();
1779
- if (next !== void 0) next();
1883
+ const next = this.waitQueue.values().next();
1884
+ if (!next.done) {
1885
+ this.waitQueue.delete(next.value);
1886
+ next.value();
1887
+ }
1780
1888
  }
1781
1889
  };
1782
1890
 
1783
- // src/http/credentials.ts
1784
- var CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
1785
- "ApiIntegrationCode",
1786
- "UserName",
1787
- "Secret",
1788
- "ImpersonationResourceId"
1789
- ]);
1790
- function assertCredentialShape(headers, auth) {
1791
- const owned = new Set(CREDENTIAL_HEADER_NAMES);
1792
- for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
1793
- for (const name of Object.keys(headers)) {
1794
- if (!owned.has(name)) continue;
1795
- const value = headers[name];
1796
- const shape = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
1797
- if (shape === void 0) continue;
1798
- throw new AutotaskConfigError(
1799
- `${name} ${CREDENTIAL_ENV_LOAD_ACTION} (${shape})`,
1800
- {
1801
- code: "INVALID_CREDENTIAL_SHAPE",
1802
- suggestedAction: "Load the credential with the shell (`set -a; . ./.env; set +a`) or with loadAutotaskCredentialsFromEnv() from node-autotask; single-quoted values must be shell-sourced, not parsed by a quote-preserving loader. No request was sent."
1803
- }
1804
- );
1891
+ // src/http/hourly-gates.ts
1892
+ var ORIGIN_HOURLY_CEILING = 1e4;
1893
+ var REGISTRY = /* @__PURE__ */ Symbol.for("node-autotask.origin-hourly-gates.v1");
1894
+ var root = globalThis;
1895
+ var registry = root[REGISTRY] ??= { budgets: /* @__PURE__ */ new Map(), active: 0, waiting: 0, requests: 0 };
1896
+ function budgetFor(url) {
1897
+ const origin = new URL(url).origin.toLowerCase();
1898
+ let entry = registry.budgets.get(origin);
1899
+ if (entry === void 0) {
1900
+ for (const [key, previous] of registry.budgets) {
1901
+ if (new HourlyBudget(ORIGIN_HOURLY_CEILING, "agent", "origin", previous.stamps).snapshot().used === 0) registry.budgets.delete(key);
1902
+ }
1903
+ entry = { stamps: [] };
1904
+ registry.budgets.set(origin, entry);
1905
+ }
1906
+ return new HourlyBudget(ORIGIN_HOURLY_CEILING, "agent", "origin", entry.stamps);
1907
+ }
1908
+ function admitHourlyAttempt(url, local, now) {
1909
+ const origin = budgetFor(url);
1910
+ const budgets = local === void 0 ? [origin] : [local, origin];
1911
+ let blocked;
1912
+ for (const budget of budgets) {
1913
+ const waitMs = budget.waitMs(now);
1914
+ if (waitMs > (blocked?.waitMs ?? 0)) blocked = { admitted: false, budget, waitMs };
1915
+ }
1916
+ if (blocked !== void 0) return blocked;
1917
+ for (const budget of budgets) budget.record(now);
1918
+ registry.active += 1;
1919
+ let active = true;
1920
+ return { admitted: true, finish: () => {
1921
+ if (active) {
1922
+ active = false;
1923
+ registry.active -= 1;
1924
+ }
1925
+ } };
1926
+ }
1927
+ async function waitHourlyAdmission(blocked, deadlineAt, signal, ctx) {
1928
+ if (signal.aborted) throw signal.reason;
1929
+ const now = Date.now();
1930
+ const waitMs = blocked.budget.waitMs(now);
1931
+ if (waitMs === 0) return;
1932
+ if (waitMs >= deadlineAt - now) throw blocked.budget.exhausted(waitMs, ctx);
1933
+ registry.waiting += 1;
1934
+ try {
1935
+ await sleep(waitMs, signal);
1936
+ } finally {
1937
+ registry.waiting -= 1;
1805
1938
  }
1806
1939
  }
1807
- function credentialShapeExpectation(headers, auth) {
1808
- const owned = new Set(CREDENTIAL_HEADER_NAMES);
1809
- for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
1810
- const names = Object.keys(headers).filter((name) => owned.has(name));
1811
- if (names.length === 0) return void 0;
1812
- let problem;
1813
- for (const name of names) {
1814
- const value = headers[name];
1815
- problem = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
1816
- if (problem !== void 0) break;
1817
- }
1818
- return {
1819
- headerNames: names,
1820
- allValuesClean: problem === void 0,
1821
- ...problem !== void 0 ? { problem } : {}
1940
+ function trackHourlyRequest() {
1941
+ registry.requests += 1;
1942
+ let active = true;
1943
+ return () => {
1944
+ if (active) {
1945
+ active = false;
1946
+ registry.requests -= 1;
1947
+ }
1822
1948
  };
1823
1949
  }
1824
1950
 
@@ -14062,6 +14188,437 @@ var UNTRUSTED_FIELDS_BY_RESOURCE = {
14062
14188
  ]
14063
14189
  };
14064
14190
 
14191
+ // src/http/object-key.ts
14192
+ var UNKNOWN_OBJECT_KEY = "unknown-object";
14193
+ var roots = /* @__PURE__ */ new Map();
14194
+ var byResource = /* @__PURE__ */ new Map();
14195
+ var byKey = /* @__PURE__ */ new Map();
14196
+ function descriptor(row) {
14197
+ const key = row.apiEntity ?? row.resource;
14198
+ let value = byKey.get(key);
14199
+ if (value === void 0) {
14200
+ value = { key, children: /* @__PURE__ */ new Map() };
14201
+ byKey.set(key, value);
14202
+ }
14203
+ return value;
14204
+ }
14205
+ for (const row of Object.values(RELATIONSHIP_MAP)) {
14206
+ const value = descriptor(row);
14207
+ byResource.set(row.resource, value);
14208
+ const path = row.path?.replace(/^\/?v\d+\.\d+\//i, "").replace(/^\//, "");
14209
+ if (path !== void 0 && !path.includes("/")) roots.set(path.toLowerCase(), value);
14210
+ }
14211
+ for (const [alias, resource] of [["expenses", "expense_reports"], ["userdefinedfields", "user_defined_field_definitions"]]) {
14212
+ const value = byResource.get(resource);
14213
+ if (value !== void 0) roots.set(alias, value);
14214
+ }
14215
+ for (const row of Object.values(RELATIONSHIP_MAP)) {
14216
+ const parent = row.parent === null ? void 0 : byResource.get(row.parent.resource);
14217
+ if (parent !== void 0 && row.parent?.segment != null) {
14218
+ parent.children.set(row.parent.segment.toLowerCase(), byResource.get(row.resource));
14219
+ }
14220
+ }
14221
+ function canonicalObjectKey(url) {
14222
+ let path;
14223
+ if (url instanceof URL) {
14224
+ if (url.protocol !== "https:" && url.protocol !== "http:") return UNKNOWN_OBJECT_KEY;
14225
+ path = url.pathname;
14226
+ } else {
14227
+ try {
14228
+ if (/^[a-z][a-z\d+.-]*:/i.test(url)) {
14229
+ const parsed = new URL(url);
14230
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return UNKNOWN_OBJECT_KEY;
14231
+ path = parsed.pathname;
14232
+ } else {
14233
+ if (!url.startsWith("/")) return UNKNOWN_OBJECT_KEY;
14234
+ path = url.split(/[?#]/, 1)[0];
14235
+ }
14236
+ } catch {
14237
+ return UNKNOWN_OBJECT_KEY;
14238
+ }
14239
+ }
14240
+ let parts;
14241
+ try {
14242
+ parts = path.split("/").filter(Boolean).map((part) => decodeURIComponent(part).toLowerCase());
14243
+ } catch {
14244
+ return UNKNOWN_OBJECT_KEY;
14245
+ }
14246
+ if (parts.some((part) => part === "." || part === ".." || /[/\\]/.test(part))) return UNKNOWN_OBJECT_KEY;
14247
+ const version = parts.findIndex((part) => /^v\d+\.\d+$/.test(part));
14248
+ if (version >= 0) {
14249
+ if (parts.slice(0, version).some((part) => roots.has(part))) return UNKNOWN_OBJECT_KEY;
14250
+ parts = parts.slice(version + 1);
14251
+ } else if (parts[0] === "atservicesrest") parts = parts.slice(1);
14252
+ let object = roots.get(parts[0] ?? "");
14253
+ if (object === void 0) return UNKNOWN_OBJECT_KEY;
14254
+ if (object.key === "zone_information") return parts.length === 1 ? void 0 : UNKNOWN_OBJECT_KEY;
14255
+ let offset = 1;
14256
+ while (offset < parts.length) {
14257
+ const part = parts[offset];
14258
+ if (/^\d+$/.test(part)) {
14259
+ offset++;
14260
+ if (offset === parts.length) return object.key;
14261
+ const child = object.children.get(parts[offset]);
14262
+ if (child !== void 0) {
14263
+ object = child;
14264
+ offset++;
14265
+ continue;
14266
+ }
14267
+ }
14268
+ const tail = parts.slice(offset);
14269
+ if (tail[0] === "query") return object.key;
14270
+ if (tail[0] === "entityinformation") return object.key;
14271
+ if (tail.length === 1) return object.key;
14272
+ return UNKNOWN_OBJECT_KEY;
14273
+ }
14274
+ return object.key;
14275
+ }
14276
+
14277
+ // src/http/object-threads.ts
14278
+ var REGISTRY2 = /* @__PURE__ */ Symbol.for("node-autotask.object-thread-gates.v1");
14279
+ var NOTIFY = /* @__PURE__ */ Symbol.for("node-autotask.object-thread-notify.v1");
14280
+ var OBJECT_THREAD_LIMIT = 3;
14281
+ var state = globalThis;
14282
+ function unsupported() {
14283
+ return new AutotaskConfigError("Unsupported shared object-thread semaphore; refusing admission");
14284
+ }
14285
+ function available(semaphore) {
14286
+ const legacy = semaphore;
14287
+ if (!Number.isInteger(legacy.inFlight) || legacy.inFlight < 0 || legacy.inFlight > OBJECT_THREAD_LIMIT || legacy.maxConcurrent !== OBJECT_THREAD_LIMIT || !(legacy.waitQueue instanceof Set)) {
14288
+ throw unsupported();
14289
+ }
14290
+ return legacy.inFlight < OBJECT_THREAD_LIMIT && legacy.waitQueue.size === 0 && (typeof semaphore.canAcquire !== "function" || semaphore.canAcquire());
14291
+ }
14292
+ function observe(semaphore, notify) {
14293
+ let notifications = semaphore[NOTIFY];
14294
+ if (notifications === void 0) {
14295
+ notifications = { listeners: /* @__PURE__ */ new Map() };
14296
+ semaphore[NOTIFY] = notifications;
14297
+ const original = semaphore.release;
14298
+ const shared = notifications;
14299
+ semaphore.release = function() {
14300
+ original.call(this);
14301
+ for (const listener of shared.listeners.keys()) listener();
14302
+ };
14303
+ }
14304
+ const listeners = notifications.listeners;
14305
+ listeners.set(notify, (listeners.get(notify) ?? 0) + 1);
14306
+ return () => {
14307
+ const count = listeners.get(notify) ?? 0;
14308
+ if (count <= 1) listeners.delete(notify);
14309
+ else listeners.set(notify, count - 1);
14310
+ };
14311
+ }
14312
+ function retainObjectThread(url, trackingIdentifier) {
14313
+ const target = new URL(url);
14314
+ const object = canonicalObjectKey(target.pathname);
14315
+ if (object === void 0) return void 0;
14316
+ const key = crypto.createHash("sha256").update(JSON.stringify([target.origin, trackingIdentifier.trim().toLowerCase(), object])).digest("hex");
14317
+ const registry2 = state[REGISTRY2] ??= /* @__PURE__ */ new Map();
14318
+ let entry = registry2.get(key);
14319
+ if (entry === void 0) {
14320
+ entry = { semaphore: new Semaphore(OBJECT_THREAD_LIMIT), users: 0 };
14321
+ registry2.set(key, entry);
14322
+ }
14323
+ const active = entry;
14324
+ if (!Number.isInteger(active.users) || active.users < 0 || typeof active.semaphore?.acquire !== "function" || typeof active.semaphore.release !== "function") {
14325
+ throw unsupported();
14326
+ }
14327
+ available(active.semaphore);
14328
+ active.users += 1;
14329
+ let left = false;
14330
+ return {
14331
+ identity: active,
14332
+ listen: (notify) => observe(active.semaphore, notify),
14333
+ available: () => available(active.semaphore),
14334
+ acquire: (signal) => active.semaphore.acquire(signal),
14335
+ release: () => active.semaphore.release(),
14336
+ leave: () => {
14337
+ if (left) return;
14338
+ left = true;
14339
+ active.users -= 1;
14340
+ if (active.users === 0 && registry2.get(key) === active) registry2.delete(key);
14341
+ }
14342
+ };
14343
+ }
14344
+
14345
+ // src/http/transport-admission.ts
14346
+ var KEY = /* @__PURE__ */ Symbol.for("node-autotask.transport-admission.v2");
14347
+ var root2 = globalThis;
14348
+ var coordinator = root2[KEY] ??= { ready: { rows: [], available: () => true }, dirty: /* @__PURE__ */ new Set(), objects: /* @__PURE__ */ new Map(), signals: /* @__PURE__ */ new WeakMap(), sequence: 0, draining: false, batching: 0 };
14349
+ function subscribe(signal, aborted) {
14350
+ let queue = coordinator.signals.get(signal);
14351
+ if (queue === void 0) {
14352
+ const callbacks = /* @__PURE__ */ new Set();
14353
+ queue = { callbacks, listener: () => {
14354
+ coordinator.signals.delete(signal);
14355
+ coordinator.batching += 1;
14356
+ try {
14357
+ for (const callback of callbacks) callback();
14358
+ } finally {
14359
+ coordinator.batching -= 1;
14360
+ drain();
14361
+ }
14362
+ } };
14363
+ coordinator.signals.set(signal, queue);
14364
+ signal.addEventListener("abort", queue.listener, { once: true });
14365
+ }
14366
+ const shared = queue;
14367
+ shared.callbacks.add(aborted);
14368
+ return () => {
14369
+ shared.callbacks.delete(aborted);
14370
+ if (shared.callbacks.size === 0) {
14371
+ coordinator.signals.delete(signal);
14372
+ signal.removeEventListener("abort", shared.listener);
14373
+ }
14374
+ };
14375
+ }
14376
+ function earlier(a, b) {
14377
+ return a.head.sequence < b.head.sequence;
14378
+ }
14379
+ function swap(heap, a, b) {
14380
+ const rows = heap.rows;
14381
+ [rows[a], rows[b]] = [rows[b], rows[a]];
14382
+ rows[a].index = a;
14383
+ rows[b].index = b;
14384
+ }
14385
+ function remove(pair) {
14386
+ const heap = pair.heap;
14387
+ if (heap === void 0) return;
14388
+ const index = pair.index;
14389
+ const last = heap.rows.pop();
14390
+ pair.heap = void 0;
14391
+ if (last === pair) return;
14392
+ heap.rows[index] = last;
14393
+ last.index = index;
14394
+ let current = index;
14395
+ while (current > 0) {
14396
+ const parent = Math.floor((current - 1) / 2);
14397
+ if (!earlier(heap.rows[current], heap.rows[parent])) break;
14398
+ swap(heap, current, parent);
14399
+ current = parent;
14400
+ }
14401
+ if (current !== index) return;
14402
+ for (; ; ) {
14403
+ const left = current * 2 + 1;
14404
+ const right = left + 1;
14405
+ if (left >= heap.rows.length) break;
14406
+ const child = right < heap.rows.length && earlier(heap.rows[right], heap.rows[left]) ? right : left;
14407
+ if (!earlier(heap.rows[child], heap.rows[current])) break;
14408
+ swap(heap, current, child);
14409
+ current = child;
14410
+ }
14411
+ }
14412
+ function insert(heap, pair) {
14413
+ pair.heap = heap;
14414
+ pair.index = heap.rows.length;
14415
+ heap.rows.push(pair);
14416
+ let current = pair.index;
14417
+ while (current > 0) {
14418
+ const parent = Math.floor((current - 1) / 2);
14419
+ if (!earlier(heap.rows[current], heap.rows[parent])) break;
14420
+ swap(heap, current, parent);
14421
+ current = parent;
14422
+ }
14423
+ }
14424
+ function reconsider(pair) {
14425
+ const origin = pair.origin;
14426
+ pair.origin = void 0;
14427
+ remove(pair);
14428
+ if (origin !== void 0) coordinator.dirty.add(origin);
14429
+ if (pair.head === void 0) return false;
14430
+ if (pair.client.active >= pair.client.maxConcurrent) insert(pair.client.waiting, pair);
14431
+ else if (pair.object !== void 0 && !pair.object.gate.available()) insert(pair.object.waiting, pair);
14432
+ else {
14433
+ insert(coordinator.ready, pair);
14434
+ return true;
14435
+ }
14436
+ return false;
14437
+ }
14438
+ function unlink(ticket) {
14439
+ const pair = ticket.pair;
14440
+ if (ticket.previous !== void 0) ticket.previous.next = ticket.next;
14441
+ else pair.head = ticket.next;
14442
+ if (ticket.next !== void 0) ticket.next.previous = ticket.previous;
14443
+ else pair.tail = ticket.previous;
14444
+ ticket.previous = void 0;
14445
+ ticket.next = void 0;
14446
+ if (pair.head === void 0) pair.client.pairs.delete(pair.object?.gate.identity);
14447
+ }
14448
+ function drain() {
14449
+ if (coordinator.draining || coordinator.batching > 0) return;
14450
+ coordinator.draining = true;
14451
+ try {
14452
+ for (; ; ) {
14453
+ for (const heap of coordinator.dirty) {
14454
+ coordinator.dirty.delete(heap);
14455
+ while (heap.rows.length > 0 && heap.available()) {
14456
+ const pair2 = heap.rows[0];
14457
+ if (reconsider(pair2)) {
14458
+ pair2.origin = heap;
14459
+ break;
14460
+ }
14461
+ }
14462
+ }
14463
+ const pair = coordinator.ready.rows[0];
14464
+ if (pair === void 0) break;
14465
+ remove(pair);
14466
+ if (pair.client.active >= pair.client.maxConcurrent || pair.object !== void 0 && !pair.object.gate.available()) {
14467
+ reconsider(pair);
14468
+ continue;
14469
+ }
14470
+ const origin = pair.origin;
14471
+ pair.origin = void 0;
14472
+ if (origin !== void 0) coordinator.dirty.add(origin);
14473
+ const ticket = pair.head;
14474
+ unlink(ticket);
14475
+ ticket.grant();
14476
+ if (pair.head !== void 0) reconsider(pair);
14477
+ }
14478
+ } finally {
14479
+ coordinator.draining = false;
14480
+ }
14481
+ }
14482
+ function wake(heap) {
14483
+ coordinator.dirty.add(heap);
14484
+ drain();
14485
+ }
14486
+ function admissionClient(maxConcurrent) {
14487
+ const client = { maxConcurrent, active: 0, pairs: /* @__PURE__ */ new Map(), waiting: { rows: [], available: () => client.active < client.maxConcurrent } };
14488
+ return client;
14489
+ }
14490
+ async function acquireTransport(client, url, trackingIdentifier, signal) {
14491
+ if (signal.aborted) throw signal.reason;
14492
+ const retained = retainObjectThread(url, trackingIdentifier);
14493
+ let object = retained === void 0 ? void 0 : coordinator.objects.get(retained.identity);
14494
+ if (retained !== void 0 && object === void 0) {
14495
+ object = { gate: retained, references: 0, stop: () => void 0, waiting: { rows: [], available: () => retained.available() } };
14496
+ const shared = object;
14497
+ shared.stop = retained.listen(() => wake(shared.waiting));
14498
+ coordinator.objects.set(retained.identity, shared);
14499
+ }
14500
+ if (object !== void 0) object.references += 1;
14501
+ const drop = () => {
14502
+ retained?.leave();
14503
+ if (object !== void 0 && --object.references === 0) {
14504
+ object.stop();
14505
+ coordinator.objects.delete(object.gate.identity);
14506
+ }
14507
+ };
14508
+ let pair = client.pairs.get(retained?.identity);
14509
+ if (pair === void 0) {
14510
+ pair = { client, object, index: -1 };
14511
+ client.pairs.set(retained?.identity, pair);
14512
+ }
14513
+ const queue = pair;
14514
+ return new Promise((resolve, reject) => {
14515
+ let released = false;
14516
+ let unsubscribe = () => void 0;
14517
+ const leave = () => {
14518
+ if (released) return;
14519
+ released = true;
14520
+ coordinator.batching += 1;
14521
+ client.active -= 1;
14522
+ coordinator.dirty.add(client.waiting);
14523
+ try {
14524
+ retained?.release();
14525
+ } finally {
14526
+ drop();
14527
+ coordinator.batching -= 1;
14528
+ drain();
14529
+ }
14530
+ };
14531
+ const aborted = () => {
14532
+ const front = queue.head === ticket;
14533
+ if (front) remove(queue);
14534
+ unlink(ticket);
14535
+ unsubscribe();
14536
+ drop();
14537
+ reject(signal.reason);
14538
+ if (front) reconsider(queue);
14539
+ drain();
14540
+ };
14541
+ const ticket = {
14542
+ sequence: coordinator.sequence++,
14543
+ pair: queue,
14544
+ grant: () => {
14545
+ unsubscribe();
14546
+ client.active += 1;
14547
+ let acquired;
14548
+ try {
14549
+ acquired = retained?.acquire(signal) ?? Promise.resolve();
14550
+ } catch (error) {
14551
+ client.active -= 1;
14552
+ drop();
14553
+ reject(error);
14554
+ wake(client.waiting);
14555
+ return;
14556
+ }
14557
+ void acquired.then(() => {
14558
+ if (signal.aborted) {
14559
+ leave();
14560
+ reject(signal.reason);
14561
+ } else resolve(leave);
14562
+ }, (error) => {
14563
+ client.active -= 1;
14564
+ drop();
14565
+ reject(error);
14566
+ wake(client.waiting);
14567
+ });
14568
+ }
14569
+ };
14570
+ ticket.previous = queue.tail;
14571
+ if (queue.tail !== void 0) queue.tail.next = ticket;
14572
+ else queue.head = ticket;
14573
+ queue.tail = ticket;
14574
+ unsubscribe = subscribe(signal, aborted);
14575
+ if (queue.head === ticket) reconsider(queue);
14576
+ drain();
14577
+ });
14578
+ }
14579
+
14580
+ // src/http/credentials.ts
14581
+ var CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
14582
+ "ApiIntegrationCode",
14583
+ "UserName",
14584
+ "Secret",
14585
+ "ImpersonationResourceId"
14586
+ ]);
14587
+ function assertCredentialShape(headers, auth) {
14588
+ const owned = new Set(CREDENTIAL_HEADER_NAMES);
14589
+ for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
14590
+ for (const name of Object.keys(headers)) {
14591
+ if (!owned.has(name)) continue;
14592
+ const value = headers[name];
14593
+ const shape = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
14594
+ if (shape === void 0) continue;
14595
+ throw new AutotaskConfigError(
14596
+ `${name} ${CREDENTIAL_ENV_LOAD_ACTION} (${shape})`,
14597
+ {
14598
+ code: "INVALID_CREDENTIAL_SHAPE",
14599
+ suggestedAction: "Load the credential with the shell (`set -a; . ./.env; set +a`) or with loadAutotaskCredentialsFromEnv() from node-autotask; single-quoted values must be shell-sourced, not parsed by a quote-preserving loader. No request was sent."
14600
+ }
14601
+ );
14602
+ }
14603
+ }
14604
+ function credentialShapeExpectation(headers, auth) {
14605
+ const owned = new Set(CREDENTIAL_HEADER_NAMES);
14606
+ for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
14607
+ const names = Object.keys(headers).filter((name) => owned.has(name));
14608
+ if (names.length === 0) return void 0;
14609
+ let problem;
14610
+ for (const name of names) {
14611
+ const value = headers[name];
14612
+ problem = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
14613
+ if (problem !== void 0) break;
14614
+ }
14615
+ return {
14616
+ headerNames: names,
14617
+ allValuesClean: problem === void 0,
14618
+ ...problem !== void 0 ? { problem } : {}
14619
+ };
14620
+ }
14621
+
14065
14622
  // src/http/envelope.ts
14066
14623
  var INVALID_SHAPE_ACTION = "Report the unexpected response shape; verify baseUrl points at the REST API.";
14067
14624
  function attachEmptyReasonDetails(err) {
@@ -14191,38 +14748,45 @@ function canReResolveZone(reResolveZoneOn401, zone, opts) {
14191
14748
  }
14192
14749
  async function discoverZoneBase(userName, maxResponseBytes, signal, ctx) {
14193
14750
  const discoveryUrl = `${ZONE_DISCOVERY_URL}?user=${encodeURIComponent(userName)}`;
14194
- let res;
14195
- try {
14196
- res = await fetch(discoveryUrl, {
14197
- method: "GET",
14198
- headers: { Accept: "application/json" },
14199
- redirect: "manual",
14200
- // a redirect off the discovery host is a fault, not a target
14201
- signal
14202
- });
14203
- } catch {
14204
- return void 0;
14205
- }
14206
- if (res.status < 200 || res.status >= 300) {
14207
- await res.body?.cancel().catch(() => void 0);
14208
- return void 0;
14209
- }
14210
- let text;
14751
+ if (signal.aborted) return void 0;
14752
+ const admission = admitHourlyAttempt(discoveryUrl, void 0, Date.now());
14753
+ if (!admission.admitted) return void 0;
14211
14754
  try {
14212
- text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
14213
- } catch {
14214
- return void 0;
14215
- }
14216
- let body;
14217
- try {
14218
- body = JSON.parse(text);
14219
- } catch {
14220
- return void 0;
14221
- }
14222
- if (!isRecord2(body) || typeof body.url !== "string" || body.url.trim().length === 0) {
14223
- return void 0;
14755
+ let res;
14756
+ try {
14757
+ res = await fetch(discoveryUrl, {
14758
+ method: "GET",
14759
+ headers: { Accept: "application/json" },
14760
+ redirect: "manual",
14761
+ // a redirect off the discovery host is a fault, not a target
14762
+ signal
14763
+ });
14764
+ } catch {
14765
+ return void 0;
14766
+ }
14767
+ if (res.status < 200 || res.status >= 300) {
14768
+ await res.body?.cancel().catch(() => void 0);
14769
+ return void 0;
14770
+ }
14771
+ let text;
14772
+ try {
14773
+ text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
14774
+ } catch {
14775
+ return void 0;
14776
+ }
14777
+ let body;
14778
+ try {
14779
+ body = JSON.parse(text);
14780
+ } catch {
14781
+ return void 0;
14782
+ }
14783
+ if (!isRecord2(body) || typeof body.url !== "string" || body.url.trim().length === 0) {
14784
+ return void 0;
14785
+ }
14786
+ return normalizeZoneBase(body.url);
14787
+ } finally {
14788
+ admission.finish();
14224
14789
  }
14225
- return normalizeZoneBase(body.url);
14226
14790
  }
14227
14791
 
14228
14792
  // src/http/HttpClient.ts
@@ -14266,8 +14830,8 @@ var HttpClient = class {
14266
14830
  maxResponseBytes;
14267
14831
  /** Local hourly budget (undefined when `rateLimit.perHour` is off). */
14268
14832
  hourly;
14269
- /** FIFO semaphore bounding in-flight requests to `maxConcurrent`. */
14270
- semaphore;
14833
+ /** Client identity for atomic local/object capacity admission. */
14834
+ admission;
14271
14835
  /** Tenant 429 cooldown gate (issue #6; ON by default). */
14272
14836
  cooldownEnabled;
14273
14837
  cooldownMaxMs;
@@ -14330,7 +14894,7 @@ var HttpClient = class {
14330
14894
  this.cooldownMaxMs = config.cooldown.maxMs;
14331
14895
  this.cooldownDefaultMs = config.cooldown.defaultMs;
14332
14896
  this.maxConcurrent = config.maxConcurrent;
14333
- this.semaphore = new Semaphore(config.maxConcurrent);
14897
+ this.admission = admissionClient(config.maxConcurrent);
14334
14898
  this.timeoutMs = config.timeoutMs;
14335
14899
  this.logger = config.logger;
14336
14900
  this.redactPersonalData = config.redactPersonalData;
@@ -14339,8 +14903,9 @@ var HttpClient = class {
14339
14903
  /**
14340
14904
  * The LOCAL hourly-budget state (the sliding window this client counts):
14341
14905
  * `{ perHour, used, remaining }` — `undefined` when `rateLimit.perHour`
14342
- * is off. The limiter is PER PROCESS (issue #4): it cannot see other
14343
- * instances or integrations on the tenant — the tenant-wide count is
14906
+ * is off. This optional quota is PER CLIENT (issue #4); the separate
14907
+ * always-on origin ceiling is shared within the JavaScript realm. Neither
14908
+ * measures external integrations — the vendor-wide count is
14344
14909
  * `thresholdInformation.get()`.
14345
14910
  */
14346
14911
  hourlyBudget() {
@@ -14518,38 +15083,73 @@ var HttpClient = class {
14518
15083
  * zone maintenance gate (issue #285), which admits one probe per poll
14519
15084
  * interval while open. An already-aborted caller still gets the abort error.
14520
15085
  */
14521
- gate(s) {
15086
+ gate(s, auditRefusal = true) {
14522
15087
  const cooldown = this.cooldownEnabled && !s.opts.bypassCooldown ? cooldownRefusal(this.tenantKey, s.ctx) : void 0;
14523
- const verdict = cooldown ?? admitMaintenance(this.hostKey, s.ctx);
15088
+ const owned = s.maintenanceProbe?.host === this.hostKey ? s.maintenanceProbe.gate : void 0;
15089
+ const verdict = cooldown ?? admitMaintenance(this.hostKey, s.ctx, owned);
14524
15090
  if (verdict === "send") return;
14525
15091
  if (!(verdict instanceof AutotaskError)) {
15092
+ if (s.maintenanceProbe !== void 0 && (s.maintenanceProbe.host !== this.hostKey || s.maintenanceProbe.gate !== verdict)) {
15093
+ releaseMaintenanceProbe(s.maintenanceProbe.host, s.maintenanceProbe.gate);
15094
+ }
14526
15095
  s.maintenanceProbe = { host: this.hostKey, gate: verdict };
14527
15096
  return;
14528
15097
  }
14529
15098
  if (s.callerSignal?.aborted) throw this.interrupted(s);
14530
- this.auditNotSent(s, verdict.code);
15099
+ if (auditRefusal) this.auditNotSent(s, verdict.code);
14531
15100
  throw verdict;
14532
15101
  }
14533
15102
  // ---- the attempt --------------------------------------------------------
14534
15103
  /**
14535
- * Take the hourly slot and a semaphore permit, fetch, and read the body.
15104
+ * Acquire client/object capacity together, charge the attempt, fetch and read the body.
14536
15105
  * `retry` when a network error is retriable (already waited); throws the
14537
15106
  * typed error otherwise. The permit is released on every path.
14538
15107
  */
14539
15108
  async sendOnce(s) {
14540
15109
  const { method, opts, ctx } = s;
14541
- try {
14542
- await this.hourly?.take(s.deadlineAt, s.signal, ctx);
14543
- } catch (err) {
14544
- if (s.signal.aborted) throw this.interrupted(s);
14545
- throw err;
15110
+ let release;
15111
+ for (; ; ) {
15112
+ let releaseThreads;
15113
+ try {
15114
+ releaseThreads = await acquireTransport(this.admission, s.url, this.auth.apiIntegrationCode, s.signal);
15115
+ } catch (err) {
15116
+ if (s.signal.aborted) throw this.interrupted(s);
15117
+ throw err;
15118
+ }
15119
+ let finishHourly = () => void 0;
15120
+ let released = false;
15121
+ const releaseCurrent = () => {
15122
+ if (released) return;
15123
+ released = true;
15124
+ finishHourly();
15125
+ releaseThreads();
15126
+ };
15127
+ try {
15128
+ if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
15129
+ this.gate(s, false);
15130
+ if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
15131
+ const admission = admitHourlyAttempt(s.url, this.hourly, Date.now());
15132
+ if (!admission.admitted) {
15133
+ releaseCurrent();
15134
+ await waitHourlyAdmission(admission, s.deadlineAt, s.signal, ctx);
15135
+ continue;
15136
+ }
15137
+ finishHourly = admission.finish;
15138
+ release = releaseCurrent;
15139
+ s.wireAttempts += 1;
15140
+ break;
15141
+ } catch (err) {
15142
+ releaseCurrent();
15143
+ if (s.signal.aborted) throw this.interrupted(s);
15144
+ if ((err instanceof RateLimitError || err instanceof MaintenanceError) && s.wireAttempts > 0) delete err.notSent;
15145
+ throw err;
15146
+ }
14546
15147
  }
14547
- await this.semaphore.acquire();
14548
15148
  let res;
14549
15149
  try {
14550
15150
  res = await fetch(s.url, { method, headers: s.headers, body: s.bodyText, signal: s.signal, redirect: "manual" });
14551
15151
  } catch (err) {
14552
- this.semaphore.release();
15152
+ release();
14553
15153
  if (s.signal.aborted || isAbortLike(err)) throw this.interrupted(s);
14554
15154
  const delay = backoffDelay(s.attempt);
14555
15155
  if (s.attempt < s.maxRetries && s.retriable5xx && await this.retryAfterDelay(s, delay, `network error on ${method} ${opts.path}`)) {
@@ -14573,7 +15173,7 @@ var HttpClient = class {
14573
15173
  }
14574
15174
  text = await readBodyText(res, this.maxResponseBytes, `${method} ${opts.path}`, { ...ctx, httpStatus: status });
14575
15175
  } catch (err) {
14576
- this.semaphore.release();
15176
+ release();
14577
15177
  if (err instanceof AutotaskError) throw err;
14578
15178
  if (s.signal.aborted || isAbortLike(err)) throw this.interrupted(s);
14579
15179
  throw new AutotaskNetworkError(
@@ -14581,7 +15181,7 @@ var HttpClient = class {
14581
15181
  ctx
14582
15182
  );
14583
15183
  }
14584
- this.semaphore.release();
15184
+ release();
14585
15185
  s.lastStatus = status;
14586
15186
  return { retry: false, res, status, text };
14587
15187
  }
@@ -14771,7 +15371,8 @@ var HttpClient = class {
14771
15371
  status: s.lastStatus,
14772
15372
  durationMs: Date.now() - s.started,
14773
15373
  body: s.auditBody,
14774
- errorCode: err instanceof AutotaskError ? err.code : "NETWORK_ERROR"
15374
+ errorCode: err instanceof AutotaskError ? err.code : "NETWORK_ERROR",
15375
+ ...s.wireAttempts === 0 ? { notSent: true } : {}
14775
15376
  });
14776
15377
  if (this.fieldCache !== void 0 && err instanceof AutotaskError) {
14777
15378
  const op = typeof opts.operation === "string" ? opts.operation : void 0;
@@ -14854,12 +15455,14 @@ var HttpClient = class {
14854
15455
  lastStatus: void 0,
14855
15456
  zoneRetry: void 0,
14856
15457
  attempt: 0,
15458
+ wireAttempts: 0,
14857
15459
  maintenanceProbe: void 0,
14858
15460
  maintenancePage: false,
14859
15461
  // Armed LAST in the literal: nothing after this can throw, and the single
14860
15462
  // try/finally below clears it on every exit path (#190).
14861
15463
  deadlineTimer: setTimeout(() => deadline.abort(), timeoutMs)
14862
15464
  };
15465
+ const finishRequest = trackHourlyRequest();
14863
15466
  try {
14864
15467
  this.gate(s);
14865
15468
  this.logger.debug?.(`[autotask] ${method} ${opts.path}`, correlationId);
@@ -14881,10 +15484,11 @@ var HttpClient = class {
14881
15484
  this.onFailure(s, err);
14882
15485
  throw err;
14883
15486
  } finally {
14884
- this.invalidateAfterWrite(opts);
15487
+ if (s.wireAttempts > 0) this.invalidateAfterWrite(opts);
14885
15488
  }
14886
15489
  } finally {
14887
15490
  clearTimeout(s.deadlineTimer);
15491
+ finishRequest();
14888
15492
  if (s.maintenanceProbe !== void 0) releaseMaintenanceProbe(s.maintenanceProbe.host, s.maintenanceProbe.gate);
14889
15493
  }
14890
15494
  }
@@ -15240,6 +15844,56 @@ var WORKFLOW_RESOURCES = [
15240
15844
  "projects"
15241
15845
  ];
15242
15846
 
15847
+ // src/utils/bounded.ts
15848
+ async function runBounded(fn, items, opts) {
15849
+ const { concurrency, signal, settle } = opts;
15850
+ if (!Number.isInteger(concurrency) || concurrency <= 0) {
15851
+ throw new AutotaskConfigError("batch concurrency must be a positive integer");
15852
+ }
15853
+ const results = new Array(items.length);
15854
+ let next = 0;
15855
+ let failure;
15856
+ const fail = (error, index) => {
15857
+ if (failure === void 0 || opts.orderedErrors === true && index < failure.index) failure = { error, index };
15858
+ };
15859
+ const worker = async () => {
15860
+ while (failure === void 0 && next < items.length) {
15861
+ if (signal?.aborted) {
15862
+ fail(signal.reason, -1);
15863
+ return;
15864
+ }
15865
+ const i = next++;
15866
+ try {
15867
+ const item = items[i];
15868
+ const value = await (signal === void 0 ? fn(item) : runWithSignal(signal, () => fn(item)));
15869
+ results[i] = settle ? { status: "fulfilled", value } : value;
15870
+ } catch (error) {
15871
+ if (settle) results[i] = { status: "rejected", reason: error };
15872
+ else fail(error, i);
15873
+ }
15874
+ }
15875
+ };
15876
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
15877
+ if (failure !== void 0) throw failure.error;
15878
+ return results;
15879
+ }
15880
+ async function mapReadTasks(http, items, fn) {
15881
+ const signal = ambientCallerSignal();
15882
+ const abort = () => new AutotaskAbortError("Read fan-out aborted by the caller");
15883
+ if (signal?.aborted) throw abort();
15884
+ try {
15885
+ const results = await runBounded(fn, items, { concurrency: http === void 0 ? DEFAULT_MAX_CONCURRENT : http.maxConcurrent, orderedErrors: true, ...signal === void 0 ? {} : { signal } });
15886
+ if (signal?.aborted) throw abort();
15887
+ return results;
15888
+ } catch (error) {
15889
+ if (signal?.aborted && !(error instanceof AutotaskAbortError)) throw abort();
15890
+ throw error;
15891
+ }
15892
+ }
15893
+ function readTasks(http, tasks) {
15894
+ return mapReadTasks(http, tasks, (task) => task());
15895
+ }
15896
+
15243
15897
  // src/operations/fieldCatalog.ts
15244
15898
  var MAX_FIELD_CATALOG_WIRE = 60;
15245
15899
  var FIELD_CATALOG_HONESTY_NOTE = "Live field metadata reports the SHAPE of a field (existence, requiredness, type, maxLength, read-only, queryable, picklist-ness) as FLAGS and NAMES: picklist-ness as a flag (isPickList) and picklist field names (picklistFields). With the opt-in `labels: true`, picklist rows carry the vendor's exposed picklist VALUES (labels next to each value); without it the op serves no VALUES. It cannot resolve a picklist VALUE the vendor does not expose to this API user (a vendor-withheld picklist value): retrying the catalog will not surface a withheld value; that gap is vendor-side, not a client defect.";
@@ -15303,7 +15957,7 @@ async function capabilitySets() {
15303
15957
  const fieldOps = /* @__PURE__ */ new Map();
15304
15958
  const udfCapable = /* @__PURE__ */ new Set();
15305
15959
  const resources = /* @__PURE__ */ new Set();
15306
- for (const rec of await chunkSGH7F2CH_cjs.loadCapabilityRecords()) {
15960
+ for (const rec of await chunkKAZE4WC7_cjs.loadCapabilityRecords()) {
15307
15961
  if (rec.resource === "operations") continue;
15308
15962
  resources.add(rec.resource);
15309
15963
  if (rec.operation === "getFieldInfo") fieldOps.set(rec.resource, rec);
@@ -15314,7 +15968,7 @@ async function capabilitySets() {
15314
15968
  var derivedIndexPromise = null;
15315
15969
  function derivedIndexLoad() {
15316
15970
  if (derivedIndexPromise === null) {
15317
- derivedIndexPromise = chunkSGH7F2CH_cjs.loadCapabilityRecords().then((records) => {
15971
+ derivedIndexPromise = chunkKAZE4WC7_cjs.loadCapabilityRecords().then((records) => {
15318
15972
  const index = /* @__PURE__ */ new Map();
15319
15973
  for (const rec of records) {
15320
15974
  const declared = rec.metadata?.derivedFields;
@@ -15512,13 +16166,25 @@ function kindFetches(holder, resource) {
15512
16166
  udf: () => holder?.getUdfInfo?.() ?? Promise.reject(new AutotaskError(`fieldCatalog: the client exposes no getUdfInfo read for "${resource}"`, { code: "INVALID_RESPONSE", category: "server" }))
15513
16167
  };
15514
16168
  }
15515
- async function sweepResource(ctx, resource, tally) {
15516
- const { client, include, fieldsFilter, labels, fresh } = ctx;
15517
- const cache = client.http.fieldCache;
16169
+ async function readKind(ctx, resource, kind, fetch2) {
16170
+ const cache = ctx.client.http.fieldCache;
16171
+ const peek = cache !== void 0 && !ctx.fresh ? cache.peek(fieldKey(resource, kind)) : { hit: false, age: null };
16172
+ if (peek.hit && cache !== void 0) {
16173
+ return { kind, peek, outcome: { status: "fulfilled", value: cache.get(fieldKey(resource, kind)) } };
16174
+ }
16175
+ try {
16176
+ const value = await fetch2();
16177
+ return { kind, peek, outcome: { status: "fulfilled", value } };
16178
+ } catch (error) {
16179
+ if (!isAutotaskError(error) || error.code === "ABORTED") throw error;
16180
+ return { kind, peek, outcome: { status: "rejected", reason: error } };
16181
+ }
16182
+ }
16183
+ async function sweepResource(ctx, resource, tally, reads) {
16184
+ const { fieldsFilter, labels } = ctx;
15518
16185
  const fieldOp = ctx.fieldOps.get(resource);
15519
16186
  if (fieldOp === void 0) return void 0;
15520
16187
  const apiEntity = apiEntityFor(fieldOp);
15521
- const holder = client[camelKey(resource)];
15522
16188
  const row = {
15523
16189
  resource,
15524
16190
  apiEntity,
@@ -15534,8 +16200,6 @@ async function sweepResource(ctx, resource, tally) {
15534
16200
  wire: 0,
15535
16201
  error: null
15536
16202
  };
15537
- const fetches = kindFetches(holder, resource);
15538
- if (fresh) cache?.invalidate(`${resource}:`);
15539
16203
  const projectList = (kind, list) => {
15540
16204
  const projected = list.map((f) => projectFieldRow(f, labels, kind === "udf"));
15541
16205
  if (kind === "fields") applyFieldsFilter(projected, fieldsFilter, row);
@@ -15544,28 +16208,18 @@ async function sweepResource(ctx, resource, tally) {
15544
16208
  };
15545
16209
  let allCached = true;
15546
16210
  const ages = [];
15547
- for (const kind of include) {
15548
- const peek = cache !== void 0 && !fresh ? cache.peek(fieldKey(resource, kind)) : { hit: false, age: null };
15549
- if (peek.hit !== true) allCached = false;
15550
- if (peek.hit === true && cache !== void 0) {
15551
- const value2 = cache.get(fieldKey(resource, kind));
15552
- if (kind === "info") row.info = value2 ?? null;
15553
- else projectList(kind, Array.isArray(value2) ? value2 : []);
15554
- if (peek.age !== null) ages.push(peek.age);
15555
- continue;
15556
- }
15557
- let value;
15558
- try {
15559
- value = await fetches[kind]();
15560
- } catch (err) {
15561
- if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16211
+ for (const { kind, peek, outcome } of reads) {
16212
+ if (!peek.hit) {
16213
+ allCached = false;
15562
16214
  tally.wireUsed += 1;
15563
16215
  row.wire += 1;
15564
- if (row.error === null) row.error = { code: err.code, message: err.message };
16216
+ } else if (peek.age !== null) ages.push(peek.age);
16217
+ if (outcome.status === "rejected") {
16218
+ const error = outcome.reason;
16219
+ if (row.error === null) row.error = { code: error.code, message: error.message };
15565
16220
  continue;
15566
16221
  }
15567
- tally.wireUsed += 1;
15568
- row.wire += 1;
16222
+ const value = outcome.value;
15569
16223
  if (kind === "info") {
15570
16224
  row.info = value ?? null;
15571
16225
  } else {
@@ -15610,9 +16264,20 @@ async function fieldCatalog(client, opts) {
15610
16264
  const zone = client.config.zone ?? "unknown";
15611
16265
  const rows = [];
15612
16266
  const tally = { wireUsed: 0, anyPicklistValues: false };
15613
- const ctx = { client, include, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
16267
+ const ctx = { client, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
15614
16268
  for (const resource of targets) {
15615
- const row = await sweepResource(ctx, resource, tally);
16269
+ apiEntityFor(fieldOps.get(resource));
16270
+ if (ctx.fresh) cache?.invalidate(`${resource}:`);
16271
+ }
16272
+ const tasks = targets.flatMap((resource) => {
16273
+ const holder = client[camelKey(resource)];
16274
+ const fetches = kindFetches(holder, resource);
16275
+ return include.map((kind) => ({ resource, kind, fetch: fetches[kind] }));
16276
+ });
16277
+ const reads = await mapReadTasks(client.http, tasks, ({ resource, kind, fetch: fetch2 }) => readKind(ctx, resource, kind, fetch2));
16278
+ for (let index = 0; index < targets.length; index += 1) {
16279
+ const start = index * include.length;
16280
+ const row = await sweepResource(ctx, targets[index], tally, reads.slice(start, start + include.length));
15616
16281
  if (row !== void 0) rows.push(row);
15617
16282
  }
15618
16283
  const result = {
@@ -15795,6 +16460,14 @@ function entityNameFromPath(resourcePath) {
15795
16460
  return snake;
15796
16461
  }
15797
16462
 
16463
+ // src/operations/nameSnapshot.ts
16464
+ function nameRecordSnapshot(cache, path, id, operation) {
16465
+ const body = cache?.get(path);
16466
+ if (body === void 0) return void 0;
16467
+ const entity = path.split("/").at(-2);
16468
+ return () => unwrapItem(body, id, operation, entity);
16469
+ }
16470
+
15798
16471
  // src/operations/expandResourceNames.ts
15799
16472
  var EXPAND_RESOURCE_NAMES_MAX_IDS = 500;
15800
16473
  function composeName(record) {
@@ -15805,6 +16478,27 @@ function composeName(record) {
15805
16478
  }
15806
16479
  return parts.length > 0 ? parts.join(" ") : null;
15807
16480
  }
16481
+ function resourceNameFailure(err) {
16482
+ if (err instanceof NotFoundError) return { name: null, blind: true };
16483
+ if (isAutotaskError(err) && err.code !== "ABORTED") {
16484
+ const error = { code: err.code, message: err.message };
16485
+ if (err.httpStatus !== void 0) error.httpStatus = err.httpStatus;
16486
+ return { name: null, blind: false, error };
16487
+ }
16488
+ throw err;
16489
+ }
16490
+ function resourceNameSnapshot(cache, id) {
16491
+ if (cache === void 0) return void 0;
16492
+ const path = `/V1.0/Resources/${id}`;
16493
+ if (cache.get(contextAbsentKey(path)) !== void 0) return { name: null, blind: true };
16494
+ const record = nameRecordSnapshot(cache, path, id, "resources.get");
16495
+ if (record === void 0) return void 0;
16496
+ try {
16497
+ return { name: composeName(record()), blind: false };
16498
+ } catch (err) {
16499
+ return resourceNameFailure(err);
16500
+ }
16501
+ }
15808
16502
  async function expandResourceNames(client, ids2, opts = {}) {
15809
16503
  if (opts.maxIds !== void 0 && (!Number.isInteger(opts.maxIds) || opts.maxIds < 1)) {
15810
16504
  throw new AutotaskConfigError(`expandResourceNames: maxIds must be an integer >= 1 (got ${String(opts.maxIds)})`);
@@ -15857,13 +16551,21 @@ async function expandResourceNames(client, ids2, opts = {}) {
15857
16551
  const holder = client.resources;
15858
16552
  const cache = client.http.readCache;
15859
16553
  const fresh = opts.fresh === true;
16554
+ const warm = /* @__PURE__ */ new Map();
16555
+ if (!fresh) {
16556
+ for (const id of unique) {
16557
+ const snapshot = resourceNameSnapshot(cache, id);
16558
+ if (snapshot !== void 0) warm.set(String(id), snapshot);
16559
+ }
16560
+ }
15860
16561
  const byId2 = /* @__PURE__ */ new Map();
15861
- for (const id of unique) {
16562
+ await mapReadTasks(client.http, unique, async (id) => {
15862
16563
  const k = String(id);
15863
16564
  const absentKey = contextAbsentKey(`/V1.0/Resources/${k}`);
15864
- if (cache !== void 0 && !fresh && cache.get(absentKey) !== void 0) {
15865
- byId2.set(k, { name: null, blind: true });
15866
- continue;
16565
+ const snapshot = warm.get(k);
16566
+ if (snapshot !== void 0) {
16567
+ byId2.set(k, snapshot);
16568
+ return;
15867
16569
  }
15868
16570
  const epoch = cache?.epoch ?? 0;
15869
16571
  try {
@@ -15874,17 +16576,11 @@ async function expandResourceNames(client, ids2, opts = {}) {
15874
16576
  if (err instanceof NotFoundError) {
15875
16577
  cache?.set(absentKey, CONTEXT_ABSENT_MARKER, epoch);
15876
16578
  byId2.set(k, { name: null, blind: true });
15877
- continue;
15878
- }
15879
- if (isAutotaskError(err) && err.code !== "ABORTED") {
15880
- const e = { code: err.code, message: err.message };
15881
- if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
15882
- byId2.set(k, { name: null, blind: false, error: e });
15883
- continue;
16579
+ return;
15884
16580
  }
15885
- throw err;
16581
+ byId2.set(k, resourceNameFailure(err));
15886
16582
  }
15887
- }
16583
+ });
15888
16584
  const results = [];
15889
16585
  for (const id of canonical) {
15890
16586
  const out = byId2.get(String(id));
@@ -16049,6 +16745,13 @@ var FK_TABLE_PATH = {
16049
16745
  company: "/V1.0/Companies",
16050
16746
  ticket: "/V1.0/Tickets"
16051
16747
  };
16748
+ var FK_GET_OPERATION = {
16749
+ role: "roles.get",
16750
+ billingCode: "billing_codes.get",
16751
+ contract: "contracts.get",
16752
+ company: "companies.get",
16753
+ ticket: "tickets.get"
16754
+ };
16052
16755
  var FK_NAME_FIELD = {
16053
16756
  role: "name",
16054
16757
  billingCode: "name",
@@ -16080,13 +16783,15 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16080
16783
  const readCache = http.readCache;
16081
16784
  const section = { truncated: false, rows: {}, reasons: {} };
16082
16785
  let remaining = budget;
16786
+ const tasks = [];
16083
16787
  let contractLobPointer;
16084
16788
  let contractLobUnread;
16085
16789
  const coldResource = [];
16790
+ const warmResources = /* @__PURE__ */ new Map();
16086
16791
  for (const id of plan.resourceIds) {
16087
- const path = `/V1.0/Resources/${id}`;
16088
- if (readCache !== void 0 && (readCache.peek(path).hit || readCache.peek(contextAbsentKey(path)).hit)) continue;
16089
- coldResource.push(id);
16792
+ const snapshot = resourceNameSnapshot(readCache, id);
16793
+ if (snapshot === void 0) coldResource.push(id);
16794
+ else warmResources.set(String(id), snapshot);
16090
16795
  }
16091
16796
  const withinBudget = coldResource.slice(0, remaining);
16092
16797
  const overBudgetResource = coldResource.slice(remaining);
@@ -16106,12 +16811,21 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16106
16811
  }
16107
16812
  pass = pass.slice(0, 500);
16108
16813
  }
16109
- const res = await expandResourceNames(client, pass);
16110
- for (const r of res.results) {
16111
- const row = { name: r.name, blind: r.blind };
16112
- if (r.error !== void 0) row.error = faultRow(r.error);
16113
- section.rows[`resource:${r.id}`] = row;
16114
- }
16814
+ tasks.push(async () => {
16815
+ const cold = pass.filter((id) => !warmResources.has(String(id)));
16816
+ const outcomes = new Map(warmResources);
16817
+ if (cold.length > 0) {
16818
+ for (const row of (await expandResourceNames(client, cold)).results) outcomes.set(String(row.id), row);
16819
+ }
16820
+ return () => {
16821
+ for (const id of pass) {
16822
+ const r = outcomes.get(String(id));
16823
+ const row = { name: r.name, blind: r.blind };
16824
+ if (r.error !== void 0) row.error = faultRow(r.error);
16825
+ section.rows[`resource:${id}`] = row;
16826
+ }
16827
+ };
16828
+ });
16115
16829
  }
16116
16830
  const holders = {
16117
16831
  role: client.roles,
@@ -16122,10 +16836,13 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16122
16836
  };
16123
16837
  for (const fk2 of plan.recordFks) {
16124
16838
  const key = `${fk2.table}:${fk2.id}`;
16125
- const cold = readCache === void 0 || readCache.get(`${FK_TABLE_PATH[fk2.table]}/${fk2.id}`) === void 0;
16839
+ const snapshot = nameRecordSnapshot(readCache, `${FK_TABLE_PATH[fk2.table]}/${fk2.id}`, fk2.id, FK_GET_OPERATION[fk2.table]);
16840
+ const cold = snapshot === void 0;
16126
16841
  if (cold) {
16127
16842
  if (remaining < 1) {
16128
- section.rows[key] = { name: null, blind: false };
16843
+ tasks.push(async () => () => {
16844
+ section.rows[key] = { name: null, blind: false };
16845
+ });
16129
16846
  section.truncated = true;
16130
16847
  if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16131
16848
  contractLobUnread = "capped";
@@ -16134,41 +16851,51 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16134
16851
  }
16135
16852
  remaining -= 1;
16136
16853
  }
16137
- try {
16138
- const record = await holders[fk2.table].get(fk2.id);
16139
- if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16140
- contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
16141
- }
16142
- section.rows[key] = { name: fkName(record, fk2.table), blind: false };
16143
- } catch (err) {
16144
- if (err instanceof NotFoundError) {
16145
- section.rows[key] = { name: null, blind: true };
16146
- } else if (isAutotaskError(err) && err.code !== "ABORTED") {
16147
- section.rows[key] = { name: null, blind: false, error: faultRow(err) };
16148
- if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16149
- contractLobUnread = "unresolved";
16854
+ tasks.push(async () => {
16855
+ let row;
16856
+ try {
16857
+ const record = snapshot !== void 0 ? snapshot() : await holders[fk2.table].get(fk2.id);
16858
+ if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16859
+ contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
16860
+ }
16861
+ row = { name: fkName(record, fk2.table), blind: false };
16862
+ } catch (err) {
16863
+ if (err instanceof NotFoundError) {
16864
+ row = { name: null, blind: true };
16865
+ } else if (isAutotaskError(err) && err.code !== "ABORTED") {
16866
+ row = { name: null, blind: false, error: faultRow(err) };
16867
+ if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16868
+ contractLobUnread = "unresolved";
16869
+ }
16870
+ } else {
16871
+ throw err;
16150
16872
  }
16151
- } else {
16152
- throw err;
16153
16873
  }
16154
- }
16874
+ return () => {
16875
+ section.rows[key] = row;
16876
+ };
16877
+ });
16155
16878
  }
16156
16879
  const picklists = {};
16157
16880
  if (plan.labelFields.length > 0) {
16158
- try {
16159
- const labelResource = plan.labelResource ?? "tickets";
16160
- const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
16161
- const row = catalog.rows.find((r) => r.resource === labelResource);
16162
- if (row !== void 0 && row.error === null && row.fields !== void 0) {
16163
- for (const f of plan.labelFields) {
16164
- const frow = row.fields.find((x) => x.name === f);
16165
- picklists[f] = frow?.picklistValues;
16881
+ tasks.push(async () => {
16882
+ try {
16883
+ const labelResource = plan.labelResource ?? "tickets";
16884
+ const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
16885
+ const row = catalog.rows.find((r) => r.resource === labelResource);
16886
+ if (row !== void 0 && row.error === null && row.fields !== void 0) {
16887
+ for (const f of plan.labelFields) {
16888
+ const frow = row.fields.find((x) => x.name === f);
16889
+ picklists[f] = frow?.picklistValues;
16890
+ }
16166
16891
  }
16892
+ } catch (err) {
16893
+ if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16167
16894
  }
16168
- } catch (err) {
16169
- if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16170
- }
16895
+ return () => void 0;
16896
+ });
16171
16897
  }
16898
+ for (const merge of await readTasks(http, tasks)) merge();
16172
16899
  let lineOfBusiness2 = null;
16173
16900
  const lobId = plan.lineOfBusinessId ?? contractLobPointer;
16174
16901
  if (lobId !== void 0) {
@@ -16243,6 +16970,88 @@ var BOUNDED_QUERY_MAX_LIMIT = 2500;
16243
16970
  var LATEST_MAX_COUNT_PROBES = 64;
16244
16971
  var MARKER_RECOVERY_LIMIT = 5;
16245
16972
 
16973
+ // src/read-cache.ts
16974
+ var READ_FAILURE_OBSERVER = /* @__PURE__ */ Symbol("record read failure observer");
16975
+ function observeRecordReadFailures(http, observer) {
16976
+ Object.defineProperty(http, READ_FAILURE_OBSERVER, { value: observer });
16977
+ }
16978
+ function subscriberError(error, operation) {
16979
+ const copies = /* @__PURE__ */ new Map();
16980
+ const copyValue = (value) => {
16981
+ if (value === null || typeof value !== "object") return value;
16982
+ if (!(value instanceof Error) && !isRecord(value) && !Array.isArray(value)) return value;
16983
+ const prior = copies.get(value);
16984
+ if (prior !== void 0) return prior;
16985
+ const copy = value instanceof Error ? Object.setPrototypeOf(new Error(value.message), Object.getPrototypeOf(value)) : Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
16986
+ copies.set(value, copy);
16987
+ const descriptors = Object.getOwnPropertyDescriptors(value);
16988
+ if (value === error) descriptors.operation = { ...descriptors.operation, value: operation };
16989
+ for (const key of Reflect.ownKeys(descriptors)) {
16990
+ const descriptor2 = descriptors[key];
16991
+ if ("value" in descriptor2) descriptor2.value = copyValue(descriptor2.value);
16992
+ }
16993
+ Object.defineProperties(copy, descriptors);
16994
+ if (value instanceof Error && descriptors.stack?.set !== void 0) descriptors.stack.set.call(copy, value.stack);
16995
+ return copy;
16996
+ };
16997
+ return copyValue(error);
16998
+ }
16999
+ function cachedRead(http, cache, key, path, operation, request, fresh, shouldStore) {
17000
+ if (cache === void 0) return request();
17001
+ let ownsLoader = false;
17002
+ const loader = (signal) => {
17003
+ ownsLoader = true;
17004
+ return request(signal);
17005
+ };
17006
+ const options = {
17007
+ signal: ambientCallerSignal(),
17008
+ fresh,
17009
+ shouldStore,
17010
+ abortError: () => new AutotaskAbortError(`Request aborted: GET ${path}`, {
17011
+ operation,
17012
+ suggestedAction: "The caller aborted; re-issue the call if still needed."
17013
+ })
17014
+ };
17015
+ return cache.load(key, loader, options).catch((error) => {
17016
+ if (ownsLoader || !(error instanceof AutotaskError) || error.details?.budgetScope !== "client" || error.notSent !== true) throw error;
17017
+ if (options.signal?.aborted) throw options.abortError();
17018
+ const warm = cache.get(key);
17019
+ return warm !== void 0 ? warm : cache.load(key, loader, { ...options, fresh: true });
17020
+ }).catch((error) => {
17021
+ if (!(error instanceof AutotaskError)) throw error;
17022
+ const failure = subscriberError(error, operation);
17023
+ http[READ_FAILURE_OBSERVER]?.(failure);
17024
+ throw failure;
17025
+ });
17026
+ }
17027
+ function cachedRecordGet(http, path, operation, fresh = false) {
17028
+ return cachedRead(
17029
+ http,
17030
+ http.readCache,
17031
+ path,
17032
+ path,
17033
+ operation,
17034
+ (signal) => http.request({ method: "GET", path, operation, signal }),
17035
+ fresh
17036
+ );
17037
+ }
17038
+ function cachedMetadataGet(http, resource, kind, path, operation, unwrap, fresh = false, maxRetries) {
17039
+ const cache = http.fieldCache;
17040
+ const request = (signal) => {
17041
+ return http.request({ method: "GET", path, operation, signal, maxRetries }).then(unwrap).catch((error) => {
17042
+ if (error instanceof AutotaskError && (error.code === "INVALID_RESPONSE" || error.details?.deterministic === true)) {
17043
+ cache?.invalidate(`${resource}:`);
17044
+ }
17045
+ throw error;
17046
+ });
17047
+ };
17048
+ return cachedRead(http, cache, fieldKey(resource, kind), path, operation, request, fresh, (value) => {
17049
+ if (value === null || value === void 0) return false;
17050
+ if (Array.isArray(value)) return value.length > 0;
17051
+ return typeof value !== "object" || Object.keys(value).length > 0;
17052
+ });
17053
+ }
17054
+
16246
17055
  // src/field-sets.ts
16247
17056
  var MODEL_FIELD_SETS = {
16248
17057
  "appointments": ["id", "createDateTime", "creatorResourceID", "description", "endDateTime", "resourceID", "startDateTime", "title", "updateDateTime"],
@@ -16454,6 +17263,19 @@ async function boundedPart(http, path, conditions, limit, operation, includeFiel
16454
17263
  return { items, capped, hasMore: capped && pageDetails.nextPageUrl != null };
16455
17264
  }
16456
17265
 
17266
+ // src/utils/model-fields.ts
17267
+ var lookups = /* @__PURE__ */ new Map();
17268
+ function modelFieldLookup(resourceKey) {
17269
+ if (!Object.hasOwn(MODEL_FIELD_SETS, resourceKey)) return void 0;
17270
+ let lookup = lookups.get(resourceKey);
17271
+ if (lookup === void 0) {
17272
+ const names = new Set(MODEL_FIELD_SETS[resourceKey]);
17273
+ lookup = (field) => names.has(field);
17274
+ lookups.set(resourceKey, lookup);
17275
+ }
17276
+ return lookup;
17277
+ }
17278
+
16457
17279
  // src/resources/special/_shared/relation-filters.ts
16458
17280
  var JOIN_SET_CAP = 300;
16459
17281
  function capJoinSet(ids2, cap = JOIN_SET_CAP) {
@@ -16467,8 +17289,8 @@ var RELATION_TARGETS = {
16467
17289
  project: { resource: "projects", path: "/V1.0/Projects/query" }
16468
17290
  };
16469
17291
  function relationsFor(resourceKey) {
16470
- const fields = MODEL_FIELD_SETS[resourceKey] ?? [];
16471
- return Object.keys(RELATION_TARGETS).filter((rel) => fields.includes(`${rel}ID`));
17292
+ const hasField = modelFieldLookup(resourceKey);
17293
+ return Object.keys(RELATION_TARGETS).filter((rel) => hasField?.(`${rel}ID`) === true);
16472
17294
  }
16473
17295
  function selfPrefixes(resourceKey) {
16474
17296
  const rels = Object.keys(RELATION_TARGETS).filter((rel) => RELATION_TARGETS[rel].resource === resourceKey);
@@ -16513,7 +17335,7 @@ function validateRelationLeaves(resourceKey, conditions, op) {
16513
17335
  if (rest.length > 0 || !sub) fail("is not <relation>.<field> (multi-hop relations are not supported)");
16514
17336
  if (!valid.includes(rel)) fail(`names an unknown relation for ${resourceKey} (valid: ${valid.join(", ") || "none"})`);
16515
17337
  const parentFields = MODEL_FIELD_SETS[RELATION_TARGETS[rel].resource];
16516
- if (parentFields !== void 0 && !parentFields.includes(sub)) {
17338
+ if (parentFields !== void 0 && modelFieldLookup(RELATION_TARGETS[rel].resource)?.(sub) !== true) {
16517
17339
  fail(`names a field unknown on ${RELATION_TARGETS[rel].resource}`);
16518
17340
  }
16519
17341
  }
@@ -16524,36 +17346,52 @@ async function rewriteRelationFilters(http, resourceKey, conditions, op) {
16524
17346
  if (!hasRelationConditions(conditions)) return void 0;
16525
17347
  const conds = conditions;
16526
17348
  validateRelationLeaves(resourceKey, conds, op);
17349
+ const parentReads = /* @__PURE__ */ new Map();
16527
17350
  const parentIds = async (rel, leaves) => {
16528
17351
  const target = RELATION_TARGETS[rel];
16529
17352
  const parentConds = buildFilter(leaves.map((l) => ({ ...l, field: l.field.slice(rel.length + 1) }))).filter;
16530
- const res = await boundedPart(http, target.path, parentConds, JOIN_SET_CAP, op, ["id"]);
16531
- if (res.hasMore) {
16532
- throw new AutotaskConfigError(
16533
- `${op}: the ${rel}.* conditions match more than ${JOIN_SET_CAP} ${target.resource} \u2014 the ${resourceKey} query was not issued (a partial ${rel} set would give partial results)`,
16534
- { operation: op, suggestedAction: `Narrow the ${rel}.* conditions (e.g. add a ${rel} date or status condition) or filter ${resourceKey} by ${rel}ID directly.` }
16535
- );
17353
+ const key = JSON.stringify([target.path, parentConds], (_key, value) => isRecord2(value) ? Object.fromEntries(Object.keys(value).sort().map((name) => [name, value[name]])) : value);
17354
+ let pending = parentReads.get(key);
17355
+ if (pending === void 0) {
17356
+ pending = (async () => {
17357
+ const res = await boundedPart(http, target.path, parentConds, JOIN_SET_CAP, op, ["id"]);
17358
+ if (res.hasMore) {
17359
+ throw new AutotaskConfigError(
17360
+ `${op}: the ${rel}.* conditions match more than ${JOIN_SET_CAP} ${target.resource} \u2014 the ${resourceKey} query was not issued (a partial ${rel} set would give partial results)`,
17361
+ { operation: op, suggestedAction: `Narrow the ${rel}.* conditions (e.g. add a ${rel} date or status condition) or filter ${resourceKey} by ${rel}ID directly.` }
17362
+ );
17363
+ }
17364
+ return capJoinSet(res.items.map((r) => Number(r.id)).filter((n) => Number.isFinite(n) && n > 0)).ids;
17365
+ })();
17366
+ parentReads.set(key, pending);
16536
17367
  }
16537
- return capJoinSet(res.items.map((r) => Number(r.id)).filter((n) => Number.isFinite(n) && n > 0)).ids;
17368
+ return [...await pending];
16538
17369
  };
16539
17370
  const NEVER = null;
17371
+ const rewriteLeaf = async (c) => {
17372
+ const [rel, field] = c.field.split(".");
17373
+ if (selfPrefixes(resourceKey).includes(rel)) return { ...c, field };
17374
+ const ids2 = await parentIds(rel, [c]);
17375
+ return ids2.length === 0 ? void 0 : { field: `${rel}ID`, op: "in", value: ids2 };
17376
+ };
16540
17377
  const rewrite = async (list, mode) => {
17378
+ if (mode === "or" && !list.some((c) => Array.isArray(c.items) && hasRelationConditions(c.items))) {
17379
+ const parts = await mapReadTasks(http, list, (c) => isRelationLeaf(c) ? rewriteLeaf(c) : Promise.resolve(c));
17380
+ const out2 = parts.filter((c) => c !== void 0);
17381
+ return out2.length === 0 ? NEVER : out2;
17382
+ }
16541
17383
  const out = [];
16542
17384
  const byRel = /* @__PURE__ */ new Map();
16543
17385
  for (const c of list) {
16544
17386
  if (isRelationLeaf(c)) {
16545
17387
  const parts = c.field.split(".");
16546
- if (parts.length === 2 && selfPrefixes(resourceKey).includes(parts[0])) {
16547
- out.push({ ...c, field: parts[1] });
17388
+ if (mode === "or" || parts.length === 2 && selfPrefixes(resourceKey).includes(parts[0])) {
17389
+ const leaf = await rewriteLeaf(c);
17390
+ if (leaf !== void 0) out.push(leaf);
16548
17391
  continue;
16549
17392
  }
16550
17393
  const rel = parts[0];
16551
- if (mode === "and") {
16552
- byRel.set(rel, [...byRel.get(rel) ?? [], c]);
16553
- continue;
16554
- }
16555
- const ids2 = await parentIds(rel, [c]);
16556
- if (ids2.length > 0) out.push({ field: `${rel}ID`, op: "in", value: ids2 });
17394
+ byRel.set(rel, [...byRel.get(rel) ?? [], c]);
16557
17395
  continue;
16558
17396
  }
16559
17397
  if (isRecord2(c) && (c.op === "and" || c.op === "or") && Array.isArray(c.items) && hasRelationConditions(c.items)) {
@@ -16590,6 +17428,17 @@ var ROW_FK_TABLES = {
16590
17428
  billingCodeID: "billingCode"
16591
17429
  };
16592
17430
  var isResourceFkField = (field) => field === "resourceID" || field.endsWith("ResourceID");
17431
+ function rowNamePlan(rows, resourceKey, picklistFields = []) {
17432
+ const builder = createNamePlan(picklistFields, resourceKey);
17433
+ for (const row of rows) {
17434
+ for (const [field, value] of Object.entries(row)) {
17435
+ const table = ROW_FK_TABLES[field];
17436
+ if (table !== void 0) builder.addFk(table, value);
17437
+ else if (isResourceFkField(field)) builder.addResource(value);
17438
+ }
17439
+ }
17440
+ return builder.plan();
17441
+ }
16593
17442
  var LABEL_NAME_MAX_CHARS = 200;
16594
17443
  function untrustedName(name) {
16595
17444
  if (name === null) return null;
@@ -16608,8 +17457,8 @@ async function labelRows(client, resourceKey, rows) {
16608
17457
  for (const row of rows) for (const k of Object.keys(row)) keys.add(k);
16609
17458
  if (keys.size === 0) return { rows: [...rows] };
16610
17459
  let picklistFields = [];
16611
- const modelFields = MODEL_FIELD_SETS[resourceKey] ?? [];
16612
- const candidates = [...keys].filter((f) => f !== "id" && modelFields.includes(f) && ROW_FK_TABLES[f] === void 0 && !isResourceFkField(f));
17460
+ const modelHas = modelFieldLookup(resourceKey);
17461
+ const candidates = [...keys].filter((f) => f !== "id" && modelHas?.(f) === true && ROW_FK_TABLES[f] === void 0 && !isResourceFkField(f));
16613
17462
  if (candidates.length > 0) {
16614
17463
  try {
16615
17464
  const catalog = await fieldCatalog(client, { resources: [resourceKey], labels: true });
@@ -16623,16 +17472,7 @@ async function labelRows(client, resourceKey, rows) {
16623
17472
  }
16624
17473
  const labelled = (field) => picklistFields.includes(field) || ROW_FK_TABLES[field] !== void 0 || isResourceFkField(field);
16625
17474
  if (![...keys].some(labelled)) return { rows: [...rows] };
16626
- const builder = createNamePlan(picklistFields, resourceKey);
16627
- for (const row of rows) {
16628
- for (const [field, value] of Object.entries(row)) {
16629
- const table = ROW_FK_TABLES[field];
16630
- if ((value === 0 || value === "0") && table !== "company") continue;
16631
- if (table !== void 0) builder.addFk(table, value);
16632
- else if (isResourceFkField(field)) builder.addResource(value);
16633
- }
16634
- }
16635
- const plan = builder.plan();
17475
+ const plan = rowNamePlan(rows, resourceKey, picklistFields);
16636
17476
  const names = plan.resourceIds.length === 0 && plan.recordFks.length === 0 && picklistFields.length === 0 ? void 0 : await resolveCompositeNames(client.http, plan);
16637
17477
  const out = rows.map((row) => {
16638
17478
  const r = { ...row };
@@ -16655,21 +17495,39 @@ async function labelRows(client, resourceKey, rows) {
16655
17495
  return { rows: out, names: { note: parts.join("; "), ...Object.keys(names.section.reasons).length > 0 ? { reasons: names.section.reasons } : {} } };
16656
17496
  }
16657
17497
  async function labelFetchResults(client, result) {
16658
- const byResource = /* @__PURE__ */ new Map();
17498
+ const byResource2 = /* @__PURE__ */ new Map();
16659
17499
  result.results.forEach((r, i) => {
16660
- if (r.found && r.value !== null) byResource.set(r.resource, [...byResource.get(r.resource) ?? [], i]);
17500
+ if (r.found && r.value !== null) byResource2.set(r.resource, [...byResource2.get(r.resource) ?? [], i]);
16661
17501
  });
16662
17502
  const results = [...result.results];
17503
+ const groups = [...byResource2].map(([resource, indices]) => ({ resource, indices, rows: indices.map((i) => results[i].value) }));
17504
+ const seen = /* @__PURE__ */ new Set();
17505
+ let dependent = false;
17506
+ for (const group of groups) {
17507
+ const plan = rowNamePlan(group.rows, group.resource);
17508
+ const targets = [...plan.resourceIds.map((id) => `resource:${String(id)}`), ...plan.recordFks.map((fk2) => `${fk2.table}:${String(fk2.id)}`)];
17509
+ for (const target of targets) {
17510
+ if (seen.has(target)) dependent = true;
17511
+ seen.add(target);
17512
+ }
17513
+ }
17514
+ const labelledGroups = /* @__PURE__ */ new Map();
17515
+ const labelled = await mapReadTasks(
17516
+ dependent ? { maxConcurrent: 1 } : client.http,
17517
+ groups,
17518
+ async (group) => ({ resource: group.resource, result: await labelRows(client, group.resource, group.rows) })
17519
+ );
17520
+ for (const group of labelled) labelledGroups.set(group.resource, group.result);
16663
17521
  const notes = [];
16664
17522
  const reasons = {};
16665
- for (const [resource, indices] of byResource) {
16666
- const labelled = await labelRows(client, resource, indices.map((i) => results[i].value));
17523
+ for (const [resource, indices] of byResource2) {
17524
+ const labelled2 = labelledGroups.get(resource);
16667
17525
  indices.forEach((idx, j) => {
16668
- results[idx] = { ...results[idx], value: labelled.rows[j] };
17526
+ results[idx] = { ...results[idx], value: labelled2.rows[j] };
16669
17527
  });
16670
- if (labelled.names !== void 0) {
16671
- notes.push(labelled.names.note);
16672
- for (const [field, why] of Object.entries(labelled.names.reasons ?? {})) reasons[field] = why;
17528
+ if (labelled2.names !== void 0) {
17529
+ notes.push(labelled2.names.note);
17530
+ for (const [field, why] of Object.entries(labelled2.names.reasons ?? {})) reasons[field] = why;
16673
17531
  }
16674
17532
  }
16675
17533
  if (notes.length === 0) return { ...result, results };
@@ -16732,7 +17590,7 @@ var QueryBase = class {
16732
17590
  // Query walk (wired to the G3 walker; cursor-follow per the pinned wire)
16733
17591
  // ------------------------------------------------------------------
16734
17592
  /** One page fetch: page 1 POSTs the QueryModel body; later pages POST the same body (`buildQueryBody`) to the absolute cursor (issue #118). */
16735
- async fetchPage(params, page, pageSize, state) {
17593
+ async fetchPage(params, page, pageSize, state2) {
16736
17594
  if (params.includeFields !== void 0) {
16737
17595
  params = { ...params, includeFields: params.includeFields.map((field) => normalizeOwnField(this.config.key, field)) };
16738
17596
  }
@@ -16740,9 +17598,9 @@ var QueryBase = class {
16740
17598
  if (page === 1) {
16741
17599
  const req = buildQueryRequest(this.http.baseUrl, this.resourcePath, { ...params, maxRecords: pageSize });
16742
17600
  const body2 = await this.http.request({ ...req, operation });
16743
- return this.readPage(body2, page, pageSize, state);
17601
+ return this.readPage(body2, page, pageSize, state2);
16744
17602
  }
16745
- const cursor = state.cursor;
17603
+ const cursor = state2.cursor;
16746
17604
  if (cursor === null) {
16747
17605
  throw new AutotaskError(`No pagination cursor available for page ${page} of ${operation}`, {
16748
17606
  code: "INVALID_RESPONSE",
@@ -16758,13 +17616,13 @@ var QueryBase = class {
16758
17616
  operation,
16759
17617
  idempotent: true
16760
17618
  });
16761
- return this.readPage(res, page, pageSize, state);
17619
+ return this.readPage(res, page, pageSize, state2);
16762
17620
  }
16763
17621
  /** @internal */
16764
- readPage(body, page, pageSize, state) {
17622
+ readPage(body, page, pageSize, state2) {
16765
17623
  const { items, pageDetails } = unwrapItems(body, `${this.config.key}.query`);
16766
- state.cursor = pageDetails.nextPageUrl ?? null;
16767
- const hasMore = state.cursor !== null;
17624
+ state2.cursor = pageDetails.nextPageUrl ?? null;
17625
+ const hasMore = state2.cursor !== null;
16768
17626
  return {
16769
17627
  items,
16770
17628
  page,
@@ -16778,9 +17636,9 @@ var QueryBase = class {
16778
17636
  }
16779
17637
  /** Build the per-walk fetcher (closure keeps cursor state private to this walk). */
16780
17638
  pageFetcher(params) {
16781
- const state = { cursor: null };
17639
+ const state2 = { cursor: null };
16782
17640
  const p = params ?? {};
16783
- return (page, pageSize) => this.fetchPage(p, page, pageSize, state);
17641
+ return (page, pageSize) => this.fetchPage(p, page, pageSize, state2);
16784
17642
  }
16785
17643
  /** @internal */
16786
17644
  walkPageSize(params) {
@@ -16945,7 +17803,7 @@ var QueryBase = class {
16945
17803
  * state).
16946
17804
  * @internal */
16947
17805
  async walkBounded(p, limit, pageSizeBase, labelPages = false) {
16948
- const state = { cursor: null };
17806
+ const state2 = { cursor: null };
16949
17807
  const items = [];
16950
17808
  let pages2 = 0;
16951
17809
  let sliced = 0;
@@ -16958,7 +17816,7 @@ var QueryBase = class {
16958
17816
  guard = true;
16959
17817
  break;
16960
17818
  }
16961
- const page = await this.fetchPage(p, pages2 + 1, pageSize, state);
17819
+ const page = await this.fetchPage(p, pages2 + 1, pageSize, state2);
16962
17820
  pages2 += 1;
16963
17821
  if (labelPages && this.http.client !== void 0) {
16964
17822
  const labelled = await labelRows(this.http.client, this.config.key, page.items);
@@ -16979,7 +17837,7 @@ var QueryBase = class {
16979
17837
  note: [...nameNotes].join("; "),
16980
17838
  ...Object.keys(nameReasons).length === 0 ? {} : { reasons: nameReasons }
16981
17839
  };
16982
- return { items, pages: pages2, guard, sliced, cursor: state.cursor, ...names === void 0 ? {} : { names } };
17840
+ return { items, pages: pages2, guard, sliced, cursor: state2.cursor, ...names === void 0 ? {} : { names } };
16983
17841
  }
16984
17842
  /** A walk stop is TRUNCATED when the 1000-page guard fired, or the limit
16985
17843
  * was met with a live next cursor (or a sliced final page): rows exist
@@ -17252,21 +18110,15 @@ var MetaBase = class extends QueryBase {
17252
18110
  * and the composite ROOT read of a hot resource (issue #36 — the
17253
18111
  * ticket-composite root) must see the live record, never a snapshot.
17254
18112
  * The entry's TTL follows the path (`readTtlFor`: reference tables 1 h).
18113
+ * Equivalent non-fresh misses share one request through the cache loader;
18114
+ * the ambient signal belongs to this subscriber, never to the shared wire.
17255
18115
  * @internal */
17256
18116
  async cachedGet(path, operation, fresh = false) {
17257
- const cache = this.http.readCache;
17258
- if (cache !== void 0 && !fresh) {
17259
- const hit = cache.get(path);
17260
- if (hit !== void 0) return hit;
17261
- }
17262
- const epoch = cache?.epoch;
17263
- const res = await this.http.request({ method: "GET", path, operation });
17264
- cache?.set(path, res, epoch);
17265
- return res;
18117
+ return cachedRecordGet(this.http, path, operation, fresh);
17266
18118
  }
17267
18119
  /**
17268
- * Entity-metadata read through the opt-in field cache (issue #31; off by
17269
- * default: with no fieldCache this is exactly one `http.request` — the
18120
+ * Entity-metadata read through the default-on field cache (issue #31;
18121
+ * with no fieldCache this is exactly one `http.request` — the
17270
18122
  * bit-for-bit uncached trio path). One private helper beside `cachedGet`,
17271
18123
  * for the same three reasons the read cache exists: a vendor drift
17272
18124
  * (deterministic 500, INVALID_RESPONSE) must not be served stale, repeat
@@ -17274,7 +18126,9 @@ var MetaBase = class extends QueryBase {
17274
18126
  * duplicate requests. The UNWRAPPED value is stored (never the raw
17275
18127
  * envelope); an EMPTY or FAILED result is never cached (a failure
17276
18128
  * rejects before any `set`; an empty is refused by the cache itself);
17277
- * concurrent callers share ONE in-flight wire request; the drift signal
18129
+ * concurrent callers share one wire with independent cancellation and cloned
18130
+ * values; invalidation detaches older reads before they can repopulate
18131
+ * the cache. The drift signal
17278
18132
  * (the INVALID_RESPONSE shape drift, the deterministic validation 500)
17279
18133
  * invalidates THIS entity's entries so the next call refetches
17280
18134
  * (transport-level signals are also invalidated in the transport's own
@@ -17283,29 +18137,7 @@ var MetaBase = class extends QueryBase {
17283
18137
  * @internal
17284
18138
  */
17285
18139
  async cachedMeta(kind, path, operation, unwrap, fresh = false) {
17286
- const cache = this.http.fieldCache;
17287
- if (cache === void 0) {
17288
- const res = await this.http.request({ method: "GET", path, operation });
17289
- return unwrap(res);
17290
- }
17291
- const key = fieldKey(this.config.key, kind);
17292
- if (!fresh) {
17293
- const shared = cache.inflight(key);
17294
- if (shared !== void 0) return shared;
17295
- const hit = cache.get(key);
17296
- if (hit !== void 0) return hit;
17297
- }
17298
- const work = this.http.request({ method: "GET", path, operation }).then((body) => {
17299
- const value = unwrap(body);
17300
- if (!isEmpty(value)) cache.set(key, value);
17301
- return value;
17302
- });
17303
- work.catch((err) => {
17304
- if (err instanceof AutotaskError && (err.code === "INVALID_RESPONSE" || err.details?.deterministic === true)) {
17305
- cache.invalidate(`${this.config.key}:`);
17306
- }
17307
- });
17308
- return cache.track(key, work);
18140
+ return cachedMetadataGet(this.http, this.config.key, kind, path, operation, unwrap, fresh);
17309
18141
  }
17310
18142
  /** `GET /V1.0/<E>/{id}` → `{ item }` unwrapped (`item: null` → NotFoundError). */
17311
18143
  async getGlobal(id, fresh = false) {
@@ -17611,8 +18443,8 @@ var MetaBase = class extends QueryBase {
17611
18443
  );
17612
18444
  }
17613
18445
  const leaf = fields.map((field) => ({ field, op: "eq", value }));
17614
- const root = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
17615
- const items = await this.queryPage1([root], 2);
18446
+ const root3 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18447
+ const items = await this.queryPage1([root3], 2);
17616
18448
  if (items.length === 1) {
17617
18449
  return { value: items[0], resolutionCost: "server-filter", scanned: 0, scanTruncated: false };
17618
18450
  }
@@ -17718,13 +18550,13 @@ var MetaBase = class extends QueryBase {
17718
18550
  async scanForExactMatch(value, fields) {
17719
18551
  const caps = this.resolutionCaps;
17720
18552
  const pageSize = Math.max(1, Math.floor(caps.maxScanRecords / caps.maxScanPages));
17721
- const state = { cursor: null };
18553
+ const state2 = { cursor: null };
17722
18554
  let scanned = 0;
17723
18555
  let pages2 = 0;
17724
18556
  let found = null;
17725
18557
  let exhausted = false;
17726
18558
  for (; ; ) {
17727
- const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state);
18559
+ const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state2);
17728
18560
  pages2 += 1;
17729
18561
  for (const item of page.items) {
17730
18562
  scanned += 1;
@@ -17779,7 +18611,7 @@ var MetaBase = class extends QueryBase {
17779
18611
  }
17780
18612
  const limit = opts.limit === void 0 ? 25 : clampPageSize(opts.limit);
17781
18613
  const leaf = fields.map((field) => ({ field, op: "contains", value: text }));
17782
- const root = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18614
+ const root3 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
17783
18615
  for (const key of Object.keys(opts)) {
17784
18616
  if (key !== "limit" && key !== "companyID" && key !== "includeFields") {
17785
18617
  throw new AutotaskConfigError(`search: unknown opts key "${key}" \u2014 the bag is closed: limit, companyID, includeFields`);
@@ -17793,7 +18625,7 @@ var MetaBase = class extends QueryBase {
17793
18625
  }
17794
18626
  const companyID = opts.companyID === void 0 ? void 0 : Number(opts.companyID);
17795
18627
  const includeFields = opts.includeFields === void 0 ? void 0 : opts.includeFields.includes("id") ? opts.includeFields : ["id", ...opts.includeFields];
17796
- const conditions = companyID === void 0 ? [root] : [{ field: "companyID", op: "eq", value: companyID }, root];
18628
+ const conditions = companyID === void 0 ? [root3] : [{ field: "companyID", op: "eq", value: companyID }, root3];
17797
18629
  const rows = await this.queryEntity(`${this.resourcePath}/query`, conditions, {
17798
18630
  maxRecords: limit,
17799
18631
  ...includeFields !== void 0 ? { includeFields } : {}
@@ -17824,11 +18656,6 @@ var MetaBase = class extends QueryBase {
17824
18656
  return this.searchBase(value, { limit });
17825
18657
  }
17826
18658
  };
17827
- function isEmpty(value) {
17828
- if (value === null || value === void 0) return true;
17829
- if (Array.isArray(value)) return value.length === 0;
17830
- return typeof value === "object" && Object.keys(value).length === 0;
17831
- }
17832
18659
 
17833
18660
  // src/resources/base/mutations.ts
17834
18661
  var MutationBase = class extends MetaBase {
@@ -20066,20 +20893,20 @@ var GenericResource = class extends BaseResource {
20066
20893
  this.requireHelper("getContext");
20067
20894
  const cfg = this.config;
20068
20895
  const rootField = cfg.contextRootField ?? this.config.key;
20069
- const root = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20070
- const result = { [rootField]: root };
20071
- for (const [name, idField, targetPath] of cfg.contextParts ?? []) {
20072
- result[name] = await this.contextFetch(targetPath, root[idField]);
20073
- }
20896
+ const root3 = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20897
+ const result = { [rootField]: root3 };
20898
+ const parts = cfg.contextParts ?? [];
20899
+ const values = await mapReadTasks(this.http, parts, ([, idField, targetPath]) => this.contextFetch(targetPath, root3[idField]));
20900
+ for (const [i, [name]] of parts.entries()) result[name] = values[i];
20074
20901
  if (opts.names === true) {
20075
20902
  const builder = createNamePlan();
20076
20903
  for (const sib of cfg.nameSiblings ?? []) {
20077
- const fk2 = root[sib.field];
20904
+ const fk2 = root3[sib.field];
20078
20905
  if (sib.kind === "resource") builder.addResource(fk2);
20079
20906
  else builder.addFk(sib.kind, fk2);
20080
20907
  }
20081
20908
  const names = await resolveCompositeNames(this.http, builder.plan(), { maxNameReads: opts.maxNameReads });
20082
- const row = { ...root };
20909
+ const row = { ...root3 };
20083
20910
  for (const sib of cfg.nameSiblings ?? []) {
20084
20911
  addNameSibling(row, sib.field, (v) => sib.kind === "resource" ? names.resourceName(v) : names.recordName(sib.kind, v));
20085
20912
  }
@@ -20248,9 +21075,9 @@ async function searchFuzzy(resource, query, opts = {}) {
20248
21075
  if (!opts.includeInactive) filter.push({ field: "isActive", op: "eq", value: true });
20249
21076
  const index = companyIndex(resource.http);
20250
21077
  index?.ensure();
20251
- const state = index?.state() ?? { state: "off" };
21078
+ const state2 = index?.state() ?? { state: "off" };
20252
21079
  const revision = index?.revision();
20253
- const indexed = state.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
21080
+ const indexed = state2.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
20254
21081
  const res = await resource.http.request({
20255
21082
  method: "POST",
20256
21083
  idempotent: true,
@@ -20269,7 +21096,7 @@ async function searchFuzzy(resource, query, opts = {}) {
20269
21096
  const records = await addCompanyFamilies(resource.http, items.map((row) => row.record), "companies.searchFuzzy");
20270
21097
  for (let i = 0; i < items.length; i++) items[i].record = records[i];
20271
21098
  }
20272
- return { items, tier: state.state === "warm" && validIndex ? "index+live" : "live", truncated: live.length >= 500 || ranked.length > limit, pieces, index: validIndex ? state : index.state() };
21099
+ return { items, tier: state2.state === "warm" && validIndex ? "index+live" : "live", truncated: live.length >= 500 || ranked.length > limit, pieces, index: validIndex ? state2 : index.state() };
20273
21100
  }
20274
21101
 
20275
21102
  // src/operations/invoke/fieldNames.ts
@@ -20359,12 +21186,14 @@ function readIncludeNames(record, includeFields) {
20359
21186
  return names;
20360
21187
  }
20361
21188
  function resolveAuthority(record, live) {
20362
- if (live !== null) return { known: live, authority: "the tenant's live entity field metadata" };
21189
+ if (live !== null) return { known: live, authority: "the tenant's live entity field metadata", hasField: (name) => live.includes(name) };
20363
21190
  const vendored = MODEL_FIELD_SETS[record.resource];
21191
+ const modelHas = modelFieldLookup(record.resource);
20364
21192
  const liveOnlyExempt = Array.isArray(record.metadata?.liveOnlyFields) ? record.metadata.liveOnlyFields : [];
20365
- if (vendored === void 0) return void 0;
21193
+ if (vendored === void 0 || modelHas === void 0) return void 0;
20366
21194
  return {
20367
21195
  known: [...vendored, ...liveOnlyExempt],
21196
+ hasField: (name) => modelHas(name) || liveOnlyExempt.includes(name),
20368
21197
  authority: liveOnlyExempt.length > 0 ? "the vendored spec (src/field-sets.ts) + the plan-pinned live-only fields (exempt from the vendored refusal)" : "the vendored spec (src/field-sets.ts)"
20369
21198
  };
20370
21199
  }
@@ -20414,8 +21243,8 @@ async function findUnknownFieldNames(record, holder, lists) {
20414
21243
  const resolved = resolveAuthority(record, await liveFieldNames(holder));
20415
21244
  if (resolved === void 0) return void 0;
20416
21245
  const unknown = {};
20417
- for (const [key, names] of Object.entries(lists)) unknown[key] = [...new Set(names.filter((name) => !resolved.known.includes(name)))];
20418
- return { ...resolved, unknown };
21246
+ for (const [key, names] of Object.entries(lists)) unknown[key] = [...new Set(names.filter((name) => !resolved.hasField(name)))];
21247
+ return { known: resolved.known, authority: resolved.authority, unknown };
20419
21248
  }
20420
21249
 
20421
21250
  // src/resources/special/_shared/ticketStatus.ts
@@ -20435,21 +21264,13 @@ function picklistOf(fields) {
20435
21264
  return out;
20436
21265
  }
20437
21266
  async function readFields(http, fresh) {
20438
- const cache = http.fieldCache;
20439
- const key = fieldKey("tickets", "fields");
20440
- if (!fresh && cache !== void 0) {
20441
- const shared = cache.inflight(key);
20442
- if (shared !== void 0) return await shared;
20443
- const hit = cache.get(key);
20444
- if (hit !== void 0) return hit;
20445
- }
20446
- const res = await http.request({ method: "GET", path: "/V1.0/Tickets/entityInformation/fields", operation: OP, maxRetries: 0 });
20447
- const fields = res?.fields;
20448
- if (!Array.isArray(fields)) {
20449
- throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
20450
- }
20451
- if (fields.length > 0) cache?.set(key, fields);
20452
- return fields;
21267
+ return cachedMetadataGet(http, "tickets", "fields", "/V1.0/Tickets/entityInformation/fields", OP, (res) => {
21268
+ const fields = res?.fields;
21269
+ if (!Array.isArray(fields)) {
21270
+ throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
21271
+ }
21272
+ return fields;
21273
+ }, fresh, 0);
20453
21274
  }
20454
21275
  function assumed(allowAssumed, operation) {
20455
21276
  if (!allowAssumed) {
@@ -20539,7 +21360,8 @@ function validateProjection(fields) {
20539
21360
  const names = [...new Set(list)];
20540
21361
  const entity = PART_ENTITY[part];
20541
21362
  const known = MODEL_FIELD_SETS[entity] ?? [];
20542
- const unknown = names.filter((n) => !known.includes(n));
21363
+ const hasField = modelFieldLookup(entity);
21364
+ const unknown = names.filter((n) => hasField?.(n) !== true);
20543
21365
  if (unknown.length > 0) {
20544
21366
  throw new AutotaskConfigError(
20545
21367
  `fullProfile: fields.${part} has unknown field name(s) ${formatUnknownNameList(unknown)} against the vendored spec for ${entity} (${known.length} fields; operations.fieldCatalog resources: ["${entity}"] lists the live set) \u2014 no request was issued`
@@ -20671,14 +21493,16 @@ async function fullProfile(resource, id, opts = {}) {
20671
21493
  const proj = validateProjection(opts.fields);
20672
21494
  const companyID = parseIdentifier(id, "id");
20673
21495
  const company = await resource.get(companyID);
20674
- const locations = await scopedCompanyQuery(http, "/V1.0/CompanyLocations/query", companyID, locLimit, proj.locations);
20675
- const contacts = await scopedCompanyQuery(http, "/V1.0/Contacts/query", companyID, contactLimit, proj.contacts);
20676
- const notes = await scopedCompanyQuery(http, "/V1.0/CompanyNotes/query", companyID, noteLimit, proj.notes);
20677
- const projects = await scopedCompanyQuery(http, "/V1.0/Projects/query", companyID, projectLimit, proj.projects);
20678
- const openTickets = await readOpenTickets(http, companyID, ticketLimit, proj.openTickets, {
20679
- ...opts.excludeStatusIds === void 0 ? {} : { excludeStatusIds: opts.excludeStatusIds },
20680
- ...opts.allowAssumed === void 0 ? {} : { allowAssumed: opts.allowAssumed }
20681
- });
21496
+ const [locations, contacts, notes, projects, openTickets] = await readTasks(http, [
21497
+ () => scopedCompanyQuery(http, "/V1.0/CompanyLocations/query", companyID, locLimit, proj.locations),
21498
+ () => scopedCompanyQuery(http, "/V1.0/Contacts/query", companyID, contactLimit, proj.contacts),
21499
+ () => scopedCompanyQuery(http, "/V1.0/CompanyNotes/query", companyID, noteLimit, proj.notes),
21500
+ () => scopedCompanyQuery(http, "/V1.0/Projects/query", companyID, projectLimit, proj.projects),
21501
+ () => readOpenTickets(http, companyID, ticketLimit, proj.openTickets, {
21502
+ ...opts.excludeStatusIds === void 0 ? {} : { excludeStatusIds: opts.excludeStatusIds },
21503
+ ...opts.allowAssumed === void 0 ? {} : { allowAssumed: opts.allowAssumed }
21504
+ })
21505
+ ]);
20682
21506
  const result = {
20683
21507
  company,
20684
21508
  locations: { items: locations, capped: locations.length >= locLimit },
@@ -20808,7 +21632,7 @@ async function prepareCrmWrite(resource, input) {
20808
21632
  if (input.intent === "create_company" && status !== "matched") {
20809
21633
  const eff = effectiveRequiredFields(null, RELATIONSHIP_MAP.companies?.zoneFacts);
20810
21634
  const research = (f) => ["companyType", "ownerResourceID", "countryID"].includes(f) ? "lookup" : "web_if_available_else_ask";
20811
- const lookups = {
21635
+ const lookups2 = {
20812
21636
  companyType: { via: "operations.fieldCatalog", resource: "companies", field: "companyType", labels: true, note: "map the user wording to one returned label; never hardcode ids" },
20813
21637
  ownerResourceID: { via: "resources.get / the staff resolver", note: "owners cannot be enumerated on a blind surface: take a known resource id and confirm it with resources.get" },
20814
21638
  countryID: { via: "countries.query", note: "resolve the country name to an id; never guess" }
@@ -20819,7 +21643,7 @@ async function prepareCrmWrite(resource, input) {
20819
21643
  ];
20820
21644
  for (const [f, source] of wanted) {
20821
21645
  if (has(co[f]) || needsInput.some((n) => n.field === f)) continue;
20822
- needsInput.push({ field: f, why: source === "policy" ? `CRM policy: a new company needs ${f} (the vendor auto-creates a "Primary Address" location from it)` : `the vendor requires ${f} to create a company`, source, ...lookups[f] ? { lookup: lookups[f] } : {}, research: research(f) });
21646
+ needsInput.push({ field: f, why: source === "policy" ? `CRM policy: a new company needs ${f} (the vendor auto-creates a "Primary Address" location from it)` : `the vendor requires ${f} to create a company`, source, ...lookups2[f] ? { lookup: lookups2[f] } : {}, research: research(f) });
20823
21647
  }
20824
21648
  }
20825
21649
  if (input.intent === "add_contact") {
@@ -20938,11 +21762,7 @@ async function fetchCompanies(http, ids2, limit) {
20938
21762
  const out = [];
20939
21763
  for (const id of ids2.slice(0, limit)) {
20940
21764
  try {
20941
- const res = await http.request({
20942
- method: "GET",
20943
- path: `/V1.0/Companies/${id}`,
20944
- operation: "companies.searchByDomain"
20945
- });
21765
+ const res = await cachedRecordGet(http, `/V1.0/Companies/${id}`, "companies.searchByDomain");
20946
21766
  const body = res;
20947
21767
  const item = body && "item" in body ? body.item : null;
20948
21768
  if (item) out.push(item);
@@ -21378,9 +22198,11 @@ var CompaniesResource = class extends GenericResource {
21378
22198
  * fetch; no sub-lists; absent/dangling references come back null). */
21379
22199
  async getContext(id) {
21380
22200
  const company = await this.fetchRecordRaw("/V1.0/Companies", id);
21381
- const root = company;
21382
- const ownerResource = await this.contextFetch("/V1.0/Resources", root["ownerResourceID"]);
21383
- const parentCompany = await this.contextFetch("/V1.0/Companies", root["parentCompanyID"]);
22201
+ const root3 = company;
22202
+ const [ownerResource, parentCompany] = await readTasks(this.http, [
22203
+ () => this.contextFetch("/V1.0/Resources", root3["ownerResourceID"]),
22204
+ () => this.contextFetch("/V1.0/Companies", root3["parentCompanyID"])
22205
+ ]);
21384
22206
  return { company, ownerResource, parentCompany };
21385
22207
  }
21386
22208
  /** Node-parity special op (hand-written in src/resources/special/companies/search.ts). */
@@ -21647,6 +22469,14 @@ var DEFAULT_LIMIT2 = 25;
21647
22469
  function resourceFor(client, key) {
21648
22470
  return client[camelKey(key)];
21649
22471
  }
22472
+ function searchable(client, key) {
22473
+ const holder = resourceFor(client, key);
22474
+ return holder !== void 0 && typeof holder.search === "function" && (typeof holder.hasSearch !== "function" || holder.hasSearch()) ? holder : void 0;
22475
+ }
22476
+ async function searchRows(holder, text, limit) {
22477
+ const matches = await holder.search(text, { limit });
22478
+ return Array.isArray(matches) ? matches.filter((m) => typeof m === "object" && m !== null) : [];
22479
+ }
21650
22480
  async function searchAcrossResources(client, query, opts = {}) {
21651
22481
  const text = query.trim();
21652
22482
  if (text === "") {
@@ -21663,12 +22493,23 @@ async function searchAcrossResources(client, query, opts = {}) {
21663
22493
  }
21664
22494
  const results = [];
21665
22495
  const skipped = [];
22496
+ if (totalLimit === void 0) {
22497
+ const completed = await mapReadTasks(client.http, keys, async (key) => {
22498
+ const holder = searchable(client, key);
22499
+ return holder === void 0 ? void 0 : { resource: key, matches: await searchRows(holder, text, limit) };
22500
+ });
22501
+ completed.forEach((row, i) => {
22502
+ if (row === void 0) skipped.push(keys[i]);
22503
+ else results.push(row);
22504
+ });
22505
+ return { query: text, results, skipped };
22506
+ }
21666
22507
  const notSearched = [];
21667
- let remaining = totalLimit ?? Infinity;
22508
+ let remaining = totalLimit;
21668
22509
  let hitQuota = false;
21669
22510
  for (const key of keys) {
21670
- const holder = resourceFor(client, key);
21671
- if (holder === void 0 || typeof holder.search !== "function" || typeof holder.hasSearch === "function" && !holder.hasSearch()) {
22511
+ const holder = searchable(client, key);
22512
+ if (holder === void 0) {
21672
22513
  skipped.push(key);
21673
22514
  continue;
21674
22515
  }
@@ -21677,14 +22518,12 @@ async function searchAcrossResources(client, query, opts = {}) {
21677
22518
  continue;
21678
22519
  }
21679
22520
  const ask = Math.min(limit, remaining);
21680
- const matches = await holder.search(text, { limit: ask });
21681
- const rows = Array.isArray(matches) ? matches.filter((m) => typeof m === "object" && m !== null).map((m) => m) : [];
21682
- if (totalLimit !== void 0) rows.length = Math.min(rows.length, ask);
22521
+ const rows = await searchRows(holder, text, ask);
22522
+ rows.length = Math.min(rows.length, ask);
21683
22523
  results.push({ resource: key, matches: rows });
21684
22524
  remaining -= rows.length;
21685
22525
  if (rows.length === ask) hitQuota = true;
21686
22526
  }
21687
- if (totalLimit === void 0) return { query: text, results, skipped };
21688
22527
  return { query: text, results, skipped, notSearched, truncated: notSearched.length > 0 || hitQuota };
21689
22528
  }
21690
22529
 
@@ -21716,11 +22555,10 @@ async function resolveAny(client, identifier, opts = {}) {
21716
22555
  }
21717
22556
  const configuredCap = Math.min(client.config?.resolution?.maxScanRecords ?? 500, 500);
21718
22557
  const limit = Math.min(opts.limit ?? configuredCap, configuredCap);
21719
- const results = [];
21720
- for (const key of keys) {
22558
+ const results = await mapReadTasks(client.http, keys, async (key) => {
21721
22559
  const holder = resourceFor2(client, key);
21722
22560
  if (holder === void 0 || typeof holder.resolveDetailed !== "function") {
21723
- results.push({
22561
+ return {
21724
22562
  resource: key,
21725
22563
  value: null,
21726
22564
  resolutionCost: missCost(identifier),
@@ -21728,8 +22566,7 @@ async function resolveAny(client, identifier, opts = {}) {
21728
22566
  scanTruncated: false,
21729
22567
  candidates: [],
21730
22568
  error: "NO_RESOLVE"
21731
- });
21732
- continue;
22569
+ };
21733
22570
  }
21734
22571
  try {
21735
22572
  const r = await holder.resolveDetailed(identifier);
@@ -21741,7 +22578,7 @@ async function resolveAny(client, identifier, opts = {}) {
21741
22578
  scanTruncated: r.scanTruncated,
21742
22579
  candidates: (r.candidates ?? []).map((c) => c.id)
21743
22580
  };
21744
- results.push(outcome);
22581
+ return outcome;
21745
22582
  } catch (err) {
21746
22583
  let code;
21747
22584
  let candidates = [];
@@ -21756,7 +22593,7 @@ async function resolveAny(client, identifier, opts = {}) {
21756
22593
  } else {
21757
22594
  throw err;
21758
22595
  }
21759
- results.push({
22596
+ return {
21760
22597
  resource: key,
21761
22598
  value: null,
21762
22599
  resolutionCost: missCost(identifier),
@@ -21764,9 +22601,9 @@ async function resolveAny(client, identifier, opts = {}) {
21764
22601
  scanTruncated: code === "RESOLUTION_TRUNCATED",
21765
22602
  candidates,
21766
22603
  error: code
21767
- });
22604
+ };
21768
22605
  }
21769
- }
22606
+ });
21770
22607
  const cleanMiss = results.every((r) => r.value === null && r.candidates.length === 0 && !r.scanTruncated && (r.error === void 0 || r.error === "NOT_FOUND"));
21771
22608
  if (match === "auto" && typeof identifier === "string" && !/^\d+$/.test(identifier.trim()) && cleanMiss) {
21772
22609
  const contains = await searchAcrossResources(client, identifier, { resources: keys, limit });
@@ -21928,7 +22765,7 @@ function dateBucketLabel(value, bucket) {
21928
22765
  var queryResourceKeysPromise = null;
21929
22766
  function queryResourceKeys() {
21930
22767
  if (queryResourceKeysPromise === null) {
21931
- queryResourceKeysPromise = chunkSGH7F2CH_cjs.loadCapabilityRecords().then((records) => {
22768
+ queryResourceKeysPromise = chunkKAZE4WC7_cjs.loadCapabilityRecords().then((records) => {
21932
22769
  const s = /* @__PURE__ */ new Set();
21933
22770
  for (const rec of records) if (rec.operation === "query") s.add(rec.resource);
21934
22771
  return s;
@@ -22050,7 +22887,7 @@ function parseTopAndLimit(opts, problems) {
22050
22887
  return { top, limit };
22051
22888
  }
22052
22889
  async function checkFieldNames(resourceKey, conditions, opts, problems) {
22053
- const records = resourceKey === void 0 ? [] : await chunkSGH7F2CH_cjs.loadCapabilityRecords();
22890
+ const records = resourceKey === void 0 ? [] : await chunkKAZE4WC7_cjs.loadCapabilityRecords();
22054
22891
  const record = resourceKey === void 0 ? void 0 : records.find((r) => r.resource === resourceKey && r.operation === "query");
22055
22892
  if (record === void 0) return void 0;
22056
22893
  const strings = (v) => Array.isArray(v) ? v.filter((f) => typeof f === "string" && f.trim() !== "") : [];
@@ -22333,6 +23170,7 @@ var shortName = (operation) => operation.split(".").pop() ?? operation;
22333
23170
  // src/operations/fetchByIds.ts
22334
23171
  var FETCH_BY_IDS_MAX_ITEMS = 500;
22335
23172
  var FETCH_BY_IDS_CHUNK_SIZE = 250;
23173
+ var itemKey = (resource, id) => `${resource}:${String(id)}`;
22336
23174
  function project2(value, fields) {
22337
23175
  const out = {};
22338
23176
  for (const f of fields) {
@@ -22386,7 +23224,8 @@ function validateFetchManyItems(items, cap, opName = "fetchByIds", capRef = `FET
22386
23224
  }
22387
23225
  const resourceKey = item.resource;
22388
23226
  const fields = MODEL_FIELD_SETS[resourceKey];
22389
- if (fields === void 0) {
23227
+ const hasField = modelFieldLookup(resourceKey);
23228
+ if (fields === void 0 || hasField === void 0) {
22390
23229
  problems.push(
22391
23230
  `${at}.resource: "${resourceKey}" is not a single-record GETtable resource (${Object.keys(MODEL_FIELD_SETS).length} known) \u2014 see autotask_catalog for the exact plan keys`
22392
23231
  );
@@ -22421,7 +23260,7 @@ function validateFetchManyItems(items, cap, opName = "fetchByIds", capRef = `FET
22421
23260
  continue;
22422
23261
  }
22423
23262
  for (const f of item.fields) {
22424
- if (!fields.includes(f)) {
23263
+ if (!hasField(f)) {
22425
23264
  problems.push(
22426
23265
  `${at}.fields: "${f}" is not a field of ${resourceKey} \u2014 a hallucinated field is a shape error, not a silent projection-miss (exact vendor field names via operations.fieldCatalog)`
22427
23266
  );
@@ -22460,8 +23299,8 @@ async function fetchByIds(client, items, opts = {}) {
22460
23299
  }
22461
23300
  groups.set(item.resource, g);
22462
23301
  }
22463
- const byKey = /* @__PURE__ */ new Map();
22464
- for (const [key, group] of groups) {
23302
+ const byKey2 = /* @__PURE__ */ new Map();
23303
+ const plans = [...groups].map(([key, group]) => {
22465
23304
  const holder = client[camelKey(key)];
22466
23305
  if (holder === void 0) {
22467
23306
  throw new AutotaskConfigError(`fetchByIds: the client exposes no accessor for resource "${key}"`, {
@@ -22479,7 +23318,10 @@ async function fetchByIds(client, items, opts = {}) {
22479
23318
  }
22480
23319
  }
22481
23320
  const includeFields = group.anyFields && group.indices.every((i) => items[i].fields !== void 0) ? [...group.fields] : void 0;
22482
- const kOf = (id) => `${key}:${String(id)}`;
23321
+ const kOf = (id) => itemKey(key, id);
23322
+ return { key, holder, resourcePath, unique, includeFields, kOf };
23323
+ });
23324
+ await mapReadTasks(client.http, plans, async ({ key, resourcePath, unique, includeFields, kOf }) => {
22483
23325
  const foundRows = await fetchIdChunks(client.http, resourcePath, unique, includeFields, `${key}.fetchByIds`, {
22484
23326
  chunkSize: FETCH_BY_IDS_CHUNK_SIZE,
22485
23327
  maxRecords: FETCH_BY_IDS_CHUNK_SIZE,
@@ -22489,39 +23331,39 @@ async function fetchByIds(client, items, opts = {}) {
22489
23331
  if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
22490
23332
  for (const u of chunk) {
22491
23333
  const q = kOf(u);
22492
- if (!byKey.has(q)) byKey.set(q, { found: false, value: null, error: e });
23334
+ if (!byKey2.has(q)) byKey2.set(q, { found: false, value: null, error: e });
22493
23335
  }
22494
23336
  return true;
22495
23337
  }
22496
23338
  });
22497
23339
  for (const [k, row] of foundRows) {
22498
23340
  const q = kOf(k);
22499
- if (!byKey.has(q)) byKey.set(q, { found: true, value: row });
23341
+ if (!byKey2.has(q)) byKey2.set(q, { found: true, value: row });
22500
23342
  }
22501
- for (const id of unique) {
22502
- const k = kOf(id);
22503
- if (byKey.has(k)) continue;
22504
- try {
22505
- const value = await holder.get(id);
22506
- byKey.set(k, { found: true, value });
22507
- } catch (err) {
22508
- if (err instanceof NotFoundError) {
22509
- byKey.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
22510
- } else if (isAutotaskError(err) && err.code !== "ABORTED") {
22511
- const e = { code: err.code, message: err.message };
22512
- if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
22513
- byKey.set(k, { found: false, value: null, error: e });
22514
- } else {
22515
- throw err;
22516
- }
23343
+ });
23344
+ const missing = plans.flatMap((plan) => plan.unique.filter((id) => !byKey2.has(plan.kOf(id))).map((id) => ({ plan, id })));
23345
+ await mapReadTasks(client.http, missing, async ({ plan: { holder, kOf }, id }) => {
23346
+ const k = kOf(id);
23347
+ try {
23348
+ const value = await holder.get(id);
23349
+ byKey2.set(k, { found: true, value });
23350
+ } catch (err) {
23351
+ if (err instanceof NotFoundError) {
23352
+ byKey2.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
23353
+ } else if (isAutotaskError(err) && err.code !== "ABORTED") {
23354
+ const e = { code: err.code, message: err.message };
23355
+ if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
23356
+ byKey2.set(k, { found: false, value: null, error: e });
23357
+ } else {
23358
+ throw err;
22517
23359
  }
22518
23360
  }
22519
- }
23361
+ });
22520
23362
  const results = [];
22521
23363
  for (let i = 0; i < items.length; i += 1) {
22522
23364
  const item = items[i];
22523
23365
  const id = canonical[i];
22524
- const out = byKey.get(`${item.resource}:${String(id)}`);
23366
+ const out = byKey2.get(itemKey(item.resource, id));
22525
23367
  const value = out.found ? item.fields !== void 0 ? project2(out.value, item.fields) : out.value : null;
22526
23368
  results.push(
22527
23369
  out.found ? { resource: item.resource, id, found: true, value } : { resource: item.resource, id, found: false, value: null, error: out.error }
@@ -22690,7 +23532,7 @@ async function uiLink(client, input) {
22690
23532
  var indexPromise = null;
22691
23533
  function operationIndex() {
22692
23534
  if (indexPromise === null) {
22693
- indexPromise = chunkSGH7F2CH_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
23535
+ indexPromise = chunkKAZE4WC7_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
22694
23536
  }
22695
23537
  return indexPromise;
22696
23538
  }
@@ -23049,7 +23891,10 @@ async function revenueRollup(client, opts) {
23049
23891
  const groupDims = v.groupBy.map((d) => DIMENSIONS[d]);
23050
23892
  const paths = [.../* @__PURE__ */ new Set([CONTRACTS_PATH, ...groupDims.flatMap((d) => d.picklist ? [d.picklist] : [])])];
23051
23893
  const labels = {};
23052
- for (const p of paths) labels[p] = await readPicklists(http, p, OP4);
23894
+ const labelValues = await mapReadTasks(http, paths, (path) => readPicklists(http, path, OP4));
23895
+ paths.forEach((path, index) => {
23896
+ labels[path] = labelValues[index];
23897
+ });
23053
23898
  const contractLabels = labels[CONTRACTS_PATH];
23054
23899
  const typeValues = contractLabels.get("contractType") ?? /* @__PURE__ */ new Map();
23055
23900
  const inTypes = v.contractTypes ? resolveSelector(OP4, "contractTypes", v.contractTypes, typeValues) : new Map([...typeValues].filter(([, l]) => DEFAULT_CONTRACT_TYPE_RE.test(l)));
@@ -23078,10 +23923,12 @@ async function revenueRollup(client, opts) {
23078
23923
  const invoiceFilter = (voided2) => [...windowOn("invoiceDateTime"), { field: "isVoided", op: "eq", value: voided2 }];
23079
23924
  const withVoided = v.scopeKind !== "contractIDs";
23080
23925
  const voidedFilter = [...invoiceFilter(true), ...scopeIds !== void 0 && withVoided ? [{ field: "companyID", op: "in", value: scopeIds }] : []];
23081
- const nInvoices = await invoices.count({ filter: invoiceFilter(false) });
23082
- const nLines = await billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] });
23083
23926
  const uninvoicedFilter = [{ field: "invoiceID", op: "notExist" }, ...windowOn("itemDate"), ...scopeCond];
23084
- const nUninvoiced = v.nonChargeable ? await billingItems.count({ filter: uninvoicedFilter }) : 0;
23927
+ const [nInvoices, nLines, nUninvoiced] = await readTasks(http, [
23928
+ () => invoices.count({ filter: invoiceFilter(false) }),
23929
+ () => billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] }),
23930
+ () => v.nonChargeable ? billingItems.count({ filter: uninvoicedFilter }) : Promise.resolve(0)
23931
+ ]);
23085
23932
  if (typeof nInvoices !== "number" || typeof nLines !== "number" || typeof nUninvoiced !== "number") throw blindCountError(OP4, "the roll-up", BLIND_ACTION);
23086
23933
  const joinsNeeded = Object.keys(JOINS).filter((j) => j === "contracts" || groupDims.some((d) => d.joins?.[j]));
23087
23934
  const chunks4 = pages(nInvoices);
@@ -23126,14 +23973,17 @@ async function revenueRollup(client, opts) {
23126
23973
  if (v.nonChargeable && uninvoiced.length !== nUninvoiced) throw countMismatchError(OP4, "uninvoiced line", uninvoiced.length, nUninvoiced);
23127
23974
  const all = uninvoiced.length > 0 ? [...lines, ...uninvoiced] : lines;
23128
23975
  const joined = Object.fromEntries(Object.keys(JOINS).map((j) => [j, /* @__PURE__ */ new Map()]));
23129
- for (const j of joinsNeeded) {
23976
+ const fetchJoin = async (j) => {
23130
23977
  const spec = JOINS[j];
23131
23978
  const res = spec.make(http);
23132
23979
  const fields = [.../* @__PURE__ */ new Set([...spec.fields, ...groupDims.flatMap((d) => d.joins?.[j] ?? [])])];
23133
23980
  const want = [...new Set(spec.ids(all, joined))].filter((id) => id > 0).sort((a, b) => a - b);
23134
23981
  const rows = await client.batch((c) => collectRows(res, [{ field: "id", op: "in", value: c }], fields, PAGE), idChunks(want, PAGE), { concurrency: CONCURRENCY });
23135
23982
  for (const r of rows.flat()) joined[j].set(num(r["id"]), r);
23136
- }
23983
+ };
23984
+ const levels = ["organizationalLevel1s", "organizationalLevel2s"];
23985
+ await mapReadTasks(http, joinsNeeded.filter((j) => !levels.includes(j)), fetchJoin);
23986
+ await mapReadTasks(http, joinsNeeded.filter((j) => levels.includes(j)), fetchJoin);
23137
23987
  return fold(v, { invoiceById, voided, lines, uninvoiced, joined, labels, inTypes, inCategories, scopeIds, calls: budget.spent(), estimate });
23138
23988
  }
23139
23989
  function refusal(v, estimate, fixed, scopeIds, joinCount) {
@@ -23515,7 +24365,7 @@ function capJoinSet2(ids2, cap) {
23515
24365
  }
23516
24366
  async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity) {
23517
24367
  const unique = [...new Set(ids2)].sort((a, b) => a - b);
23518
- const byKey = /* @__PURE__ */ new Map();
24368
+ const byKey2 = /* @__PURE__ */ new Map();
23519
24369
  const misses = [];
23520
24370
  const notes = [];
23521
24371
  const found = await fetchIdChunks(http, entityPath, unique, fields, operation, {
@@ -23525,17 +24375,17 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
23525
24375
  const code = err instanceof AutotaskError ? err.code : "SERVER_ERROR";
23526
24376
  for (const k of chunk) {
23527
24377
  const id = Number(k);
23528
- if (!byKey.has(id) && !misses.some((m) => m.id === id)) misses.push({ id, code, message: err instanceof Error ? err.message : String(err) });
24378
+ if (!byKey2.has(id) && !misses.some((m) => m.id === id)) misses.push({ id, code, message: err instanceof Error ? err.message : String(err) });
23529
24379
  }
23530
24380
  return true;
23531
24381
  }
23532
24382
  });
23533
- for (const [k, row] of found) byKey.set(Number(k), row);
23534
- const queryMissed = unique.filter((k) => !byKey.has(k) && !misses.some((m) => m.id === k));
24383
+ for (const [k, row] of found) byKey2.set(Number(k), row);
24384
+ const queryMissed = unique.filter((k) => !byKey2.has(k) && !misses.some((m) => m.id === k));
23535
24385
  for (const k of queryMissed) {
23536
24386
  try {
23537
24387
  const res = await http.request({ method: "GET", path: `${entityPath}/${k}`, operation });
23538
- byKey.set(k, unwrapItem(res, k, operation, entity));
24388
+ byKey2.set(k, unwrapItem(res, k, operation, entity));
23539
24389
  } catch (err) {
23540
24390
  if (err instanceof NotFoundError) {
23541
24391
  misses.push({ id: k, code: "NOT_FOUND", message: err.message });
@@ -23546,14 +24396,14 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
23546
24396
  }
23547
24397
  }
23548
24398
  }
23549
- const items = unique.map((k) => byKey.get(k)).filter((r) => r !== void 0);
24399
+ const items = unique.map((k) => byKey2.get(k)).filter((r) => r !== void 0);
23550
24400
  const gotByQuery = unique.length - queryMissed.length;
23551
- if (queryMissed.length > 0 && gotByQuery === 0 && byKey.size > 0) {
24401
+ if (queryMissed.length > 0 && gotByQuery === 0 && byKey2.size > 0) {
23552
24402
  notes.push(
23553
- `the chunk \`id in\` query returned 0 rows for ${byKey.size} id(s) \u2014 the per-id get fallback resolved them (the list-scoping quirk: get-by-id is the authority)`
24403
+ `the chunk \`id in\` query returned 0 rows for ${byKey2.size} id(s) \u2014 the per-id get fallback resolved them (the list-scoping quirk: get-by-id is the authority)`
23554
24404
  );
23555
24405
  }
23556
- const foundIds = new Set(byKey.keys());
24406
+ const foundIds = new Set(byKey2.keys());
23557
24407
  if (misses.length > 0) {
23558
24408
  const byCode = /* @__PURE__ */ new Map();
23559
24409
  for (const m of misses) byCode.set(m.code, (byCode.get(m.code) ?? 0) + 1);
@@ -23645,6 +24495,17 @@ function makeFetchCtx(rawHttp, v, contractId, budget, sharedExpenses) {
23645
24495
  };
23646
24496
  return { v, OP: OP14, id, idNum, rawHttp, http, wires, windowOn, readPart, windowedPart, truncatedMonths, ...sharedExpenses ? { sharedExpenses } : {} };
23647
24497
  }
24498
+ function forkFetchCtx(ctx) {
24499
+ return makeFetchCtx(ctx.rawHttp, ctx.v, ctx.id, ctx.wires.budget, ctx.sharedExpenses);
24500
+ }
24501
+ function mergeFetchContexts(ctx, branches) {
24502
+ for (const branch of branches) {
24503
+ ctx.wires.issued += branch.wires.issued;
24504
+ ctx.wires.requests += branch.wires.requests;
24505
+ if (branch.wires.note) appendWiresNote(ctx.wires, branch.wires.note);
24506
+ Object.assign(ctx.truncatedMonths, branch.truncatedMonths);
24507
+ }
24508
+ }
23648
24509
 
23649
24510
  // src/resources/special/contracts/profitability.util.ts
23650
24511
  function dateToDay(v) {
@@ -23793,11 +24654,7 @@ async function fetchCustomer(ctx, companyID) {
23793
24654
  let customerAbsent;
23794
24655
  if (companyID > 0) {
23795
24656
  try {
23796
- const res = await ctx.http.request({
23797
- method: "GET",
23798
- path: `/V1.0/Companies/${companyID}`,
23799
- operation: ctx.OP
23800
- });
24657
+ const res = await cachedRecordGet(ctx.http, `/V1.0/Companies/${companyID}`, ctx.OP);
23801
24658
  const item = unwrapItem(res, companyID, ctx.OP, "company");
23802
24659
  customer = item ?? null;
23803
24660
  customerStatus = "ok";
@@ -23827,16 +24684,17 @@ async function resolveContractType(ctx, contractType) {
23827
24684
  const isTimeAndMaterials = contractTypeKnown && TIME_AND_MATERIALS_LABEL_RE.test(contractTypeLabel);
23828
24685
  return { contractTypeLabel, contractTypeKnown, isBlockHours, isTimeAndMaterials };
23829
24686
  }
23830
- async function fetchRoot(ctx, resource) {
23831
- const contractCached = ctx.rawHttp.readCache?.get(`/V1.0/Contracts/${ctx.id}`) !== void 0;
23832
- const contract = await resource.get(ctx.id);
24687
+ async function fetchRoot(ctx) {
24688
+ const body = await cachedRecordGet(ctx.http, `/V1.0/Contracts/${ctx.id}`, "contracts.get");
24689
+ const contract = unwrapItem(body, ctx.id, "contracts.get", "contract");
23833
24690
  ctx.wires.issued += 1;
23834
- if (!contractCached) ctx.wires.requests += 1;
23835
24691
  const contractRow = contract;
23836
24692
  const companyID = num(contractRow["companyID"]);
23837
24693
  const contractType = num(contractRow["contractType"]);
23838
- const customerStage = await fetchCustomer(ctx, companyID);
23839
- const typeStage = await resolveContractType(ctx, contractType);
24694
+ const [customerStage, typeStage] = await readTasks(ctx.http, [
24695
+ () => fetchCustomer(ctx, companyID),
24696
+ () => resolveContractType(ctx, contractType)
24697
+ ]);
23840
24698
  return { contract, contractRow, contractType, ...customerStage, ...typeStage };
23841
24699
  }
23842
24700
  async function fetchCharges(ctx) {
@@ -23847,27 +24705,29 @@ async function fetchCharges(ctx) {
23847
24705
  const raw = await ctx.readPart("/V1.0/ContractCharges/query", chargesCond, ["id", "chargeType", "billableAmount", "extendedCost", "unitCost", "unitPrice", "unitQuantity", "datePurchased", "isBilled", "status", "contractServiceID"]);
23848
24706
  return { charges: raw.items, chargesPart: stampPart("contract_charges", raw, chargesCond) };
23849
24707
  }
23850
- async function fetchBlocks(ctx, root) {
23851
- if (!root.isBlockHours) {
24708
+ async function fetchBlocks(ctx, root3) {
24709
+ if (!root3.isBlockHours) {
23852
24710
  return skipPart(
23853
- root.contractTypeKnown ? `skipped: not a Block Hours contract (contractType ${root.contractType} "${root.contractTypeLabel}") \u2014 included hours apply to hour blocks only (zero wire)` : `skipped: the contract type is unknown (contractType ${root.contractType || "absent"}; label unresolved) \u2014 included hours are not evaluable (zero wire)`
24711
+ root3.contractTypeKnown ? `skipped: not a Block Hours contract (contractType ${root3.contractType} "${root3.contractTypeLabel}") \u2014 included hours apply to hour blocks only (zero wire)` : `skipped: the contract type is unknown (contractType ${root3.contractType || "absent"}; label unresolved) \u2014 included hours are not evaluable (zero wire)`
23854
24712
  );
23855
24713
  }
23856
24714
  const blocksCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23857
24715
  const raw = await ctx.readPart("/V1.0/ContractBlocks/query", blocksCond, ["id", "datePurchased", "startDate", "endDate", "hours", "hoursApproved", "status", "isPaid"]);
23858
24716
  return stampPart("contract_blocks", raw, blocksCond);
23859
24717
  }
23860
- async function fetchContractState(ctx, root) {
24718
+ async function fetchContractState(ctx, root3) {
23861
24719
  const servicesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23862
- const servicesRaw = await ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]);
23863
24720
  const unitsCond = [{ field: "contractID", op: "eq", value: ctx.id }, ...ctx.windowOn("startDate")];
23864
- const units = await ctx.windowedPart("contractServiceUnits", "contract_service_units", "/V1.0/ContractServiceUnits/query", unitsCond, ["id", "contractServiceID", "serviceID", "units", "price", "cost", "internalCurrencyPrice", "startDate", "endDate", "approveAndPostDate"], "startDate");
23865
- const { chargesPart, charges } = await fetchCharges(ctx);
23866
24721
  const roleCostsCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23867
- const roleCostsRaw = await ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]);
23868
24722
  const ratesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23869
- const ratesRaw = await ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]);
23870
- const blocksPart = await fetchBlocks(ctx, root);
24723
+ const [servicesRaw, units, { chargesPart, charges }, roleCostsRaw, ratesRaw, blocksPart] = await readTasks(ctx.http, [
24724
+ () => ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]),
24725
+ () => ctx.windowedPart("contractServiceUnits", "contract_service_units", "/V1.0/ContractServiceUnits/query", unitsCond, ["id", "contractServiceID", "serviceID", "units", "price", "cost", "internalCurrencyPrice", "startDate", "endDate", "approveAndPostDate"], "startDate"),
24726
+ () => fetchCharges(ctx),
24727
+ () => ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]),
24728
+ () => ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]),
24729
+ () => fetchBlocks(ctx, root3)
24730
+ ]);
23871
24731
  return { servicesRaw, servicesCond, unitRows: units.rows, unitsPartRaw: units.part, chargesPart, charges, roleCostsRaw, roleCostsCond, ratesRaw, ratesCond, blocksPart };
23872
24732
  }
23873
24733
  async function fetchBillingItems(ctx) {
@@ -24230,25 +25090,46 @@ async function fetchSubscriptionsJoin(ctx) {
24230
25090
  }
24231
25091
 
24232
25092
  // src/resources/special/contracts/profitability.data.ts
24233
- async function gather(ctx, resource) {
24234
- const root = await fetchRoot(ctx, resource);
24235
- const state = await fetchContractState(ctx, root);
24236
- const billing = await fetchBilling(ctx);
24237
- const time = await fetchTime(ctx);
24238
- const activity = await fetchTicketActivity(ctx, time.entries);
24239
- const open = await fetchOpenTickets(ctx);
24240
- const res = await fetchResources(ctx, time.entries);
24241
- const join = await fetchTicketJoinParts(ctx, [...activity.ticketsActRaw.items, ...open.openTickets], time.entries);
24242
- const subs = await fetchSubscriptionsJoin(ctx);
24243
- return { root, state, billing, time, activity, open, res, join, subs };
25093
+ async function gather(ctx) {
25094
+ const root3 = await fetchRoot(ctx);
25095
+ const stages = Object.fromEntries(
25096
+ ["state", "billing", "time", "activity", "open", "res", "join", "subs"].map((name) => [name, forkFetchCtx(ctx)])
25097
+ );
25098
+ let timeRead;
25099
+ const timeTask = () => timeRead ??= fetchTime(stages.time);
25100
+ let activityRead;
25101
+ const activityTask = () => activityRead ??= timeTask().then((time) => fetchTicketActivity(stages.activity, time.entries));
25102
+ let openRead;
25103
+ const openTask = () => openRead ??= fetchOpenTickets(stages.open);
25104
+ const tasks = {
25105
+ state: () => fetchContractState(stages.state, root3),
25106
+ billing: () => fetchBilling(stages.billing),
25107
+ time: timeTask,
25108
+ activity: activityTask,
25109
+ open: openTask,
25110
+ res: async () => fetchResources(stages.res, (await timeTask()).entries),
25111
+ join: async () => {
25112
+ const activity = await activityTask();
25113
+ const open = await openTask();
25114
+ const time = await timeTask();
25115
+ Object.assign(stages.join.truncatedMonths, stages.time.truncatedMonths);
25116
+ return fetchTicketJoinParts(stages.join, [...activity.ticketsActRaw.items, ...open.openTickets], time.entries);
25117
+ },
25118
+ subs: () => fetchSubscriptionsJoin(stages.subs)
25119
+ };
25120
+ const order = ctx.http.maxConcurrent === 1 ? ["state", "billing", "time", "activity", "open", "res", "join", "subs"] : ["state", "billing", "time", "open", "subs", "activity", "res", "join"];
25121
+ const completed = await mapReadTasks(ctx.http, order, async (name) => [name, await tasks[name]()]);
25122
+ const parts = Object.fromEntries(completed);
25123
+ mergeFetchContexts(ctx, Object.values(stages));
25124
+ return { root: root3, ...parts };
24244
25125
  }
24245
25126
  function stampListParts(v, f) {
24246
- const { state, activity, join } = f;
25127
+ const { state: state2, activity, join } = f;
24247
25128
  return {
24248
- servicesPart: stampPart("contract_services", state.servicesRaw, state.servicesCond),
24249
- unitsPart: state.unitsPartRaw,
24250
- roleCostsPart: stampPart("contract_role_costs", state.roleCostsRaw, state.roleCostsCond),
24251
- ratesPart: stampPart("contract_rates", state.ratesRaw, state.ratesCond),
25129
+ servicesPart: stampPart("contract_services", state2.servicesRaw, state2.servicesCond),
25130
+ unitsPart: state2.unitsPartRaw,
25131
+ roleCostsPart: stampPart("contract_role_costs", state2.roleCostsRaw, state2.roleCostsCond),
25132
+ ratesPart: stampPart("contract_rates", state2.ratesRaw, state2.ratesCond),
24252
25133
  ticketsActivityPart: stampPart("tickets", activity.ticketsActRaw, activity.ticketsActCond, [
24253
25134
  ...activity.ticketsActRaw.hasMore ? [`${join.fetchedTickets.size} ticket(s) returned of possibly more \u2014 the checks cover the returned set only`] : [],
24254
25135
  ...activity.refTicketIds.truncated ? [`the time-referenced ticket ids are capped at ${v.maxTicketsForJoin} of ${activity.refTicketIds.total} \u2014 the rest read as ticket_not_in_fetched_set`] : []
@@ -24889,7 +25770,7 @@ async function profitability(resource, contractId, opts, sharedExpenses) {
24889
25770
  const v = validateProfitabilityOptions(contractId, opts);
24890
25771
  const ctx = makeFetchCtx(resource.http, v, contractId, PROFITABILITY_WIRE_BUDGET, sharedExpenses);
24891
25772
  const asOf = (/* @__PURE__ */ new Date()).toISOString();
24892
- const f = await gather(ctx, resource);
25773
+ const f = await gather(ctx);
24893
25774
  const fc = makeFoldCtx(ctx, f, stampListParts(v, f), Date.parse(asOf));
24894
25775
  return assemble(ctx, fc, asOf);
24895
25776
  }
@@ -24976,17 +25857,30 @@ function validate2(opts) {
24976
25857
  function latchingHttp(raw, spend) {
24977
25858
  const counted = countingHttp(raw, spend);
24978
25859
  let fatal;
25860
+ const controller = new AbortController();
25861
+ const caller = ambientCallerSignal();
25862
+ const signal = caller === void 0 ? controller.signal : AbortSignal.any([caller, controller.signal]);
24979
25863
  const http = Object.create(counted);
24980
- http.request = async (o) => {
25864
+ const latch = (err) => {
25865
+ if (err instanceof RateLimitError || err instanceof AutotaskError && err.code === "BUDGET_EXCEEDED") {
25866
+ fatal ??= err;
25867
+ controller.abort(fatal);
25868
+ }
25869
+ };
25870
+ observeRecordReadFailures(http, latch);
25871
+ const fail = (err) => {
25872
+ latch(err);
25873
+ throw err;
25874
+ };
25875
+ http.request = (o) => {
24981
25876
  if (fatal) throw fatal;
24982
25877
  try {
24983
- return await counted.request(o);
25878
+ return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail);
24984
25879
  } catch (err) {
24985
- if (err instanceof RateLimitError || err instanceof AutotaskError && err.code === "BUDGET_EXCEEDED") fatal ??= err;
24986
- throw err;
25880
+ return fail(err);
24987
25881
  }
24988
25882
  };
24989
- return { http, fatal: () => fatal };
25883
+ return { http, fatal: () => fatal, signal };
24990
25884
  }
24991
25885
  async function portfolioMargin(client, opts) {
24992
25886
  const v = validate2(opts);
@@ -24997,7 +25891,7 @@ async function portfolioMargin(client, opts) {
24997
25891
  { phase: estimate === 0 ? "estimate" : "walk", budget: v.budget, vendorCalls: spent, ...estimate > 0 ? { estimate } : {} },
24998
25892
  `Pass maxVendorCalls > ${v.budget} (cap ${BUDGET_CAP2}) or fewer contracts.`
24999
25893
  ));
25000
- const { http, fatal } = latchingHttp(client.http, budget.spend);
25894
+ const { http, fatal, signal } = latchingHttp(client.http, budget.spend);
25001
25895
  const contracts = new ContractsResource(http, PAGE2);
25002
25896
  let typeMap;
25003
25897
  if (v.contractTypes) {
@@ -25044,7 +25938,7 @@ async function portfolioMargin(client, opts) {
25044
25938
  let results;
25045
25939
  try {
25046
25940
  const shared = countFault ?? (expenseCount === 0 ? { rows: [], contractOf: /* @__PURE__ */ new Map(), misses: 0 } : await readTicketExpenses(http, expenseItems, expenseFilter, expenseCount));
25047
- results = await client.batch((id) => profitability(contracts, id, v.profitOpts, shared), ids2, { concurrency: CONCURRENCY2 });
25941
+ results = await client.withSignal(signal, () => client.batch((id) => profitability(contracts, id, v.profitOpts, shared), ids2, { concurrency: CONCURRENCY2 }));
25048
25942
  } catch (err) {
25049
25943
  throw fatal() ?? err;
25050
25944
  }
@@ -25287,8 +26181,10 @@ async function recurringRevenue(client, opts) {
25287
26181
  ];
25288
26182
  const subsRes = res("subscriptions");
25289
26183
  const subFilter = [{ field: "effectiveDate", op: "lt", value: next }, { field: "expirationDate", op: "gte", value: v.asOf }];
25290
- const nContracts = await countOf(contractsRes, "contract", contractFilter);
25291
- const nSubs = await countOf(subsRes, "subscription", subFilter);
26184
+ const [nContracts, nSubs] = await readTasks(http, [
26185
+ () => countOf(contractsRes, "contract", contractFilter),
26186
+ () => countOf(subsRes, "subscription", subFilter)
26187
+ ]);
25292
26188
  const chunks4 = Math.ceil(nContracts / CHUNK);
25293
26189
  const subCalls = Math.ceil(nSubs / PAGE3) + (nSubs > 0 ? 1 : 0) + Math.ceil(nSubs / CHUNK) + (v.scopeIds ? 1 : Math.ceil((nContracts + nSubs) / CHUNK));
25294
26190
  const refuse3 = (calls, sets2) => {
@@ -25327,26 +26223,35 @@ async function recurringRevenue(client, opts) {
25327
26223
  nCharges: 0
25328
26224
  };
25329
26225
  });
25330
- for (const x of sets) {
25331
- x.nUnits = await countOf(res("contract_service_units"), "service unit", x.unitFilter);
25332
- x.nCharges = await countOf(res("contract_charges"), "charge", x.chargeFilter);
25333
- }
26226
+ await mapReadTasks(http, sets.flatMap((x) => [
26227
+ async () => {
26228
+ x.nUnits = await countOf(res("contract_service_units"), "service unit", x.unitFilter);
26229
+ },
26230
+ async () => {
26231
+ x.nCharges = await countOf(res("contract_charges"), "charge", x.chargeFilter);
26232
+ }
26233
+ ]), (task) => task());
25334
26234
  const nUnits = sets.reduce((a, x) => a + x.nUnits, 0);
25335
26235
  const nCharges = sets.reduce((a, x) => a + x.nCharges, 0);
25336
26236
  estimate = budget.spent() + sets.reduce((a, x) => a + Math.ceil(x.nUnits / PAGE3) + Math.ceil(x.nCharges / PAGE3), 0) + subCalls;
25337
26237
  if (estimate > v.budget) {
25338
26238
  throw refuse3(estimate, { contracts: nContracts, serviceUnits: nUnits, charges: nCharges, subscriptions: nSubs });
25339
26239
  }
25340
- const units = [];
25341
- const charges = [];
25342
- for (const x of sets) {
25343
- units.push(...await gated(res("contract_service_units"), "service unit", x.unitFilter, ["id", "contractID", "contractServiceID", "startDate", "endDate", "units", "price", "internalCurrencyPrice"], x.nUnits));
25344
- charges.push(...await gated(res("contract_charges"), "charge", x.chargeFilter, ["id", "contractID", "billableAmount", "internalCurrencyBillableAmount"], x.nCharges));
25345
- }
25346
- const subs = await gated(subsRes, "subscription", subFilter, ["id", "configurationItemID", "periodPrice", "periodType", "status"], nSubs);
25347
- const labels = subs.length > 0 ? await readPicklists(http, "/V1.0/Subscriptions", OP6) : /* @__PURE__ */ new Map();
25348
- const ciIds = [...new Set(subs.map((s) => num(s["configurationItemID"])).filter((n) => n > 0))].sort((a, b) => a - b);
25349
- const cis = ciIds.length > 0 ? await fetchIdChunks(http, "/V1.0/ConfigurationItems", ciIds, ["companyID"], OP6, { chunkSize: CHUNK }) : /* @__PURE__ */ new Map();
26240
+ const [unitSets, chargeSets, { subs, labels, cis }] = await readTasks(http, [
26241
+ () => mapReadTasks(http, sets, (x) => gated(res("contract_service_units"), "service unit", x.unitFilter, ["id", "contractID", "contractServiceID", "startDate", "endDate", "units", "price", "internalCurrencyPrice"], x.nUnits)),
26242
+ () => mapReadTasks(http, sets, (x) => gated(res("contract_charges"), "charge", x.chargeFilter, ["id", "contractID", "billableAmount", "internalCurrencyBillableAmount"], x.nCharges)),
26243
+ async () => {
26244
+ const subs2 = await gated(subsRes, "subscription", subFilter, ["id", "configurationItemID", "periodPrice", "periodType", "status"], nSubs);
26245
+ const ciIds = [...new Set(subs2.map((s) => num(s["configurationItemID"])).filter((n) => n > 0))].sort((a, b) => a - b);
26246
+ const [labels2, cis2] = await readTasks(http, [
26247
+ () => subs2.length > 0 ? readPicklists(http, "/V1.0/Subscriptions", OP6) : Promise.resolve(/* @__PURE__ */ new Map()),
26248
+ () => ciIds.length > 0 ? fetchIdChunks(http, "/V1.0/ConfigurationItems", ciIds, ["companyID"], OP6, { chunkSize: CHUNK }) : Promise.resolve(/* @__PURE__ */ new Map())
26249
+ ]);
26250
+ return { subs: subs2, labels: labels2, cis: cis2 };
26251
+ }
26252
+ ]);
26253
+ const units = unitSets.flat();
26254
+ const charges = chargeSets.flat();
25350
26255
  const contractOf = new Map(contracts.map((c) => [num(c["id"]), c]));
25351
26256
  const latest = /* @__PURE__ */ new Map();
25352
26257
  for (const u of units) {
@@ -26059,7 +26964,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
26059
26964
  suggestedAction: "Narrow the dateWorked window, or page it with cursor (rows mode reports unconfirmed entries via truncated)."
26060
26965
  });
26061
26966
  }
26062
- for (const [id, state] of joined.states) states.set(id, state);
26967
+ for (const [id, state2] of joined.states) states.set(id, state2);
26063
26968
  cursor = page.items.length === 0 ? null : page.pageDetails.nextPageUrl ?? null;
26064
26969
  } while (cursor !== null);
26065
26970
  spend();
@@ -26077,7 +26982,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
26077
26982
  });
26078
26983
  }
26079
26984
  let postedCount = 0;
26080
- for (const state of states.values()) if (state === "posted") postedCount += 1;
26985
+ for (const state2 of states.values()) if (state2 === "posted") postedCount += 1;
26081
26986
  return { window, total: states.size, postedCount, unpostedCount: states.size - postedCount, vendorCalls: callBudget.spent(), estimate, budget };
26082
26987
  }
26083
26988
  async function dateWorkedWindow(resource, from, to, opts) {
@@ -26098,8 +27003,8 @@ async function dateWorkedWindow(resource, from, to, opts) {
26098
27003
  const { states, incomplete } = await postedStateOf(http, items, OP14);
26099
27004
  let postedCount = 0;
26100
27005
  let unpostedCount = 0;
26101
- for (const state of states.values()) {
26102
- if (state === "posted") postedCount += 1;
27006
+ for (const state2 of states.values()) {
27007
+ if (state2 === "posted") postedCount += 1;
26103
27008
  else unpostedCount += 1;
26104
27009
  }
26105
27010
  return {
@@ -26383,12 +27288,14 @@ async function wipHours(client, opts) {
26383
27288
  } else {
26384
27289
  const contractIds = positiveIds2(wipIn.map((e) => e["contractID"]));
26385
27290
  gate(chunks2(contractIds.length) + (contractIds.length > 0 ? 1 : 0), "before label reads", { contracts: contractIds.length });
26386
- const contracts = await readChunks2(http, "/V1.0/Contracts", contractIds, ["contractType"]);
27291
+ const [contracts, types] = await readTasks(http, [
27292
+ () => readChunks2(http, "/V1.0/Contracts", contractIds, ["contractType"]),
27293
+ async () => contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0
27294
+ ]);
26387
27295
  const typeOf = (id) => contracts.get(String(id))?.["contractType"];
26388
27296
  const bad = contractIds.filter((id) => typeof typeOf(id) !== "number");
26389
27297
  if (bad.length > 0) throw unresolved("contracts", bad);
26390
27298
  keyOfEntry = (e) => num(e["contractID"]) > 0 ? typeOf(num(e["contractID"])) : null;
26391
- const types = contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0;
26392
27299
  for (const [id, label] of types ?? []) labels.set(id, { label });
26393
27300
  }
26394
27301
  const approvalData = entries.some((e) => isApproved(e));
@@ -26580,8 +27487,10 @@ async function nonChargeableWork(client, opts) {
26580
27487
  const contractIds = distinctIds(ncLines.map((x) => x.line["contractID"]), 1);
26581
27488
  const typed = v.groupBy === "contractType";
26582
27489
  gate(chunks3(contractIds.length) + (typed && contractIds.length > 0 ? 1 : 0) + (v.includeUnpostedTime ? 1 : 0), "before label reads", { contracts: contractIds.length });
26583
- const contracts = await readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]);
26584
- const types = typed && contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP11)).get("contractType") : void 0;
27490
+ const [contracts, types] = await readTasks(http, [
27491
+ () => readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]),
27492
+ async () => typed && contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP11)).get("contractType") : void 0
27493
+ ]);
26585
27494
  keyOfLine = (line) => {
26586
27495
  if (num(line["contractID"]) === 0) return null;
26587
27496
  const c = contracts.get(String(line["contractID"]));
@@ -27063,6 +27972,10 @@ async function openTicketsOfPart(client, field, id, limit) {
27063
27972
  const filter = [{ field, op: "eq", value: id }, ...closed.map((v) => ({ field: "status", op: "noteq", value: v }))];
27064
27973
  return { ...await compositePart(client, "tickets.query", [{ filter, limit }]), closedStatus };
27065
27974
  }
27975
+ async function joinedCompositePart(client, source, idField, targetOp, targetField, limit, absent) {
27976
+ const ids2 = numericIds(source.value?.items ?? [], idField).slice(0, IN_FILTER_CAP);
27977
+ return ids2.length === 0 ? { value: null, absent } : await compositePart(client, targetOp, [{ filter: [{ field: targetField, op: "in", value: ids2 }], limit }]);
27978
+ }
27066
27979
 
27067
27980
  // src/resources/special/contracts/fullProfile.ts
27068
27981
  var OP12 = "contracts.fullProfile";
@@ -27073,21 +27986,23 @@ async function fullProfile2(resource, id, opts = {}) {
27073
27986
  const serviceLimit = compositePartLimit(opts.serviceLimit, "serviceLimit", OP12);
27074
27987
  const billingRuleLimit = compositePartLimit(opts.billingRuleLimit, "billingRuleLimit", OP12);
27075
27988
  const contractId = parseIdentifier(id, "id");
27076
- const root = await invokeRead(client, "contracts.get", [contractId]);
27077
- const services = await compositePart(client, "contract_services.query", [
27078
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
27079
- ]);
27080
- const billingRules = await compositePart(client, "contract_billing_rules.query", [
27081
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: billingRuleLimit }
27082
- ]);
27083
- const charges = await compositePart(client, "contract_charges.query", [
27084
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: CHARGES_RECENT_CAP, latest: CHARGES_RECENT_CAP }
27085
- ]);
27086
- const units = await compositePart(client, "contract_service_units.query", [
27087
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: SERVICE_UNITS_CAP }
27989
+ const root3 = await invokeRead(client, "contracts.get", [contractId]);
27990
+ const [services, billingRules, charges, units] = await readTasks(resource.http, [
27991
+ () => compositePart(client, "contract_services.query", [
27992
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
27993
+ ]),
27994
+ () => compositePart(client, "contract_billing_rules.query", [
27995
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: billingRuleLimit }
27996
+ ]),
27997
+ () => compositePart(client, "contract_charges.query", [
27998
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: CHARGES_RECENT_CAP, latest: CHARGES_RECENT_CAP }
27999
+ ]),
28000
+ () => compositePart(client, "contract_service_units.query", [
28001
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: SERVICE_UNITS_CAP }
28002
+ ])
27088
28003
  ]);
27089
28004
  return {
27090
- root,
28005
+ root: root3,
27091
28006
  parts: {
27092
28007
  services,
27093
28008
  billing_rules: billingRules,
@@ -27194,7 +28109,6 @@ exports.GenericResource = GenericResource;
27194
28109
  exports.HostPolicyDeniedError = HostPolicyDeniedError;
27195
28110
  exports.HttpClient = HttpClient;
27196
28111
  exports.INVOKE_OPTION_KEYS = INVOKE_OPTION_KEYS;
27197
- exports.IN_FILTER_CAP = IN_FILTER_CAP;
27198
28112
  exports.InvoicesResource = InvoicesResource;
27199
28113
  exports.MAX_FIELD_CATALOG_WIRE = MAX_FIELD_CATALOG_WIRE;
27200
28114
  exports.MIN_FIELD_CATALOG_MAX_BYTES = MIN_FIELD_CATALOG_MAX_BYTES;
@@ -27232,6 +28146,7 @@ exports.buildDryRunResult = buildDryRunResult;
27232
28146
  exports.buildQueryRequest = buildQueryRequest;
27233
28147
  exports.buildReadCache = buildReadCache;
27234
28148
  exports.buildUiLink = buildUiLink;
28149
+ exports.cachedRecordGet = cachedRecordGet;
27235
28150
  exports.clientOf = clientOf;
27236
28151
  exports.compositePart = compositePart;
27237
28152
  exports.compositePartLimit = compositePartLimit;
@@ -27255,19 +28170,20 @@ exports.invokeWrite = invokeWrite;
27255
28170
  exports.isAutotaskError = isAutotaskError;
27256
28171
  exports.isClosedStatus = isClosedStatus;
27257
28172
  exports.isDeterministicVendor500 = isDeterministicVendor500;
28173
+ exports.joinedCompositePart = joinedCompositePart;
27258
28174
  exports.mergeDetails = mergeDetails;
27259
28175
  exports.mergePartialBody = mergePartialBody;
27260
28176
  exports.needsConfirmation = needsConfirmation;
27261
28177
  exports.nextActionFor = nextActionFor;
27262
28178
  exports.nonChargeableWork = nonChargeableWork;
27263
28179
  exports.notPersistedFields = notPersistedFields;
27264
- exports.numericIds = numericIds;
27265
28180
  exports.openStatusFilter = openStatusFilter;
27266
28181
  exports.openTicketsOfPart = openTicketsOfPart;
27267
28182
  exports.parseIdentifier = parseIdentifier;
27268
28183
  exports.parseVendorErrors = parseVendorErrors;
27269
28184
  exports.portfolioMargin = portfolioMargin;
27270
28185
  exports.queryRows = queryRows;
28186
+ exports.readTasks = readTasks;
27271
28187
  exports.recurringRevenue = recurringRevenue;
27272
28188
  exports.refuse = refuse2;
27273
28189
  exports.relationshipMap = relationshipMap;
@@ -27279,6 +28195,7 @@ exports.resolveLineOfBusinessChain = resolveLineOfBusinessChain;
27279
28195
  exports.resolveStaff = resolveStaff;
27280
28196
  exports.resolveTicketStatusSemantics = resolveTicketStatusSemantics;
27281
28197
  exports.revenueRollup = revenueRollup;
28198
+ exports.runBounded = runBounded;
27282
28199
  exports.runMove = runMove;
27283
28200
  exports.runWithSignal = runWithSignal;
27284
28201
  exports.sanitiseResult = sanitiseResult;