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