node-autotask 0.68.0 → 0.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +18 -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-HFWOHUVF.cjs → chunk-24GRFW55.cjs} +236 -222
  9. package/dist/{chunk-BF22HBNT.js → chunk-2BB7OASJ.js} +3 -30
  10. package/dist/{chunk-OUVUQQXH.js → chunk-AH6WAGPS.js} +80 -66
  11. package/dist/{chunk-CG6OPTFG.cjs → chunk-DPRY3CUJ.cjs} +30 -57
  12. package/dist/{chunk-V2GE763R.cjs → chunk-JLBSUZ5B.cjs} +993 -395
  13. package/dist/{chunk-SGH7F2CH.cjs → chunk-KAZE4WC7.cjs} +3 -3
  14. package/dist/{chunk-DPJLN5BB.js → chunk-QDBJCGQD.js} +986 -390
  15. package/dist/{chunk-JCMXQUIC.js → chunk-SCFB5MF3.js} +3 -3
  16. package/dist/{index-DQ08uOH0.d.ts → index-CxBU31jT.d.ts} +16 -9
  17. package/dist/{index-mIsdpO5d.d.cts → index-WZ3A8nG6.d.cts} +16 -9
  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 +77 -16
  33. package/docs/LIVE-TESTING.md +16 -2
  34. package/docs/VENDOR-QUIRKS.md +54 -0
  35. package/docs/performance-finance.md +35 -0
  36. package/examples/mcp-env-config.ts +3 -4
  37. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
- import { loadCapabilityRecords } from './chunk-JCMXQUIC.js';
1
+ import { loadCapabilityRecords } from './chunk-SCFB5MF3.js';
2
2
  import { NoopLogger, REDACTED, deepMarkUntrusted, wrapUntrusted } from './chunk-7NKB4UXV.js';
3
- import { randomUUID } from 'crypto';
3
+ import { randomUUID, createHash } from 'crypto';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
5
5
 
6
6
  // src/errors/base.ts
