node-autotask 0.69.1 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -616,6 +616,27 @@ function isKnownZone(zone) {
616
616
  return typeof zone === "string" && ZONES.includes(zone);
617
617
  }
618
618
 
619
+ // src/metadata-projection.ts
620
+ var METADATA_PROJECTION = /* @__PURE__ */ Symbol.for("node-autotask.metadata-projection.v1");
621
+ function projectMetadata(value, projector) {
622
+ return structuredClone(projector(value));
623
+ }
624
+ async function readMetadataProjection(holder, kind, projector, fallbackReader) {
625
+ const hook = holder !== null && (typeof holder === "object" || typeof holder === "function") ? holder[METADATA_PROJECTION] : void 0;
626
+ const owned = hook?.call(holder, kind, projector);
627
+ owned?.guard();
628
+ if (owned?.projected !== void 0) {
629
+ const value2 = await owned.projected;
630
+ owned.guard();
631
+ return value2;
632
+ }
633
+ const raw = await fallbackReader();
634
+ owned?.guard();
635
+ const value = projector(raw);
636
+ owned?.guard();
637
+ return value;
638
+ }
639
+
619
640
  // src/cache.ts
620
641
  var READ_CACHE_MAX_ENTRIES = 4096;
621
642
  var REFERENCE_TTL_MS = 36e5;
@@ -628,6 +649,7 @@ function readTtlFor(key, ttlMs) {
628
649
  const entity = key.split("\0")[0].split("/").at(-2);
629
650
  return entity !== void 0 && REFERENCE_ENTITIES.includes(entity) ? Math.max(ttlMs, REFERENCE_TTL_MS) : ttlMs;
630
651
  }