@@ -114,7 +114,7 @@ var ConflictError = class extends AutotaskError {
114
114
  var RateLimitError = class extends AutotaskError {
115
115
  /** Seconds the server asked the client to wait (`Retry-After`), when present. */
116
116
  retryAfter;
117
- /** True when the call was refused locally (the tenant cooldown gate) and never sent. */
117
+ /** True when the call was refused locally (cooldown or hourly admission) and never sent. */
118
118
  notSent;
119
119
  constructor(message, options = {}) {
120
120
  super(message, { code: "RATE_LIMITED", category: "rate_limit", retryable: true, ...options });
@@ -634,6 +634,7 @@ var TtlCache = class {
634
634
  ttlFor;
635
635
  store = /* @__PURE__ */ new Map();
636
636
  inflightMap = /* @__PURE__ */ new Map();
637
+ loads = /* @__PURE__ */ new Map();
637
638
  epochCounter = 0;
638
639
  constructor(ttlMs, options = {}) {
639
640
  if (!Number.isInteger(ttlMs) || ttlMs <= 0) {
@@ -657,6 +658,85 @@ var TtlCache = class {
657
658
  }
658
659
  return structuredClone(entry.value);
659
660
  }
661
+ /**
662
+ * Load one record once for concurrent callers. Each subscriber owns its
663
+ * cancellation and receives a copy. The wire read is cancelled only when
664
+ * its last subscriber leaves. A fresh load starts a new flight and prevents
665
+ * an older flight from replacing its result; invalidation detaches flights
666
+ * without changing the answer owed to their existing subscribers.
667
+ * @internal
668
+ */
669
+ async load(key, loader, opts) {
670
+ const { signal } = opts;
671
+ if (signal?.aborted) throw opts.abortError();
672
+ if (!opts.fresh) {
673
+ const hit = this.get(key);
674
+ if (hit !== void 0) return hit;
675
+ }
676
+ let flight = opts.fresh ? void 0 : this.loads.get(key);
677
+ let start;
678
+ if (flight === void 0) {
679
+ const epoch = this.epoch;
680
+ const controller = new AbortController();
681
+ const created = { controller, promise: Promise.resolve(), subscribers: 0, settled: false };
682
+ created.promise = new Promise((resolve, reject) => {
683
+ start = () => {
684
+ try {
685
+ resolve(loader(controller.signal));
686
+ } catch (error) {
687
+ if (this.loads.get(key) === created) this.loads.delete(key);
688
+ reject(error);
689
+ }
690
+ };
691
+ }).then((value) => {
692
+ if (this.loads.get(key) === created && !controller.signal.aborted) this.set(key, value, epoch);
693
+ return value;
694
+ });
695
+ const settled = () => {
696
+ created.settled = true;
697
+ if (this.loads.get(key) === created) this.loads.delete(key);
698
+ };
699
+ created.promise.then(settled, settled);
700
+ this.loads.set(key, created);
701
+ flight = created;
702
+ }
703
+ const shared = flight;
704
+ shared.subscribers += 1;
705
+ const result = new Promise((resolve, reject) => {
706
+ let active = true;
707
+ const leave = () => {
708
+ if (!active) return false;
709
+ active = false;
710
+ signal?.removeEventListener("abort", aborted);
711
+ shared.subscribers -= 1;
712
+ if (shared.subscribers === 0 && !shared.settled) {
713
+ if (this.loads.get(key) === shared) this.loads.delete(key);
714
+ shared.controller.abort();
715
+ }
716
+ return true;
717
+ };
718
+ const aborted = () => {
719
+ if (leave()) reject(opts.abortError());
720
+ };
721
+ signal?.addEventListener("abort", aborted, { once: true });
722
+ shared.promise.then(
723
+ (value) => {
724
+ if (leave()) {
725
+ try {
726
+ resolve(structuredClone(value));
727
+ } catch (error) {
728
+ reject(error);
729
+ }
730
+ }
731
+ },
732
+ (error) => {
733
+ if (leave()) reject(error);
734
+ }
735
+ );
736
+ });
737
+ start?.();
738
+ return result;
739
+ }
660
740
  /** Store `value` under `key`. `epoch` is the value the caller read BEFORE its
661
741
  * wire request: a read that straddled a `clear()` (a write) is dropped. */
662
742
  set(key, value, epoch = this.epochCounter) {
@@ -691,12 +771,14 @@ var TtlCache = class {
691
771
  /** Drop one key. */
692
772
  delete(key) {
693
773
  this.inflightMap.delete(key);
774
+ this.loads.delete(key);
694
775
  return this.store.delete(key);
695
776
  }
696
777
  /** Drop every stored and in-flight key that starts with `prefix`. */
697
778
  invalidate(prefix) {
698
779
  for (const key of [...this.store.keys()]) if (key.startsWith(prefix)) this.store.delete(key);
699
780
  for (const key of [...this.inflightMap.keys()]) if (key.startsWith(prefix)) this.inflightMap.delete(key);
781
+ for (const key of [...this.loads.keys()]) if (key.startsWith(prefix)) this.loads.delete(key);
700
782
  }
701
783
  /** Drop every expired entry (returns the number removed). */
702
784
  purgeExpired() {
@@ -723,6 +805,7 @@ var TtlCache = class {
723
805
  this.epochCounter += 1;
724
806
  this.store.clear();
725
807
  this.inflightMap.clear();
808
+ this.loads.clear();
726
809
  }
727
810
  };
728
811
 
@@ -801,9 +884,10 @@ function cooldownDurationMs(retryAfterSecs, opts) {
801
884
  }
802
885
  return Math.min(retryAfterSecs !== void 0 ? retryAfterSecs * 1e3 : opts.defaultMs, opts.maxMs);
803
886
  }
804
- function admitMaintenance(host, ctx) {
887
+ function admitMaintenance(host, ctx, owned) {
805
888
  const gate = maintenance.get(host);
806
889
  if (gate === void 0) return "send";
890
+ if (gate === owned && gate.probing) return gate;
807
891
  const now = Date.now();
808
892
  if (!gate.probing && now >= gate.nextProbeAt) {
809
893
  gate.probing = true;
@@ -1445,8 +1529,8 @@ function buildFilter(conditions) {
1445
1529
  if (list.length === 0) {
1446
1530
  throw new AutotaskConfigError("buildFilter requires at least one condition");
1447
1531
  }
1448
- const root = list.length === 1 ? list[0] : { op: "and", items: list };
1449
- const filter = { filter: [root] };
1532
+ const root2 = list.length === 1 ? list[0] : { op: "and", items: list };
1533
+ const filter = { filter: [root2] };
1450
1534
  validateFilter(filter);
1451
1535
  return filter;
1452
1536
  }
@@ -1715,41 +1799,48 @@ function bodySnippet(text, redactPersonalData) {
1715
1799
 
1716
1800
  // src/http/limits.ts
1717
1801
  var HourlyBudget = class {
1718
- constructor(perHour, profile) {
1802
+ constructor(perHour, profile, scope = "local", stamps = []) {
1719
1803
  this.perHour = perHour;
1720
1804
  this.profile = profile;
1805
+ this.scope = scope;
1806
+ this.stamps = stamps;
1721
1807
  }
1722
1808
  perHour;
1723
1809
  profile;
1724
- /** Request timestamps inside the trailing hour. */
1725
- stamps = [];
1810
+ scope;
1811
+ stamps;
1726
1812
  prune(now) {
1727
- while (this.stamps.length > 0 && this.stamps[0] <= now - HOUR_MS) this.stamps.shift();
1813
+ let expired = 0;
1814
+ while (expired < this.stamps.length && this.stamps[expired] <= now - HOUR_MS) expired += 1;
1815
+ if (expired > 0) this.stamps.splice(0, expired);
1728
1816
  }
1729
1817
  snapshot() {
1730
1818
  this.prune(Date.now());
1731
1819
  return { perHour: this.perHour, used: this.stamps.length, remaining: Math.max(0, this.perHour - this.stamps.length) };
1732
1820
  }
1733
- /** Waits for a slot within the call budget, else throws. */
1734
- async take(deadlineAt, signal, ctx) {
1735
- for (; ; ) {
1736
- const now = Date.now();
1737
- this.prune(now);
1738
- if (this.stamps.length < this.perHour) {
1739
- this.stamps.push(now);
1740
- return;
1741
- }
1742
- const waitMs = this.stamps[0] + HOUR_MS - now;
1743
- if (waitMs >= deadlineAt - now) {
1744
- const err = new RateLimitError(`Client-side rateLimit.perHour (${this.perHour}) exhausted; next slot in ${Math.ceil(waitMs / 1e3)}s`, {
1745
- ...ctx,
1746
- 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."
1747
- });
1748
- err.retryAfter = Math.ceil(waitMs / 1e3);
1749
- throw err;
1821
+ /** Non-mutating admission check (apart from pruning); callers can inspect several quotas atomically. */
1822
+ waitMs(now) {
1823
+ this.prune(now);
1824
+ return this.stamps.length < this.perHour ? 0 : Math.max(0, this.stamps[0] + HOUR_MS - now);
1825
+ }
1826
+ /** Record an actual attempt immediately after every applicable quota was checked, without awaiting. */
1827
+ record(now) {
1828
+ this.stamps.push(now);
1829
+ }
1830
+ /** The typed local refusal. Its scope determines advice; the shared ceiling cannot be raised. */
1831
+ exhausted(waitMs, ctx) {
1832
+ const shared = this.scope === "origin";
1833
+ const err = new RateLimitError(
1834
+ 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`,
1835
+ {
1836
+ ...ctx,
1837
+ details: { budgetScope: shared ? "process_origin" : "client" },
1838
+ 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."
1750
1839
  }
1751
- await sleep(waitMs, signal);
1752
- }
1840
+ );
1841
+ err.retryAfter = Math.ceil(waitMs / 1e3);
1842
+ err.notSent = true;
1843
+ return err;
1753
1844
  }
1754
1845
  };
1755
1846
  var Semaphore = class {
@@ -1758,65 +1849,95 @@ var Semaphore = class {
1758
1849
  }
1759
1850
  maxConcurrent;
1760
1851
  inFlight = 0;
1761
- waitQueue = [];
1762
- acquire() {
1852
+ waitQueue = /* @__PURE__ */ new Set();
1853
+ acquire(signal) {
1854
+ if (signal?.aborted) return Promise.reject(signal.reason);
1763
1855
  if (this.inFlight < this.maxConcurrent) {
1764
1856
  this.inFlight += 1;
1765
1857
  return Promise.resolve();
1766
1858
  }
1767
- return new Promise((resolve) => {
1768
- this.waitQueue.push(() => {
1859
+ return new Promise((resolve, reject) => {
1860
+ const aborted = () => {
1861
+ this.waitQueue.delete(grant);
1862
+ signal?.removeEventListener("abort", aborted);
1863
+ reject(signal?.reason);
1864
+ };
1865
+ const grant = () => {
1866
+ signal?.removeEventListener("abort", aborted);
1769
1867
  this.inFlight += 1;
1770
1868
  resolve();
1771
- });
1869
+ };
1870
+ this.waitQueue.add(grant);
1871
+ signal?.addEventListener("abort", aborted, { once: true });
1772
1872
  });
1773
1873
  }
1774
1874
  release() {
1775
1875
  this.inFlight -= 1;
1776
- const next = this.waitQueue.shift();
1777
- if (next !== void 0) next();
1876
+ const next = this.waitQueue.values().next();
1877
+ if (!next.done) {
1878
+ this.waitQueue.delete(next.value);
1879
+ next.value();
1880
+ }
1778
1881
  }
1779
1882
  };
1780
1883
 
1781
- // src/http/credentials.ts
1782
- var CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
1783
- "ApiIntegrationCode",
1784
- "UserName",
1785
- "Secret",
1786
- "ImpersonationResourceId"
1787
- ]);
1788
- function assertCredentialShape(headers, auth) {
1789
- const owned = new Set(CREDENTIAL_HEADER_NAMES);
1790
- for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
1791
- for (const name of Object.keys(headers)) {
1792
- if (!owned.has(name)) continue;
1793
- const value = headers[name];
1794
- const shape = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
1795
- if (shape === void 0) continue;
1796
- throw new AutotaskConfigError(
1797
- `${name} ${CREDENTIAL_ENV_LOAD_ACTION} (${shape})`,
1798
- {
1799
- code: "INVALID_CREDENTIAL_SHAPE",
1800
- 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."
1801
- }
1802
- );
1884
+ // src/http/hourly-gates.ts
1885
+ var ORIGIN_HOURLY_CEILING = 1e4;
1886
+ var REGISTRY = /* @__PURE__ */ Symbol.for("node-autotask.origin-hourly-gates.v1");
1887
+ var root = globalThis;
1888
+ var registry = root[REGISTRY] ??= { budgets: /* @__PURE__ */ new Map(), active: 0, waiting: 0, requests: 0 };
1889
+ function budgetFor(url) {
1890
+ const origin = new URL(url).origin.toLowerCase();
1891
+ let entry = registry.budgets.get(origin);
1892
+ if (entry === void 0) {
1893
+ for (const [key, previous] of registry.budgets) {
1894
+ if (new HourlyBudget(ORIGIN_HOURLY_CEILING, "agent", "origin", previous.stamps).snapshot().used === 0) registry.budgets.delete(key);
1895
+ }
1896
+ entry = { stamps: [] };
1897
+ registry.budgets.set(origin, entry);
1898
+ }
1899
+ return new HourlyBudget(ORIGIN_HOURLY_CEILING, "agent", "origin", entry.stamps);
1900
+ }
1901
+ function admitHourlyAttempt(url, local, now) {
1902
+ const origin = budgetFor(url);
1903
+ const budgets = local === void 0 ? [origin] : [local, origin];
1904
+ let blocked;
1905
+ for (const budget of budgets) {
1906
+ const waitMs = budget.waitMs(now);
1907
+ if (waitMs > (blocked?.waitMs ?? 0)) blocked = { admitted: false, budget, waitMs };
1908
+ }
1909
+ if (blocked !== void 0) return blocked;
1910
+ for (const budget of budgets) budget.record(now);
1911
+ registry.active += 1;
1912
+ let active = true;
1913
+ return { admitted: true, finish: () => {
1914
+ if (active) {
1915
+ active = false;
1916
+ registry.active -= 1;
1917
+ }
1918
+ } };
1919
+ }
1920
+ async function waitHourlyAdmission(blocked, deadlineAt, signal, ctx) {
1921
+ if (signal.aborted) throw signal.reason;
1922
+ const now = Date.now();
1923
+ const waitMs = blocked.budget.waitMs(now);
1924
+ if (waitMs === 0) return;
1925
+ if (waitMs >= deadlineAt - now) throw blocked.budget.exhausted(waitMs, ctx);
1926
+ registry.waiting += 1;
1927
+ try {
1928
+ await sleep(waitMs, signal);
1929
+ } finally {
1930
+ registry.waiting -= 1;
1803
1931
  }
1804
1932
  }
1805
- function credentialShapeExpectation(headers, auth) {
1806
- const owned = new Set(CREDENTIAL_HEADER_NAMES);
1807
- for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
1808
- const names = Object.keys(headers).filter((name) => owned.has(name));
1809
- if (names.length === 0) return void 0;
1810
- let problem;
1811
- for (const name of names) {
1812
- const value = headers[name];
1813
- problem = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
1814
- if (problem !== void 0) break;
1815
- }
1816
- return {
1817
- headerNames: names,
1818
- allValuesClean: problem === void 0,
1819
- ...problem !== void 0 ? { problem } : {}
1933
+ function trackHourlyRequest() {
1934
+ registry.requests += 1;
1935
+ let active = true;
1936
+ return () => {
1937
+ if (active) {
1938
+ active = false;
1939
+ registry.requests -= 1;
1940
+ }
1820
1941
  };
1821
1942
  }
1822
1943
 
@@ -14060,6 +14181,171 @@ var UNTRUSTED_FIELDS_BY_RESOURCE = {
14060
14181
  ]
14061
14182
  };
14062
14183
 
14184
+ // src/http/object-key.ts
14185
+ var UNKNOWN_OBJECT_KEY = "unknown-object";
14186
+ var roots = /* @__PURE__ */ new Map();
14187
+ var byResource = /* @__PURE__ */ new Map();
14188
+ var byKey = /* @__PURE__ */ new Map();
14189
+ function descriptor(row) {
14190
+ const key = row.apiEntity ?? row.resource;
14191
+ let value = byKey.get(key);
14192
+ if (value === void 0) {
14193
+ value = { key, children: /* @__PURE__ */ new Map() };
14194
+ byKey.set(key, value);
14195
+ }
14196
+ return value;
14197
+ }
14198
+ for (const row of Object.values(RELATIONSHIP_MAP)) {
14199
+ const value = descriptor(row);
14200
+ byResource.set(row.resource, value);
14201
+ const path = row.path?.replace(/^\/?v\d+\.\d+\//i, "").replace(/^\//, "");
14202
+ if (path !== void 0 && !path.includes("/")) roots.set(path.toLowerCase(), value);
14203
+ }
14204
+ for (const [alias, resource] of [["expenses", "expense_reports"], ["userdefinedfields", "user_defined_field_definitions"]]) {
14205
+ const value = byResource.get(resource);
14206
+ if (value !== void 0) roots.set(alias, value);
14207
+ }
14208
+ for (const row of Object.values(RELATIONSHIP_MAP)) {
14209
+ const parent = row.parent === null ? void 0 : byResource.get(row.parent.resource);
14210
+ if (parent !== void 0 && row.parent?.segment != null) {
14211
+ parent.children.set(row.parent.segment.toLowerCase(), byResource.get(row.resource));
14212
+ }
14213
+ }
14214
+ function canonicalObjectKey(url) {
14215
+ let path;
14216
+ if (url instanceof URL) {
14217
+ if (url.protocol !== "https:" && url.protocol !== "http:") return UNKNOWN_OBJECT_KEY;
14218
+ path = url.pathname;
14219
+ } else {
14220
+ try {
14221
+ if (/^[a-z][a-z\d+.-]*:/i.test(url)) {
14222
+ const parsed = new URL(url);
14223
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return UNKNOWN_OBJECT_KEY;
14224
+ path = parsed.pathname;
14225
+ } else {
14226
+ if (!url.startsWith("/")) return UNKNOWN_OBJECT_KEY;
14227
+ path = url.split(/[?#]/, 1)[0];
14228
+ }
14229
+ } catch {
14230
+ return UNKNOWN_OBJECT_KEY;
14231
+ }
14232
+ }
14233
+ let parts;
14234
+ try {
14235
+ parts = path.split("/").filter(Boolean).map((part) => decodeURIComponent(part).toLowerCase());
14236
+ } catch {
14237
+ return UNKNOWN_OBJECT_KEY;
14238
+ }
14239
+ if (parts.some((part) => part === "." || part === ".." || /[/\\]/.test(part))) return UNKNOWN_OBJECT_KEY;
14240
+ const version = parts.findIndex((part) => /^v\d+\.\d+$/.test(part));
14241
+ if (version >= 0) {
14242
+ if (parts.slice(0, version).some((part) => roots.has(part))) return UNKNOWN_OBJECT_KEY;
14243
+ parts = parts.slice(version + 1);
14244
+ } else if (parts[0] === "atservicesrest") parts = parts.slice(1);
14245
+ let object = roots.get(parts[0] ?? "");
14246
+ if (object === void 0) return UNKNOWN_OBJECT_KEY;
14247
+ if (object.key === "zone_information") return parts.length === 1 ? void 0 : UNKNOWN_OBJECT_KEY;
14248
+ let offset = 1;
14249
+ while (offset < parts.length) {
14250
+ const part = parts[offset];
14251
+ if (/^\d+$/.test(part)) {
14252
+ offset++;
14253
+ if (offset === parts.length) return object.key;
14254
+ const child = object.children.get(parts[offset]);
14255
+ if (child !== void 0) {
14256
+ object = child;
14257
+ offset++;
14258
+ continue;
14259
+ }
14260
+ }
14261
+ const tail = parts.slice(offset);
14262
+ if (tail[0] === "query") return object.key;
14263
+ if (tail[0] === "entityinformation") return object.key;
14264
+ if (tail.length === 1) return object.key;
14265
+ return UNKNOWN_OBJECT_KEY;
14266
+ }
14267
+ return object.key;
14268
+ }
14269
+
14270
+ // src/http/object-threads.ts
14271
+ var REGISTRY2 = /* @__PURE__ */ Symbol.for("node-autotask.object-thread-gates.v1");
14272
+ var OBJECT_THREAD_LIMIT = 3;
14273
+ var state = globalThis;
14274
+ async function acquireObjectThread(url, trackingIdentifier, signal) {
14275
+ if (signal.aborted) throw signal.reason;
14276
+ const target = new URL(url);
14277
+ const object = canonicalObjectKey(target.pathname);
14278
+ if (object === void 0) return () => void 0;
14279
+ const key = createHash("sha256").update(JSON.stringify([target.origin, trackingIdentifier.trim().toLowerCase(), object])).digest("hex");
14280
+ const registry2 = state[REGISTRY2] ??= /* @__PURE__ */ new Map();
14281
+ let entry = registry2.get(key);
14282
+ if (entry === void 0) {
14283
+ entry = { semaphore: new Semaphore(OBJECT_THREAD_LIMIT), users: 0 };
14284
+ registry2.set(key, entry);
14285
+ }
14286
+ const active = entry;
14287
+ active.users += 1;
14288
+ const leave = () => {
14289
+ active.users -= 1;
14290
+ if (active.users === 0 && registry2.get(key) === active) registry2.delete(key);
14291
+ };
14292
+ try {
14293
+ await active.semaphore.acquire(signal);
14294
+ } catch (error) {
14295
+ leave();
14296
+ throw error;
14297
+ }
14298
+ let released = false;
14299
+ return () => {
14300
+ if (released) return;
14301
+ released = true;
14302
+ active.semaphore.release();
14303
+ leave();
14304
+ };
14305
+ }
14306
+
14307
+ // src/http/credentials.ts
14308
+ var CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
14309
+ "ApiIntegrationCode",
14310
+ "UserName",
14311
+ "Secret",
14312
+ "ImpersonationResourceId"
14313
+ ]);
14314
+ function assertCredentialShape(headers, auth) {
14315
+ const owned = new Set(CREDENTIAL_HEADER_NAMES);
14316
+ for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
14317
+ for (const name of Object.keys(headers)) {
14318
+ if (!owned.has(name)) continue;
14319
+ const value = headers[name];
14320
+ const shape = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
14321
+ if (shape === void 0) continue;
14322
+ throw new AutotaskConfigError(
14323
+ `${name} ${CREDENTIAL_ENV_LOAD_ACTION} (${shape})`,
14324
+ {
14325
+ code: "INVALID_CREDENTIAL_SHAPE",
14326
+ 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."
14327
+ }
14328
+ );
14329
+ }
14330
+ }
14331
+ function credentialShapeExpectation(headers, auth) {
14332
+ const owned = new Set(CREDENTIAL_HEADER_NAMES);
14333
+ for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
14334
+ const names = Object.keys(headers).filter((name) => owned.has(name));
14335
+ if (names.length === 0) return void 0;
14336
+ let problem;
14337
+ for (const name of names) {
14338
+ const value = headers[name];
14339
+ problem = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
14340
+ if (problem !== void 0) break;
14341
+ }
14342
+ return {
14343
+ headerNames: names,
14344
+ allValuesClean: problem === void 0,
14345
+ ...problem !== void 0 ? { problem } : {}
14346
+ };
14347
+ }
14348
+
14063
14349
  // src/http/envelope.ts
14064
14350
  var INVALID_SHAPE_ACTION = "Report the unexpected response shape; verify baseUrl points at the REST API.";
14065
14351
  function attachEmptyReasonDetails(err) {
@@ -14189,38 +14475,45 @@ function canReResolveZone(reResolveZoneOn401, zone, opts) {
14189
14475
  }
14190
14476
  async function discoverZoneBase(userName, maxResponseBytes, signal, ctx) {
14191
14477
  const discoveryUrl = `${ZONE_DISCOVERY_URL}?user=${encodeURIComponent(userName)}`;
14192
- let res;
14193
- try {
14194
- res = await fetch(discoveryUrl, {
14195
- method: "GET",
14196
- headers: { Accept: "application/json" },
14197
- redirect: "manual",
14198
- // a redirect off the discovery host is a fault, not a target
14199
- signal
14200
- });
14201
- } catch {
14202
- return void 0;
14203
- }
14204
- if (res.status < 200 || res.status >= 300) {
14205
- await res.body?.cancel().catch(() => void 0);
14206
- return void 0;
14207
- }
14208
- let text;
14478
+ if (signal.aborted) return void 0;
14479
+ const admission = admitHourlyAttempt(discoveryUrl, void 0, Date.now());
14480
+ if (!admission.admitted) return void 0;
14209
14481
  try {
14210
- text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
14211
- } catch {
14212
- return void 0;
14213
- }
14214
- let body;
14215
- try {
14216
- body = JSON.parse(text);
14217
- } catch {
14218
- return void 0;
14219
- }
14220
- if (!isRecord2(body) || typeof body.url !== "string" || body.url.trim().length === 0) {
14221
- return void 0;
14482
+ let res;
14483
+ try {
14484
+ res = await fetch(discoveryUrl, {
14485
+ method: "GET",
14486
+ headers: { Accept: "application/json" },
14487
+ redirect: "manual",
14488
+ // a redirect off the discovery host is a fault, not a target
14489
+ signal
14490
+ });
14491
+ } catch {
14492
+ return void 0;
14493
+ }
14494
+ if (res.status < 200 || res.status >= 300) {
14495
+ await res.body?.cancel().catch(() => void 0);
14496
+ return void 0;
14497
+ }
14498
+ let text;
14499
+ try {
14500
+ text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
14501
+ } catch {
14502
+ return void 0;
14503
+ }
14504
+ let body;
14505
+ try {
14506
+ body = JSON.parse(text);
14507
+ } catch {
14508
+ return void 0;
14509
+ }
14510
+ if (!isRecord2(body) || typeof body.url !== "string" || body.url.trim().length === 0) {
14511
+ return void 0;
14512
+ }
14513
+ return normalizeZoneBase(body.url);
14514
+ } finally {
14515
+ admission.finish();
14222
14516
  }
14223
- return normalizeZoneBase(body.url);
14224
14517
  }
14225
14518
 
14226
14519
  // src/http/HttpClient.ts
@@ -14337,8 +14630,9 @@ var HttpClient = class {
14337
14630
  /**
14338
14631
  * The LOCAL hourly-budget state (the sliding window this client counts):
14339
14632
  * `{ perHour, used, remaining }` — `undefined` when `rateLimit.perHour`
14340
- * is off. The limiter is PER PROCESS (issue #4): it cannot see other
14341
- * instances or integrations on the tenant — the tenant-wide count is
14633
+ * is off. This optional quota is PER CLIENT (issue #4); the separate
14634
+ * always-on origin ceiling is shared within the JavaScript realm. Neither
14635
+ * measures external integrations — the vendor-wide count is
14342
14636
  * `thresholdInformation.get()`.
14343
14637
  */
14344
14638
  hourlyBudget() {
@@ -14516,16 +14810,20 @@ var HttpClient = class {
14516
14810
  * zone maintenance gate (issue #285), which admits one probe per poll
14517
14811
  * interval while open. An already-aborted caller still gets the abort error.
14518
14812
  */
14519
- gate(s) {
14813
+ gate(s, auditRefusal = true) {
14520
14814
  const cooldown = this.cooldownEnabled && !s.opts.bypassCooldown ? cooldownRefusal(this.tenantKey, s.ctx) : void 0;
14521
- const verdict = cooldown ?? admitMaintenance(this.hostKey, s.ctx);
14815
+ const owned = s.maintenanceProbe?.host === this.hostKey ? s.maintenanceProbe.gate : void 0;
14816
+ const verdict = cooldown ?? admitMaintenance(this.hostKey, s.ctx, owned);
14522
14817
  if (verdict === "send") return;
14523
14818
  if (!(verdict instanceof AutotaskError)) {
14819
+ if (s.maintenanceProbe !== void 0 && (s.maintenanceProbe.host !== this.hostKey || s.maintenanceProbe.gate !== verdict)) {
14820
+ releaseMaintenanceProbe(s.maintenanceProbe.host, s.maintenanceProbe.gate);
14821
+ }
14524
14822
  s.maintenanceProbe = { host: this.hostKey, gate: verdict };
14525
14823
  return;
14526
14824
  }
14527
14825
  if (s.callerSignal?.aborted) throw this.interrupted(s);
14528
- this.auditNotSent(s, verdict.code);
14826
+ if (auditRefusal) this.auditNotSent(s, verdict.code);
14529
14827
  throw verdict;
14530
14828
  }
14531
14829
  // ---- the attempt --------------------------------------------------------
@@ -14536,18 +14834,51 @@ var HttpClient = class {
14536
14834
  */
14537
14835
  async sendOnce(s) {
14538
14836
  const { method, opts, ctx } = s;
14539
- try {
14540
- await this.hourly?.take(s.deadlineAt, s.signal, ctx);
14541
- } catch (err) {
14542
- if (s.signal.aborted) throw this.interrupted(s);
14543
- throw err;
14837
+ let release;
14838
+ for (; ; ) {
14839
+ try {
14840
+ await this.semaphore.acquire(s.signal);
14841
+ } catch (err) {
14842
+ if (s.signal.aborted) throw this.interrupted(s);
14843
+ throw err;
14844
+ }
14845
+ let releaseObject = () => void 0;
14846
+ let finishHourly = () => void 0;
14847
+ let released = false;
14848
+ const releaseCurrent = () => {
14849
+ if (released) return;
14850
+ released = true;
14851
+ finishHourly();
14852
+ releaseObject();
14853
+ this.semaphore.release();
14854
+ };
14855
+ try {
14856
+ releaseObject = await acquireObjectThread(s.url, this.auth.apiIntegrationCode, s.signal);
14857
+ if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
14858
+ this.gate(s, false);
14859
+ if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
14860
+ const admission = admitHourlyAttempt(s.url, this.hourly, Date.now());
14861
+ if (!admission.admitted) {
14862
+ releaseCurrent();
14863
+ await waitHourlyAdmission(admission, s.deadlineAt, s.signal, ctx);
14864
+ continue;
14865
+ }
14866
+ finishHourly = admission.finish;
14867
+ release = releaseCurrent;
14868
+ s.wireAttempts += 1;
14869
+ break;
14870
+ } catch (err) {
14871
+ releaseCurrent();
14872
+ if (s.signal.aborted) throw this.interrupted(s);
14873
+ if ((err instanceof RateLimitError || err instanceof MaintenanceError) && s.wireAttempts > 0) delete err.notSent;
14874
+ throw err;
14875
+ }
14544
14876
  }
14545
- await this.semaphore.acquire();
14546
14877
  let res;
14547
14878
  try {
14548
14879
  res = await fetch(s.url, { method, headers: s.headers, body: s.bodyText, signal: s.signal, redirect: "manual" });
14549
14880
  } catch (err) {
14550
- this.semaphore.release();
14881
+ release();
14551
14882
  if (s.signal.aborted || isAbortLike(err)) throw this.interrupted(s);
14552
14883
  const delay = backoffDelay(s.attempt);
14553
14884
  if (s.attempt < s.maxRetries && s.retriable5xx && await this.retryAfterDelay(s, delay, `network error on ${method} ${opts.path}`)) {
@@ -14571,7 +14902,7 @@ var HttpClient = class {
14571
14902
  }
14572
14903
  text = await readBodyText(res, this.maxResponseBytes, `${method} ${opts.path}`, { ...ctx, httpStatus: status });
14573
14904
  } catch (err) {
14574
- this.semaphore.release();
14905
+ release();
14575
14906
  if (err instanceof AutotaskError) throw err;
14576
14907
  if (s.signal.aborted || isAbortLike(err)) throw this.interrupted(s);
14577
14908
  throw new AutotaskNetworkError(
@@ -14579,7 +14910,7 @@ var HttpClient = class {
14579
14910
  ctx
14580
14911
  );
14581
14912
  }
14582
- this.semaphore.release();
14913
+ release();
14583
14914
  s.lastStatus = status;
14584
14915
  return { retry: false, res, status, text };
14585
14916
  }
@@ -14769,7 +15100,8 @@ var HttpClient = class {
14769
15100
  status: s.lastStatus,
14770
15101
  durationMs: Date.now() - s.started,
14771
15102
  body: s.auditBody,
14772
- errorCode: err instanceof AutotaskError ? err.code : "NETWORK_ERROR"
15103
+ errorCode: err instanceof AutotaskError ? err.code : "NETWORK_ERROR",
15104
+ ...s.wireAttempts === 0 ? { notSent: true } : {}
14773
15105
  });
14774
15106
  if (this.fieldCache !== void 0 && err instanceof AutotaskError) {
14775
15107
  const op = typeof opts.operation === "string" ? opts.operation : void 0;
@@ -14852,12 +15184,14 @@ var HttpClient = class {
14852
15184
  lastStatus: void 0,
14853
15185
  zoneRetry: void 0,
14854
15186
  attempt: 0,
15187
+ wireAttempts: 0,
14855
15188
  maintenanceProbe: void 0,
14856
15189
  maintenancePage: false,
14857
15190
  // Armed LAST in the literal: nothing after this can throw, and the single
14858
15191
  // try/finally below clears it on every exit path (#190).
14859
15192
  deadlineTimer: setTimeout(() => deadline.abort(), timeoutMs)
14860
15193
  };
15194
+ const finishRequest = trackHourlyRequest();
14861
15195
  try {
14862
15196
  this.gate(s);
14863
15197
  this.logger.debug?.(`[autotask] ${method} ${opts.path}`, correlationId);
@@ -14879,10 +15213,11 @@ var HttpClient = class {
14879
15213
  this.onFailure(s, err);
14880
15214
  throw err;
14881
15215
  } finally {
14882
- this.invalidateAfterWrite(opts);
15216
+ if (s.wireAttempts > 0) this.invalidateAfterWrite(opts);
14883
15217
  }
14884
15218
  } finally {
14885
15219
  clearTimeout(s.deadlineTimer);
15220
+ finishRequest();
14886
15221
  if (s.maintenanceProbe !== void 0) releaseMaintenanceProbe(s.maintenanceProbe.host, s.maintenanceProbe.gate);
14887
15222
  }
14888
15223
  }
@@ -14953,17 +15288,14 @@ async function collectAll(fetchPage, opts = {}) {
14953
15288
  return all;
14954
15289
  }
14955
15290
 
14956
- // src/search/company-names.ts
14957
- var LEGAL_SUFFIXES = /* @__PURE__ */ new Set(["pty", "ltd", "limited", "inc", "llc", "co", "corp", "gmbh"]);
14958
- var STOPWORDS = /* @__PURE__ */ new Set(["the", "and", "of"]);
14959
- function normaliseCompanyName(value) {
14960
- return value.normalize("NFKD").replace(new RegExp("\\p{M}+", "gu"), "").toLowerCase().replace(/&/g, " and ").replace(/[^\p{L}\p{N}]+/gu, " ").split(/\s+/).filter((t) => t && t !== "the").join(" ");
15291
+ // src/search/fuzzy-text.ts
15292
+ function normaliseText(value, options = {}) {
15293
+ let folded = value.normalize("NFKD").replace(new RegExp("\\p{M}+", "gu"), "").toLowerCase();
15294
+ if (options.ampersandAsAnd) folded = folded.replace(/&/g, " and ");
15295
+ return folded.replace(/[^\p{L}\p{N}]+/gu, " ").split(/\s+/).filter((term) => term && !options.excludeTerms?.has(term)).join(" ");
14961
15296
  }
14962
- function companyTerms(value) {
14963
- return normaliseCompanyName(value).split(" ").filter((t) => t && !LEGAL_SUFFIXES.has(t) && !STOPWORDS.has(t));
14964
- }
14965
- function companyDedupeName(value) {
14966
- return normaliseCompanyName(value).split(" ").filter((t) => !LEGAL_SUFFIXES.has(t)).join(" ");
15297
+ function textTerms(value, normalise = normaliseText, excludeTerms) {
15298
+ return normalise(value).split(" ").filter((term) => term && !excludeTerms?.has(term));
14967
15299
  }
14968
15300
  function ngramsOf(token) {
14969
15301
  if (token.length < 3) return [token];
@@ -14999,6 +15331,67 @@ function editDistanceAtMost(a, b, k) {
14999
15331
  }
15000
15332
  return previous[b.length];
15001
15333
  }
15334
+ function textFragments(terms) {
15335
+ const pieces = /* @__PURE__ */ new Set();
15336
+ const prefixes = /* @__PURE__ */ new Set();
15337
+ const longest = [...terms].sort((a, b) => b.length - a.length || a.localeCompare(b)).slice(0, 2);
15338
+ for (const word of longest) {
15339
+ const count = Math.max(1, Math.min(editBudget(word) + 1, Math.floor(word.length / 4)));
15340
+ for (let i = 0; i < count; i++) pieces.add(word.slice(Math.floor(i * word.length / count), Math.floor((i + 1) * word.length / count)));
15341
+ if (word.length >= 4 && word.length <= 6) prefixes.add(word.slice(0, 3));
15342
+ }
15343
+ if (terms.length > 1) pieces.add(terms.join(""));
15344
+ return { pieces: [...pieces], prefixes: [...prefixes] };
15345
+ }
15346
+ function scoreTerms(terms, words) {
15347
+ const candidates = [...words, words.join("")];
15348
+ const matchedTerms = [];
15349
+ let distance = 0;
15350
+ for (const term of terms) {
15351
+ const budget = editBudget(term);
15352
+ const best = Math.min(budget + 1, ...candidates.map((word) => editDistanceAtMost(term, word, budget)));
15353
+ if (best <= budget) {
15354
+ matchedTerms.push(term);
15355
+ distance += best;
15356
+ }
15357
+ }
15358
+ if (terms.length > 1) {
15359
+ const compact = terms.join("");
15360
+ const budget = editBudget(compact);
15361
+ const best = Math.min(budget + 1, ...candidates.map((word) => editDistanceAtMost(compact, word, budget)));
15362
+ if (best <= budget && matchedTerms.length < terms.length) return { coverage: terms.length, distance: best, matchedTerms: [...terms] };
15363
+ }
15364
+ return matchedTerms.length === 0 ? void 0 : { coverage: matchedTerms.length, distance, matchedTerms };
15365
+ }
15366
+ function compareTermScores(a, b) {
15367
+ return b.coverage - a.coverage || a.distance - b.distance;
15368
+ }
15369
+ function vocabularyCandidates(vocabulary, terms) {
15370
+ const keys = /* @__PURE__ */ new Set();
15371
+ for (const term of terms) {
15372
+ const budget = editBudget(term);
15373
+ const words = [...vocabulary.keys()].filter((word) => Math.abs(word.length - term.length) <= budget).map((word) => ({ word, dice: diceCoefficient(term, word) })).sort((a, b) => b.dice - a.dice);
15374
+ for (const { word } of words) if (editDistanceAtMost(term, word, budget) <= budget) {
15375
+ for (const key of vocabulary.get(word)) keys.add(key);
15376
+ }
15377
+ }
15378
+ return keys;
15379
+ }
15380
+
15381
+ // src/search/company-names.ts
15382
+ var LEGAL_SUFFIXES = /* @__PURE__ */ new Set(["pty", "ltd", "limited", "inc", "llc", "co", "corp", "gmbh"]);
15383
+ var STOPWORDS = /* @__PURE__ */ new Set(["the", "and", "of"]);
15384
+ var NAME_EXCLUSIONS = /* @__PURE__ */ new Set(["the"]);
15385
+ var SCORE_EXCLUSIONS = /* @__PURE__ */ new Set([...LEGAL_SUFFIXES, ...STOPWORDS]);
15386
+ function normaliseCompanyName(value) {
15387
+ return normaliseText(value, { ampersandAsAnd: true, excludeTerms: NAME_EXCLUSIONS });
15388
+ }
15389
+ function companyTerms(value) {
15390
+ return textTerms(value, normaliseCompanyName, SCORE_EXCLUSIONS);
15391
+ }
15392
+ function companyDedupeName(value) {
15393
+ return textTerms(value, normaliseCompanyName, LEGAL_SUFFIXES).join(" ");
15394
+ }
15002
15395
 
15003
15396
  // src/search/company-index.ts
15004
15397
  var COMPANY_INDEX_WRITE_DEBOUNCE_MS = 1e3;
@@ -15072,18 +15465,9 @@ var CompanyNameIndex = class {
15072
15465
  if (this.timer) clearTimeout(this.timer);
15073
15466
  if (this.started) this.start(COMPANY_INDEX_WRITE_DEBOUNCE_MS);
15074
15467
  }
15075
- /** Candidate generation uses n-gram Dice order, then the edit bound as authority.
15076
- * A Dice floor would lose valid short-word swaps, so zero-overlap vocabulary
15077
- * remains eligible when its length is within the edit budget. */
15468
+ /** The index owns company rows; the shared engine selects vocabulary keys. */
15078
15469
  candidates(terms) {
15079
- const ids2 = /* @__PURE__ */ new Set();
15080
- for (const term of terms) {
15081
- const budget = editBudget(term);
15082
- const words = [...this.vocabulary.keys()].filter((word) => Math.abs(word.length - term.length) <= budget).map((word) => ({ word, dice: diceCoefficient(term, word) })).sort((a, b) => b.dice - a.dice);
15083
- for (const { word } of words) if (editDistanceAtMost(term, word, budget) <= budget) {
15084
- for (const id of this.vocabulary.get(word)) ids2.add(id);
15085
- }
15086
- }
15470
+ const ids2 = vocabularyCandidates(this.vocabulary, terms);
15087
15471
  return [...ids2].map((id) => ({ ...this.rows.get(id) }));
15088
15472
  }
15089
15473
  schedule(delay, fn) {
@@ -15744,6 +16128,64 @@ function entityNameFromPath(resourcePath) {
15744
16128
  return snake;
15745
16129
  }
15746
16130
 
16131
+ // src/utils/bounded.ts
16132
+ async function runBounded(fn, items, opts) {
16133
+ const { concurrency, signal, settle } = opts;
16134
+ if (!Number.isInteger(concurrency) || concurrency <= 0) {
16135
+ throw new AutotaskConfigError("batch concurrency must be a positive integer");
16136
+ }
16137
+ const results = new Array(items.length);
16138
+ let next = 0;
16139
+ let failure;
16140
+ const fail = (error, index) => {
16141
+ if (failure === void 0 || opts.orderedErrors === true && index < failure.index) failure = { error, index };
16142
+ };
16143
+ const worker = async () => {
16144
+ while (failure === void 0 && next < items.length) {
16145
+ if (signal?.aborted) {
16146
+ fail(signal.reason, -1);
16147
+ return;
16148
+ }
16149
+ const i = next++;
16150
+ try {
16151
+ const item = items[i];
16152
+ const value = await (signal === void 0 ? fn(item) : runWithSignal(signal, () => fn(item)));
16153
+ results[i] = settle ? { status: "fulfilled", value } : value;
16154
+ } catch (error) {
16155
+ if (settle) results[i] = { status: "rejected", reason: error };
16156
+ else fail(error, i);
16157
+ }
16158
+ }
16159
+ };
16160
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
16161
+ if (failure !== void 0) throw failure.error;
16162
+ return results;
16163
+ }
16164
+ async function mapReadTasks(http, items, fn) {
16165
+ const signal = ambientCallerSignal();
16166
+ const abort = () => new AutotaskAbortError("Read fan-out aborted by the caller");
16167
+ if (signal?.aborted) throw abort();
16168
+ try {
16169
+ const results = await runBounded(fn, items, { concurrency: http.maxConcurrent, orderedErrors: true, ...signal === void 0 ? {} : { signal } });
16170
+ if (signal?.aborted) throw abort();
16171
+ return results;
16172
+ } catch (error) {
16173
+ if (signal?.aborted && !(error instanceof AutotaskAbortError)) throw abort();
16174
+ throw error;
16175
+ }
16176
+ }
16177
+ function readTasks(http, tasks) {
16178
+ return mapReadTasks(http, tasks, (task) => task());
16179
+ }
16180
+
16181
+ // src/operations/nameSnapshot.ts
16182
+ function nameRecordSnapshot(cache, path, id, operation) {
16183
+ const body = cache?.get(path);
16184
+ if (body === void 0) return void 0;
16185
+ const entity = path.split("/").at(-2);
16186
+ return () => unwrapItem(body, id, operation, entity);
16187
+ }
16188
+
15747
16189
  // src/operations/expandResourceNames.ts
15748
16190
  var EXPAND_RESOURCE_NAMES_MAX_IDS = 500;
15749
16191
  function composeName(record) {
@@ -15754,6 +16196,27 @@ function composeName(record) {
15754
16196
  }
15755
16197
  return parts.length > 0 ? parts.join(" ") : null;
15756
16198
  }
16199
+ function resourceNameFailure(err) {
16200
+ if (err instanceof NotFoundError) return { name: null, blind: true };
16201
+ if (isAutotaskError(err) && err.code !== "ABORTED") {
16202
+ const error = { code: err.code, message: err.message };
16203
+ if (err.httpStatus !== void 0) error.httpStatus = err.httpStatus;
16204
+ return { name: null, blind: false, error };
16205
+ }
16206
+ throw err;
16207
+ }
16208
+ function resourceNameSnapshot(cache, id) {
16209
+ if (cache === void 0) return void 0;
16210
+ const path = `/V1.0/Resources/${id}`;
16211
+ if (cache.get(contextAbsentKey(path)) !== void 0) return { name: null, blind: true };
16212
+ const record = nameRecordSnapshot(cache, path, id, "resources.get");
16213
+ if (record === void 0) return void 0;
16214
+ try {
16215
+ return { name: composeName(record()), blind: false };
16216
+ } catch (err) {
16217
+ return resourceNameFailure(err);
16218
+ }
16219
+ }
15757
16220
  async function expandResourceNames(client, ids2, opts = {}) {
15758
16221
  if (opts.maxIds !== void 0 && (!Number.isInteger(opts.maxIds) || opts.maxIds < 1)) {
15759
16222
  throw new AutotaskConfigError(`expandResourceNames: maxIds must be an integer >= 1 (got ${String(opts.maxIds)})`);
@@ -15806,13 +16269,21 @@ async function expandResourceNames(client, ids2, opts = {}) {
15806
16269
  const holder = client.resources;
15807
16270
  const cache = client.http.readCache;
15808
16271
  const fresh = opts.fresh === true;
16272
+ const warm = /* @__PURE__ */ new Map();
16273
+ if (!fresh) {
16274
+ for (const id of unique) {
16275
+ const snapshot = resourceNameSnapshot(cache, id);
16276
+ if (snapshot !== void 0) warm.set(String(id), snapshot);
16277
+ }
16278
+ }
15809
16279
  const byId2 = /* @__PURE__ */ new Map();
15810
- for (const id of unique) {
16280
+ await mapReadTasks(client.http, unique, async (id) => {
15811
16281
  const k = String(id);
15812
16282
  const absentKey = contextAbsentKey(`/V1.0/Resources/${k}`);
15813
- if (cache !== void 0 && !fresh && cache.get(absentKey) !== void 0) {
15814
- byId2.set(k, { name: null, blind: true });
15815
- continue;
16283
+ const snapshot = warm.get(k);
16284
+ if (snapshot !== void 0) {
16285
+ byId2.set(k, snapshot);
16286
+ return;
15816
16287
  }
15817
16288
  const epoch = cache?.epoch ?? 0;
15818
16289
  try {
@@ -15823,17 +16294,11 @@ async function expandResourceNames(client, ids2, opts = {}) {
15823
16294
  if (err instanceof NotFoundError) {
15824
16295
  cache?.set(absentKey, CONTEXT_ABSENT_MARKER, epoch);
15825
16296
  byId2.set(k, { name: null, blind: true });
15826
- continue;
15827
- }
15828
- if (isAutotaskError(err) && err.code !== "ABORTED") {
15829
- const e = { code: err.code, message: err.message };
15830
- if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
15831
- byId2.set(k, { name: null, blind: false, error: e });
15832
- continue;
16297
+ return;
15833
16298
  }
15834
- throw err;
16299
+ byId2.set(k, resourceNameFailure(err));
15835
16300
  }
15836
- }
16301
+ });
15837
16302
  const results = [];
15838
16303
  for (const id of canonical) {
15839
16304
  const out = byId2.get(String(id));
@@ -15998,6 +16463,13 @@ var FK_TABLE_PATH = {
15998
16463
  company: "/V1.0/Companies",
15999
16464
  ticket: "/V1.0/Tickets"
16000
16465
  };
16466
+ var FK_GET_OPERATION = {
16467
+ role: "roles.get",
16468
+ billingCode: "billing_codes.get",
16469
+ contract: "contracts.get",
16470
+ company: "companies.get",
16471
+ ticket: "tickets.get"
16472
+ };
16001
16473
  var FK_NAME_FIELD = {
16002
16474
  role: "name",
16003
16475
  billingCode: "name",
@@ -16029,13 +16501,15 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16029
16501
  const readCache = http.readCache;
16030
16502
  const section = { truncated: false, rows: {}, reasons: {} };
16031
16503
  let remaining = budget;
16504
+ const tasks = [];
16032
16505
  let contractLobPointer;
16033
16506
  let contractLobUnread;
16034
16507
  const coldResource = [];
16508
+ const warmResources = /* @__PURE__ */ new Map();
16035
16509
  for (const id of plan.resourceIds) {
16036
- const path = `/V1.0/Resources/${id}`;
16037
- if (readCache !== void 0 && (readCache.peek(path).hit || readCache.peek(contextAbsentKey(path)).hit)) continue;
16038
- coldResource.push(id);
16510
+ const snapshot = resourceNameSnapshot(readCache, id);
16511
+ if (snapshot === void 0) coldResource.push(id);
16512
+ else warmResources.set(String(id), snapshot);
16039
16513
  }
16040
16514
  const withinBudget = coldResource.slice(0, remaining);
16041
16515
  const overBudgetResource = coldResource.slice(remaining);
@@ -16055,12 +16529,21 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16055
16529
  }
16056
16530
  pass = pass.slice(0, 500);
16057
16531
  }
16058
- const res = await expandResourceNames(client, pass);
16059
- for (const r of res.results) {
16060
- const row = { name: r.name, blind: r.blind };
16061
- if (r.error !== void 0) row.error = faultRow(r.error);
16062
- section.rows[`resource:${r.id}`] = row;
16063
- }
16532
+ tasks.push(async () => {
16533
+ const cold = pass.filter((id) => !warmResources.has(String(id)));
16534
+ const outcomes = new Map(warmResources);
16535
+ if (cold.length > 0) {
16536
+ for (const row of (await expandResourceNames(client, cold)).results) outcomes.set(String(row.id), row);
16537
+ }
16538
+ return () => {
16539
+ for (const id of pass) {
16540
+ const r = outcomes.get(String(id));
16541
+ const row = { name: r.name, blind: r.blind };
16542
+ if (r.error !== void 0) row.error = faultRow(r.error);
16543
+ section.rows[`resource:${id}`] = row;
16544
+ }
16545
+ };
16546
+ });
16064
16547
  }
16065
16548
  const holders = {
16066
16549
  role: client.roles,
@@ -16071,10 +16554,13 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16071
16554
  };
16072
16555
  for (const fk2 of plan.recordFks) {
16073
16556
  const key = `${fk2.table}:${fk2.id}`;
16074
- const cold = readCache === void 0 || readCache.get(`${FK_TABLE_PATH[fk2.table]}/${fk2.id}`) === void 0;
16557
+ const snapshot = nameRecordSnapshot(readCache, `${FK_TABLE_PATH[fk2.table]}/${fk2.id}`, fk2.id, FK_GET_OPERATION[fk2.table]);
16558
+ const cold = snapshot === void 0;
16075
16559
  if (cold) {
16076
16560
  if (remaining < 1) {
16077
- section.rows[key] = { name: null, blind: false };
16561
+ tasks.push(async () => () => {
16562
+ section.rows[key] = { name: null, blind: false };
16563
+ });
16078
16564
  section.truncated = true;
16079
16565
  if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16080
16566
  contractLobUnread = "capped";
@@ -16083,41 +16569,51 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16083
16569
  }
16084
16570
  remaining -= 1;
16085
16571
  }
16086
- try {
16087
- const record = await holders[fk2.table].get(fk2.id);
16088
- if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16089
- contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
16090
- }
16091
- section.rows[key] = { name: fkName(record, fk2.table), blind: false };
16092
- } catch (err) {
16093
- if (err instanceof NotFoundError) {
16094
- section.rows[key] = { name: null, blind: true };
16095
- } else if (isAutotaskError(err) && err.code !== "ABORTED") {
16096
- section.rows[key] = { name: null, blind: false, error: faultRow(err) };
16097
- if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16098
- contractLobUnread = "unresolved";
16572
+ tasks.push(async () => {
16573
+ let row;
16574
+ try {
16575
+ const record = snapshot !== void 0 ? snapshot() : await holders[fk2.table].get(fk2.id);
16576
+ if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16577
+ contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
16578
+ }
16579
+ row = { name: fkName(record, fk2.table), blind: false };
16580
+ } catch (err) {
16581
+ if (err instanceof NotFoundError) {
16582
+ row = { name: null, blind: true };
16583
+ } else if (isAutotaskError(err) && err.code !== "ABORTED") {
16584
+ row = { name: null, blind: false, error: faultRow(err) };
16585
+ if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16586
+ contractLobUnread = "unresolved";
16587
+ }
16588
+ } else {
16589
+ throw err;
16099
16590
  }
16100
- } else {
16101
- throw err;
16102
16591
  }
16103
- }
16592
+ return () => {
16593
+ section.rows[key] = row;
16594
+ };
16595
+ });
16104
16596
  }
16105
16597
  const picklists = {};
16106
16598
  if (plan.labelFields.length > 0) {
16107
- try {
16108
- const labelResource = plan.labelResource ?? "tickets";
16109
- const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
16110
- const row = catalog.rows.find((r) => r.resource === labelResource);
16111
- if (row !== void 0 && row.error === null && row.fields !== void 0) {
16112
- for (const f of plan.labelFields) {
16113
- const frow = row.fields.find((x) => x.name === f);
16114
- picklists[f] = frow?.picklistValues;
16599
+ tasks.push(async () => {
16600
+ try {
16601
+ const labelResource = plan.labelResource ?? "tickets";
16602
+ const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
16603
+ const row = catalog.rows.find((r) => r.resource === labelResource);
16604
+ if (row !== void 0 && row.error === null && row.fields !== void 0) {
16605
+ for (const f of plan.labelFields) {
16606
+ const frow = row.fields.find((x) => x.name === f);
16607
+ picklists[f] = frow?.picklistValues;
16608
+ }
16115
16609
  }
16610
+ } catch (err) {
16611
+ if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16116
16612
  }
16117
- } catch (err) {
16118
- if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16119
- }
16613
+ return () => void 0;
16614
+ });
16120
16615
  }
16616
+ for (const merge of await readTasks(http, tasks)) merge();
16121
16617
  let lineOfBusiness2 = null;
16122
16618
  const lobId = plan.lineOfBusinessId ?? contractLobPointer;
16123
16619
  if (lobId !== void 0) {
@@ -16192,6 +16688,61 @@ var BOUNDED_QUERY_MAX_LIMIT = 2500;
16192
16688
  var LATEST_MAX_COUNT_PROBES = 64;
16193
16689
  var MARKER_RECOVERY_LIMIT = 5;
16194
16690
 
16691
+ // src/read-cache.ts
16692
+ var READ_FAILURE_OBSERVER = /* @__PURE__ */ Symbol("record read failure observer");
16693
+ function observeRecordReadFailures(http, observer) {
16694
+ Object.defineProperty(http, READ_FAILURE_OBSERVER, { value: observer });
16695
+ }
16696
+ function subscriberError(error, operation) {
16697
+ const copies = /* @__PURE__ */ new Map();
16698
+ const copyValue = (value) => {
16699
+ if (value === null || typeof value !== "object") return value;
16700
+ if (!(value instanceof Error) && !isRecord(value) && !Array.isArray(value)) return value;
16701
+ const prior = copies.get(value);
16702
+ if (prior !== void 0) return prior;
16703
+ const copy = value instanceof Error ? Object.setPrototypeOf(new Error(value.message), Object.getPrototypeOf(value)) : Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
16704
+ copies.set(value, copy);
16705
+ const descriptors = Object.getOwnPropertyDescriptors(value);
16706
+ if (value === error) descriptors.operation = { ...descriptors.operation, value: operation };
16707
+ for (const key of Reflect.ownKeys(descriptors)) {
16708
+ const descriptor2 = descriptors[key];
16709
+ if ("value" in descriptor2) descriptor2.value = copyValue(descriptor2.value);
16710
+ }
16711
+ Object.defineProperties(copy, descriptors);
16712
+ if (value instanceof Error && descriptors.stack?.set !== void 0) descriptors.stack.set.call(copy, value.stack);
16713
+ return copy;
16714
+ };
16715
+ return copyValue(error);
16716
+ }
16717
+ function cachedRecordGet(http, path, operation, fresh = false) {
16718
+ const cache = http.readCache;
16719
+ if (cache === void 0) return http.request({ method: "GET", path, operation });
16720
+ let ownsLoader = false;
16721
+ const loader = (signal) => {
16722
+ ownsLoader = true;
16723
+ return http.request({ method: "GET", path, operation, signal });
16724
+ };
16725
+ const options = {
16726
+ signal: ambientCallerSignal(),
16727
+ fresh,
16728
+ abortError: () => new AutotaskAbortError(`Request aborted: GET ${path}`, {
16729
+ operation,
16730
+ suggestedAction: "The caller aborted; re-issue the call if still needed."
16731
+ })
16732
+ };
16733
+ return cache.load(path, loader, options).catch((error) => {
16734
+ if (ownsLoader || !(error instanceof AutotaskError) || error.details?.budgetScope !== "client" || error.notSent !== true) throw error;
16735
+ if (options.signal?.aborted) throw options.abortError();
16736
+ const warm = cache.get(path);
16737
+ return warm !== void 0 ? warm : cache.load(path, loader, { ...options, fresh: true });
16738
+ }).catch((error) => {
16739
+ if (!(error instanceof AutotaskError)) throw error;
16740
+ const failure = subscriberError(error, operation);
16741
+ http[READ_FAILURE_OBSERVER]?.(failure);
16742
+ throw failure;
16743
+ });
16744
+ }
16745
+
16195
16746
  // src/field-sets.ts
16196
16747
  var MODEL_FIELD_SETS = {
16197
16748
  "appointments": ["id", "createDateTime", "creatorResourceID", "description", "endDateTime", "resourceID", "startDateTime", "title", "updateDateTime"],
@@ -16604,14 +17155,14 @@ async function labelRows(client, resourceKey, rows) {
16604
17155
  return { rows: out, names: { note: parts.join("; "), ...Object.keys(names.section.reasons).length > 0 ? { reasons: names.section.reasons } : {} } };
16605
17156
  }
16606
17157
  async function labelFetchResults(client, result) {
16607
- const byResource = /* @__PURE__ */ new Map();
17158
+ const byResource2 = /* @__PURE__ */ new Map();
16608
17159
  result.results.forEach((r, i) => {
16609
- if (r.found && r.value !== null) byResource.set(r.resource, [...byResource.get(r.resource) ?? [], i]);
17160
+ if (r.found && r.value !== null) byResource2.set(r.resource, [...byResource2.get(r.resource) ?? [], i]);
16610
17161
  });
16611
17162
  const results = [...result.results];
16612
17163
  const notes = [];
16613
17164
  const reasons = {};
16614
- for (const [resource, indices] of byResource) {
17165
+ for (const [resource, indices] of byResource2) {
16615
17166
  const labelled = await labelRows(client, resource, indices.map((i) => results[i].value));
16616
17167
  indices.forEach((idx, j) => {
16617
17168
  results[idx] = { ...results[idx], value: labelled.rows[j] };
@@ -16681,7 +17232,7 @@ var QueryBase = class {
16681
17232
  // Query walk (wired to the G3 walker; cursor-follow per the pinned wire)
16682
17233
  // ------------------------------------------------------------------
16683
17234
  /** One page fetch: page 1 POSTs the QueryModel body; later pages POST the same body (`buildQueryBody`) to the absolute cursor (issue #118). */
16684
- async fetchPage(params, page, pageSize, state) {
17235
+ async fetchPage(params, page, pageSize, state2) {
16685
17236
  if (params.includeFields !== void 0) {
16686
17237
  params = { ...params, includeFields: params.includeFields.map((field) => normalizeOwnField(this.config.key, field)) };
16687
17238
  }
@@ -16689,9 +17240,9 @@ var QueryBase = class {
16689
17240
  if (page === 1) {
16690
17241
  const req = buildQueryRequest(this.http.baseUrl, this.resourcePath, { ...params, maxRecords: pageSize });
16691
17242
  const body2 = await this.http.request({ ...req, operation });
16692
- return this.readPage(body2, page, pageSize, state);
17243
+ return this.readPage(body2, page, pageSize, state2);
16693
17244
  }
16694
- const cursor = state.cursor;
17245
+ const cursor = state2.cursor;
16695
17246
  if (cursor === null) {
16696
17247
  throw new AutotaskError(`No pagination cursor available for page ${page} of ${operation}`, {
16697
17248
  code: "INVALID_RESPONSE",
@@ -16707,13 +17258,13 @@ var QueryBase = class {
16707
17258
  operation,
16708
17259
  idempotent: true
16709
17260
  });
16710
- return this.readPage(res, page, pageSize, state);
17261
+ return this.readPage(res, page, pageSize, state2);
16711
17262
  }
16712
17263
  /** @internal */
16713
- readPage(body, page, pageSize, state) {
17264
+ readPage(body, page, pageSize, state2) {
16714
17265
  const { items, pageDetails } = unwrapItems(body, `${this.config.key}.query`);
16715
- state.cursor = pageDetails.nextPageUrl ?? null;
16716
- const hasMore = state.cursor !== null;
17266
+ state2.cursor = pageDetails.nextPageUrl ?? null;
17267
+ const hasMore = state2.cursor !== null;
16717
17268
  return {
16718
17269
  items,
16719
17270
  page,
@@ -16727,9 +17278,9 @@ var QueryBase = class {
16727
17278
  }
16728
17279
  /** Build the per-walk fetcher (closure keeps cursor state private to this walk). */
16729
17280
  pageFetcher(params) {
16730
- const state = { cursor: null };
17281
+ const state2 = { cursor: null };
16731
17282
  const p = params ?? {};
16732
- return (page, pageSize) => this.fetchPage(p, page, pageSize, state);
17283
+ return (page, pageSize) => this.fetchPage(p, page, pageSize, state2);
16733
17284
  }
16734
17285
  /** @internal */
16735
17286
  walkPageSize(params) {
@@ -16894,7 +17445,7 @@ var QueryBase = class {
16894
17445
  * state).
16895
17446
  * @internal */
16896
17447
  async walkBounded(p, limit, pageSizeBase, labelPages = false) {
16897
- const state = { cursor: null };
17448
+ const state2 = { cursor: null };
16898
17449
  const items = [];
16899
17450
  let pages2 = 0;
16900
17451
  let sliced = 0;
@@ -16907,7 +17458,7 @@ var QueryBase = class {
16907
17458
  guard = true;
16908
17459
  break;
16909
17460
  }
16910
- const page = await this.fetchPage(p, pages2 + 1, pageSize, state);
17461
+ const page = await this.fetchPage(p, pages2 + 1, pageSize, state2);
16911
17462
  pages2 += 1;
16912
17463
  if (labelPages && this.http.client !== void 0) {
16913
17464
  const labelled = await labelRows(this.http.client, this.config.key, page.items);
@@ -16928,7 +17479,7 @@ var QueryBase = class {
16928
17479
  note: [...nameNotes].join("; "),
16929
17480
  ...Object.keys(nameReasons).length === 0 ? {} : { reasons: nameReasons }
16930
17481
  };
16931
- return { items, pages: pages2, guard, sliced, cursor: state.cursor, ...names === void 0 ? {} : { names } };
17482
+ return { items, pages: pages2, guard, sliced, cursor: state2.cursor, ...names === void 0 ? {} : { names } };
16932
17483
  }
16933
17484
  /** A walk stop is TRUNCATED when the 1000-page guard fired, or the limit
16934
17485
  * was met with a live next cursor (or a sliced final page): rows exist
@@ -17201,17 +17752,11 @@ var MetaBase = class extends QueryBase {
17201
17752
  * and the composite ROOT read of a hot resource (issue #36 — the
17202
17753
  * ticket-composite root) must see the live record, never a snapshot.
17203
17754
  * The entry's TTL follows the path (`readTtlFor`: reference tables 1 h).
17755
+ * Equivalent non-fresh misses share one request through the cache loader;
17756
+ * the ambient signal belongs to this subscriber, never to the shared wire.
17204
17757
  * @internal */
17205
17758
  async cachedGet(path, operation, fresh = false) {
17206
- const cache = this.http.readCache;
17207
- if (cache !== void 0 && !fresh) {
17208
- const hit = cache.get(path);
17209
- if (hit !== void 0) return hit;
17210
- }
17211
- const epoch = cache?.epoch;
17212
- const res = await this.http.request({ method: "GET", path, operation });
17213
- cache?.set(path, res, epoch);
17214
- return res;
17759
+ return cachedRecordGet(this.http, path, operation, fresh);
17215
17760
  }
17216
17761
  /**
17217
17762
  * Entity-metadata read through the opt-in field cache (issue #31; off by
@@ -17560,8 +18105,8 @@ var MetaBase = class extends QueryBase {
17560
18105
  );
17561
18106
  }
17562
18107
  const leaf = fields.map((field) => ({ field, op: "eq", value }));
17563
- const root = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
17564
- const items = await this.queryPage1([root], 2);
18108
+ const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18109
+ const items = await this.queryPage1([root2], 2);
17565
18110
  if (items.length === 1) {
17566
18111
  return { value: items[0], resolutionCost: "server-filter", scanned: 0, scanTruncated: false };
17567
18112
  }
@@ -17667,13 +18212,13 @@ var MetaBase = class extends QueryBase {
17667
18212
  async scanForExactMatch(value, fields) {
17668
18213
  const caps = this.resolutionCaps;
17669
18214
  const pageSize = Math.max(1, Math.floor(caps.maxScanRecords / caps.maxScanPages));
17670
- const state = { cursor: null };
18215
+ const state2 = { cursor: null };
17671
18216
  let scanned = 0;
17672
18217
  let pages2 = 0;
17673
18218
  let found = null;
17674
18219
  let exhausted = false;
17675
18220
  for (; ; ) {
17676
- const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state);
18221
+ const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state2);
17677
18222
  pages2 += 1;
17678
18223
  for (const item of page.items) {
17679
18224
  scanned += 1;
@@ -17728,7 +18273,7 @@ var MetaBase = class extends QueryBase {
17728
18273
  }
17729
18274
  const limit = opts.limit === void 0 ? 25 : clampPageSize(opts.limit);
17730
18275
  const leaf = fields.map((field) => ({ field, op: "contains", value: text }));
17731
- const root = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18276
+ const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
17732
18277
  for (const key of Object.keys(opts)) {
17733
18278
  if (key !== "limit" && key !== "companyID" && key !== "includeFields") {
17734
18279
  throw new AutotaskConfigError(`search: unknown opts key "${key}" \u2014 the bag is closed: limit, companyID, includeFields`);
@@ -17742,7 +18287,7 @@ var MetaBase = class extends QueryBase {
17742
18287
  }
17743
18288
  const companyID = opts.companyID === void 0 ? void 0 : Number(opts.companyID);
17744
18289
  const includeFields = opts.includeFields === void 0 ? void 0 : opts.includeFields.includes("id") ? opts.includeFields : ["id", ...opts.includeFields];
17745
- const conditions = companyID === void 0 ? [root] : [{ field: "companyID", op: "eq", value: companyID }, root];
18290
+ const conditions = companyID === void 0 ? [root2] : [{ field: "companyID", op: "eq", value: companyID }, root2];
17746
18291
  const rows = await this.queryEntity(`${this.resourcePath}/query`, conditions, {
17747
18292
  maxRecords: limit,
17748
18293
  ...includeFields !== void 0 ? { includeFields } : {}
@@ -20015,20 +20560,20 @@ var GenericResource = class extends BaseResource {
20015
20560
  this.requireHelper("getContext");
20016
20561
  const cfg = this.config;
20017
20562
  const rootField = cfg.contextRootField ?? this.config.key;
20018
- const root = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20019
- const result = { [rootField]: root };
20020
- for (const [name, idField, targetPath] of cfg.contextParts ?? []) {
20021
- result[name] = await this.contextFetch(targetPath, root[idField]);
20022
- }
20563
+ const root2 = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20564
+ const result = { [rootField]: root2 };
20565
+ const parts = cfg.contextParts ?? [];
20566
+ const values = await mapReadTasks(this.http, parts, ([, idField, targetPath]) => this.contextFetch(targetPath, root2[idField]));
20567
+ for (const [i, [name]] of parts.entries()) result[name] = values[i];
20023
20568
  if (opts.names === true) {
20024
20569
  const builder = createNamePlan();
20025
20570
  for (const sib of cfg.nameSiblings ?? []) {
20026
- const fk2 = root[sib.field];
20571
+ const fk2 = root2[sib.field];
20027
20572
  if (sib.kind === "resource") builder.addResource(fk2);
20028
20573
  else builder.addFk(sib.kind, fk2);
20029
20574
  }
20030
20575
  const names = await resolveCompositeNames(this.http, builder.plan(), { maxNameReads: opts.maxNameReads });
20031
- const row = { ...root };
20576
+ const row = { ...root2 };
20032
20577
  for (const sib of cfg.nameSiblings ?? []) {
20033
20578
  addNameSibling(row, sib.field, (v) => sib.kind === "resource" ? names.resourceName(v) : names.recordName(sib.kind, v));
20034
20579
  }
@@ -20180,37 +20725,11 @@ function prepare(query, opts) {
20180
20725
  return { terms, limit };
20181
20726
  }
20182
20727
  function companyPieces(terms) {
20183
- const pieces = /* @__PURE__ */ new Set();
20184
- const prefixes = /* @__PURE__ */ new Set();
20185
- const longest = [...terms].sort((a, b) => b.length - a.length || a.localeCompare(b)).slice(0, 2);
20186
- for (const word of longest) {
20187
- const count = Math.max(1, Math.min(editBudget(word) + 1, Math.floor(word.length / 4)));
20188
- for (let i = 0; i < count; i++) pieces.add(word.slice(Math.floor(i * word.length / count), Math.floor((i + 1) * word.length / count)));
20189
- if (word.length >= 4 && word.length <= 6) prefixes.add(word.slice(0, 3));
20190
- }
20191
- if (terms.length > 1) pieces.add(terms.join(""));
20192
- return { pieces: [...pieces], prefixes: [...prefixes] };
20728
+ return textFragments(terms);
20193
20729
  }
20194
20730
  function score(record, terms, source) {
20195
- const words = companyTerms(record.companyName ?? "");
20196
- const candidates = [...words, words.join("")];
20197
- const matchedTerms = [];
20198
- let distance = 0;
20199
- for (const term of terms) {
20200
- const budget = editBudget(term);
20201
- const best = Math.min(budget + 1, ...candidates.map((word) => editDistanceAtMost(term, word, budget)));
20202
- if (best <= budget) {
20203
- matchedTerms.push(term);
20204
- distance += best;
20205
- }
20206
- }
20207
- if (terms.length > 1) {
20208
- const compact = terms.join("");
20209
- const budget = editBudget(compact);
20210
- const best = Math.min(budget + 1, ...candidates.map((word) => editDistanceAtMost(compact, word, budget)));
20211
- if (best <= budget && matchedTerms.length < terms.length) return { record, source, coverage: terms.length, distance: best, matchedTerms: [...terms] };
20212
- }
20213
- return matchedTerms.length === 0 ? void 0 : { record, source, coverage: matchedTerms.length, distance, matchedTerms };
20731
+ const match = scoreTerms(terms, companyTerms(record.companyName ?? ""));
20732
+ return match === void 0 ? void 0 : { record, source, ...match };
20214
20733
  }
20215
20734
  async function searchFuzzy(resource, query, opts = {}) {
20216
20735
  const { terms, limit } = prepare(query, opts);
@@ -20223,9 +20742,9 @@ async function searchFuzzy(resource, query, opts = {}) {
20223
20742
  if (!opts.includeInactive) filter.push({ field: "isActive", op: "eq", value: true });
20224
20743
  const index = companyIndex(resource.http);
20225
20744
  index?.ensure();
20226
- const state = index?.state() ?? { state: "off" };
20745
+ const state2 = index?.state() ?? { state: "off" };
20227
20746
  const revision = index?.revision();
20228
- const indexed = state.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
20747
+ const indexed = state2.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
20229
20748
  const res = await resource.http.request({
20230
20749
  method: "POST",
20231
20750
  idempotent: true,
@@ -20238,13 +20757,13 @@ async function searchFuzzy(resource, query, opts = {}) {
20238
20757
  const validIndex = index?.revision() === revision;
20239
20758
  for (const row of validIndex ? indexed : []) if (typeof row.id === "number") merged.set(row.id, { row, source: "index" });
20240
20759
  for (const row of live) if (typeof row.id === "number") merged.set(row.id, { row: slimCompany(row), source: merged.has(row.id) ? "both" : "live" });
20241
- const ranked = [...merged.values()].filter(({ row }) => opts.includeInactive || row.isActive === true).map(({ row, source }) => score(row, terms, source)).filter((row) => row !== void 0).sort((a, b) => b.coverage - a.coverage || a.distance - b.distance || Number(b.record.isActive === true) - Number(a.record.isActive === true) || (a.record.id ?? 0) - (b.record.id ?? 0));
20760
+ const ranked = [...merged.values()].filter(({ row }) => opts.includeInactive || row.isActive === true).map(({ row, source }) => score(row, terms, source)).filter((row) => row !== void 0).sort((a, b) => compareTermScores(a, b) || Number(b.record.isActive === true) - Number(a.record.isActive === true) || (a.record.id ?? 0) - (b.record.id ?? 0));
20242
20761
  const items = ranked.slice(0, limit);
20243
20762
  if (opts.includeFamily) {
20244
20763
  const records = await addCompanyFamilies(resource.http, items.map((row) => row.record), "companies.searchFuzzy");
20245
20764
  for (let i = 0; i < items.length; i++) items[i].record = records[i];
20246
20765
  }
20247
- return { items, tier: state.state === "warm" && validIndex ? "index+live" : "live", truncated: live.length >= 500 || ranked.length > limit, pieces, index: validIndex ? state : index.state() };
20766
+ return { items, tier: state2.state === "warm" && validIndex ? "index+live" : "live", truncated: live.length >= 500 || ranked.length > limit, pieces, index: validIndex ? state2 : index.state() };
20248
20767
  }
20249
20768
 
20250
20769
  // src/operations/invoke/fieldNames.ts
@@ -20418,13 +20937,17 @@ async function readFields(http, fresh) {
20418
20937
  const hit = cache.get(key);
20419
20938
  if (hit !== void 0) return hit;
20420
20939
  }
20421
- const res = await http.request({ method: "GET", path: "/V1.0/Tickets/entityInformation/fields", operation: OP, maxRetries: 0 });
20422
- const fields = res?.fields;
20423
- if (!Array.isArray(fields)) {
20424
- throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
20425
- }
20426
- if (fields.length > 0) cache?.set(key, fields);
20427
- return fields;
20940
+ const epoch = cache?.epoch;
20941
+ const work = (async () => {
20942
+ const res = await http.request({ method: "GET", path: "/V1.0/Tickets/entityInformation/fields", operation: OP, maxRetries: 0 });
20943
+ const fields = res?.fields;
20944
+ if (!Array.isArray(fields)) {
20945
+ throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
20946
+ }
20947
+ if (fields.length > 0) cache?.set(key, fields, epoch);
20948
+ return fields;
20949
+ })();
20950
+ return cache !== void 0 && !fresh ? cache.track(key, work) : work;
20428
20951
  }
20429
20952
  function assumed(allowAssumed, operation) {
20430
20953
  if (!allowAssumed) {
@@ -20646,14 +21169,16 @@ async function fullProfile(resource, id, opts = {}) {
20646
21169
  const proj = validateProjection(opts.fields);
20647
21170
  const companyID = parseIdentifier(id, "id");
20648
21171
  const company = await resource.get(companyID);
20649
- const locations = await scopedCompanyQuery(http, "/V1.0/CompanyLocations/query", companyID, locLimit, proj.locations);
20650
- const contacts = await scopedCompanyQuery(http, "/V1.0/Contacts/query", companyID, contactLimit, proj.contacts);
20651
- const notes = await scopedCompanyQuery(http, "/V1.0/CompanyNotes/query", companyID, noteLimit, proj.notes);
20652
- const projects = await scopedCompanyQuery(http, "/V1.0/Projects/query", companyID, projectLimit, proj.projects);
20653
- const openTickets = await readOpenTickets(http, companyID, ticketLimit, proj.openTickets, {
20654
- ...opts.excludeStatusIds === void 0 ? {} : { excludeStatusIds: opts.excludeStatusIds },
20655
- ...opts.allowAssumed === void 0 ? {} : { allowAssumed: opts.allowAssumed }
20656
- });
21172
+ const [locations, contacts, notes, projects, openTickets] = await readTasks(http, [
21173
+ () => scopedCompanyQuery(http, "/V1.0/CompanyLocations/query", companyID, locLimit, proj.locations),
21174
+ () => scopedCompanyQuery(http, "/V1.0/Contacts/query", companyID, contactLimit, proj.contacts),
21175
+ () => scopedCompanyQuery(http, "/V1.0/CompanyNotes/query", companyID, noteLimit, proj.notes),
21176
+ () => scopedCompanyQuery(http, "/V1.0/Projects/query", companyID, projectLimit, proj.projects),
21177
+ () => readOpenTickets(http, companyID, ticketLimit, proj.openTickets, {
21178
+ ...opts.excludeStatusIds === void 0 ? {} : { excludeStatusIds: opts.excludeStatusIds },
21179
+ ...opts.allowAssumed === void 0 ? {} : { allowAssumed: opts.allowAssumed }
21180
+ })
21181
+ ]);
20657
21182
  const result = {
20658
21183
  company,
20659
21184
  locations: { items: locations, capped: locations.length >= locLimit },
@@ -20913,11 +21438,7 @@ async function fetchCompanies(http, ids2, limit) {
20913
21438
  const out = [];
20914
21439
  for (const id of ids2.slice(0, limit)) {
20915
21440
  try {
20916
- const res = await http.request({
20917
- method: "GET",
20918
- path: `/V1.0/Companies/${id}`,
20919
- operation: "companies.searchByDomain"
20920
- });
21441
+ const res = await cachedRecordGet(http, `/V1.0/Companies/${id}`, "companies.searchByDomain");
20921
21442
  const body = res;
20922
21443
  const item = body && "item" in body ? body.item : null;
20923
21444
  if (item) out.push(item);
@@ -21353,9 +21874,11 @@ var CompaniesResource = class extends GenericResource {
21353
21874
  * fetch; no sub-lists; absent/dangling references come back null). */
21354
21875
  async getContext(id) {
21355
21876
  const company = await this.fetchRecordRaw("/V1.0/Companies", id);
21356
- const root = company;
21357
- const ownerResource = await this.contextFetch("/V1.0/Resources", root["ownerResourceID"]);
21358
- const parentCompany = await this.contextFetch("/V1.0/Companies", root["parentCompanyID"]);
21877
+ const root2 = company;
21878
+ const [ownerResource, parentCompany] = await readTasks(this.http, [
21879
+ () => this.contextFetch("/V1.0/Resources", root2["ownerResourceID"]),
21880
+ () => this.contextFetch("/V1.0/Companies", root2["parentCompanyID"])
21881
+ ]);
21359
21882
  return { company, ownerResource, parentCompany };
21360
21883
  }
21361
21884
  /** Node-parity special op (hand-written in src/resources/special/companies/search.ts). */
@@ -22435,7 +22958,7 @@ async function fetchByIds(client, items, opts = {}) {
22435
22958
  }
22436
22959
  groups.set(item.resource, g);
22437
22960
  }
22438
- const byKey = /* @__PURE__ */ new Map();
22961
+ const byKey2 = /* @__PURE__ */ new Map();
22439
22962
  for (const [key, group] of groups) {
22440
22963
  const holder = client[camelKey(key)];
22441
22964
  if (holder === void 0) {
@@ -22464,28 +22987,28 @@ async function fetchByIds(client, items, opts = {}) {
22464
22987
  if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
22465
22988
  for (const u of chunk) {
22466
22989
  const q = kOf(u);
22467
- if (!byKey.has(q)) byKey.set(q, { found: false, value: null, error: e });
22990
+ if (!byKey2.has(q)) byKey2.set(q, { found: false, value: null, error: e });
22468
22991
  }
22469
22992
  return true;
22470
22993
  }
22471
22994
  });
22472
22995
  for (const [k, row] of foundRows) {
22473
22996
  const q = kOf(k);
22474
- if (!byKey.has(q)) byKey.set(q, { found: true, value: row });
22997
+ if (!byKey2.has(q)) byKey2.set(q, { found: true, value: row });
22475
22998
  }
22476
22999
  for (const id of unique) {
22477
23000
  const k = kOf(id);
22478
- if (byKey.has(k)) continue;
23001
+ if (byKey2.has(k)) continue;
22479
23002
  try {
22480
23003
  const value = await holder.get(id);
22481
- byKey.set(k, { found: true, value });
23004
+ byKey2.set(k, { found: true, value });
22482
23005
  } catch (err) {
22483
23006
  if (err instanceof NotFoundError) {
22484
- byKey.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
23007
+ byKey2.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
22485
23008
  } else if (isAutotaskError(err) && err.code !== "ABORTED") {
22486
23009
  const e = { code: err.code, message: err.message };
22487
23010
  if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
22488
- byKey.set(k, { found: false, value: null, error: e });
23011
+ byKey2.set(k, { found: false, value: null, error: e });
22489
23012
  } else {
22490
23013
  throw err;
22491
23014
  }
@@ -22496,7 +23019,7 @@ async function fetchByIds(client, items, opts = {}) {
22496
23019
  for (let i = 0; i < items.length; i += 1) {
22497
23020
  const item = items[i];
22498
23021
  const id = canonical[i];
22499
- const out = byKey.get(`${item.resource}:${String(id)}`);
23022
+ const out = byKey2.get(`${item.resource}:${String(id)}`);
22500
23023
  const value = out.found ? item.fields !== void 0 ? project2(out.value, item.fields) : out.value : null;
22501
23024
  results.push(
22502
23025
  out.found ? { resource: item.resource, id, found: true, value } : { resource: item.resource, id, found: false, value: null, error: out.error }
@@ -23024,7 +23547,10 @@ async function revenueRollup(client, opts) {
23024
23547
  const groupDims = v.groupBy.map((d) => DIMENSIONS[d]);
23025
23548
  const paths = [.../* @__PURE__ */ new Set([CONTRACTS_PATH, ...groupDims.flatMap((d) => d.picklist ? [d.picklist] : [])])];
23026
23549
  const labels = {};
23027
- for (const p of paths) labels[p] = await readPicklists(http, p, OP4);
23550
+ const labelValues = await mapReadTasks(http, paths, (path) => readPicklists(http, path, OP4));
23551
+ paths.forEach((path, index) => {
23552
+ labels[path] = labelValues[index];
23553
+ });
23028
23554
  const contractLabels = labels[CONTRACTS_PATH];
23029
23555
  const typeValues = contractLabels.get("contractType") ?? /* @__PURE__ */ new Map();
23030
23556
  const inTypes = v.contractTypes ? resolveSelector(OP4, "contractTypes", v.contractTypes, typeValues) : new Map([...typeValues].filter(([, l]) => DEFAULT_CONTRACT_TYPE_RE.test(l)));
@@ -23053,10 +23579,12 @@ async function revenueRollup(client, opts) {
23053
23579
  const invoiceFilter = (voided2) => [...windowOn("invoiceDateTime"), { field: "isVoided", op: "eq", value: voided2 }];
23054
23580
  const withVoided = v.scopeKind !== "contractIDs";
23055
23581
  const voidedFilter = [...invoiceFilter(true), ...scopeIds !== void 0 && withVoided ? [{ field: "companyID", op: "in", value: scopeIds }] : []];
23056
- const nInvoices = await invoices.count({ filter: invoiceFilter(false) });
23057
- const nLines = await billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] });
23058
23582
  const uninvoicedFilter = [{ field: "invoiceID", op: "notExist" }, ...windowOn("itemDate"), ...scopeCond];
23059
- const nUninvoiced = v.nonChargeable ? await billingItems.count({ filter: uninvoicedFilter }) : 0;
23583
+ const [nInvoices, nLines, nUninvoiced] = await readTasks(http, [
23584
+ () => invoices.count({ filter: invoiceFilter(false) }),
23585
+ () => billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] }),
23586
+ () => v.nonChargeable ? billingItems.count({ filter: uninvoicedFilter }) : Promise.resolve(0)
23587
+ ]);
23060
23588
  if (typeof nInvoices !== "number" || typeof nLines !== "number" || typeof nUninvoiced !== "number") throw blindCountError(OP4, "the roll-up", BLIND_ACTION);
23061
23589
  const joinsNeeded = Object.keys(JOINS).filter((j) => j === "contracts" || groupDims.some((d) => d.joins?.[j]));
23062
23590
  const chunks4 = pages(nInvoices);
@@ -23101,14 +23629,17 @@ async function revenueRollup(client, opts) {
23101
23629
  if (v.nonChargeable && uninvoiced.length !== nUninvoiced) throw countMismatchError(OP4, "uninvoiced line", uninvoiced.length, nUninvoiced);
23102
23630
  const all = uninvoiced.length > 0 ? [...lines, ...uninvoiced] : lines;
23103
23631
  const joined = Object.fromEntries(Object.keys(JOINS).map((j) => [j, /* @__PURE__ */ new Map()]));
23104
- for (const j of joinsNeeded) {
23632
+ const fetchJoin = async (j) => {
23105
23633
  const spec = JOINS[j];
23106
23634
  const res = spec.make(http);
23107
23635
  const fields = [.../* @__PURE__ */ new Set([...spec.fields, ...groupDims.flatMap((d) => d.joins?.[j] ?? [])])];
23108
23636
  const want = [...new Set(spec.ids(all, joined))].filter((id) => id > 0).sort((a, b) => a - b);
23109
23637
  const rows = await client.batch((c) => collectRows(res, [{ field: "id", op: "in", value: c }], fields, PAGE), idChunks(want, PAGE), { concurrency: CONCURRENCY });
23110
23638
  for (const r of rows.flat()) joined[j].set(num(r["id"]), r);
23111
- }
23639
+ };
23640
+ const levels = ["organizationalLevel1s", "organizationalLevel2s"];
23641
+ await mapReadTasks(http, joinsNeeded.filter((j) => !levels.includes(j)), fetchJoin);
23642
+ await mapReadTasks(http, joinsNeeded.filter((j) => levels.includes(j)), fetchJoin);
23112
23643
  return fold(v, { invoiceById, voided, lines, uninvoiced, joined, labels, inTypes, inCategories, scopeIds, calls: budget.spent(), estimate });
23113
23644
  }
23114
23645
  function refusal(v, estimate, fixed, scopeIds, joinCount) {
@@ -23490,7 +24021,7 @@ function capJoinSet2(ids2, cap) {
23490
24021
  }
23491
24022
  async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity) {
23492
24023
  const unique = [...new Set(ids2)].sort((a, b) => a - b);
23493
- const byKey = /* @__PURE__ */ new Map();
24024
+ const byKey2 = /* @__PURE__ */ new Map();
23494
24025
  const misses = [];
23495
24026
  const notes = [];
23496
24027
  const found = await fetchIdChunks(http, entityPath, unique, fields, operation, {
@@ -23500,17 +24031,17 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
23500
24031
  const code = err instanceof AutotaskError ? err.code : "SERVER_ERROR";
23501
24032
  for (const k of chunk) {
23502
24033
  const id = Number(k);
23503
- if (!byKey.has(id) && !misses.some((m) => m.id === id)) misses.push({ id, code, message: err instanceof Error ? err.message : String(err) });
24034
+ if (!byKey2.has(id) && !misses.some((m) => m.id === id)) misses.push({ id, code, message: err instanceof Error ? err.message : String(err) });
23504
24035
  }
23505
24036
  return true;
23506
24037
  }
23507
24038
  });
23508
- for (const [k, row] of found) byKey.set(Number(k), row);
23509
- const queryMissed = unique.filter((k) => !byKey.has(k) && !misses.some((m) => m.id === k));
24039
+ for (const [k, row] of found) byKey2.set(Number(k), row);
24040
+ const queryMissed = unique.filter((k) => !byKey2.has(k) && !misses.some((m) => m.id === k));
23510
24041
  for (const k of queryMissed) {
23511
24042
  try {
23512
24043
  const res = await http.request({ method: "GET", path: `${entityPath}/${k}`, operation });
23513
- byKey.set(k, unwrapItem(res, k, operation, entity));
24044
+ byKey2.set(k, unwrapItem(res, k, operation, entity));
23514
24045
  } catch (err) {
23515
24046
  if (err instanceof NotFoundError) {
23516
24047
  misses.push({ id: k, code: "NOT_FOUND", message: err.message });
@@ -23521,14 +24052,14 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
23521
24052
  }
23522
24053
  }
23523
24054
  }
23524
- const items = unique.map((k) => byKey.get(k)).filter((r) => r !== void 0);
24055
+ const items = unique.map((k) => byKey2.get(k)).filter((r) => r !== void 0);
23525
24056
  const gotByQuery = unique.length - queryMissed.length;
23526
- if (queryMissed.length > 0 && gotByQuery === 0 && byKey.size > 0) {
24057
+ if (queryMissed.length > 0 && gotByQuery === 0 && byKey2.size > 0) {
23527
24058
  notes.push(
23528
- `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)`
24059
+ `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)`
23529
24060
  );
23530
24061
  }
23531
- const foundIds = new Set(byKey.keys());
24062
+ const foundIds = new Set(byKey2.keys());
23532
24063
  if (misses.length > 0) {
23533
24064
  const byCode = /* @__PURE__ */ new Map();
23534
24065
  for (const m of misses) byCode.set(m.code, (byCode.get(m.code) ?? 0) + 1);
@@ -23620,6 +24151,17 @@ function makeFetchCtx(rawHttp, v, contractId, budget, sharedExpenses) {
23620
24151
  };
23621
24152
  return { v, OP: OP14, id, idNum, rawHttp, http, wires, windowOn, readPart, windowedPart, truncatedMonths, ...sharedExpenses ? { sharedExpenses } : {} };
23622
24153
  }
24154
+ function forkFetchCtx(ctx) {
24155
+ return makeFetchCtx(ctx.rawHttp, ctx.v, ctx.id, ctx.wires.budget, ctx.sharedExpenses);
24156
+ }
24157
+ function mergeFetchContexts(ctx, branches) {
24158
+ for (const branch of branches) {
24159
+ ctx.wires.issued += branch.wires.issued;
24160
+ ctx.wires.requests += branch.wires.requests;
24161
+ if (branch.wires.note) appendWiresNote(ctx.wires, branch.wires.note);
24162
+ Object.assign(ctx.truncatedMonths, branch.truncatedMonths);
24163
+ }
24164
+ }
23623
24165
 
23624
24166
  // src/resources/special/contracts/profitability.util.ts
23625
24167
  function dateToDay(v) {
@@ -23768,11 +24310,7 @@ async function fetchCustomer(ctx, companyID) {
23768
24310
  let customerAbsent;
23769
24311
  if (companyID > 0) {
23770
24312
  try {
23771
- const res = await ctx.http.request({
23772
- method: "GET",
23773
- path: `/V1.0/Companies/${companyID}`,
23774
- operation: ctx.OP
23775
- });
24313
+ const res = await cachedRecordGet(ctx.http, `/V1.0/Companies/${companyID}`, ctx.OP);
23776
24314
  const item = unwrapItem(res, companyID, ctx.OP, "company");
23777
24315
  customer = item ?? null;
23778
24316
  customerStatus = "ok";
@@ -23802,16 +24340,17 @@ async function resolveContractType(ctx, contractType) {
23802
24340
  const isTimeAndMaterials = contractTypeKnown && TIME_AND_MATERIALS_LABEL_RE.test(contractTypeLabel);
23803
24341
  return { contractTypeLabel, contractTypeKnown, isBlockHours, isTimeAndMaterials };
23804
24342
  }
23805
- async function fetchRoot(ctx, resource) {
23806
- const contractCached = ctx.rawHttp.readCache?.get(`/V1.0/Contracts/${ctx.id}`) !== void 0;
23807
- const contract = await resource.get(ctx.id);
24343
+ async function fetchRoot(ctx) {
24344
+ const body = await cachedRecordGet(ctx.http, `/V1.0/Contracts/${ctx.id}`, "contracts.get");
24345
+ const contract = unwrapItem(body, ctx.id, "contracts.get", "contract");
23808
24346
  ctx.wires.issued += 1;
23809
- if (!contractCached) ctx.wires.requests += 1;
23810
24347
  const contractRow = contract;
23811
24348
  const companyID = num(contractRow["companyID"]);
23812
24349
  const contractType = num(contractRow["contractType"]);
23813
- const customerStage = await fetchCustomer(ctx, companyID);
23814
- const typeStage = await resolveContractType(ctx, contractType);
24350
+ const [customerStage, typeStage] = await readTasks(ctx.http, [
24351
+ () => fetchCustomer(ctx, companyID),
24352
+ () => resolveContractType(ctx, contractType)
24353
+ ]);
23815
24354
  return { contract, contractRow, contractType, ...customerStage, ...typeStage };
23816
24355
  }
23817
24356
  async function fetchCharges(ctx) {
@@ -23822,27 +24361,29 @@ async function fetchCharges(ctx) {
23822
24361
  const raw = await ctx.readPart("/V1.0/ContractCharges/query", chargesCond, ["id", "chargeType", "billableAmount", "extendedCost", "unitCost", "unitPrice", "unitQuantity", "datePurchased", "isBilled", "status", "contractServiceID"]);
23823
24362
  return { charges: raw.items, chargesPart: stampPart("contract_charges", raw, chargesCond) };
23824
24363
  }
23825
- async function fetchBlocks(ctx, root) {
23826
- if (!root.isBlockHours) {
24364
+ async function fetchBlocks(ctx, root2) {
24365
+ if (!root2.isBlockHours) {
23827
24366
  return skipPart(
23828
- 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)`
24367
+ root2.contractTypeKnown ? `skipped: not a Block Hours contract (contractType ${root2.contractType} "${root2.contractTypeLabel}") \u2014 included hours apply to hour blocks only (zero wire)` : `skipped: the contract type is unknown (contractType ${root2.contractType || "absent"}; label unresolved) \u2014 included hours are not evaluable (zero wire)`
23829
24368
  );
23830
24369
  }
23831
24370
  const blocksCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23832
24371
  const raw = await ctx.readPart("/V1.0/ContractBlocks/query", blocksCond, ["id", "datePurchased", "startDate", "endDate", "hours", "hoursApproved", "status", "isPaid"]);
23833
24372
  return stampPart("contract_blocks", raw, blocksCond);
23834
24373
  }
23835
- async function fetchContractState(ctx, root) {
24374
+ async function fetchContractState(ctx, root2) {
23836
24375
  const servicesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23837
- const servicesRaw = await ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]);
23838
24376
  const unitsCond = [{ field: "contractID", op: "eq", value: ctx.id }, ...ctx.windowOn("startDate")];
23839
- 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");
23840
- const { chargesPart, charges } = await fetchCharges(ctx);
23841
24377
  const roleCostsCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23842
- const roleCostsRaw = await ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]);
23843
24378
  const ratesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23844
- const ratesRaw = await ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]);
23845
- const blocksPart = await fetchBlocks(ctx, root);
24379
+ const [servicesRaw, units, { chargesPart, charges }, roleCostsRaw, ratesRaw, blocksPart] = await readTasks(ctx.http, [
24380
+ () => ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]),
24381
+ () => ctx.windowedPart("contractServiceUnits", "contract_service_units", "/V1.0/ContractServiceUnits/query", unitsCond, ["id", "contractServiceID", "serviceID", "units", "price", "cost", "internalCurrencyPrice", "startDate", "endDate", "approveAndPostDate"], "startDate"),
24382
+ () => fetchCharges(ctx),
24383
+ () => ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]),
24384
+ () => ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]),
24385
+ () => fetchBlocks(ctx, root2)
24386
+ ]);
23846
24387
  return { servicesRaw, servicesCond, unitRows: units.rows, unitsPartRaw: units.part, chargesPart, charges, roleCostsRaw, roleCostsCond, ratesRaw, ratesCond, blocksPart };
23847
24388
  }
23848
24389
  async function fetchBillingItems(ctx) {
@@ -24205,25 +24746,46 @@ async function fetchSubscriptionsJoin(ctx) {
24205
24746
  }
24206
24747
 
24207
24748
  // src/resources/special/contracts/profitability.data.ts
24208
- async function gather(ctx, resource) {
24209
- const root = await fetchRoot(ctx, resource);
24210
- const state = await fetchContractState(ctx, root);
24211
- const billing = await fetchBilling(ctx);
24212
- const time = await fetchTime(ctx);
24213
- const activity = await fetchTicketActivity(ctx, time.entries);
24214
- const open = await fetchOpenTickets(ctx);
24215
- const res = await fetchResources(ctx, time.entries);
24216
- const join = await fetchTicketJoinParts(ctx, [...activity.ticketsActRaw.items, ...open.openTickets], time.entries);
24217
- const subs = await fetchSubscriptionsJoin(ctx);
24218
- return { root, state, billing, time, activity, open, res, join, subs };
24749
+ async function gather(ctx) {
24750
+ const root2 = await fetchRoot(ctx);
24751
+ const stages = Object.fromEntries(
24752
+ ["state", "billing", "time", "activity", "open", "res", "join", "subs"].map((name) => [name, forkFetchCtx(ctx)])
24753
+ );
24754
+ let timeRead;
24755
+ const timeTask = () => timeRead ??= fetchTime(stages.time);
24756
+ let activityRead;
24757
+ const activityTask = () => activityRead ??= timeTask().then((time) => fetchTicketActivity(stages.activity, time.entries));
24758
+ let openRead;
24759
+ const openTask = () => openRead ??= fetchOpenTickets(stages.open);
24760
+ const tasks = {
24761
+ state: () => fetchContractState(stages.state, root2),
24762
+ billing: () => fetchBilling(stages.billing),
24763
+ time: timeTask,
24764
+ activity: activityTask,
24765
+ open: openTask,
24766
+ res: async () => fetchResources(stages.res, (await timeTask()).entries),
24767
+ join: async () => {
24768
+ const activity = await activityTask();
24769
+ const open = await openTask();
24770
+ const time = await timeTask();
24771
+ Object.assign(stages.join.truncatedMonths, stages.time.truncatedMonths);
24772
+ return fetchTicketJoinParts(stages.join, [...activity.ticketsActRaw.items, ...open.openTickets], time.entries);
24773
+ },
24774
+ subs: () => fetchSubscriptionsJoin(stages.subs)
24775
+ };
24776
+ const order = ctx.http.maxConcurrent === 1 ? ["state", "billing", "time", "activity", "open", "res", "join", "subs"] : ["state", "billing", "time", "open", "subs", "activity", "res", "join"];
24777
+ const completed = await mapReadTasks(ctx.http, order, async (name) => [name, await tasks[name]()]);
24778
+ const parts = Object.fromEntries(completed);
24779
+ mergeFetchContexts(ctx, Object.values(stages));
24780
+ return { root: root2, ...parts };
24219
24781
  }
24220
24782
  function stampListParts(v, f) {
24221
- const { state, activity, join } = f;
24783
+ const { state: state2, activity, join } = f;
24222
24784
  return {
24223
- servicesPart: stampPart("contract_services", state.servicesRaw, state.servicesCond),
24224
- unitsPart: state.unitsPartRaw,
24225
- roleCostsPart: stampPart("contract_role_costs", state.roleCostsRaw, state.roleCostsCond),
24226
- ratesPart: stampPart("contract_rates", state.ratesRaw, state.ratesCond),
24785
+ servicesPart: stampPart("contract_services", state2.servicesRaw, state2.servicesCond),
24786
+ unitsPart: state2.unitsPartRaw,
24787
+ roleCostsPart: stampPart("contract_role_costs", state2.roleCostsRaw, state2.roleCostsCond),
24788
+ ratesPart: stampPart("contract_rates", state2.ratesRaw, state2.ratesCond),
24227
24789
  ticketsActivityPart: stampPart("tickets", activity.ticketsActRaw, activity.ticketsActCond, [
24228
24790
  ...activity.ticketsActRaw.hasMore ? [`${join.fetchedTickets.size} ticket(s) returned of possibly more \u2014 the checks cover the returned set only`] : [],
24229
24791
  ...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`] : []
@@ -24864,7 +25426,7 @@ async function profitability(resource, contractId, opts, sharedExpenses) {
24864
25426
  const v = validateProfitabilityOptions(contractId, opts);
24865
25427
  const ctx = makeFetchCtx(resource.http, v, contractId, PROFITABILITY_WIRE_BUDGET, sharedExpenses);
24866
25428
  const asOf = (/* @__PURE__ */ new Date()).toISOString();
24867
- const f = await gather(ctx, resource);
25429
+ const f = await gather(ctx);
24868
25430
  const fc = makeFoldCtx(ctx, f, stampListParts(v, f), Date.parse(asOf));
24869
25431
  return assemble(ctx, fc, asOf);
24870
25432
  }
@@ -24951,17 +25513,30 @@ function validate2(opts) {
24951
25513
  function latchingHttp(raw, spend) {
24952
25514
  const counted = countingHttp(raw, spend);
24953
25515
  let fatal;
25516
+ const controller = new AbortController();
25517
+ const caller = ambientCallerSignal();
25518
+ const signal = caller === void 0 ? controller.signal : AbortSignal.any([caller, controller.signal]);
24954
25519
  const http = Object.create(counted);
24955
- http.request = async (o) => {
25520
+ const latch = (err) => {
25521
+ if (err instanceof RateLimitError || err instanceof AutotaskError && err.code === "BUDGET_EXCEEDED") {
25522
+ fatal ??= err;
25523
+ controller.abort(fatal);
25524
+ }
25525
+ };
25526
+ observeRecordReadFailures(http, latch);
25527
+ const fail = (err) => {
25528
+ latch(err);
25529
+ throw err;
25530
+ };
25531
+ http.request = (o) => {
24956
25532
  if (fatal) throw fatal;
24957
25533
  try {
24958
- return await counted.request(o);
25534
+ return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail);
24959
25535
  } catch (err) {
24960
- if (err instanceof RateLimitError || err instanceof AutotaskError && err.code === "BUDGET_EXCEEDED") fatal ??= err;
24961
- throw err;
25536
+ return fail(err);
24962
25537
  }
24963
25538
  };
24964
- return { http, fatal: () => fatal };
25539
+ return { http, fatal: () => fatal, signal };
24965
25540
  }
24966
25541
  async function portfolioMargin(client, opts) {
24967
25542
  const v = validate2(opts);
@@ -24972,7 +25547,7 @@ async function portfolioMargin(client, opts) {
24972
25547
  { phase: estimate === 0 ? "estimate" : "walk", budget: v.budget, vendorCalls: spent, ...estimate > 0 ? { estimate } : {} },
24973
25548
  `Pass maxVendorCalls > ${v.budget} (cap ${BUDGET_CAP2}) or fewer contracts.`
24974
25549
  ));
24975
- const { http, fatal } = latchingHttp(client.http, budget.spend);
25550
+ const { http, fatal, signal } = latchingHttp(client.http, budget.spend);
24976
25551
  const contracts = new ContractsResource(http, PAGE2);
24977
25552
  let typeMap;
24978
25553
  if (v.contractTypes) {
@@ -25019,7 +25594,7 @@ async function portfolioMargin(client, opts) {
25019
25594
  let results;
25020
25595
  try {
25021
25596
  const shared = countFault ?? (expenseCount === 0 ? { rows: [], contractOf: /* @__PURE__ */ new Map(), misses: 0 } : await readTicketExpenses(http, expenseItems, expenseFilter, expenseCount));
25022
- results = await client.batch((id) => profitability(contracts, id, v.profitOpts, shared), ids2, { concurrency: CONCURRENCY2 });
25597
+ results = await client.withSignal(signal, () => client.batch((id) => profitability(contracts, id, v.profitOpts, shared), ids2, { concurrency: CONCURRENCY2 }));
25023
25598
  } catch (err) {
25024
25599
  throw fatal() ?? err;
25025
25600
  }
@@ -25262,8 +25837,10 @@ async function recurringRevenue(client, opts) {
25262
25837
  ];
25263
25838
  const subsRes = res("subscriptions");
25264
25839
  const subFilter = [{ field: "effectiveDate", op: "lt", value: next }, { field: "expirationDate", op: "gte", value: v.asOf }];
25265
- const nContracts = await countOf(contractsRes, "contract", contractFilter);
25266
- const nSubs = await countOf(subsRes, "subscription", subFilter);
25840
+ const [nContracts, nSubs] = await readTasks(http, [
25841
+ () => countOf(contractsRes, "contract", contractFilter),
25842
+ () => countOf(subsRes, "subscription", subFilter)
25843
+ ]);
25267
25844
  const chunks4 = Math.ceil(nContracts / CHUNK);
25268
25845
  const subCalls = Math.ceil(nSubs / PAGE3) + (nSubs > 0 ? 1 : 0) + Math.ceil(nSubs / CHUNK) + (v.scopeIds ? 1 : Math.ceil((nContracts + nSubs) / CHUNK));
25269
25846
  const refuse3 = (calls, sets2) => {
@@ -25302,26 +25879,35 @@ async function recurringRevenue(client, opts) {
25302
25879
  nCharges: 0
25303
25880
  };
25304
25881
  });
25305
- for (const x of sets) {
25306
- x.nUnits = await countOf(res("contract_service_units"), "service unit", x.unitFilter);
25307
- x.nCharges = await countOf(res("contract_charges"), "charge", x.chargeFilter);
25308
- }
25882
+ await mapReadTasks(http, sets.flatMap((x) => [
25883
+ async () => {
25884
+ x.nUnits = await countOf(res("contract_service_units"), "service unit", x.unitFilter);
25885
+ },
25886
+ async () => {
25887
+ x.nCharges = await countOf(res("contract_charges"), "charge", x.chargeFilter);
25888
+ }
25889
+ ]), (task) => task());
25309
25890
  const nUnits = sets.reduce((a, x) => a + x.nUnits, 0);
25310
25891
  const nCharges = sets.reduce((a, x) => a + x.nCharges, 0);
25311
25892
  estimate = budget.spent() + sets.reduce((a, x) => a + Math.ceil(x.nUnits / PAGE3) + Math.ceil(x.nCharges / PAGE3), 0) + subCalls;
25312
25893
  if (estimate > v.budget) {
25313
25894
  throw refuse3(estimate, { contracts: nContracts, serviceUnits: nUnits, charges: nCharges, subscriptions: nSubs });
25314
25895
  }
25315
- const units = [];
25316
- const charges = [];
25317
- for (const x of sets) {
25318
- units.push(...await gated(res("contract_service_units"), "service unit", x.unitFilter, ["id", "contractID", "contractServiceID", "startDate", "endDate", "units", "price", "internalCurrencyPrice"], x.nUnits));
25319
- charges.push(...await gated(res("contract_charges"), "charge", x.chargeFilter, ["id", "contractID", "billableAmount", "internalCurrencyBillableAmount"], x.nCharges));
25320
- }
25321
- const subs = await gated(subsRes, "subscription", subFilter, ["id", "configurationItemID", "periodPrice", "periodType", "status"], nSubs);
25322
- const labels = subs.length > 0 ? await readPicklists(http, "/V1.0/Subscriptions", OP6) : /* @__PURE__ */ new Map();
25323
- const ciIds = [...new Set(subs.map((s) => num(s["configurationItemID"])).filter((n) => n > 0))].sort((a, b) => a - b);
25324
- const cis = ciIds.length > 0 ? await fetchIdChunks(http, "/V1.0/ConfigurationItems", ciIds, ["companyID"], OP6, { chunkSize: CHUNK }) : /* @__PURE__ */ new Map();
25896
+ const [unitSets, chargeSets, { subs, labels, cis }] = await readTasks(http, [
25897
+ () => mapReadTasks(http, sets, (x) => gated(res("contract_service_units"), "service unit", x.unitFilter, ["id", "contractID", "contractServiceID", "startDate", "endDate", "units", "price", "internalCurrencyPrice"], x.nUnits)),
25898
+ () => mapReadTasks(http, sets, (x) => gated(res("contract_charges"), "charge", x.chargeFilter, ["id", "contractID", "billableAmount", "internalCurrencyBillableAmount"], x.nCharges)),
25899
+ async () => {
25900
+ const subs2 = await gated(subsRes, "subscription", subFilter, ["id", "configurationItemID", "periodPrice", "periodType", "status"], nSubs);
25901
+ const ciIds = [...new Set(subs2.map((s) => num(s["configurationItemID"])).filter((n) => n > 0))].sort((a, b) => a - b);
25902
+ const [labels2, cis2] = await readTasks(http, [
25903
+ () => subs2.length > 0 ? readPicklists(http, "/V1.0/Subscriptions", OP6) : Promise.resolve(/* @__PURE__ */ new Map()),
25904
+ () => ciIds.length > 0 ? fetchIdChunks(http, "/V1.0/ConfigurationItems", ciIds, ["companyID"], OP6, { chunkSize: CHUNK }) : Promise.resolve(/* @__PURE__ */ new Map())
25905
+ ]);
25906
+ return { subs: subs2, labels: labels2, cis: cis2 };
25907
+ }
25908
+ ]);
25909
+ const units = unitSets.flat();
25910
+ const charges = chargeSets.flat();
25325
25911
  const contractOf = new Map(contracts.map((c) => [num(c["id"]), c]));
25326
25912
  const latest = /* @__PURE__ */ new Map();
25327
25913
  for (const u of units) {
@@ -26034,7 +26620,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
26034
26620
  suggestedAction: "Narrow the dateWorked window, or page it with cursor (rows mode reports unconfirmed entries via truncated)."
26035
26621
  });
26036
26622
  }
26037
- for (const [id, state] of joined.states) states.set(id, state);
26623
+ for (const [id, state2] of joined.states) states.set(id, state2);
26038
26624
  cursor = page.items.length === 0 ? null : page.pageDetails.nextPageUrl ?? null;
26039
26625
  } while (cursor !== null);
26040
26626
  spend();
@@ -26052,7 +26638,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
26052
26638
  });
26053
26639
  }
26054
26640
  let postedCount = 0;
26055
- for (const state of states.values()) if (state === "posted") postedCount += 1;
26641
+ for (const state2 of states.values()) if (state2 === "posted") postedCount += 1;
26056
26642
  return { window, total: states.size, postedCount, unpostedCount: states.size - postedCount, vendorCalls: callBudget.spent(), estimate, budget };
26057
26643
  }
26058
26644
  async function dateWorkedWindow(resource, from, to, opts) {
@@ -26073,8 +26659,8 @@ async function dateWorkedWindow(resource, from, to, opts) {
26073
26659
  const { states, incomplete } = await postedStateOf(http, items, OP14);
26074
26660
  let postedCount = 0;
26075
26661
  let unpostedCount = 0;
26076
- for (const state of states.values()) {
26077
- if (state === "posted") postedCount += 1;
26662
+ for (const state2 of states.values()) {
26663
+ if (state2 === "posted") postedCount += 1;
26078
26664
  else unpostedCount += 1;
26079
26665
  }
26080
26666
  return {
@@ -26358,12 +26944,14 @@ async function wipHours(client, opts) {
26358
26944
  } else {
26359
26945
  const contractIds = positiveIds2(wipIn.map((e) => e["contractID"]));
26360
26946
  gate(chunks2(contractIds.length) + (contractIds.length > 0 ? 1 : 0), "before label reads", { contracts: contractIds.length });
26361
- const contracts = await readChunks2(http, "/V1.0/Contracts", contractIds, ["contractType"]);
26947
+ const [contracts, types] = await readTasks(http, [
26948
+ () => readChunks2(http, "/V1.0/Contracts", contractIds, ["contractType"]),
26949
+ async () => contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0
26950
+ ]);
26362
26951
  const typeOf = (id) => contracts.get(String(id))?.["contractType"];
26363
26952
  const bad = contractIds.filter((id) => typeof typeOf(id) !== "number");
26364
26953
  if (bad.length > 0) throw unresolved("contracts", bad);
26365
26954
  keyOfEntry = (e) => num(e["contractID"]) > 0 ? typeOf(num(e["contractID"])) : null;
26366
- const types = contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0;
26367
26955
  for (const [id, label] of types ?? []) labels.set(id, { label });
26368
26956
  }
26369
26957
  const approvalData = entries.some((e) => isApproved(e));
@@ -26555,8 +27143,10 @@ async function nonChargeableWork(client, opts) {
26555
27143
  const contractIds = distinctIds(ncLines.map((x) => x.line["contractID"]), 1);
26556
27144
  const typed = v.groupBy === "contractType";
26557
27145
  gate(chunks3(contractIds.length) + (typed && contractIds.length > 0 ? 1 : 0) + (v.includeUnpostedTime ? 1 : 0), "before label reads", { contracts: contractIds.length });
26558
- const contracts = await readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]);
26559
- const types = typed && contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP11)).get("contractType") : void 0;
27146
+ const [contracts, types] = await readTasks(http, [
27147
+ () => readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]),
27148
+ async () => typed && contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP11)).get("contractType") : void 0
27149
+ ]);
26560
27150
  keyOfLine = (line) => {
26561
27151
  if (num(line["contractID"]) === 0) return null;
26562
27152
  const c = contracts.get(String(line["contractID"]));
@@ -27038,6 +27628,10 @@ async function openTicketsOfPart(client, field, id, limit) {
27038
27628
  const filter = [{ field, op: "eq", value: id }, ...closed.map((v) => ({ field: "status", op: "noteq", value: v }))];
27039
27629
  return { ...await compositePart(client, "tickets.query", [{ filter, limit }]), closedStatus };
27040
27630
  }
27631
+ async function joinedCompositePart(client, source, idField, targetOp, targetField, limit, absent) {
27632
+ const ids2 = numericIds(source.value?.items ?? [], idField).slice(0, IN_FILTER_CAP);
27633
+ return ids2.length === 0 ? { value: null, absent } : await compositePart(client, targetOp, [{ filter: [{ field: targetField, op: "in", value: ids2 }], limit }]);
27634
+ }
27041
27635
 
27042
27636
  // src/resources/special/contracts/fullProfile.ts
27043
27637
  var OP12 = "contracts.fullProfile";
@@ -27048,21 +27642,23 @@ async function fullProfile2(resource, id, opts = {}) {
27048
27642
  const serviceLimit = compositePartLimit(opts.serviceLimit, "serviceLimit", OP12);
27049
27643
  const billingRuleLimit = compositePartLimit(opts.billingRuleLimit, "billingRuleLimit", OP12);
27050
27644
  const contractId = parseIdentifier(id, "id");
27051
- const root = await invokeRead(client, "contracts.get", [contractId]);
27052
- const services = await compositePart(client, "contract_services.query", [
27053
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
27054
- ]);
27055
- const billingRules = await compositePart(client, "contract_billing_rules.query", [
27056
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: billingRuleLimit }
27057
- ]);
27058
- const charges = await compositePart(client, "contract_charges.query", [
27059
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: CHARGES_RECENT_CAP, latest: CHARGES_RECENT_CAP }
27060
- ]);
27061
- const units = await compositePart(client, "contract_service_units.query", [
27062
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: SERVICE_UNITS_CAP }
27645
+ const root2 = await invokeRead(client, "contracts.get", [contractId]);
27646
+ const [services, billingRules, charges, units] = await readTasks(resource.http, [
27647
+ () => compositePart(client, "contract_services.query", [
27648
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
27649
+ ]),
27650
+ () => compositePart(client, "contract_billing_rules.query", [
27651
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: billingRuleLimit }
27652
+ ]),
27653
+ () => compositePart(client, "contract_charges.query", [
27654
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: CHARGES_RECENT_CAP, latest: CHARGES_RECENT_CAP }
27655
+ ]),
27656
+ () => compositePart(client, "contract_service_units.query", [
27657
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: SERVICE_UNITS_CAP }
27658
+ ])
27063
27659
  ]);
27064
27660
  return {
27065
- root,
27661
+ root: root2,
27066
27662
  parts: {
27067
27663
  services,
27068
27664
  billing_rules: billingRules,
@@ -27141,4 +27737,4 @@ var ContractsResource = class extends GenericResource {
27141
27737
  }
27142
27738
  };
27143
27739
 
27144
- export { AGGREGATE_DATE_BUCKETS, AGGREGATE_DEFAULT_LIMIT, AGGREGATE_DEFAULT_TOP, AGGREGATE_TOP_MAX, AutotaskAbortError, AutotaskConfigError, AutotaskError, AutotaskNetworkError, AutotaskTimeoutError, CREATE_BLOCKER_KINDS, CREDENTIAL_ENV_LOAD_ACTION, CREDENTIAL_SHAPE_POINTER, CompaniesResource, ConfirmationRequiredError, ConflictError, ContractsResource, DEFAULT_ZONE, DeleteBoundaryError, EXPAND_RESOURCE_NAMES_MAX_IDS, EmptyResponseError, FETCH_BY_IDS_CHUNK_SIZE, FETCH_BY_IDS_MAX_ITEMS, FIELD_CACHE_KINDS, FIELD_CATALOG_HONESTY_NOTE, GenericResource, HostPolicyDeniedError, HttpClient, INVOKE_OPTION_KEYS, IN_FILTER_CAP, InvoicesResource, MAX_FIELD_CATALOG_WIRE, MIN_FIELD_CATALOG_MAX_BYTES, MIN_PREFIX_SUMMARY_LENGTH, MaintenanceError, MarkerUnsafeIdError, MoveRefusedError, NotFoundError, OperationNotSupportedError, PARAMS_BAG_KEYS, PICKLIST_VALUE_NOT_SERVED_NOTE, PaginationLimitError, QueryTooLongError, RELATIONSHIP_MAP, RateLimitError, RecoveryTruncatedError, ResolutionError, ResponseRejectedError, SIMPLE_RESOURCES, ScopeRequiredError, StaleObjectError, TICKET_LABEL_FIELDS, TimeEntriesResource, TtlCache, UI_LINK_ENTITIES, UNSCOPED_WALK_THRESHOLD, UnexpectedContentTypeError, WORKFLOW_RESOURCES, ZONES, addLabelSibling, addNameSibling, aggregate, arAging, buildDryRunResult, buildQueryRequest, buildReadCache, buildUiLink, clientOf, compositePart, compositePartLimit, createGuidance, createNamePlan, credentialShapeProblem, credentialValueSummary, cursorToPath, dateBucketLabel, effectiveRequiredFields, errorFromStatus, expandResourceNames, fetchByIds, fieldCatalog, foldFlattenedOpts, formatVendorDetail, invoke, invokeDelete, invokeRead, invokeWrite, isAutotaskError, isClosedStatus, isDeterministicVendor500, mergeDetails, mergePartialBody, needsConfirmation, nextActionFor, nonChargeableWork, notPersistedFields, numericIds, openStatusFilter, openTicketsOfPart, parseIdentifier, parseVendorErrors, portfolioMargin, queryRows, recurringRevenue, refuse2 as refuse, relationshipMap, resolveAny, resolveCompositeNames, resolveConfig, resolveCredentials, resolveLineOfBusinessChain, resolveStaff, resolveTicketStatusSemantics, revenueRollup, runMove, runWithSignal, sanitiseResult, searchAcrossResources, suspendCompanyIndex, uiLink, uiLinkFor, unknownKeysRefusal, unwrapItem, unwrapItems, unwrapOperation, validateDispatchArgs, validateInvokeOptions, validateParamsBag, vendorId, wipHours, zoneUrl };
27740
+ export { AGGREGATE_DATE_BUCKETS, AGGREGATE_DEFAULT_LIMIT, AGGREGATE_DEFAULT_TOP, AGGREGATE_TOP_MAX, AutotaskAbortError, AutotaskConfigError, AutotaskError, AutotaskNetworkError, AutotaskTimeoutError, CREATE_BLOCKER_KINDS, CREDENTIAL_ENV_LOAD_ACTION, CREDENTIAL_SHAPE_POINTER, CompaniesResource, ConfirmationRequiredError, ConflictError, ContractsResource, DEFAULT_ZONE, DeleteBoundaryError, EXPAND_RESOURCE_NAMES_MAX_IDS, EmptyResponseError, FETCH_BY_IDS_CHUNK_SIZE, FETCH_BY_IDS_MAX_ITEMS, FIELD_CACHE_KINDS, FIELD_CATALOG_HONESTY_NOTE, GenericResource, HostPolicyDeniedError, HttpClient, INVOKE_OPTION_KEYS, InvoicesResource, MAX_FIELD_CATALOG_WIRE, MIN_FIELD_CATALOG_MAX_BYTES, MIN_PREFIX_SUMMARY_LENGTH, MaintenanceError, MarkerUnsafeIdError, MoveRefusedError, NotFoundError, OperationNotSupportedError, PARAMS_BAG_KEYS, PICKLIST_VALUE_NOT_SERVED_NOTE, PaginationLimitError, QueryTooLongError, RELATIONSHIP_MAP, RateLimitError, RecoveryTruncatedError, ResolutionError, ResponseRejectedError, SIMPLE_RESOURCES, ScopeRequiredError, StaleObjectError, TICKET_LABEL_FIELDS, TimeEntriesResource, TtlCache, UI_LINK_ENTITIES, UNSCOPED_WALK_THRESHOLD, UnexpectedContentTypeError, WORKFLOW_RESOURCES, ZONES, addLabelSibling, addNameSibling, aggregate, arAging, buildDryRunResult, buildQueryRequest, buildReadCache, buildUiLink, cachedRecordGet, clientOf, compositePart, compositePartLimit, createGuidance, createNamePlan, credentialShapeProblem, credentialValueSummary, cursorToPath, dateBucketLabel, effectiveRequiredFields, errorFromStatus, expandResourceNames, fetchByIds, fieldCatalog, foldFlattenedOpts, formatVendorDetail, invoke, invokeDelete, invokeRead, invokeWrite, isAutotaskError, isClosedStatus, isDeterministicVendor500, joinedCompositePart, mergeDetails, mergePartialBody, needsConfirmation, nextActionFor, nonChargeableWork, notPersistedFields, openStatusFilter, openTicketsOfPart, parseIdentifier, parseVendorErrors, portfolioMargin, queryRows, readTasks, recurringRevenue, refuse2 as refuse, relationshipMap, resolveAny, resolveCompositeNames, resolveConfig, resolveCredentials, resolveLineOfBusinessChain, resolveStaff, resolveTicketStatusSemantics, revenueRollup, runBounded, runMove, runWithSignal, sanitiseResult, searchAcrossResources, suspendCompanyIndex, uiLink, uiLinkFor, unknownKeysRefusal, unwrapItem, unwrapItems, unwrapOperation, validateDispatchArgs, validateInvokeOptions, validateParamsBag, vendorId, wipHours, zoneUrl };