652
+ var MAX_ENTRY_PROJECTIONS = 8;
631
653
  var TtlCache = class {
632
654
  ttlMs;
633
655
  maxEntries;
@@ -648,15 +670,38 @@ var TtlCache = class {
648
670
  this.maxEntries = maxEntries;
649
671
  this.ttlFor = options.ttlFor ?? (() => ttlMs);
650
672
  }
651
- /** The live value (a copy), or `undefined` when absent or expired. */
652
- get(key) {
673
+ liveEntry(key) {
653
674
  const entry = this.store.get(key);
654
675
  if (entry === void 0) return void 0;
655
676
  if (entry.expiresAt <= Date.now()) {
656
677
  this.store.delete(key);
657
678
  return void 0;
658
679
  }
659
- return structuredClone(entry.value);
680
+ return entry;
681
+ }
682
+ /** The live value (a copy), or `undefined` when absent or expired. */
683
+ get(key) {
684
+ const entry = this.liveEntry(key);
685
+ return entry === void 0 ? void 0 : structuredClone(entry.value);
686
+ }
687
+ projectEntry(key, entry, projector) {
688
+ if (entry.projections?.has(projector)) return structuredClone(entry.projections.get(projector));
689
+ const value = projectMetadata(structuredClone(entry.value), projector);
690
+ if (this.store.get(key) === entry && entry.expiresAt > Date.now()) {
691
+ const projections = entry.projections ??= /* @__PURE__ */ new Map();
692
+ if (projections.size >= MAX_ENTRY_PROJECTIONS) {
693
+ const oldest = projections.keys().next();
694
+ if (!oldest.done) projections.delete(oldest.value);
695
+ }
696
+ projections.set(projector, value);
697
+ return structuredClone(value);
698
+ }
699
+ return value;
700
+ }
701
+ /** Clone a live derived value without cloning the full metadata on each hit. @internal */
702
+ getProjected(key, projector) {
703
+ const entry = this.liveEntry(key);
704
+ return entry === void 0 ? void 0 : this.projectEntry(key, entry, projector);
660
705
  }
661
706
  /**
662
707
  * Load one record once for concurrent callers. Each subscriber owns its
@@ -667,12 +712,23 @@ var TtlCache = class {
667
712
  * `shouldStore` controls retention, never the result returned to subscribers.
668
713
  * @internal
669
714
  */
670
- async load(key, loader, opts) {
715
+ load(key, loader, opts) {
716
+ return this.loadValue(key, loader, opts);
717
+ }
718
+ /** Projected and raw subscribers share the same raw flight and retention policy. @internal */
719
+ loadProjected(key, loader, projector, opts) {
720
+ return this.loadValue(key, loader, opts, projector);
721
+ }
722
+ async loadValue(key, loader, opts, projector) {
671
723
  const { signal } = opts;
672
724
  if (signal?.aborted) throw opts.abortError();
673
725
  if (!opts.fresh) {
674
- const hit = this.get(key);
675
- if (hit !== void 0) return hit;
726
+ const entry = this.liveEntry(key);
727
+ if (entry !== void 0 && entry.value !== void 0) {
728
+ const hit = projector === void 0 ? structuredClone(entry.value) : this.projectEntry(key, entry, projector);
729
+ if (signal?.aborted) throw opts.abortError();
730
+ return hit;
731
+ }
676
732
  }
677
733
  let flight = opts.fresh ? void 0 : this.loads.get(key);
678
734
  let start;
@@ -690,7 +746,10 @@ var TtlCache = class {
690
746
  }
691
747
  };
692
748
  }).then((value) => {
693
- if (this.loads.get(key) === created && !controller.signal.aborted && (opts.shouldStore?.(value) ?? true)) this.set(key, value, epoch);
749
+ if (this.loads.get(key) === created && !controller.signal.aborted) {
750
+ const retain = opts.shouldStore?.(value) ?? true;
751
+ if (retain && this.loads.get(key) === created && !controller.signal.aborted) created.entry = this.storeValue(key, value, epoch);
752
+ }
694
753
  return value;
695
754
  });
696
755
  const settled = () => {
@@ -724,7 +783,11 @@ var TtlCache = class {
724
783
  (value) => {
725
784
  if (leave()) {
726
785
  try {
727
- resolve(structuredClone(value));
786
+ if (signal?.aborted) throw opts.abortError();
787
+ const entry = shared.entry;
788
+ const selected = projector === void 0 ? structuredClone(value) : entry !== void 0 && this.liveEntry(key) === entry ? this.projectEntry(key, entry, projector) : projectMetadata(structuredClone(value), projector);
789
+ if (signal?.aborted) throw opts.abortError();
790
+ resolve(selected);
728
791
  } catch (error) {
729
792
  reject(error);
730
793
  }
@@ -741,14 +804,19 @@ var TtlCache = class {
741
804
  /** Store `value` under `key`. `epoch` is the value the caller read BEFORE its
742
805
  * wire request: a read that straddled a `clear()` (a write) is dropped. */
743
806
  set(key, value, epoch = this.epochCounter) {
744
- if (epoch !== this.epochCounter) return;
807
+ this.storeValue(key, value, epoch);
808
+ }
809
+ storeValue(key, value, epoch) {
810
+ if (epoch !== this.epochCounter) return void 0;
745
811
  if (!this.store.has(key) && this.store.size >= this.maxEntries && this.purgeExpired() === 0) {
746
812
  const oldest = this.store.keys().next();
747
813
  if (!oldest.done) this.store.delete(oldest.value);
748
814
  }
749
815
  const now = Date.now();
750
816
  this.store.delete(key);
751
- this.store.set(key, { value: structuredClone(value), storedAt: now, expiresAt: now + this.ttlFor(key) });
817
+ const entry = { value: structuredClone(value), storedAt: now, expiresAt: now + this.ttlFor(key) };
818
+ this.store.set(key, entry);
819
+ return entry;
752
820
  }
753
821
  /** `{ hit, age }` without consuming or cloning the entry (age in ms since stored). */
754
822
  peek(key) {
@@ -1732,6 +1800,12 @@ function isAbortLike(err) {
1732
1800
  return typeof err === "object" && err !== null && "name" in err && err.name === "AbortError";
1733
1801
  }
1734
1802
 
1803
+ // src/read-scope.ts
1804
+ var CAPTURE_READ_GUARD = /* @__PURE__ */ Symbol.for("node-autotask.capture-read-guard.v1");
1805
+ function captureReadGuard(http, operation) {
1806
+ return http[CAPTURE_READ_GUARD](operation);
1807
+ }
1808
+
1735
1809
  // src/auth.ts
1736
1810
  var AUTH_HEADERS = {
1737
1811
  integrationCode: "ApiIntegrationCode",
@@ -14791,6 +14865,13 @@ async function discoverZoneBase(userName, maxResponseBytes, signal, ctx) {
14791
14865
  var META_TRIO_VERBS = /* @__PURE__ */ new Set(["getEntityInfo", "getFieldInfo", "getUdfInfo"]);
14792
14866
  var RETRY = { done: false };
14793
14867
  var HttpClient = class {
14868
+ /** Retain this build's caller scope without sharing ambient storage. @internal */
14869
+ [CAPTURE_READ_GUARD](operation) {
14870
+ const signal = ambientCallerSignal();
14871
+ return () => {
14872
+ if (signal?.aborted) throw new AutotaskAbortError("Read aborted by the caller", { operation });
14873
+ };
14874
+ }
14794
14875
  /**
14795
14876
  * The LIVE base URL (issue #43): the construction-time value until a zone
14796
14877
  * re-point happens, then the tenant's newly resolved zone base. Reads are
@@ -15842,6 +15923,133 @@ var WORKFLOW_RESOURCES = [
15842
15923
  "projects"
15843
15924
  ];
15844
15925
 
15926
+ // src/metadata-views.ts
15927
+ function liveFieldNamesView(rows) {
15928
+ if (!Array.isArray(rows)) return null;
15929
+ const names = [];
15930
+ for (const row of rows) if (typeof row.name === "string") names.push(row.name);
15931
+ return names.length === 0 ? null : { names, known: new Set(names) };
15932
+ }
15933
+ function projectFieldRow(raw, labels = false, udf = false) {
15934
+ const r = typeof raw === "object" && raw !== null ? raw : {};
15935
+ const name = typeof r.name === "string" ? r.name : "";
15936
+ const type = typeof r.dataType === "string" ? r.dataType : typeof r.type === "string" ? r.type : "";
15937
+ const values = labels && r.isPickList === true && Array.isArray(r.picklistValues) && r.picklistValues.length > 0 ? r.picklistValues : void 0;
15938
+ const referenceEntityType = typeof r.referenceEntityType === "string" ? r.referenceEntityType : "";
15939
+ return {
15940
+ name,
15941
+ ...typeof r.label === "string" && r.label !== "" ? { label: r.label } : {},
15942
+ type,
15943
+ isRequired: r.isRequired === true,
15944
+ isReadOnly: r.isReadOnly === true,
15945
+ // Issue #219 N7: a UDF row never serves the vendor's isQueryable (it is
15946
+ // true for UDFs while a plain filter on a UDF name is refused); it serves
15947
+ // the marker the filter actually needs.
15948
+ ...udf ? { filterable: "udf-marker" } : { isQueryable: r.isQueryable === true },
15949
+ isPickList: r.isPickList === true,
15950
+ ...isObjectOrArrayType(type) ? { writeShape: "replace-all" } : {},
15951
+ maxLength: typeof r.length === "number" ? r.length : null,
15952
+ referenceEntityType,
15953
+ ...values !== void 0 ? { picklistValues: values } : {}
15954
+ };
15955
+ }
15956
+ function isObjectOrArrayType(type) {
15957
+ const t = type.trim().toLowerCase();
15958
+ return t === "object" || t === "array" || t === "collection" || t.endsWith("[]");
15959
+ }
15960
+ function exposesPicklistValues(raw) {
15961
+ const r = typeof raw === "object" && raw !== null ? raw : {};
15962
+ return Array.isArray(r.picklistValues) && r.picklistValues.length > 0;
15963
+ }
15964
+ function catalogList(raw, labels, udf) {
15965
+ return Array.isArray(raw) ? { rows: raw.map((row) => projectFieldRow(row, labels, udf)), exposesValues: raw.some(exposesPicklistValues) } : { rows: null, exposesValues: false };
15966
+ }
15967
+ var catalogFieldsView = (raw) => catalogList(raw, false, false);
15968
+ var catalogLabelledFieldsView = (raw) => catalogList(raw, true, false);
15969
+ var catalogUdfView = (raw) => catalogList(raw, false, true);
15970
+ var catalogLabelledUdfView = (raw) => catalogList(raw, true, true);
15971
+ function compactCatalogList(raw, keepValues, udf) {
15972
+ const view = catalogList(raw, keepValues, udf);
15973
+ if (view.rows === null) return { rows: null, exposesValues: view.exposesValues };
15974
+ const flags = {
15975
+ required: view.rows.filter((row) => row.isRequired).map((row) => row.name),
15976
+ readOnly: view.rows.filter((row) => row.isReadOnly).map((row) => row.name),
15977
+ queryable: view.rows.filter((row) => row.isQueryable).map((row) => row.name),
15978
+ picklistFields: view.rows.filter((row) => row.isPickList).map((row) => row.name)
15979
+ };
15980
+ return {
15981
+ rows: view.rows.map((row) => ({
15982
+ name: row.name,
15983
+ type: row.type,
15984
+ isPickList: row.isPickList,
15985
+ isReference: row.referenceEntityType !== "",
15986
+ udf,
15987
+ ...keepValues && row.picklistValues !== void 0 ? { picklistValues: row.picklistValues } : {}
15988
+ })),
15989
+ flags,
15990
+ exposesValues: view.exposesValues
15991
+ };
15992
+ }
15993
+ var compactCatalogFieldsView = (raw) => compactCatalogList(raw, false, false);
15994
+ var compactCatalogLabelledFieldsView = (raw) => compactCatalogList(raw, true, false);
15995
+ var compactCatalogUdfView = (raw) => compactCatalogList(raw, false, true);
15996
+ var compactCatalogLabelledUdfView = (raw) => compactCatalogList(raw, true, true);
15997
+ function ticketStatusView(fields) {
15998
+ if (!Array.isArray(fields)) return [];
15999
+ const status = fields.find((f) => typeof f?.name === "string" && f.name.toLowerCase() === "status");
16000
+ if (status === void 0 || status.isPickList !== true || !Array.isArray(status.picklistValues)) return [];
16001
+ const out = [];
16002
+ for (const v of status.picklistValues) {
16003
+ const id = Number(v?.value);
16004
+ if (!Number.isSafeInteger(id)) continue;
16005
+ out.push({ id, label: typeof v.label === "string" ? v.label : "" });
16006
+ }
16007
+ return out;
16008
+ }
16009
+ function primitiveData(descriptor2) {
16010
+ return descriptor2 !== void 0 && "value" in descriptor2 && (descriptor2.value === null || typeof descriptor2.value !== "object" && typeof descriptor2.value !== "function");
16011
+ }
16012
+ function picklistsView(raw) {
16013
+ if (!Array.isArray(raw)) return null;
16014
+ const fields = /* @__PURE__ */ new Map();
16015
+ for (const rawField of raw) {
16016
+ const field = projectFieldRow(rawField, true);
16017
+ if (fields.has(field.name)) continue;
16018
+ const values = field.picklistValues;
16019
+ if (values === void 0) {
16020
+ fields.set(field.name, void 0);
16021
+ continue;
16022
+ }
16023
+ const labels = /* @__PURE__ */ new Map();
16024
+ if (values.some((entry) => {
16025
+ if (entry === null || typeof entry !== "object" || Object.getPrototypeOf(entry) !== Object.prototype) return true;
16026
+ return !primitiveData(Object.getOwnPropertyDescriptor(entry, "value")) || !primitiveData(Object.getOwnPropertyDescriptor(entry, "label"));
16027
+ })) {
16028
+ fields.set(field.name, { labels, ordered: values });
16029
+ continue;
16030
+ }
16031
+ for (const value of values) {
16032
+ const key = String(value.value);
16033
+ if (!labels.has(key)) labels.set(key, typeof value.label === "string" ? value.label : null);
16034
+ }
16035
+ fields.set(field.name, { labels });
16036
+ }
16037
+ return fields;
16038
+ }
16039
+ function lookupPicklist(view, value) {
16040
+ if (view.ordered !== void 0) {
16041
+ const hit = view.ordered.find((entry) => String(entry.value) === String(value));
16042
+ return { found: hit !== void 0, label: typeof hit?.label === "string" ? hit.label : null };
16043
+ }
16044
+ const key = String(value);
16045
+ return { found: view.labels.has(key), label: view.labels.get(key) ?? null };
16046
+ }
16047
+ function ticketStatusFieldsView(fields) {
16048
+ if (!Array.isArray(fields)) return [];
16049
+ const status = fields.find((field) => typeof field?.name === "string" && field.name.toLowerCase() === "status");
16050
+ return status === void 0 ? [] : [status];
16051
+ }
16052
+
15845
16053
  // src/utils/bounded.ts
15846
16054
  async function runBounded(fn, items, opts) {
15847
16055
  const { concurrency, signal, settle } = opts;
@@ -15897,48 +16105,7 @@ var MAX_FIELD_CATALOG_WIRE = 60;
15897
16105
  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.";
15898
16106
  var MIN_FIELD_CATALOG_MAX_BYTES = 4096;
15899
16107
  var FIELD_CATALOG_OPT_KEYS = ["resources", "include", "fresh", "fields", "labels", "compact", "maxBytes"];
15900
- function projectFieldRow(raw, labels = false, udf = false) {
15901
- const r = typeof raw === "object" && raw !== null ? raw : {};
15902
- const name = typeof r.name === "string" ? r.name : "";
15903
- const type = typeof r.dataType === "string" ? r.dataType : typeof r.type === "string" ? r.type : "";
15904
- const values = labels && r.isPickList === true && Array.isArray(r.picklistValues) && r.picklistValues.length > 0 ? r.picklistValues : void 0;
15905
- const referenceEntityType = typeof r.referenceEntityType === "string" ? r.referenceEntityType : "";
15906
- return {
15907
- name,
15908
- ...typeof r.label === "string" && r.label !== "" ? { label: r.label } : {},
15909
- type,
15910
- isRequired: r.isRequired === true,
15911
- isReadOnly: r.isReadOnly === true,
15912
- // Issue #219 N7: a UDF row never serves the vendor's isQueryable (it is
15913
- // true for UDFs while a plain filter on a UDF name is refused); it serves
15914
- // the marker the filter actually needs.
15915
- ...udf ? { filterable: "udf-marker" } : { isQueryable: r.isQueryable === true },
15916
- isPickList: r.isPickList === true,
15917
- ...isObjectOrArrayType(type) ? { writeShape: "replace-all" } : {},
15918
- maxLength: typeof r.length === "number" ? r.length : null,
15919
- referenceEntityType,
15920
- ...values !== void 0 ? { picklistValues: values } : {}
15921
- };
15922
- }
15923
- function compactFieldRow(f, udf, keepValues) {
15924
- return {
15925
- name: f.name,
15926
- type: f.type,
15927
- isPickList: f.isPickList,
15928
- isReference: f.referenceEntityType !== "",
15929
- udf,
15930
- ...keepValues && f.picklistValues !== void 0 ? { picklistValues: f.picklistValues } : {}
15931
- };
15932
- }
15933
- function isObjectOrArrayType(type) {
15934
- const t = type.trim().toLowerCase();
15935
- return t === "object" || t === "array" || t === "collection" || t.endsWith("[]");
15936
- }
15937
- function exposesPicklistValues(raw) {
15938
- const r = typeof raw === "object" && raw !== null ? raw : {};
15939
- return Array.isArray(r.picklistValues) && r.picklistValues.length > 0;
15940
- }
15941
- function applyFieldsFilter(projected, filter, row) {
16108
+ function applyFieldsFilter(projected, filter, row, flags) {
15942
16109
  const kept = filter === void 0 ? projected : projected.filter((f) => filter.includes(f.name));
15943
16110
  if (filter !== void 0) {
15944
16111
  const present = new Set(projected.map((f) => f.name));
@@ -15946,10 +16113,19 @@ function applyFieldsFilter(projected, filter, row) {
15946
16113
  row.projected = true;
15947
16114
  }
15948
16115
  row.fields = kept;
15949
- row.required = kept.filter((f) => f.isRequired).map((f) => f.name);
15950
- row.readOnly = kept.filter((f) => f.isReadOnly).map((f) => f.name);
15951
- row.queryable = kept.filter((f) => f.isQueryable).map((f) => f.name);
15952
- row.picklistFields = kept.filter((f) => f.isPickList).map((f) => f.name);
16116
+ if (flags !== void 0) {
16117
+ const present = new Set(kept.map((field) => field.name));
16118
+ row.required = flags.required.filter((name) => present.has(name));
16119
+ row.readOnly = flags.readOnly.filter((name) => present.has(name));
16120
+ row.queryable = flags.queryable.filter((name) => present.has(name));
16121
+ row.picklistFields = flags.picklistFields.filter((name) => present.has(name));
16122
+ } else {
16123
+ const full = kept;
16124
+ row.required = full.filter((field) => field.isRequired).map((field) => field.name);
16125
+ row.readOnly = full.filter((field) => field.isReadOnly).map((field) => field.name);
16126
+ row.queryable = full.filter((field) => field.isQueryable).map((field) => field.name);
16127
+ row.picklistFields = full.filter((field) => field.isPickList).map((field) => field.name);
16128
+ }
15953
16129
  }
15954
16130
  async function capabilitySets() {
15955
16131
  const fieldOps = /* @__PURE__ */ new Map();
@@ -16164,14 +16340,25 @@ function kindFetches(holder, resource) {
16164
16340
  udf: () => holder?.getUdfInfo?.() ?? Promise.reject(new AutotaskError(`fieldCatalog: the client exposes no getUdfInfo read for "${resource}"`, { code: "INVALID_RESPONSE", category: "server" }))
16165
16341
  };
16166
16342
  }
16167
- async function readKind(ctx, resource, kind, fetch2) {
16343
+ function catalogProjector(kind, ctx) {
16344
+ if (ctx.compact) {
16345
+ const keepValues = ctx.labels && ctx.fieldsFilter !== void 0;
16346
+ if (kind === "fields") return keepValues ? compactCatalogLabelledFieldsView : compactCatalogFieldsView;
16347
+ if (kind === "udf") return keepValues ? compactCatalogLabelledUdfView : compactCatalogUdfView;
16348
+ }
16349
+ if (kind === "fields") return ctx.labels ? catalogLabelledFieldsView : catalogFieldsView;
16350
+ if (kind === "udf") return ctx.labels ? catalogLabelledUdfView : catalogUdfView;
16351
+ return void 0;
16352
+ }
16353
+ async function readKind(ctx, resource, kind, fetch2, holder, projector = catalogProjector(kind, ctx)) {
16168
16354
  const cache = ctx.client.http.fieldCache;
16169
16355
  const peek = cache !== void 0 && !ctx.fresh ? cache.peek(fieldKey(resource, kind)) : { hit: false, age: null };
16170
16356
  if (peek.hit && cache !== void 0) {
16171
- return { kind, peek, outcome: { status: "fulfilled", value: cache.get(fieldKey(resource, kind)) } };
16357
+ const value = projector !== void 0 && typeof cache.getProjected === "function" ? cache.getProjected(fieldKey(resource, kind), projector) ?? projector(void 0) : projector === void 0 ? cache.get(fieldKey(resource, kind)) : projector(cache.get(fieldKey(resource, kind)));
16358
+ return { kind, peek, outcome: { status: "fulfilled", value } };
16172
16359
  }
16173
16360
  try {
16174
- const value = await fetch2();
16361
+ const value = projector === void 0 ? await fetch2() : await readMetadataProjection(holder, kind, projector, fetch2);
16175
16362
  return { kind, peek, outcome: { status: "fulfilled", value } };
16176
16363
  } catch (error) {
16177
16364
  if (!isAutotaskError(error) || error.code === "ABORTED") throw error;
@@ -16179,7 +16366,7 @@ async function readKind(ctx, resource, kind, fetch2) {
16179
16366
  }
16180
16367
  }
16181
16368
  async function sweepResource(ctx, resource, tally, reads) {
16182
- const { fieldsFilter, labels } = ctx;
16369
+ const { fieldsFilter } = ctx;
16183
16370
  const fieldOp = ctx.fieldOps.get(resource);
16184
16371
  if (fieldOp === void 0) return void 0;
16185
16372
  const apiEntity = apiEntityFor(fieldOp);
@@ -16198,12 +16385,6 @@ async function sweepResource(ctx, resource, tally, reads) {
16198
16385
  wire: 0,
16199
16386
  error: null
16200
16387
  };
16201
- const projectList = (kind, list) => {
16202
- const projected = list.map((f) => projectFieldRow(f, labels, kind === "udf"));
16203
- if (kind === "fields") applyFieldsFilter(projected, fieldsFilter, row);
16204
- else row.udf = projected;
16205
- for (const f of list) if (exposesPicklistValues(f)) tally.anyPicklistValues = true;
16206
- };
16207
16388
  let allCached = true;
16208
16389
  const ages = [];
16209
16390
  for (const { kind, peek, outcome } of reads) {
@@ -16221,19 +16402,17 @@ async function sweepResource(ctx, resource, tally, reads) {
16221
16402
  if (kind === "info") {
16222
16403
  row.info = value ?? null;
16223
16404
  } else {
16224
- if (!Array.isArray(value)) {
16405
+ const view = value;
16406
+ if (view.rows === null) {
16225
16407
  if (row.error === null) row.error = { code: "INVALID_RESPONSE", message: `fieldCatalog: the ${kind} response for ${resource} was not a list` };
16226
16408
  continue;
16227
16409
  }
16228
- projectList(kind, value);
16410
+ if (kind === "fields") applyFieldsFilter(view.rows, fieldsFilter, row, view.flags);
16411
+ else row.udf = view.rows;
16412
+ if (view.exposesValues) tally.anyPicklistValues = true;
16229
16413
  }
16230
16414
  }
16231
16415
  row.cache = allCached ? { hit: true, age: ages.length > 0 ? Math.max(...ages) : 0 } : { hit: false, age: null };
16232
- if (ctx.compact) {
16233
- const keepValues = labels && fieldsFilter !== void 0;
16234
- if (row.fields !== void 0) row.fields = row.fields.map((f) => compactFieldRow(f, false, keepValues));
16235
- if (Array.isArray(row.udf)) row.udf = row.udf.map((f) => compactFieldRow(f, true, keepValues));
16236
- }
16237
16416
  const declared = await derivedFieldsFor(resource);
16238
16417
  if (declared.length > 0) {
16239
16418
  const byField = new Map(declared.map((d) => [d.field, d]));
@@ -16249,7 +16428,7 @@ async function sweepResource(ctx, resource, tally, reads) {
16249
16428
  }
16250
16429
  return row;
16251
16430
  }
16252
- async function fieldCatalog(client, opts) {
16431
+ async function prepareCatalog(client, opts) {
16253
16432
  validateCatalogOptsShape(opts);
16254
16433
  const { fieldOps, udfCapable, resources: allResources } = await capabilitySets();
16255
16434
  const include = resolveInclude(opts);
@@ -16258,11 +16437,22 @@ async function fieldCatalog(client, opts) {
16258
16437
  const labels = resolveLabels(opts);
16259
16438
  const { compact, maxBytes } = resolveSizeOpts(opts);
16260
16439
  assertWithinWireCap(targets.length, include.length);
16440
+ const ctx = { client, include, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
16441
+ return { ctx, targets, compact, maxBytes };
16442
+ }
16443
+ async function fieldCatalogPicklists(client, resource, fields) {
16444
+ const { ctx } = await prepareCatalog(client, { resources: [resource], labels: true, fields: [...fields] });
16445
+ const holder = client[camelKey(resource)];
16446
+ const [read] = await mapReadTasks(client.http, [resource], () => readKind(ctx, resource, "fields", kindFetches(holder, resource).fields, holder, picklistsView));
16447
+ return read.outcome.status === "fulfilled" ? read.outcome.value : null;
16448
+ }
16449
+ async function fieldCatalog(client, opts) {
16450
+ const { ctx, targets, compact, maxBytes } = await prepareCatalog(client, opts);
16451
+ const { include, labels, fieldOps, udfCapable } = ctx;
16261
16452
  const cache = client.http.fieldCache;
16262
16453
  const zone = client.config.zone ?? "unknown";
16263
16454
  const rows = [];
16264
16455
  const tally = { wireUsed: 0, anyPicklistValues: false };
16265
- const ctx = { client, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
16266
16456
  for (const resource of targets) {
16267
16457
  apiEntityFor(fieldOps.get(resource));
16268
16458
  if (ctx.fresh) cache?.invalidate(`${resource}:`);
@@ -16270,9 +16460,9 @@ async function fieldCatalog(client, opts) {
16270
16460
  const tasks = targets.flatMap((resource) => {
16271
16461
  const holder = client[camelKey(resource)];
16272
16462
  const fetches = kindFetches(holder, resource);
16273
- return include.map((kind) => ({ resource, kind, fetch: fetches[kind] }));
16463
+ return include.map((kind) => ({ resource, kind, fetch: fetches[kind], holder }));
16274
16464
  });
16275
- const reads = await mapReadTasks(client.http, tasks, ({ resource, kind, fetch: fetch2 }) => readKind(ctx, resource, kind, fetch2));
16465
+ const reads = await mapReadTasks(client.http, tasks, ({ resource, kind, fetch: fetch2, holder }) => readKind(ctx, resource, kind, fetch2, holder));
16276
16466
  for (let index = 0; index < targets.length; index += 1) {
16277
16467
  const start = index * include.length;
16278
16468
  const row = await sweepResource(ctx, targets[index], tally, reads.slice(start, start + include.length));
@@ -16874,19 +17064,12 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16874
17064
  };
16875
17065
  });
16876
17066
  }
16877
- const picklists = {};
17067
+ let picklists = null;
16878
17068
  if (plan.labelFields.length > 0) {
16879
17069
  tasks.push(async () => {
16880
17070
  try {
16881
17071
  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
- }
16889
- }
17072
+ picklists = await fieldCatalogPicklists(client, labelResource, plan.labelFields);
16890
17073
  } catch (err) {
16891
17074
  if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16892
17075
  }
@@ -16922,17 +17105,17 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16922
17105
  recordName: (table, id) => section.rows[`${table}:${id}`]?.name ?? null,
16923
17106
  labelFor: (field, value) => {
16924
17107
  if (value === null || value === void 0) return null;
16925
- const values = picklists[field];
17108
+ const values = picklists?.get(field);
16926
17109
  if (values === void 0) {
16927
17110
  section.reasons[field] = FIELD_CATALOG_HONESTY_NOTE;
16928
17111
  return null;
16929
17112
  }
16930
- const hit = values.find((v) => String(v.value) === String(value));
16931
- if (hit === void 0) {
17113
+ const hit = lookupPicklist(values, value);
17114
+ if (!hit.found) {
16932
17115
  if (String(value) !== "0") section.reasons[field] = PICKLIST_VALUE_NOT_SERVED_NOTE;
16933
17116
  return null;
16934
17117
  }
16935
- return typeof hit.label === "string" ? hit.label : null;
17118
+ return hit.label;
16936
17119
  }
16937
17120
  };
16938
17121
  }
@@ -16994,8 +17177,7 @@ function subscriberError(error, operation) {
16994
17177
  };
16995
17178
  return copyValue(error);
16996
17179
  }
16997
- function cachedRead(http, cache, key, path, operation, request, fresh, shouldStore) {
16998
- if (cache === void 0) return request();
17180
+ function cachedRead(http, cache, key, path, operation, request, fresh, shouldStore, projector) {
16999
17181
  let ownsLoader = false;
17000
17182
  const loader = (signal) => {
17001
17183
  ownsLoader = true;
@@ -17010,11 +17192,21 @@ function cachedRead(http, cache, key, path, operation, request, fresh, shouldSto
17010
17192
  suggestedAction: "The caller aborted; re-issue the call if still needed."
17011
17193
  })
17012
17194
  };
17013
- return cache.load(key, loader, options).catch((error) => {
17195
+ const select = (value) => {
17196
+ if (options.signal?.aborted) throw options.abortError();
17197
+ const selected = projector === void 0 ? value : projectMetadata(value, projector);
17198
+ if (options.signal?.aborted) throw options.abortError();
17199
+ return selected;
17200
+ };
17201
+ if (cache === void 0) return request().then(select);
17202
+ const load = (fresh2) => projector !== void 0 && typeof cache.loadProjected === "function" ? cache.loadProjected(key, loader, projector, { ...options, fresh: fresh2 }) : cache.load(key, loader, { ...options, fresh: fresh2 }).then(select);
17203
+ return load(fresh).catch((error) => {
17014
17204
  if (ownsLoader || !(error instanceof AutotaskError) || error.details?.budgetScope !== "client" || error.notSent !== true) throw error;
17015
17205
  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 });
17206
+ const projected = projector !== void 0 && typeof cache.getProjected === "function";
17207
+ const warm = projected ? cache.getProjected(key, projector) : cache.get(key);
17208
+ if (options.signal?.aborted) throw options.abortError();
17209
+ return warm !== void 0 ? projected ? warm : select(warm) : load(true);
17018
17210
  }).catch((error) => {
17019
17211
  if (!(error instanceof AutotaskError)) throw error;
17020
17212
  const failure = subscriberError(error, operation);
@@ -17033,7 +17225,7 @@ function cachedRecordGet(http, path, operation, fresh = false) {
17033
17225
  fresh
17034
17226
  );
17035
17227
  }
17036
- function cachedMetadataGet(http, resource, kind, path, operation, unwrap, fresh = false, maxRetries) {
17228
+ function cachedMetadataGet(http, resource, kind, path, operation, unwrap, fresh = false, maxRetries, projector) {
17037
17229
  const cache = http.fieldCache;
17038
17230
  const request = (signal) => {
17039
17231
  return http.request({ method: "GET", path, operation, signal, maxRetries }).then(unwrap).catch((error) => {
@@ -17047,7 +17239,7 @@ function cachedMetadataGet(http, resource, kind, path, operation, unwrap, fresh
17047
17239
  if (value === null || value === void 0) return false;
17048
17240
  if (Array.isArray(value)) return value.length > 0;
17049
17241
  return typeof value !== "object" || Object.keys(value).length > 0;
17050
- });
17242
+ }, projector);
17051
17243
  }
17052
17244
 
17053
17245
  // src/field-sets.ts
@@ -17545,6 +17737,12 @@ function validateWalkBag(walk, prefix, details) {
17545
17737
  return wr;
17546
17738
  }
17547
17739
 
17740
+ // src/operations/query-pages.ts
17741
+ var PREPARE_BOUNDED_QUERY = /* @__PURE__ */ Symbol.for("node-autotask.prepare-bounded-query.v1");
17742
+ function assertPageReadActive(operation) {
17743
+ if (ambientCallerSignal()?.aborted) throw new AutotaskAbortError("Bounded query page consumption aborted by the caller", { operation });
17744
+ }
17745
+
17548
17746
  // src/resources/base/query.ts
17549
17747
  var QueryBase = class {
17550
17748
  httpClient;
@@ -17719,6 +17917,22 @@ var QueryBase = class {
17719
17917
  * Pure read; no mutation paths involved.
17720
17918
  */
17721
17919
  async queryBounded(params) {
17920
+ return this.boundedQueryResult(params);
17921
+ }
17922
+ /** Internal governed consumer hook; all validation and paging stay shared. @internal */
17923
+ [PREPARE_BOUNDED_QUERY]() {
17924
+ const guard = captureReadGuard(this.http, `${this.config.key}.query`);
17925
+ return {
17926
+ guard,
17927
+ consume: async (params, consume) => {
17928
+ guard();
17929
+ const { items, ...summary } = await this.boundedQueryResult(params, consume);
17930
+ guard();
17931
+ return summary;
17932
+ }
17933
+ };
17934
+ }
17935
+ async boundedQueryResult(params, consume) {
17722
17936
  if (Array.isArray(params)) {
17723
17937
  throw new AutotaskConfigError(
17724
17938
  "queryBounded: params must be an object { filter?, limit?, latest?, includeFields? } \u2014 a bare conditions array is not accepted (wrap it: { filter: [...] })"
@@ -17765,13 +17979,28 @@ var QueryBase = class {
17765
17979
  if (latest !== void 0) {
17766
17980
  return this.applyNoteChars(await this.latestWalk(walkParams, Math.max(limit, latest), latest), noteChars);
17767
17981
  }
17768
- const { items, pages: pages2, guard, sliced, cursor, names } = await this.walkBounded(walkParams, cap, limit, labelPages);
17769
- const hasMore = maxRows === void 0 ? (items.length >= cap || guard) && (sliced > 0 || cursor !== null) : guard || sliced > 0 || cursor !== null;
17770
- const result = { items, fetched: items.length, hasMore, pagesWalked: pages2 };
17982
+ let truncatedFields = 0;
17983
+ const sink = consume === void 0 ? void 0 : async (rows, page) => {
17984
+ const projected = this.applyNoteChars({ items: rows, fetched: rows.length, hasMore: false, pagesWalked: 1 }, noteChars);
17985
+ truncatedFields += projected.noteCharsTruncated ?? 0;
17986
+ assertPageReadActive(`${this.config.key}.query`);
17987
+ try {
17988
+ await consume({ items: projected.items, page });
17989
+ } catch (error) {
17990
+ assertPageReadActive(`${this.config.key}.query`);
17991
+ throw error;
17992
+ }
17993
+ assertPageReadActive(`${this.config.key}.query`);
17994
+ };
17995
+ const { items, fetched, pages: pages2, guard, sliced, cursor, names } = await this.walkBounded(walkParams, cap, limit, labelPages, sink);
17996
+ const hasMore = maxRows === void 0 ? (fetched >= cap || guard) && (sliced > 0 || cursor !== null) : guard || sliced > 0 || cursor !== null;
17997
+ const result = { items, fetched, hasMore, pagesWalked: pages2 };
17771
17998
  if (maxRows !== void 0) result.truncated = hasMore;
17772
17999
  if (names !== void 0) result.names = names;
17773
18000
  this.stampEmptyQueryResult(result, params);
17774
- return this.applyNoteChars(result, noteChars);
18001
+ if (consume === void 0) return this.applyNoteChars(result, noteChars);
18002
+ if (truncatedFields > 0) result.noteCharsTruncated = truncatedFields;
18003
+ return result;
17775
18004
  }
17776
18005
  /** Issue #61 (slice A): the noteChars truncation at the SINGLE chokepoint
17777
18006
  * of `queryBounded` — the normal walk and the `latest` paths both
@@ -17800,9 +18029,10 @@ var QueryBase = class {
17800
18029
  * SOFT stop (never a throw). ONE per-walk closure (walks never share
17801
18030
  * state).
17802
18031
  * @internal */
17803
- async walkBounded(p, limit, pageSizeBase, labelPages = false) {
18032
+ async walkBounded(p, limit, pageSizeBase, labelPages = false, consume) {
17804
18033
  const state2 = { cursor: null };
17805
18034
  const items = [];
18035
+ let fetched = 0;
17806
18036
  let pages2 = 0;
17807
18037
  let sliced = 0;
17808
18038
  let guard = false;
@@ -17814,6 +18044,7 @@ var QueryBase = class {
17814
18044
  guard = true;
17815
18045
  break;
17816
18046
  }
18047
+ if (consume !== void 0) assertPageReadActive(`${this.config.key}.query`);
17817
18048
  const page = await this.fetchPage(p, pages2 + 1, pageSize, state2);
17818
18049
  pages2 += 1;
17819
18050
  if (labelPages && this.http.client !== void 0) {
@@ -17824,18 +18055,20 @@ var QueryBase = class {
17824
18055
  Object.assign(nameReasons, labelled.names.reasons);
17825
18056
  }
17826
18057
  }
17827
- const remaining = limit - items.length;
18058
+ const remaining = limit - fetched;
17828
18059
  const take = page.items.slice(0, remaining);
17829
18060
  sliced += Math.max(0, page.items.length - remaining);
17830
- items.push(...take);
17831
- if (items.length >= limit) break;
18061
+ fetched += take.length;
18062
+ if (consume === void 0) items.push(...take);
18063
+ else await consume(take, pages2);
18064
+ if (fetched >= limit) break;
17832
18065
  if (!page.hasMore || page.items.length === 0) break;
17833
18066
  }
17834
18067
  const names = nameNotes.size === 0 ? void 0 : {
17835
18068
  note: [...nameNotes].join("; "),
17836
18069
  ...Object.keys(nameReasons).length === 0 ? {} : { reasons: nameReasons }
17837
18070
  };
17838
- return { items, pages: pages2, guard, sliced, cursor: state2.cursor, ...names === void 0 ? {} : { names } };
18071
+ return { items, fetched, pages: pages2, guard, sliced, cursor: state2.cursor, ...names === void 0 ? {} : { names } };
17839
18072
  }
17840
18073
  /** A walk stop is TRUNCATED when the 1000-page guard fired, or the limit
17841
18074
  * was met with a live next cursor (or a sliced final page): rows exist
@@ -17859,7 +18092,7 @@ var QueryBase = class {
17859
18092
  * speculation).
17860
18093
  * @internal */
17861
18094
  stampEmptyQueryResult(result, params) {
17862
- if (result.items.length !== 0) return;
18095
+ if (result.fetched !== 0) return;
17863
18096
  result.blindSurface = blindStampFor(BLIND_SURFACE_STAMPS[this.config.key]?.query, params?.filter);
17864
18097
  const pinnedReason = normalizedConditions(params?.filter) === void 0 ? EMPTY_REASON_STAMPS[this.config.key]?.query : void 0;
17865
18098
  if (result.blindSurface !== void 0 || pinnedReason !== void 0) {
@@ -18095,7 +18328,7 @@ var QueryBase = class {
18095
18328
  };
18096
18329
 
18097
18330
  // src/resources/base/meta.ts
18098
- var MetaBase = class extends QueryBase {
18331
+ var MetaBase = class _MetaBase extends QueryBase {
18099
18332
  // ------------------------------------------------------------------
18100
18333
  // Single-record reads
18101
18334
  // ------------------------------------------------------------------
@@ -18242,21 +18475,7 @@ var MetaBase = class extends QueryBase {
18242
18475
  * entity's entries via the fieldCache's `invalidate` first — the trio
18243
18476
  * keeps its no-arg surface (the registry/MCP arity pin). */
18244
18477
  async getEntityInfo() {
18245
- return await this.cachedMeta(
18246
- "info",
18247
- `${this.resourcePath}/entityInformation`,
18248
- `${this.config.key}.getEntityInfo`,
18249
- (res) => {
18250
- const body = isRecord2(res) ? res : void 0;
18251
- if (body === void 0 || !isRecord2(body.info)) {
18252
- throw new AutotaskError("Expected the entityInformation envelope { info }; got a different shape", {
18253
- code: "INVALID_RESPONSE",
18254
- category: "server"
18255
- });
18256
- }
18257
- return body.info;
18258
- }
18259
- );
18478
+ return await this.metadataRead("info");
18260
18479
  }
18261
18480
  /** `GET /V1.0/<E>/entityInformation/fields` → `{ fields }` unwrapped.
18262
18481
  * Goes through the field cache when it is present (issue #80:
@@ -18266,12 +18485,7 @@ var MetaBase = class extends QueryBase {
18266
18485
  * entity's entries via the fieldCache's `invalidate` first — the trio
18267
18486
  * keeps its no-arg surface (the registry/MCP arity pin). */
18268
18487
  async getFieldInfo() {
18269
- return await this.cachedMeta(
18270
- "fields",
18271
- `${this.resourcePath}/entityInformation/fields`,
18272
- `${this.config.key}.getFieldInfo`,
18273
- (res) => this.unwrapFields(res, "FieldInformationResultModel")
18274
- );
18488
+ return await this.metadataRead("fields");
18275
18489
  }
18276
18490
  /** `GET /V1.0/<E>/entityInformation/userDefinedFields` → `{ fields }` unwrapped.
18277
18491
  * Goes through the field cache when it is present (issue #80:
@@ -18281,12 +18495,29 @@ var MetaBase = class extends QueryBase {
18281
18495
  * entity's entries via the fieldCache's `invalidate` first — the trio
18282
18496
  * keeps its no-arg surface (the registry/MCP arity pin). */
18283
18497
  async getUdfInfo() {
18284
- return await this.cachedMeta(
18285
- "udf",
18286
- `${this.resourcePath}/entityInformation/userDefinedFields`,
18287
- `${this.config.key}.getUdfInfo`,
18288
- (res) => this.unwrapFields(res, "UserDefinedFieldInformationResultModel")
18289
- );
18498
+ return await this.metadataRead("udf");
18499
+ }
18500
+ /** Capture the owning transport's context; overridden readers keep their original path. @internal */
18501
+ [METADATA_PROJECTION](kind, projector) {
18502
+ const reader = kind === "info" ? "getEntityInfo" : kind === "fields" ? "getFieldInfo" : "getUdfInfo";
18503
+ const guard = captureReadGuard(this.http, `${this.config.key}.${reader}`);
18504
+ guard();
18505
+ if (this[reader] !== _MetaBase.prototype[reader] || this.cachedMeta !== _MetaBase.prototype.cachedMeta) return { guard };
18506
+ return { guard, projected: this.metadataRead(kind, projector) };
18507
+ }
18508
+ metadataRead(kind, projector) {
18509
+ const suffix = kind === "info" ? "" : kind === "fields" ? "/fields" : "/userDefinedFields";
18510
+ const operation = kind === "info" ? "getEntityInfo" : kind === "fields" ? "getFieldInfo" : "getUdfInfo";
18511
+ const path = `${this.resourcePath}/entityInformation${suffix}`;
18512
+ const unwrap = (res) => {
18513
+ if (kind !== "info") return this.unwrapFields(res, kind === "fields" ? "FieldInformationResultModel" : "UserDefinedFieldInformationResultModel");
18514
+ const body = isRecord2(res) ? res : void 0;
18515
+ if (body === void 0 || !isRecord2(body.info)) {
18516
+ throw new AutotaskError("Expected the entityInformation envelope { info }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
18517
+ }
18518
+ return body.info;
18519
+ };
18520
+ return projector === void 0 ? this.cachedMeta(kind, path, `${this.config.key}.${operation}`, unwrap) : cachedMetadataGet(this.http, this.config.key, kind, path, `${this.config.key}.${operation}`, unwrap, false, void 0, projector);
18290
18521
  }
18291
18522
  /** @internal */
18292
18523
  unwrapFields(body, envelopeName) {
@@ -21103,13 +21334,7 @@ async function liveFieldNames(holder) {
21103
21334
  const reader = holder.getFieldInfo;
21104
21335
  if (typeof reader !== "function") return null;
21105
21336
  try {
21106
- const rows = await reader.call(holder);
21107
- if (!Array.isArray(rows)) return null;
21108
- const names = [];
21109
- for (const row of rows) {
21110
- if (typeof row.name === "string") names.push(row.name);
21111
- }
21112
- return names.length > 0 ? names : null;
21337
+ return await readMetadataProjection(holder, "fields", liveFieldNamesView, () => reader.call(holder));
21113
21338
  } catch (err) {
21114
21339
  if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
21115
21340
  return null;
@@ -21184,7 +21409,7 @@ function readIncludeNames(record, includeFields) {
21184
21409
  return names;
21185
21410
  }
21186
21411
  function resolveAuthority(record, live) {
21187
- if (live !== null) return { known: live, authority: "the tenant's live entity field metadata", hasField: (name) => live.includes(name) };
21412
+ if (live !== null) return { known: live.names, authority: "the tenant's live entity field metadata", hasField: (name) => live.known.has(name) };
21188
21413
  const vendored = MODEL_FIELD_SETS[record.resource];
21189
21414
  const modelHas = modelFieldLookup(record.resource);
21190
21415
  const liveOnlyExempt = Array.isArray(record.metadata?.liveOnlyFields) ? record.metadata.liveOnlyFields : [];
@@ -21249,18 +21474,6 @@ async function findUnknownFieldNames(record, holder, lists) {
21249
21474
  var ASSUMED_CLOSED_STATUS_ID = 5;
21250
21475
  var CLOSED_STATUS_LABELS = ["complete", "completed", "closed", "cancelled", "canceled", "resolved"];
21251
21476
  var OP = "tickets.statusSemantics";
21252
- function picklistOf(fields) {
21253
- if (!Array.isArray(fields)) return [];
21254
- const status = fields.find((f) => typeof f?.name === "string" && f.name.toLowerCase() === "status");
21255
- if (status === void 0 || status.isPickList !== true || !Array.isArray(status.picklistValues)) return [];
21256
- const out = [];
21257
- for (const v of status.picklistValues) {
21258
- const id = Number(v?.value);
21259
- if (!Number.isSafeInteger(id)) continue;
21260
- out.push({ id, label: typeof v.label === "string" ? v.label : "" });
21261
- }
21262
- return out;
21263
- }
21264
21477
  async function readFields(http, fresh) {
21265
21478
  return cachedMetadataGet(http, "tickets", "fields", "/V1.0/Tickets/entityInformation/fields", OP, (res) => {
21266
21479
  const fields = res?.fields;
@@ -21268,7 +21481,7 @@ async function readFields(http, fresh) {
21268
21481
  throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
21269
21482
  }
21270
21483
  return fields;
21271
- }, fresh, 0);
21484
+ }, fresh, 0, ticketStatusFieldsView);
21272
21485
  }
21273
21486
  function assumed(allowAssumed, operation) {
21274
21487
  if (!allowAssumed) {
@@ -21305,7 +21518,7 @@ async function resolveTicketStatusSemantics(http, opts = {}, operation = OP) {
21305
21518
  if (e instanceof AutotaskError && e.code === "ABORTED") throw e;
21306
21519
  return assumed(allowAssumed, operation);
21307
21520
  }
21308
- const picklist = picklistOf(fields);
21521
+ const picklist = ticketStatusView(fields);
21309
21522
  const closedIds = picklist.filter((v) => CLOSED_STATUS_LABELS.includes(v.label.trim().toLowerCase())).map((v) => v.id);
21310
21523
  if (closedIds.length === 0) return assumed(allowAssumed, operation);
21311
21524
  const labels = picklist.filter((v) => closedIds.includes(v.id)).map((v) => `${v.id} ${v.label}`).join(", ");
@@ -27867,25 +28080,46 @@ async function requireReadBack(record, operation, opts) {
27867
28080
  }
27868
28081
  var PRE_REQUEST_VALIDATORS = [
27869
28082
  (c) => governPreRequest(c.record, c.operation, c.opts),
28083
+ (c) => {
28084
+ if (!c.streaming) return;
28085
+ if (!c.boundedQuery) throw new AutotaskConfigError("invokeReadPages: only primitive query reads support bounded page consumption", { operation: c.operation });
28086
+ const holder = c.holder;
28087
+ const prepare2 = holder[PREPARE_BOUNDED_QUERY];
28088
+ if (typeof prepare2 !== "function") {
28089
+ throw new AutotaskConfigError("invokeReadPages: the resource does not support governed bounded page consumption", { operation: c.operation });
28090
+ }
28091
+ const session = prepare2.call(holder);
28092
+ if (typeof session?.guard !== "function" || typeof session.consume !== "function") throw new AutotaskConfigError("invokeReadPages: the resource has no scoped page consumer", { operation: c.operation });
28093
+ c.pageSession = session;
28094
+ session.guard();
28095
+ },
27870
28096
  (c) => requireReadBack(c.record, c.operation, c.opts),
27871
28097
  (c) => validateDispatchArgs(c.record, c.args),
27872
28098
  (c) => validateParamsBag(c.record, c.args),
27873
28099
  (c) => validateFreshSpelling(c.record, c.args),
28100
+ (c) => {
28101
+ if (!c.streaming) return;
28102
+ const bag = c.args[0];
28103
+ if (bag?.["walk"] === void 0 || bag?.["latest"] !== void 0) {
28104
+ throw new AutotaskConfigError("invokeReadPages: an explicit walk.maxRows query without latest is required", { operation: c.operation });
28105
+ }
28106
+ },
27874
28107
  (c) => c.boundedQuery || c.countedQuery ? validateQueryFieldNames(c.record, c.holder, c.args) : Promise.resolve(void 0)
27875
28108
  ];
27876
28109
  async function runPreRequestPass(ctx) {
27877
28110
  for (const step of PRE_REQUEST_VALIDATORS) await step(ctx);
27878
28111
  }
27879
- async function invokeMode(client, operation, argsIn = [], opts = {}) {
28112
+ async function prepareInvocation(client, operation, argsIn, opts, streaming = false) {
27880
28113
  const record = await resolveRecord(operation);
27881
28114
  const args = resolveDispatchArgs(record, argsIn);
27882
28115
  const boundedQuery = record.kind === "primitive" && record.operation === "query";
27883
28116
  const countedQuery = record.kind === "primitive" && record.operation === "count";
27884
28117
  const holder = resolveHolder(client, record, operation);
27885
- await runPreRequestPass({ record, operation, args, opts, client, holder, boundedQuery, countedQuery });
28118
+ const context = { record, operation, args, opts, client, holder, boundedQuery, countedQuery, streaming };
28119
+ await runPreRequestPass(context);
27886
28120
  const labelQuery = boundedQuery && readNamesOpt(client, args[0]?.["names"], `invoke: "${record.id}" params bag`);
27887
28121
  const methodName = boundedQuery ? "queryBounded" : record.operation;
27888
- const method = holder[methodName];
28122
+ const method = streaming ? context.pageSession?.consume : holder[methodName];
27889
28123
  if (typeof method !== "function") {
27890
28124
  throw new AutotaskConfigError(
27891
28125
  `invoke: "${record.resource}.${methodName}" is not a callable method on the client`,
@@ -27901,6 +28135,10 @@ async function invokeMode(client, operation, argsIn = [], opts = {}) {
27901
28135
  if (boundedQuery && args[0]?.["acknowledgeUnscoped"] !== true) {
27902
28136
  scopeNote = (await guardUnscopedQueryWalk(holder, record.id, args[0])).note;
27903
28137
  }
28138
+ return { record, args, holder, method, callArgs, labelQuery, scopeNote, pageSession: context.pageSession };
28139
+ }
28140
+ async function invokeMode(client, operation, argsIn = [], opts = {}) {
28141
+ const { record, args, holder, method, callArgs, labelQuery, scopeNote } = await prepareInvocation(client, operation, argsIn, opts);
27904
28142
  const result = await method.apply(holder, callArgs);
27905
28143
  if (labelQuery && args[0]?.["walk"] === void 0 && Array.isArray(result?.items)) {
27906
28144
  const bounded = result;
@@ -27916,6 +28154,15 @@ async function invoke(client, operation, args = [], opts = {}) {
27916
28154
  async function invokeRead(client, operation, args = [], opts = {}) {
27917
28155
  return invokeMode(client, operation, args, { ...opts, mode: "read" });
27918
28156
  }
28157
+ async function invokeReadPages(client, operation, args, onPage, opts = {}) {
28158
+ if (typeof onPage !== "function") throw new AutotaskConfigError("invokeReadPages: onPage must be a function", { operation });
28159
+ const prepared = await prepareInvocation(client, operation, args, { ...opts, mode: "read" }, true);
28160
+ prepared.pageSession.guard();
28161
+ const consume = prepared.method;
28162
+ const result = await consume.call(prepared.holder, prepared.callArgs[0], onPage);
28163
+ prepared.pageSession.guard();
28164
+ return prepared.scopeNote === void 0 ? result : { ...result, scopeNote: prepared.scopeNote };
28165
+ }
27919
28166
  async function invokeWrite(client, operation, args = [], opts = {}) {
27920
28167
  return invokeMode(client, operation, args, { ...opts, mode: "write" });
27921
28168
  }
@@ -28079,4 +28326,4 @@ var ContractsResource = class extends GenericResource {
28079
28326
  }
28080
28327
  };
28081
28328
 
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 };
28329
+ 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, invokeReadPages, 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 };