node-autotask 0.92.0 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/MCP_TOOL_CATALOG.json +255 -9
  3. package/README.md +1 -1
  4. package/capabilities.json +1042 -222
  5. package/dist/capabilities-data.js +1296 -476
  6. package/dist/capabilities.cjs +4 -4
  7. package/dist/capabilities.js +1 -1
  8. package/dist/{chunk-ATDGRAX2.cjs → chunk-2FM7MRK2.cjs} +32 -30
  9. package/dist/{chunk-ELAU2MT5.js → chunk-3SURRIOQ.js} +4 -2
  10. package/dist/{chunk-2MC3LDZU.js → chunk-DCISF6AG.js} +3 -3
  11. package/dist/{chunk-XAOWO42G.js → chunk-FCQPZAIK.js} +4 -2
  12. package/dist/{chunk-NQNAEA23.js → chunk-HJKI5VVJ.js} +981 -523
  13. package/dist/{chunk-QXJQIZCT.cjs → chunk-SBHQIPCJ.cjs} +3 -3
  14. package/dist/{chunk-JPZ7M7QI.cjs → chunk-X7FGWEZ2.cjs} +202 -200
  15. package/dist/{chunk-H24SV774.cjs → chunk-ZIBH42H3.cjs} +987 -527
  16. package/dist/{index-B9y5IwT1.d.cts → index-Cbos4Wgx.d.cts} +100 -2
  17. package/dist/{index-B9y5IwT1.d.ts → index-Cbos4Wgx.d.ts} +100 -2
  18. package/dist/{index-lWek2NrV.d.cts → index-CnNxnu7M.d.cts} +14 -2
  19. package/dist/{index-U7Lepdm2.d.ts → index-coyFHSSF.d.ts} +14 -2
  20. package/dist/index.cjs +89 -85
  21. package/dist/index.d.cts +8 -4
  22. package/dist/index.d.ts +8 -4
  23. package/dist/index.js +5 -5
  24. package/dist/operations/index.cjs +51 -51
  25. package/dist/operations/index.d.cts +7 -4
  26. package/dist/operations/index.d.ts +7 -4
  27. package/dist/operations/index.js +2 -2
  28. package/dist/pool.cjs +12 -12
  29. package/dist/pool.d.cts +1 -1
  30. package/dist/pool.d.ts +1 -1
  31. package/dist/pool.js +4 -4
  32. package/dist/resources/index.cjs +27 -27
  33. package/dist/resources/index.d.cts +2 -2
  34. package/dist/resources/index.d.ts +2 -2
  35. package/dist/resources/index.js +3 -3
  36. package/dist/types/index.d.cts +1 -1
  37. package/dist/types/index.d.ts +1 -1
  38. package/docs/API.md +40 -2
  39. package/examples/mcp-server-http.ts +6 -3
  40. package/package.json +1 -1
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkQXJQIZCT_cjs = require('./chunk-QXJQIZCT.cjs');
3
+ var chunkSBHQIPCJ_cjs = require('./chunk-SBHQIPCJ.cjs');
4
4
  var chunkCM5O672I_cjs = require('./chunk-CM5O672I.cjs');
5
5
  var crypto = require('crypto');
6
6
  var async_hooks = require('async_hooks');
7
+ var util = require('util');
7
8
 
8
9
  // src/errors/base.ts
9
10
  function nextActionFor(code, opts = {}) {
@@ -1442,6 +1443,7 @@ function resolveConfig(config) {
1442
1443
  }
1443
1444
 
1444
1445
  // src/http/types.ts
1446
+ var INVENTORY_APPROVAL_PRODUCT_ID = /* @__PURE__ */ Symbol("inventoryApprovalProductId");
1445
1447
  var IDEMPOTENT_METHODS = ["GET", "PUT", "DELETE"];
1446
1448
  var AUDIT_DECIMAL_ID = /^(?:0|[1-9]\d{0,18})$/;
1447
1449
  var MAX_AUDIT_ID = "9223372036854775807";
@@ -6051,7 +6053,26 @@ var RELATIONSHIP_MAP = {
6051
6053
  "workflowResource": false,
6052
6054
  "group": "B",
6053
6055
  "parent": null,
6054
- "children": [],
6056
+ "children": [
6057
+ {
6058
+ "resource": "organizational_resources",
6059
+ "apiEntity": "OrganizationalResource",
6060
+ "parentField": "organizationalLevelAssociationID",
6061
+ "parentSegment": "Resources",
6062
+ "tier": "advanced",
6063
+ "workflowResource": false,
6064
+ "specialOps": [
6065
+ "listByParent"
6066
+ ],
6067
+ "searchCovers": null,
6068
+ "scopedOps": {
6069
+ "create": false,
6070
+ "query": true,
6071
+ "update": false,
6072
+ "delete": false
6073
+ }
6074
+ }
6075
+ ],
6055
6076
  "naturalKeys": {
6056
6077
  "hasSearch": false,
6057
6078
  "searchCovers": null,
@@ -7302,6 +7323,24 @@ var RELATIONSHIP_MAP = {
7302
7323
  "delete": true
7303
7324
  }
7304
7325
  },
7326
+ {
7327
+ "resource": "resource_daily_availabilities",
7328
+ "apiEntity": "ResourceDailyAvailability",
7329
+ "parentField": "resourceID",
7330
+ "parentSegment": "DailyAvailabilities",
7331
+ "tier": "advanced",
7332
+ "workflowResource": false,
7333
+ "specialOps": [
7334
+ "listByParent"
7335
+ ],
7336
+ "searchCovers": null,
7337
+ "scopedOps": {
7338
+ "create": false,
7339
+ "query": true,
7340
+ "update": false,
7341
+ "delete": false
7342
+ }
7343
+ },
7305
7344
  {
7306
7345
  "resource": "resource_role_queues",
7307
7346
  "apiEntity": "ResourceRoleQueue",
@@ -11125,6 +11164,56 @@ var RELATIONSHIP_MAP = {
11125
11164
  "zoneFacts": null,
11126
11165
  "deleteBoundary": null,
11127
11166
  "markerField": null
11167
+ },
11168
+ "resource_daily_availabilities": {
11169
+ "resource": "resource_daily_availabilities",
11170
+ "apiEntity": "ResourceDailyAvailability",
11171
+ "kind": "entity",
11172
+ "path": "ResourceDailyAvailabilities",
11173
+ "parentScoped": true,
11174
+ "tier": "advanced",
11175
+ "workflowResource": false,
11176
+ "group": "B",
11177
+ "parent": {
11178
+ "resource": "resources",
11179
+ "segment": "DailyAvailabilities",
11180
+ "field": "resourceID"
11181
+ },
11182
+ "children": [],
11183
+ "naturalKeys": {
11184
+ "hasSearch": false,
11185
+ "searchCovers": null,
11186
+ "findBy": []
11187
+ },
11188
+ "blindSurfaces": null,
11189
+ "zoneFacts": null,
11190
+ "deleteBoundary": null,
11191
+ "markerField": null
11192
+ },
11193
+ "organizational_resources": {
11194
+ "resource": "organizational_resources",
11195
+ "apiEntity": "OrganizationalResource",
11196
+ "kind": "entity",
11197
+ "path": "OrganizationalResources",
11198
+ "parentScoped": true,
11199
+ "tier": "advanced",
11200
+ "workflowResource": false,
11201
+ "group": "B",
11202
+ "parent": {
11203
+ "resource": "organizational_level_associations",
11204
+ "segment": "Resources",
11205
+ "field": "organizationalLevelAssociationID"
11206
+ },
11207
+ "children": [],
11208
+ "naturalKeys": {
11209
+ "hasSearch": false,
11210
+ "searchCovers": null,
11211
+ "findBy": []
11212
+ },
11213
+ "blindSurfaces": null,
11214
+ "zoneFacts": null,
11215
+ "deleteBoundary": null,
11216
+ "markerField": null
11128
11217
  }
11129
11218
  };
11130
11219
  var BLIND_SURFACE_STAMPS = {
@@ -16604,6 +16693,9 @@ var UNTRUSTED_FIELDS_BY_RESOURCE = {
16604
16693
  "shipping_types": [
16605
16694
  "description",
16606
16695
  "name"
16696
+ ],
16697
+ "resource_daily_availabilities": [
16698
+ "travelAvailability"
16607
16699
  ]
16608
16700
  };
16609
16701
 
@@ -17062,11 +17154,22 @@ function auditReadTarget(path, operation) {
17062
17154
  function isKnowledgeBaseRootResource(resource) {
17063
17155
  return resource === "knowledge_base_categories" || resource === "knowledge_base_articles";
17064
17156
  }
17157
+ var STAFF_COLLECTION_PATHS = {
17158
+ organizational_resources: /^\/v1\.0\/OrganizationalLevelAssociations\/\d+\/Resources\/?$/i,
17159
+ resource_daily_availabilities: /^\/v1\.0\/Resources\/\d+\/DailyAvailabilities\/?$/i
17160
+ };
17161
+ function hasNativeStaffCollection(resource) {
17162
+ return Object.hasOwn(STAFF_COLLECTION_PATHS, resource);
17163
+ }
17065
17164
  function isExactRecordResource(resource) {
17066
- return resource === "inventory_locations" || resource === "inventory_items" || resource === "internal_locations" || resource === "shipping_types" || isKnowledgeBaseRootResource(resource);
17165
+ return hasNativeStaffCollection(resource) || resource === "inventory_locations" || resource === "inventory_items" || resource === "internal_locations" || resource === "shipping_types" || isKnowledgeBaseRootResource(resource);
17067
17166
  }
17068
- var EXACT_RECORD_PATH = /^\/v1\.0\/(?:InventoryLocations|InventoryItems|InternalLocations|ShippingTypes|KnowledgeBaseArticles|KnowledgeBaseCategories(?:\/\d+\/KnowledgeBaseArticles)?)(?:\/(query(?:\/(?:next|previous|count))?|\d+))?\/?$/i;
17167
+ var EXACT_RECORD_PATH = /^\/v1\.0\/(?:OrganizationalResources|ResourceDailyAvailabilities|InventoryLocations|InventoryItems|InternalLocations|ShippingTypes|KnowledgeBaseArticles|KnowledgeBaseCategories(?:\/\d+\/KnowledgeBaseArticles)?)(?:\/(query(?:\/(?:next|previous|count))?|\d+))?\/?$/i;
17069
17168
  function exactRecordResponseTarget(path, method, operation) {
17169
+ if (method === "GET" && operation?.endsWith(".listByParent")) {
17170
+ const resource = operation.slice(0, -".listByParent".length);
17171
+ if (hasNativeStaffCollection(resource) && STAFF_COLLECTION_PATHS[resource].test(path)) return "query";
17172
+ }
17070
17173
  const match = EXACT_RECORD_PATH.exec(path);
17071
17174
  if (match === null) return void 0;
17072
17175
  const suffix = match[1]?.toLowerCase();
@@ -17134,7 +17237,7 @@ function validateExactRecordResponse(body, target, path, method, requestBody, op
17134
17237
  if (String(id) !== expectedId) {
17135
17238
  throw new AutotaskConfigError(`returned ${resource} id must match the requested id`, { operation });
17136
17239
  }
17137
- if (parts.length === 6) {
17240
+ if (entity === "knowledgebasearticles" && parts.length === 6) {
17138
17241
  const parent = ownField(item, "articleCategoryID");
17139
17242
  if (typeof parent !== "number" || !Number.isInteger(parent) || parent <= 0 || parent > 2147483647) {
17140
17243
  invalid("Expected a valid category ID in the Knowledge Base article response");
@@ -17160,13 +17263,22 @@ function decodeResponseJson(text, auditTarget, recordTarget, path) {
17160
17263
  }
17161
17264
  const idTokens = /* @__PURE__ */ new WeakMap();
17162
17265
  const receiptTokens = /* @__PURE__ */ new WeakMap();
17163
- const holidaySetTokens = /* @__PURE__ */ new WeakMap();
17164
- const internalLocations = path !== void 0 && /^\/v1\.0\/InternalLocations\//i.test(path);
17266
+ const signedIdTokens = /* @__PURE__ */ new WeakMap();
17267
+ const nativeStaffQuery = recordTarget === "query" && path !== void 0;
17268
+ const organizationalList = nativeStaffQuery && STAFF_COLLECTION_PATHS.organizational_resources.test(path);
17269
+ const nativeParentField = organizationalList ? "organizationalLevelAssociationID" : nativeStaffQuery && STAFF_COLLECTION_PATHS.resource_daily_availabilities.test(path) ? "resourceID" : void 0;
17270
+ const invalidNativeParents = nativeParentField === void 0 ? void 0 : /* @__PURE__ */ new WeakSet();
17271
+ const organizationalRead = organizationalList || path !== void 0 && (target === "query" || target === "item") && /^\/v1\.0\/OrganizationalResources\//i.test(path);
17272
+ const signedIdField = organizationalRead ? "soapParentPropertyId" : path !== void 0 && /^\/v1\.0\/InternalLocations\//i.test(path) ? "holidaySetId" : void 0;
17165
17273
  const body = JSON.parse(text, function(key, value, context) {
17166
17274
  if (typeof value === "number" && context?.source !== void 0) {
17167
- if (key === "id") idTokens.set(this, context.source);
17168
- if (key === "itemId" && target === "mutation") receiptTokens.set(this, context.source);
17169
- if (internalLocations && key === "holidaySetId") holidaySetTokens.set(this, context.source);
17275
+ const token = context.source;
17276
+ if (key === "id") idTokens.set(this, token);
17277
+ if (key === "itemId" && target === "mutation") receiptTokens.set(this, token);
17278
+ if (key === signedIdField) signedIdTokens.set(this, token);
17279
+ if (key === nativeParentField && (!isAuditDecimalId(token) || value > 2147483647)) {
17280
+ invalidNativeParents?.add(this);
17281
+ }
17170
17282
  }
17171
17283
  return value;
17172
17284
  });
@@ -17174,9 +17286,12 @@ function decodeResponseJson(text, auditTarget, recordTarget, path) {
17174
17286
  if (Array.isArray(rows)) {
17175
17287
  for (const row of rows) {
17176
17288
  if (!isRecord2(row)) continue;
17177
- const holidaySet = holidaySetTokens.get(row);
17178
- if (holidaySet !== void 0 && !Number.isSafeInteger(row.holidaySetId) && isSignedInt64Token(holidaySet)) {
17179
- row.holidaySetId = holidaySet;
17289
+ if (nativeParentField !== void 0 && invalidNativeParents?.has(row)) {
17290
+ row[nativeParentField] = null;
17291
+ }
17292
+ const signedId = signedIdTokens.get(row);
17293
+ if (signedIdField !== void 0 && signedId !== void 0 && !Number.isSafeInteger(row[signedIdField]) && isSignedInt64Token(signedId)) {
17294
+ row[signedIdField] = signedId;
17180
17295
  }
17181
17296
  const key = target === "mutation" && ownField(row, "itemId") !== void 0 ? "itemId" : "id";
17182
17297
  const value = ownField(row, key);
@@ -17226,6 +17341,16 @@ function attachEmptyReasonDetails(err) {
17226
17341
  err.details = { ...err.details ?? {} };
17227
17342
  if (stamp !== void 0) {
17228
17343
  err.details.emptyReason = stamp;
17344
+ } else if (isGetMiss && hasNativeStaffCollection(resource)) {
17345
+ const remedy = `Verify the ID with ${resource}.query and an exact id filter, or use ${resource}.listByParent with the known parent ID. Check the API user's permissions.`;
17346
+ err.suggestedAction = remedy;
17347
+ err.details.emptyReason = {
17348
+ surface,
17349
+ kind: "not-found",
17350
+ authority: `${resource}.query`,
17351
+ note: "No record at this ID was visible to this API user.",
17352
+ remedy
17353
+ };
17229
17354
  } else if (isGetMiss) {
17230
17355
  const blind = BLIND_SURFACE_STAMPS[resource]?.query;
17231
17356
  err.details.emptyReason = blind !== void 0 ? {
@@ -17803,7 +17928,8 @@ var HttpClient = class {
17803
17928
  }
17804
17929
  let parsed;
17805
17930
  try {
17806
- parsed = decodeResponseJson(text, s.auditTarget, s.recordTarget, decodeURIComponent(s.opts.path));
17931
+ const decodeTarget = opts[INVENTORY_APPROVAL_PRODUCT_ID] === true ? "item" : s.recordTarget;
17932
+ parsed = decodeResponseJson(text, s.auditTarget, decodeTarget, decodeURIComponent(s.opts.path));
17807
17933
  } catch {
17808
17934
  return this.handleNonJson2xx(s, res, status, text);
17809
17935
  }
@@ -18459,114 +18585,610 @@ function slimCompany(row) {
18459
18585
  return { id: row.id, companyName: row.companyName, isActive: row.isActive, parentCompanyID: row.parentCompanyID };
18460
18586
  }
18461
18587
 
18462
- // src/operations/requiredFields.ts
18463
- function effectiveRequiredFields(record, zoneFacts) {
18464
- const guidance = zoneFacts?.createGuidance;
18465
- const prefix = guidance?.liveProvenPrefix;
18466
- if (Array.isArray(prefix) && prefix.length > 0) {
18467
- const gates = guidance?.requiresByValue;
18468
- const gated = new Set((gates ?? []).flatMap((g) => [...g.requires.allOf ?? [], ...g.requires.anyOf ?? []]));
18469
- return {
18470
- fields: prefix.filter((f) => !gated.has(f)),
18471
- from: "live-proven",
18472
- unproven: guidance?.unproven === true,
18473
- ...Array.isArray(gates) && gates.length > 0 ? { conditional: gates } : {}
18474
- };
18475
- }
18476
- const zoneSet = zoneFacts?.createRequiredSet;
18477
- if (Array.isArray(zoneSet) && zoneSet.length > 0) {
18478
- return { fields: [...zoneSet], from: "zone", unproven: guidance?.unproven === true };
18588
+ // src/resources/base/helpers.ts
18589
+ function describeResponseShape(body) {
18590
+ if (body === null) return "null";
18591
+ if (Array.isArray(body)) return `array(len=${body.length})`;
18592
+ if (typeof body !== "object") return typeof body;
18593
+ const rec = body;
18594
+ const keys = Object.keys(rec).sort();
18595
+ const typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
18596
+ const parts = keys.slice(0, 16).map((k) => `${k}:${typeOf(rec[k])}`);
18597
+ const more = keys.length > 16 ? `, +${keys.length - 16} more` : "";
18598
+ return `{ ${parts.join(", ")}${more} }`;
18599
+ }
18600
+ function defaultMarkerToken(data) {
18601
+ for (const field of ["name", "title"]) {
18602
+ const v = data[field];
18603
+ if (typeof v === "string" && v.trim() !== "") return v.trim();
18479
18604
  }
18480
- const spec = record?.requiredFields;
18481
- return { fields: Array.isArray(spec) ? [...spec] : [], from: "spec", unproven: true };
18605
+ return null;
18482
18606
  }
18483
-
18484
- // src/operations/types.ts
18485
- var WORKFLOW_RESOURCES = [
18486
- "companies",
18487
- "tickets",
18488
- "contacts",
18489
- "configuration_items",
18490
- "projects"
18491
- ];
18492
-
18493
- // src/metadata-views.ts
18494
- function liveFieldNamesView(rows) {
18495
- if (!Array.isArray(rows)) return null;
18496
- const names = [];
18497
- for (const row of rows) if (typeof row.name === "string") names.push(row.name);
18498
- return names.length === 0 ? null : { names, known: new Set(names) };
18607
+ var CONTEXT_ABSENT_MARKER = "#context-absent";
18608
+ function contextAbsentKey(path) {
18609
+ return path + "\0context-absent";
18499
18610
  }
18500
- function projectFieldRow(raw, labels = false, udf = false) {
18501
- const r = typeof raw === "object" && raw !== null ? raw : {};
18502
- const name = typeof r.name === "string" ? r.name : "";
18503
- const type = typeof r.dataType === "string" ? r.dataType : typeof r.type === "string" ? r.type : "";
18504
- const values = labels && r.isPickList === true && Array.isArray(r.picklistValues) && r.picklistValues.length > 0 ? r.picklistValues : void 0;
18505
- const referenceEntityType = typeof r.referenceEntityType === "string" ? r.referenceEntityType : "";
18506
- return {
18507
- name,
18508
- ...typeof r.label === "string" && r.label !== "" ? { label: r.label } : {},
18509
- type,
18510
- isRequired: r.isRequired === true,
18511
- isReadOnly: r.isReadOnly === true,
18512
- // Issue #219 N7: a UDF row never serves the vendor's isQueryable (it is
18513
- // true for UDFs while a plain filter on a UDF name is refused); it serves
18514
- // the marker the filter actually needs.
18515
- ...udf ? { filterable: "udf-marker" } : { isQueryable: r.isQueryable === true },
18516
- isPickList: r.isPickList === true,
18517
- ...isObjectOrArrayType(type) ? { writeShape: "replace-all" } : {},
18518
- maxLength: typeof r.length === "number" ? r.length : null,
18519
- referenceEntityType,
18520
- ...values !== void 0 ? { picklistValues: values } : {}
18521
- };
18611
+ function noteCharsTruncationMarker(charsRemoved) {
18612
+ return `\u2026 [+${charsRemoved} chars truncated]`;
18522
18613
  }
18523
- function isObjectOrArrayType(type) {
18524
- const t = type.trim().toLowerCase();
18525
- return t === "object" || t === "array" || t === "collection" || t.endsWith("[]");
18614
+ function truncateNoteChars(items, cap, fields) {
18615
+ let truncated = 0;
18616
+ const out = items.map((item) => {
18617
+ if (!isRecord2(item)) return item;
18618
+ let changed = false;
18619
+ const copy = { ...item };
18620
+ for (const field of fields) {
18621
+ const v = copy[field];
18622
+ if (typeof v === "string" && v !== chunkCM5O672I_cjs.REDACTED && v.length > cap) {
18623
+ const end = cap > 0 && (v.charCodeAt(cap - 1) & 64512) === 55296 ? cap - 1 : cap;
18624
+ copy[field] = v.slice(0, end) + noteCharsTruncationMarker(v.length - end);
18625
+ truncated += 1;
18626
+ changed = true;
18627
+ }
18628
+ }
18629
+ return changed ? copy : item;
18630
+ });
18631
+ return [out, truncated];
18526
18632
  }
18527
- function exposesPicklistValues(raw) {
18528
- const r = typeof raw === "object" && raw !== null ? raw : {};
18529
- return Array.isArray(r.picklistValues) && r.picklistValues.length > 0;
18633
+ function blindEmptyReason(stamp) {
18634
+ return {
18635
+ surface: stamp.surface,
18636
+ kind: "blind-surface",
18637
+ note: stamp.note,
18638
+ authority: stamp.authority,
18639
+ remedy: "the note is the remedy \u2014 the authority op answers for a record"
18640
+ };
18530
18641
  }
18531
- function catalogList(raw, labels, udf) {
18532
- return Array.isArray(raw) ? { rows: raw.map((row) => projectFieldRow(row, labels, udf)), exposesValues: raw.some(exposesPicklistValues) } : { rows: null, exposesValues: false };
18642
+ function attachUpdateTargetMissReason(err, key) {
18643
+ const pinned = EMPTY_REASON_STAMPS[key]?.update;
18644
+ if (pinned === void 0) return;
18645
+ err.details = { ...err.details ?? {}, emptyReason: pinned };
18533
18646
  }
18534
- var catalogFieldsView = (raw) => catalogList(raw, false, false);
18535
- var catalogLabelledFieldsView = (raw) => catalogList(raw, true, false);
18536
- var catalogUdfView = (raw) => catalogList(raw, false, true);
18537
- var catalogLabelledUdfView = (raw) => catalogList(raw, true, true);
18538
- function compactCatalogList(raw, keepValues, udf) {
18539
- const view = catalogList(raw, keepValues, udf);
18540
- if (view.rows === null) return { rows: null, exposesValues: view.exposesValues };
18541
- const flags = {
18542
- required: view.rows.filter((row) => row.isRequired).map((row) => row.name),
18543
- readOnly: view.rows.filter((row) => row.isReadOnly).map((row) => row.name),
18544
- queryable: view.rows.filter((row) => row.isQueryable).map((row) => row.name),
18545
- picklistFields: view.rows.filter((row) => row.isPickList).map((row) => row.name)
18546
- };
18647
+ function buildDryRunResult(spec, policy) {
18648
+ if (spec.operation === "") {
18649
+ throw new AutotaskConfigError("dry-run: the operation name is required");
18650
+ }
18651
+ const wouldApply = spec.checks.every((check) => check.ok);
18652
+ const resource = spec.operation.split(".")[0] ?? spec.operation;
18653
+ const diffPart = spec.diff !== void 0 ? {
18654
+ diff: spec.diff.map((entry) => {
18655
+ if (entry.to === void 0) return entry;
18656
+ const to = isRedactedFieldName(entry.field, policy) ? chunkCM5O672I_cjs.REDACTED : redactResponseBody(entry.to, policy);
18657
+ return { ...entry, to };
18658
+ })
18659
+ } : {};
18660
+ const dataPart = spec.data !== void 0 ? { data: redactResponseBody(spec.data, policy) } : {};
18547
18661
  return {
18548
- rows: view.rows.map((row) => ({
18549
- name: row.name,
18550
- type: row.type,
18551
- isPickList: row.isPickList,
18552
- isReference: row.referenceEntityType !== "",
18553
- udf,
18554
- ...keepValues && row.picklistValues !== void 0 ? { picklistValues: row.picklistValues } : {}
18555
- })),
18556
- flags,
18557
- exposesValues: view.exposesValues
18662
+ operation: spec.operation,
18663
+ wouldApply,
18664
+ target: { resource, ids: spec.ids },
18665
+ request: { method: spec.method, path: spec.path },
18666
+ ...diffPart,
18667
+ checks: spec.checks,
18668
+ impact: spec.impact,
18669
+ simulated: true,
18670
+ warnings: spec.warnings ?? [],
18671
+ ...dataPart,
18672
+ ...spec.emptyReason !== void 0 ? { emptyReason: spec.emptyReason } : {}
18558
18673
  };
18559
18674
  }
18560
- var compactCatalogFieldsView = (raw) => compactCatalogList(raw, false, false);
18561
- var compactCatalogLabelledFieldsView = (raw) => compactCatalogList(raw, true, false);
18562
- var compactCatalogUdfView = (raw) => compactCatalogList(raw, false, true);
18563
- var compactCatalogLabelledUdfView = (raw) => compactCatalogList(raw, true, true);
18564
- function ticketStatusView(fields) {
18565
- if (!Array.isArray(fields)) return [];
18566
- const status = fields.find((f) => typeof f?.name === "string" && f.name.toLowerCase() === "status");
18567
- if (status === void 0 || status.isPickList !== true || !Array.isArray(status.picklistValues)) return [];
18675
+ function computeFieldDiff(current, data) {
18568
18676
  const out = [];
18569
- for (const v of status.picklistValues) {
18677
+ for (const [field, to] of Object.entries(data)) {
18678
+ if (field === "id" || to === void 0) continue;
18679
+ const from = Object.hasOwn(current, field) ? current[field] : void 0;
18680
+ if (from !== void 0 && JSON.stringify(from) === JSON.stringify(to)) continue;
18681
+ out.push({ field, from: from === void 0 ? null : from, to });
18682
+ }
18683
+ return out;
18684
+ }
18685
+ function mergePartialBody(current, data) {
18686
+ const merged = { ...current };
18687
+ for (const [key, value] of Object.entries(data)) {
18688
+ if (value === void 0) continue;
18689
+ merged[key] = value;
18690
+ }
18691
+ return merged;
18692
+ }
18693
+ function snapshotMutationOptions(options) {
18694
+ const { dryRun, lastModifiedDate, maxRetries, raw, verifyPersisted } = options ?? {};
18695
+ if (dryRun !== void 0 && typeof dryRun !== "boolean") {
18696
+ throw new AutotaskConfigError("dryRun must be a boolean");
18697
+ }
18698
+ return { dryRun, lastModifiedDate, maxRetries, raw, verifyPersisted };
18699
+ }
18700
+ function normalizeUdfInput(value) {
18701
+ if (Array.isArray(value)) {
18702
+ return value.map((entry) => {
18703
+ if (!isRecord2(entry) || typeof entry.name !== "string" || entry.name === "") {
18704
+ throw new AutotaskConfigError("userDefinedFields array entries must be { name, value } objects");
18705
+ }
18706
+ return { name: entry.name, value: entry.value };
18707
+ });
18708
+ }
18709
+ if (isRecord2(value)) {
18710
+ return Object.entries(value).map(([name, entryValue]) => ({ name, value: entryValue }));
18711
+ }
18712
+ throw new AutotaskConfigError("userDefinedFields must be an array of { name, value } entries or a name-to-value map");
18713
+ }
18714
+ function blindStampFor(stamp, filter) {
18715
+ if (stamp === void 0) return void 0;
18716
+ if (stamp.kind !== "unfiltered-blind") return stamp;
18717
+ const conditions = normalizedConditions(filter);
18718
+ return conditions === void 0 || conditions.length === 0 ? stamp : void 0;
18719
+ }
18720
+ function decodeFileData(body) {
18721
+ if (isRecord2(body)) {
18722
+ const data = body.data;
18723
+ if (typeof data === "string") return Buffer.from(data, "base64");
18724
+ if (Array.isArray(data) && data.every((b) => typeof b === "number")) {
18725
+ return Buffer.from(data);
18726
+ }
18727
+ }
18728
+ if (typeof body === "string") return Buffer.from(body, "base64");
18729
+ throw new AutotaskError(
18730
+ "Expected the file envelope FileQueryResultModel { data } (or a base64 string); got a different shape",
18731
+ { code: "INVALID_RESPONSE", category: "server" }
18732
+ );
18733
+ }
18734
+ var DEPLURAL_EXCEPTIONS = {
18735
+ tag_aliase: "tag_alias"
18736
+ };
18737
+ function entityNameFromPath(resourcePath) {
18738
+ const segment = resourcePath.slice(resourcePath.lastIndexOf("/") + 1);
18739
+ const snake = segment.replace(/([A-Z])/g, (_m, c, i) => (i > 0 ? `_` : "") + c.toLowerCase()).replace(/_{2,}/g, "_");
18740
+ if (snake.endsWith("ies")) return `${snake.slice(0, -3)}y`;
18741
+ if (snake.endsWith("s")) {
18742
+ const stripped = snake.slice(0, -1);
18743
+ return DEPLURAL_EXCEPTIONS[stripped] ?? stripped;
18744
+ }
18745
+ return snake;
18746
+ }
18747
+
18748
+ // src/resources/special/inventoryItems.ts
18749
+ var REFERENCES = ["inventoryLocationID", "productID"];
18750
+ var QUANTITIES = ["quantityMinimum", "quantityMaximum", "quantityOnHand"];
18751
+ var TEXT_FIELDS = ["bin", "referenceNumber"];
18752
+ var MUTATION_OPTIONS = ["dryRun", "lastModifiedDate", "maxRetries", "raw", "verifyPersisted", "expectedInventoryFacts"];
18753
+ function fail(message) {
18754
+ throw new AutotaskConfigError(`inventory_items: ${message}`);
18755
+ }
18756
+ function own(record, field) {
18757
+ return Object.hasOwn(record, field) ? record[field] : void 0;
18758
+ }
18759
+ function int32(value, label, minimum = -2147483648) {
18760
+ if (typeof value !== "number" || !Number.isInteger(value) || value < minimum || value > 2147483647) {
18761
+ fail(`${label} must be an integer between ${minimum} and 2147483647`);
18762
+ }
18763
+ return value;
18764
+ }
18765
+ function inventoryItemId(value) {
18766
+ const id = parseIdentifier(value, "inventory_items: id");
18767
+ if (!isAuditDecimalId(String(id))) fail("id must fit a signed 64-bit integer");
18768
+ return id;
18769
+ }
18770
+ function admitInventoryItem(value, creating) {
18771
+ if (!isRecord2(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail("data must be a plain record");
18772
+ const body = captureInventoryPayload(value)();
18773
+ const writable = [...QUANTITIES, ...TEXT_FIELDS, ...creating ? REFERENCES : []];
18774
+ for (const field of Object.keys(body)) {
18775
+ if (!writable.some((name) => name === field)) fail(`${field} is not a writable InventoryItems field on ${creating ? "create" : "update"}`);
18776
+ }
18777
+ if (!creating && Object.keys(body).length === 0) fail("update must contain a writable field");
18778
+ if (creating) for (const field of REFERENCES) int32(own(body, field), field, 1);
18779
+ for (const field of QUANTITIES) {
18780
+ const nonnegative = field === "quantityMinimum" || creating && field === "quantityOnHand";
18781
+ if (creating || Object.hasOwn(body, field)) int32(own(body, field), field, nonnegative ? 0 : void 0);
18782
+ }
18783
+ for (const field of TEXT_FIELDS) {
18784
+ const text = own(body, field);
18785
+ if (Object.hasOwn(body, field) && (typeof text !== "string" || text.length > 50)) fail(`${field} must be a string of at most 50 characters`);
18786
+ }
18787
+ assertQuantityRange(own(body, "quantityMinimum"), own(body, "quantityMaximum"));
18788
+ return body;
18789
+ }
18790
+ function captureInventoryPayload(value) {
18791
+ if (util.types.isProxy(value)) fail("payload must not be a Proxy");
18792
+ if (!isRecord2(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail("data must be a plain record");
18793
+ const descriptors = Object.getOwnPropertyDescriptors(value);
18794
+ const captured = /* @__PURE__ */ Object.create(null);
18795
+ const accessors = [];
18796
+ for (const [field, descriptor2] of Object.entries(descriptors)) {
18797
+ if (!descriptor2.enumerable) continue;
18798
+ if (Object.hasOwn(descriptor2, "value")) captured[field] = descriptor2.value;
18799
+ else accessors.push([field, descriptor2]);
18800
+ }
18801
+ return (allowAccessors = true) => {
18802
+ if (!allowAccessors && accessors.length > 0) fail("approved InventoryItems payload fields must be data properties; accessors are unsupported");
18803
+ const body = { ...captured };
18804
+ for (const [field, descriptor2] of accessors) {
18805
+ const capturedValue = descriptor2.get === void 0 ? void 0 : Reflect.apply(descriptor2.get, value, []);
18806
+ Object.defineProperty(body, field, { value: capturedValue, enumerable: true });
18807
+ }
18808
+ return body;
18809
+ };
18810
+ }
18811
+ function captureInventoryOptionDescriptors(options) {
18812
+ if (util.types.isProxy(options)) fail("options must not be a Proxy");
18813
+ if (!isRecord2(options)) fail("options must be an object");
18814
+ const prototype = Object.getPrototypeOf(options);
18815
+ for (let owner = prototype; owner !== null && owner !== Object.prototype; owner = Object.getPrototypeOf(owner)) {
18816
+ if (util.types.isProxy(owner)) fail("options must not inherit from a Proxy");
18817
+ }
18818
+ const descriptors = Object.getOwnPropertyDescriptors(options);
18819
+ const fact = Object.hasOwn(descriptors, "expectedInventoryFacts") ? descriptors.expectedInventoryFacts : void 0;
18820
+ if (fact === void 0 ? "expectedInventoryFacts" in options : !Object.hasOwn(fact, "value")) {
18821
+ fail("expectedInventoryFacts must be an own data property; accessors are unsupported");
18822
+ }
18823
+ const suppliedFacts = fact?.value;
18824
+ if (suppliedFacts !== void 0 && ![Object.prototype, null].includes(prototype)) fail("approved options must be a plain record");
18825
+ const expectedInventoryFacts = suppliedFacts === void 0 ? void 0 : snapshotExpectedInventoryFacts(suppliedFacts);
18826
+ return { options, descriptors, expectedInventoryFacts };
18827
+ }
18828
+ function snapshotInventoryMutationOptions(value) {
18829
+ const { options, descriptors, expectedInventoryFacts } = captureInventoryOptionDescriptors(value === void 0 ? {} : value);
18830
+ for (const key of MUTATION_OPTIONS) {
18831
+ if (key !== "expectedInventoryFacts" && !Object.hasOwn(descriptors, key) && key in options) fail(`${key} must be an own option`);
18832
+ }
18833
+ if (expectedInventoryFacts !== void 0 && Object.values(descriptors).some((descriptor2) => !Object.hasOwn(descriptor2, "value"))) fail("approved InventoryItems options must be data properties; accessors are unsupported");
18834
+ const captured = /* @__PURE__ */ Object.create(null);
18835
+ const dryRun = Object.hasOwn(descriptors, "dryRun") ? descriptors.dryRun : void 0;
18836
+ if (dryRun !== void 0) {
18837
+ const dataFlag = Object.hasOwn(dryRun, "value");
18838
+ const value2 = dataFlag ? dryRun.value : dryRun.get === void 0 ? void 0 : Reflect.apply(dryRun.get, options, []);
18839
+ captured.dryRun = !dataFlag && value2 === void 0 ? true : value2;
18840
+ }
18841
+ for (const key of MUTATION_OPTIONS) {
18842
+ if (key === "expectedInventoryFacts" || key === "dryRun") continue;
18843
+ const descriptor2 = descriptors[key];
18844
+ captured[key] = descriptor2 === void 0 ? void 0 : Object.hasOwn(descriptor2, "value") ? descriptor2.value : descriptor2.get === void 0 ? void 0 : Reflect.apply(descriptor2.get, options, []);
18845
+ }
18846
+ const result = snapshotMutationOptions(captured);
18847
+ if (expectedInventoryFacts !== void 0) result.expectedInventoryFacts = expectedInventoryFacts;
18848
+ if (result.lastModifiedDate !== void 0) fail("no documented stale timestamp is available");
18849
+ if (result.raw !== void 0 && result.raw !== false) fail("raw updates are unsupported");
18850
+ if (result.maxRetries !== void 0 && (!Number.isSafeInteger(result.maxRetries) || result.maxRetries < 0)) fail("maxRetries must be a nonnegative safe integer");
18851
+ if (result.verifyPersisted !== void 0 && typeof result.verifyPersisted !== "boolean") fail("verifyPersisted must be a boolean");
18852
+ return result;
18853
+ }
18854
+ function validateInventoryFactIntent(result, creating, data) {
18855
+ const facts = result.expectedInventoryFacts;
18856
+ if (facts === void 0) return;
18857
+ if (creating ? facts.item !== void 0 || facts.product === void 0 || facts.location === void 0 : facts.item === void 0 || facts.location !== void 0 || (Object.hasOwn(data, "quantityOnHand") ? facts.product === void 0 : facts.product !== void 0)) {
18858
+ fail("expectedInventoryFacts must supply only the facts required by this create or update");
18859
+ }
18860
+ if (creating && (facts.product.id !== data.productID || facts.location.id !== data.inventoryLocationID)) fail("expectedInventoryFacts references must match the submitted references");
18861
+ }
18862
+ function captureInventoryItemCall(value, options, creating) {
18863
+ const payload = captureInventoryPayload(value);
18864
+ const opts = snapshotInventoryMutationOptions(options);
18865
+ const body = admitInventoryItem(payload(opts.expectedInventoryFacts === void 0), creating);
18866
+ validateInventoryFactIntent(opts, creating, body);
18867
+ return { body, opts };
18868
+ }
18869
+ function deferredInventoryPayload(value, allowAccessors) {
18870
+ if (util.types.isProxy(value)) fail("payload must not be a Proxy");
18871
+ if (!isRecord2(value)) return value;
18872
+ if (![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail("data must be a plain record");
18873
+ const result = Object.create(Object.getPrototypeOf(value));
18874
+ for (const [field, descriptor2] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
18875
+ if (!descriptor2.enumerable) continue;
18876
+ if (Object.hasOwn(descriptor2, "value")) Object.defineProperty(result, field, { value: descriptor2.value, enumerable: true });
18877
+ else {
18878
+ if (!allowAccessors) fail("approved InventoryItems payload fields must be data properties; accessors are unsupported");
18879
+ let resolved = false;
18880
+ let captured;
18881
+ Object.defineProperty(result, field, { enumerable: true, get() {
18882
+ if (!resolved) {
18883
+ captured = descriptor2.get === void 0 ? void 0 : Reflect.apply(descriptor2.get, value, []);
18884
+ resolved = true;
18885
+ }
18886
+ return captured;
18887
+ } });
18888
+ }
18889
+ }
18890
+ return result;
18891
+ }
18892
+ function captureInventoryInvocationArgs(operation, args) {
18893
+ if (operation !== "inventory_items.create" && operation !== "inventory_items.update") return () => args;
18894
+ if (util.types.isProxy(args)) fail("invoke arguments must not be a Proxy");
18895
+ const array = Array.isArray(args);
18896
+ if (!array && (!isRecord2(args) || ![Object.prototype, null].includes(Object.getPrototypeOf(args))) || array && args.length !== (operation === "inventory_items.create" ? 1 : 2)) fail("InventoryItems invoke requires its documented positional or plain named inputs");
18897
+ const descriptors = Object.getOwnPropertyDescriptors(args);
18898
+ if (!array && Object.getOwnPropertySymbols(descriptors).length > 0) fail("InventoryItems named inputs must use string keys");
18899
+ const dataKey = array ? operation === "inventory_items.create" ? "0" : "1" : "data";
18900
+ const payload = descriptors[dataKey];
18901
+ const pinnedPayload = payload !== void 0 && Object.hasOwn(payload, "value") ? deferredInventoryPayload(payload.value, true) : void 0;
18902
+ return (allowAccessors = true) => {
18903
+ const result = array ? [] : Object.create(Object.getPrototypeOf(args));
18904
+ for (const [key, descriptor2] of Object.entries(descriptors)) {
18905
+ if (array && key === "length") continue;
18906
+ const enumerable = !array || descriptor2.enumerable;
18907
+ if (Object.hasOwn(descriptor2, "value")) {
18908
+ const value = key === dataKey ? deferredInventoryPayload(pinnedPayload, allowAccessors) : descriptor2.value;
18909
+ Object.defineProperty(result, key, { value, enumerable, configurable: true });
18910
+ } else {
18911
+ if (!allowAccessors) fail("approved InventoryItems named inputs must be data properties; accessors are unsupported");
18912
+ let resolved = false;
18913
+ let captured;
18914
+ Object.defineProperty(result, key, { enumerable, configurable: true, get() {
18915
+ if (!resolved) {
18916
+ const value = descriptor2.get === void 0 ? void 0 : Reflect.apply(descriptor2.get, args, []);
18917
+ captured = key === dataKey ? deferredInventoryPayload(value, true) : value;
18918
+ resolved = true;
18919
+ }
18920
+ return captured;
18921
+ } });
18922
+ }
18923
+ }
18924
+ return result;
18925
+ };
18926
+ }
18927
+ var ITEM_NUMERIC_FACTS = [...REFERENCES, ...QUANTITIES, "quantityPicked", "quantityReserved", "quantityOnOrder", "backOrderQuantity", "impersonatorCreatorResourceID"];
18928
+ var ITEM_FACT_KEYS = ["id", ...ITEM_NUMERIC_FACTS, ...TEXT_FIELDS];
18929
+ function inventoryItemGuardFacts(value) {
18930
+ const captured = closedFacts(value, ITEM_FACT_KEYS, false);
18931
+ if (!Object.hasOwn(captured, "id")) fail("inventory facts require an own item id");
18932
+ const facts = { id: inventoryItemId(captured.id) };
18933
+ for (const field of ITEM_NUMERIC_FACTS) if (Object.hasOwn(captured, field)) {
18934
+ const current = captured[field];
18935
+ facts[field] = current === null ? null : int32(current, "inventory fact");
18936
+ }
18937
+ for (const field of TEXT_FIELDS) if (Object.hasOwn(captured, field)) {
18938
+ const current = captured[field];
18939
+ if (current !== null && typeof current !== "string") fail("inventory text facts must be strings or null");
18940
+ facts[field] = current;
18941
+ }
18942
+ return facts;
18943
+ }
18944
+ function closedFacts(value, fields, closed = true) {
18945
+ if (util.types.isProxy(value)) fail("expectedInventoryFacts records must not be a Proxy");
18946
+ if (!isRecord2(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail("expectedInventoryFacts must contain plain records");
18947
+ const descriptors = Object.getOwnPropertyDescriptors(value);
18948
+ if (closed && Reflect.ownKeys(descriptors).some((key) => typeof key !== "string" || !fields.includes(key))) fail("expectedInventoryFacts contains an unsupported field");
18949
+ for (const key of fields) if (key in value && !Object.hasOwn(value, key)) fail("expectedInventoryFacts fields must be own fields");
18950
+ const captured = /* @__PURE__ */ Object.create(null);
18951
+ for (const key of fields) {
18952
+ const descriptor2 = descriptors[key];
18953
+ if (descriptor2 === void 0) continue;
18954
+ if (!Object.hasOwn(descriptor2, "value")) fail("expectedInventoryFacts fields must be data properties; accessors are unsupported");
18955
+ captured[key] = descriptor2.value;
18956
+ }
18957
+ return captured;
18958
+ }
18959
+ function snapshotExpectedInventoryFacts(value) {
18960
+ const source = closedFacts(value, ["item", "product", "location"]);
18961
+ const result = {};
18962
+ if (Object.hasOwn(source, "item")) {
18963
+ const item = closedFacts(source.item, ITEM_FACT_KEYS);
18964
+ result.item = inventoryItemGuardFacts(item);
18965
+ }
18966
+ for (const kind of ["product", "location"]) if (Object.hasOwn(source, kind)) {
18967
+ const flag = kind === "product" ? "isSerialized" : "isActive";
18968
+ const record = closedFacts(source[kind], ["id", flag]);
18969
+ const id = int32(own(record, "id"), "expected reference id", 1);
18970
+ const state2 = own(record, flag);
18971
+ if (typeof state2 !== "boolean") fail("expected reference state must be an own boolean");
18972
+ if (kind === "product") result.product = { id, isSerialized: state2 };
18973
+ else result.location = { id, isActive: state2 };
18974
+ }
18975
+ return result;
18976
+ }
18977
+ function rejectInventoryFactsOption(options, operation) {
18978
+ if (operation === "inventory_items.create" || operation === "inventory_items.update" || !isRecord2(options)) return;
18979
+ const option = Object.getOwnPropertyDescriptor(options, "expectedInventoryFacts");
18980
+ if (option === void 0 && !("expectedInventoryFacts" in options)) return;
18981
+ if (option !== void 0 && Object.hasOwn(option, "value") && option.value === void 0) return;
18982
+ fail("expectedInventoryFacts is supported only by inventory_items.create/update");
18983
+ }
18984
+ function inventoryFactsStale(operation) {
18985
+ const error = new StaleObjectError("inventory_items: approved facts changed; no mutation was sent", {
18986
+ operation,
18987
+ suggestedAction: "Read fresh inventory facts and generate a new preview and approval before retrying."
18988
+ });
18989
+ Object.assign(error, { notSent: true });
18990
+ throw error;
18991
+ }
18992
+ function rethrowInventoryGuardError(error, expected, operation) {
18993
+ if (expected !== void 0 && error instanceof NotFoundError && error.httpStatus === 200) inventoryFactsStale(operation);
18994
+ throw error;
18995
+ }
18996
+ function assertApprovedFacts(expected, actual, operation) {
18997
+ const before = expected;
18998
+ const after = actual;
18999
+ if (Object.keys(before).length !== Object.keys(after).length || Object.keys(before).some((key) => !Object.hasOwn(after, key) || before[key] !== after[key])) {
19000
+ inventoryFactsStale(operation);
19001
+ }
19002
+ }
19003
+ function assertQuantityRange(minimum, maximum) {
19004
+ if (typeof minimum === "number" && typeof maximum === "number" && maximum < minimum) fail("quantityMaximum must be at least quantityMinimum");
19005
+ }
19006
+ function exactItem(value, id, label, approvedOperation) {
19007
+ const record = isRecord2(value);
19008
+ if (approvedOperation !== void 0 && (!record || own(value, "id") === null)) {
19009
+ throw Object.assign(new AutotaskError("InventoryItems approval could not verify the Product item or its exact ID", {
19010
+ code: "INVALID_RESPONSE",
19011
+ category: "server",
19012
+ operation: approvedOperation
19013
+ }), { notSent: true });
19014
+ }
19015
+ if (!record) fail(`${label} must be a record`);
19016
+ if (approvedOperation !== void 0 && !Object.hasOwn(value, "id")) inventoryFactsStale(approvedOperation);
19017
+ const returned = own(value, "id");
19018
+ if (typeof returned !== "string" && (typeof returned !== "number" || !Number.isSafeInteger(returned))) fail(`${label} requires its own exact id`);
19019
+ if (String(returned) !== String(id)) {
19020
+ if (approvedOperation !== void 0 && isAuditDecimalId(String(returned))) inventoryFactsStale(approvedOperation);
19021
+ fail(`${label} id must match the requested id`);
19022
+ }
19023
+ return value;
19024
+ }
19025
+ async function productIsSerialized(http, id, checkedBaseUrl, maxRetries, expected, mutationOperation = "inventory_items.update") {
19026
+ const operation = "products.get";
19027
+ const body = await http.request({
19028
+ method: "GET",
19029
+ path: `/V1.0/Products/${id}`,
19030
+ operation,
19031
+ maxRetries,
19032
+ checkedBaseUrl,
19033
+ ...expected !== void 0 ? { [INVENTORY_APPROVAL_PRODUCT_ID]: true } : {}
19034
+ });
19035
+ let raw;
19036
+ try {
19037
+ raw = unwrapItem(body, id, operation, "product");
19038
+ } catch (error) {
19039
+ rethrowInventoryGuardError(error, expected === void 0 ? void 0 : { }, mutationOperation);
19040
+ }
19041
+ const product = exactItem(raw, id, "product", expected === void 0 ? void 0 : mutationOperation);
19042
+ const serialized = own(product, "isSerialized");
19043
+ if (expected !== void 0) assertApprovedFacts(expected, { id, isSerialized: serialized }, mutationOperation);
19044
+ if (typeof serialized !== "boolean") fail("product requires a fresh boolean isSerialized fact");
19045
+ return serialized;
19046
+ }
19047
+ async function guardInventoryItemCreate(http, data, checkedBaseUrl, maxRetries, expected) {
19048
+ const locationId = data.inventoryLocationID;
19049
+ const operation = "inventory_locations.get";
19050
+ const body = await http.request({ method: "GET", path: `/V1.0/InventoryLocations/${locationId}`, operation, maxRetries, checkedBaseUrl });
19051
+ let raw;
19052
+ try {
19053
+ raw = unwrapItem(body, locationId, operation, "inventory_location");
19054
+ } catch (error) {
19055
+ rethrowInventoryGuardError(error, expected, "inventory_items.create");
19056
+ }
19057
+ const location = exactItem(raw, locationId, "inventory location");
19058
+ if (expected?.location !== void 0) assertApprovedFacts(expected.location, { id: locationId, isActive: own(location, "isActive") }, "inventory_items.create");
19059
+ if (own(location, "isActive") !== true) fail("inventory location requires a fresh isActive value explicitly true");
19060
+ if (await productIsSerialized(http, data.productID, checkedBaseUrl, maxRetries, expected?.product, "inventory_items.create") && data.quantityOnHand !== 0) {
19061
+ fail("quantityOnHand must be zero when creating an item for a serialized product");
19062
+ }
19063
+ }
19064
+ async function checkInventoryItemCurrent(http, data, current, id, checkedBaseUrl, maxRetries, expected) {
19065
+ const item = exactItem(current, id, "current record");
19066
+ if (expected?.item !== void 0) assertApprovedFacts(expected.item, inventoryItemGuardFacts(item), "inventory_items.update");
19067
+ const minimum = own(data, "quantityMinimum");
19068
+ const maximum = own(data, "quantityMaximum");
19069
+ if (minimum !== void 0 || maximum !== void 0) {
19070
+ assertQuantityRange(
19071
+ minimum ?? int32(own(item, "quantityMinimum"), "current quantityMinimum", 0),
19072
+ maximum ?? int32(own(item, "quantityMaximum"), "current quantityMaximum")
19073
+ );
19074
+ }
19075
+ const onHand = own(data, "quantityOnHand");
19076
+ if (typeof onHand !== "number") return;
19077
+ const picked = int32(own(item, "quantityPicked"), "current quantityPicked");
19078
+ const reserved = int32(own(item, "quantityReserved"), "current quantityReserved");
19079
+ if (onHand < picked + reserved) fail("quantityOnHand must be at least quantityPicked plus quantityReserved");
19080
+ const productId = int32(own(item, "productID"), "current productID", 1);
19081
+ if (await productIsSerialized(http, productId, checkedBaseUrl, maxRetries, expected?.product)) fail("quantityOnHand is read-only on update for a serialized product");
19082
+ }
19083
+
19084
+ // src/operations/requiredFields.ts
19085
+ function effectiveRequiredFields(record, zoneFacts) {
19086
+ const guidance = zoneFacts?.createGuidance;
19087
+ const prefix = guidance?.liveProvenPrefix;
19088
+ if (Array.isArray(prefix) && prefix.length > 0) {
19089
+ const gates = guidance?.requiresByValue;
19090
+ const gated = new Set((gates ?? []).flatMap((g) => [...g.requires.allOf ?? [], ...g.requires.anyOf ?? []]));
19091
+ return {
19092
+ fields: prefix.filter((f) => !gated.has(f)),
19093
+ from: "live-proven",
19094
+ unproven: guidance?.unproven === true,
19095
+ ...Array.isArray(gates) && gates.length > 0 ? { conditional: gates } : {}
19096
+ };
19097
+ }
19098
+ const zoneSet = zoneFacts?.createRequiredSet;
19099
+ if (Array.isArray(zoneSet) && zoneSet.length > 0) {
19100
+ return { fields: [...zoneSet], from: "zone", unproven: guidance?.unproven === true };
19101
+ }
19102
+ const spec = record?.requiredFields;
19103
+ return { fields: Array.isArray(spec) ? [...spec] : [], from: "spec", unproven: true };
19104
+ }
19105
+
19106
+ // src/operations/types.ts
19107
+ var WORKFLOW_RESOURCES = [
19108
+ "companies",
19109
+ "tickets",
19110
+ "contacts",
19111
+ "configuration_items",
19112
+ "projects"
19113
+ ];
19114
+
19115
+ // src/metadata-views.ts
19116
+ function liveFieldNamesView(rows) {
19117
+ if (!Array.isArray(rows)) return null;
19118
+ const names = [];
19119
+ for (const row of rows) if (typeof row.name === "string") names.push(row.name);
19120
+ return names.length === 0 ? null : { names, known: new Set(names) };
19121
+ }
19122
+ function projectFieldRow(raw, labels = false, udf = false) {
19123
+ const r = typeof raw === "object" && raw !== null ? raw : {};
19124
+ const name = typeof r.name === "string" ? r.name : "";
19125
+ const type = typeof r.dataType === "string" ? r.dataType : typeof r.type === "string" ? r.type : "";
19126
+ const values = labels && r.isPickList === true && Array.isArray(r.picklistValues) && r.picklistValues.length > 0 ? r.picklistValues : void 0;
19127
+ const referenceEntityType = typeof r.referenceEntityType === "string" ? r.referenceEntityType : "";
19128
+ return {
19129
+ name,
19130
+ ...typeof r.label === "string" && r.label !== "" ? { label: r.label } : {},
19131
+ type,
19132
+ isRequired: r.isRequired === true,
19133
+ isReadOnly: r.isReadOnly === true,
19134
+ // Issue #219 N7: a UDF row never serves the vendor's isQueryable (it is
19135
+ // true for UDFs while a plain filter on a UDF name is refused); it serves
19136
+ // the marker the filter actually needs.
19137
+ ...udf ? { filterable: "udf-marker" } : { isQueryable: r.isQueryable === true },
19138
+ isPickList: r.isPickList === true,
19139
+ ...isObjectOrArrayType(type) ? { writeShape: "replace-all" } : {},
19140
+ maxLength: typeof r.length === "number" ? r.length : null,
19141
+ referenceEntityType,
19142
+ ...values !== void 0 ? { picklistValues: values } : {}
19143
+ };
19144
+ }
19145
+ function isObjectOrArrayType(type) {
19146
+ const t = type.trim().toLowerCase();
19147
+ return t === "object" || t === "array" || t === "collection" || t.endsWith("[]");
19148
+ }
19149
+ function exposesPicklistValues(raw) {
19150
+ const r = typeof raw === "object" && raw !== null ? raw : {};
19151
+ return Array.isArray(r.picklistValues) && r.picklistValues.length > 0;
19152
+ }
19153
+ function catalogList(raw, labels, udf) {
19154
+ return Array.isArray(raw) ? { rows: raw.map((row) => projectFieldRow(row, labels, udf)), exposesValues: raw.some(exposesPicklistValues) } : { rows: null, exposesValues: false };
19155
+ }
19156
+ var catalogFieldsView = (raw) => catalogList(raw, false, false);
19157
+ var catalogLabelledFieldsView = (raw) => catalogList(raw, true, false);
19158
+ var catalogUdfView = (raw) => catalogList(raw, false, true);
19159
+ var catalogLabelledUdfView = (raw) => catalogList(raw, true, true);
19160
+ function compactCatalogList(raw, keepValues, udf) {
19161
+ const view = catalogList(raw, keepValues, udf);
19162
+ if (view.rows === null) return { rows: null, exposesValues: view.exposesValues };
19163
+ const flags = {
19164
+ required: view.rows.filter((row) => row.isRequired).map((row) => row.name),
19165
+ readOnly: view.rows.filter((row) => row.isReadOnly).map((row) => row.name),
19166
+ queryable: view.rows.filter((row) => row.isQueryable).map((row) => row.name),
19167
+ picklistFields: view.rows.filter((row) => row.isPickList).map((row) => row.name)
19168
+ };
19169
+ return {
19170
+ rows: view.rows.map((row) => ({
19171
+ name: row.name,
19172
+ type: row.type,
19173
+ isPickList: row.isPickList,
19174
+ isReference: row.referenceEntityType !== "",
19175
+ udf,
19176
+ ...keepValues && row.picklistValues !== void 0 ? { picklistValues: row.picklistValues } : {}
19177
+ })),
19178
+ flags,
19179
+ exposesValues: view.exposesValues
19180
+ };
19181
+ }
19182
+ var compactCatalogFieldsView = (raw) => compactCatalogList(raw, false, false);
19183
+ var compactCatalogLabelledFieldsView = (raw) => compactCatalogList(raw, true, false);
19184
+ var compactCatalogUdfView = (raw) => compactCatalogList(raw, false, true);
19185
+ var compactCatalogLabelledUdfView = (raw) => compactCatalogList(raw, true, true);
19186
+ function ticketStatusView(fields) {
19187
+ if (!Array.isArray(fields)) return [];
19188
+ const status = fields.find((f) => typeof f?.name === "string" && f.name.toLowerCase() === "status");
19189
+ if (status === void 0 || status.isPickList !== true || !Array.isArray(status.picklistValues)) return [];
19190
+ const out = [];
19191
+ for (const v of status.picklistValues) {
18570
19192
  const id = Number(v?.value);
18571
19193
  if (!Number.isSafeInteger(id)) continue;
18572
19194
  out.push({ id, label: typeof v.label === "string" ? v.label : "" });
@@ -18698,7 +19320,7 @@ async function capabilitySets() {
18698
19320
  const fieldOps = /* @__PURE__ */ new Map();
18699
19321
  const udfCapable = /* @__PURE__ */ new Set();
18700
19322
  const resources = /* @__PURE__ */ new Set();
18701
- for (const rec of await chunkQXJQIZCT_cjs.loadCapabilityRecords()) {
19323
+ for (const rec of await chunkSBHQIPCJ_cjs.loadCapabilityRecords()) {
18702
19324
  if (rec.resource === "operations") continue;
18703
19325
  resources.add(rec.resource);
18704
19326
  if (rec.operation === "getFieldInfo") fieldOps.set(rec.resource, rec);
@@ -18709,7 +19331,7 @@ async function capabilitySets() {
18709
19331
  var derivedIndexPromise = null;
18710
19332
  function derivedIndexLoad() {
18711
19333
  if (derivedIndexPromise === null) {
18712
- derivedIndexPromise = chunkQXJQIZCT_cjs.loadCapabilityRecords().then((records) => {
19334
+ derivedIndexPromise = chunkSBHQIPCJ_cjs.loadCapabilityRecords().then((records) => {
18713
19335
  const index = /* @__PURE__ */ new Map();
18714
19336
  for (const rec of records) {
18715
19337
  const declared = rec.metadata?.derivedFields;
@@ -18935,291 +19557,131 @@ async function readKind(ctx, resource, kind, fetch2, holder, projector = catalog
18935
19557
  async function sweepResource(ctx, resource, tally, reads) {
18936
19558
  const { fieldsFilter } = ctx;
18937
19559
  const fieldOp = ctx.fieldOps.get(resource);
18938
- if (fieldOp === void 0) return void 0;
18939
- const apiEntity = apiEntityFor(fieldOp);
18940
- const row = {
18941
- resource,
18942
- apiEntity,
18943
- udfCapable: ctx.udfCapable.has(resource),
18944
- // Issue #219 N7: the UDF surface is declared with the mechanism, not a boolean.
18945
- ...ctx.udfCapable.has(resource) ? { udfFilter: "udf-marker", udfWriteShape: "merge" } : {},
18946
- unmatchedFields: [],
18947
- required: [],
18948
- readOnly: [],
18949
- queryable: [],
18950
- picklistFields: [],
18951
- cache: { hit: false, age: null },
18952
- wire: 0,
18953
- error: null
18954
- };
18955
- let allCached = true;
18956
- const ages = [];
18957
- for (const { kind, peek, outcome } of reads) {
18958
- if (!peek.hit) {
18959
- allCached = false;
18960
- tally.wireUsed += 1;
18961
- row.wire += 1;
18962
- } else if (peek.age !== null) ages.push(peek.age);
18963
- if (outcome.status === "rejected") {
18964
- const error = outcome.reason;
18965
- if (row.error === null) row.error = { code: error.code, message: error.message };
18966
- continue;
18967
- }
18968
- const value = outcome.value;
18969
- if (kind === "info") {
18970
- row.info = value ?? null;
18971
- } else {
18972
- const view = value;
18973
- if (view.rows === null) {
18974
- if (row.error === null) row.error = { code: "INVALID_RESPONSE", message: `fieldCatalog: the ${kind} response for ${resource} was not a list` };
18975
- continue;
18976
- }
18977
- if (kind === "fields") applyFieldsFilter(view.rows, fieldsFilter, row, view.flags);
18978
- else row.udf = view.rows;
18979
- if (view.exposesValues) tally.anyPicklistValues = true;
18980
- }
18981
- }
18982
- row.cache = allCached ? { hit: true, age: ages.length > 0 ? Math.max(...ages) : 0 } : { hit: false, age: null };
18983
- const declared = await derivedFieldsFor(resource);
18984
- if (declared.length > 0) {
18985
- const byField = new Map(declared.map((d) => [d.field, d]));
18986
- row.derivedFields = declared;
18987
- for (const field of ctx.compact ? [] : row.fields ?? []) {
18988
- const derivation = byField.get(field.name);
18989
- if (derivation === void 0) continue;
18990
- field.derived = {
18991
- rule: derivation.rule,
18992
- ...derivation.writableRoute !== void 0 ? { writableRoute: derivation.writableRoute } : {}
18993
- };
18994
- }
18995
- }
18996
- return row;
18997
- }
18998
- async function prepareCatalog(client, opts) {
18999
- validateCatalogOptsShape(opts);
19000
- const { fieldOps, udfCapable, resources: allResources } = await capabilitySets();
19001
- const include = resolveInclude(opts);
19002
- const targets = resolveTargets(opts, fieldOps, allResources);
19003
- const fieldsFilter = resolveFieldsFilter(opts);
19004
- const labels = resolveLabels(opts);
19005
- const { compact, maxBytes } = resolveSizeOpts(opts);
19006
- assertWithinWireCap(targets.length, include.length);
19007
- const ctx = { client, include, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
19008
- return { ctx, targets, compact, maxBytes };
19009
- }
19010
- async function fieldCatalogPicklists(client, resource, fields) {
19011
- const { ctx } = await prepareCatalog(client, { resources: [resource], labels: true, fields: [...fields] });
19012
- const holder = client[camelKey(resource)];
19013
- const [read] = await mapReadTasks(client.http, [resource], () => readKind(ctx, resource, "fields", kindFetches(holder, resource).fields, holder, picklistsView));
19014
- return read.outcome.status === "fulfilled" ? read.outcome.value : null;
19015
- }
19016
- async function fieldCatalog(client, opts) {
19017
- const { ctx, targets, compact, maxBytes } = await prepareCatalog(client, opts);
19018
- const { include, labels, fieldOps, udfCapable } = ctx;
19019
- const cache = client.http.fieldCache;
19020
- const zone = client.config.zone ?? "unknown";
19021
- const rows = [];
19022
- const tally = { wireUsed: 0, anyPicklistValues: false };
19023
- for (const resource of targets) {
19024
- apiEntityFor(fieldOps.get(resource));
19025
- if (ctx.fresh) cache?.invalidate(`${resource}:`);
19026
- }
19027
- const tasks = targets.flatMap((resource) => {
19028
- const holder = client[camelKey(resource)];
19029
- const fetches = kindFetches(holder, resource);
19030
- return include.map((kind) => ({ resource, kind, fetch: fetches[kind], holder }));
19031
- });
19032
- const reads = await mapReadTasks(client.http, tasks, ({ resource, kind, fetch: fetch2, holder }) => readKind(ctx, resource, kind, fetch2, holder));
19033
- for (let index = 0; index < targets.length; index += 1) {
19034
- const start = index * include.length;
19035
- const row = await sweepResource(ctx, targets[index], tally, reads.slice(start, start + include.length));
19036
- if (row !== void 0) rows.push(row);
19037
- }
19038
- const result = {
19039
- zone,
19040
- label: zone,
19041
- cached: cache !== void 0,
19042
- labels,
19043
- compact,
19044
- ttlMs: cache?.ttlMs ?? null,
19045
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
19046
- rows,
19047
- wireUsed: tally.wireUsed,
19048
- cap: MAX_FIELD_CATALOG_WIRE,
19049
- truncated: false,
19050
- counts: {
19051
- resources: targets.length,
19052
- fieldCapableResources: fieldOps.size,
19053
- udfCapableResources: udfCapable.size,
19054
- cached: rows.filter((r) => r.cache.hit === true).length
19055
- },
19056
- honesty: {
19057
- picklistValues: tally.anyPicklistValues ? "partial" : "unexposed",
19058
- note: FIELD_CATALOG_HONESTY_NOTE
19059
- }
19060
- };
19061
- if (maxBytes !== void 0) applyMaxBytes(result, maxBytes);
19062
- return result;
19063
- }
19064
-
19065
- // src/resources/base/helpers.ts
19066
- function describeResponseShape(body) {
19067
- if (body === null) return "null";
19068
- if (Array.isArray(body)) return `array(len=${body.length})`;
19069
- if (typeof body !== "object") return typeof body;
19070
- const rec = body;
19071
- const keys = Object.keys(rec).sort();
19072
- const typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
19073
- const parts = keys.slice(0, 16).map((k) => `${k}:${typeOf(rec[k])}`);
19074
- const more = keys.length > 16 ? `, +${keys.length - 16} more` : "";
19075
- return `{ ${parts.join(", ")}${more} }`;
19076
- }
19077
- function defaultMarkerToken(data) {
19078
- for (const field of ["name", "title"]) {
19079
- const v = data[field];
19080
- if (typeof v === "string" && v.trim() !== "") return v.trim();
19081
- }
19082
- return null;
19083
- }
19084
- var CONTEXT_ABSENT_MARKER = "#context-absent";
19085
- function contextAbsentKey(path) {
19086
- return path + "\0context-absent";
19087
- }
19088
- function noteCharsTruncationMarker(charsRemoved) {
19089
- return `\u2026 [+${charsRemoved} chars truncated]`;
19090
- }
19091
- function truncateNoteChars(items, cap, fields) {
19092
- let truncated = 0;
19093
- const out = items.map((item) => {
19094
- if (!isRecord2(item)) return item;
19095
- let changed = false;
19096
- const copy = { ...item };
19097
- for (const field of fields) {
19098
- const v = copy[field];
19099
- if (typeof v === "string" && v !== chunkCM5O672I_cjs.REDACTED && v.length > cap) {
19100
- const end = cap > 0 && (v.charCodeAt(cap - 1) & 64512) === 55296 ? cap - 1 : cap;
19101
- copy[field] = v.slice(0, end) + noteCharsTruncationMarker(v.length - end);
19102
- truncated += 1;
19103
- changed = true;
19104
- }
19105
- }
19106
- return changed ? copy : item;
19107
- });
19108
- return [out, truncated];
19109
- }
19110
- function blindEmptyReason(stamp) {
19111
- return {
19112
- surface: stamp.surface,
19113
- kind: "blind-surface",
19114
- note: stamp.note,
19115
- authority: stamp.authority,
19116
- remedy: "the note is the remedy \u2014 the authority op answers for a record"
19117
- };
19118
- }
19119
- function attachUpdateTargetMissReason(err, key) {
19120
- const pinned = EMPTY_REASON_STAMPS[key]?.update;
19121
- if (pinned === void 0) return;
19122
- err.details = { ...err.details ?? {}, emptyReason: pinned };
19123
- }
19124
- function buildDryRunResult(spec, policy) {
19125
- if (spec.operation === "") {
19126
- throw new AutotaskConfigError("dry-run: the operation name is required");
19127
- }
19128
- const wouldApply = spec.checks.every((check) => check.ok);
19129
- const resource = spec.operation.split(".")[0] ?? spec.operation;
19130
- const diffPart = spec.diff !== void 0 ? {
19131
- diff: spec.diff.map((entry) => {
19132
- if (entry.to === void 0) return entry;
19133
- const to = isRedactedFieldName(entry.field, policy) ? chunkCM5O672I_cjs.REDACTED : redactResponseBody(entry.to, policy);
19134
- return { ...entry, to };
19135
- })
19136
- } : {};
19137
- const dataPart = spec.data !== void 0 ? { data: redactResponseBody(spec.data, policy) } : {};
19138
- return {
19139
- operation: spec.operation,
19140
- wouldApply,
19141
- target: { resource, ids: spec.ids },
19142
- request: { method: spec.method, path: spec.path },
19143
- ...diffPart,
19144
- checks: spec.checks,
19145
- impact: spec.impact,
19146
- simulated: true,
19147
- warnings: spec.warnings ?? [],
19148
- ...dataPart,
19149
- ...spec.emptyReason !== void 0 ? { emptyReason: spec.emptyReason } : {}
19150
- };
19151
- }
19152
- function computeFieldDiff(current, data) {
19153
- const out = [];
19154
- for (const [field, to] of Object.entries(data)) {
19155
- if (field === "id" || to === void 0) continue;
19156
- const from = Object.hasOwn(current, field) ? current[field] : void 0;
19157
- if (from !== void 0 && JSON.stringify(from) === JSON.stringify(to)) continue;
19158
- out.push({ field, from: from === void 0 ? null : from, to });
19159
- }
19160
- return out;
19161
- }
19162
- function mergePartialBody(current, data) {
19163
- const merged = { ...current };
19164
- for (const [key, value] of Object.entries(data)) {
19165
- if (value === void 0) continue;
19166
- merged[key] = value;
19167
- }
19168
- return merged;
19169
- }
19170
- function snapshotMutationOptions(options) {
19171
- const { dryRun, lastModifiedDate, maxRetries, raw, verifyPersisted } = options ?? {};
19172
- if (dryRun !== void 0 && typeof dryRun !== "boolean") {
19173
- throw new AutotaskConfigError("dryRun must be a boolean");
19174
- }
19175
- return { dryRun, lastModifiedDate, maxRetries, raw, verifyPersisted };
19176
- }
19177
- function normalizeUdfInput(value) {
19178
- if (Array.isArray(value)) {
19179
- return value.map((entry) => {
19180
- if (!isRecord2(entry) || typeof entry.name !== "string" || entry.name === "") {
19181
- throw new AutotaskConfigError("userDefinedFields array entries must be { name, value } objects");
19560
+ if (fieldOp === void 0) return void 0;
19561
+ const apiEntity = apiEntityFor(fieldOp);
19562
+ const row = {
19563
+ resource,
19564
+ apiEntity,
19565
+ udfCapable: ctx.udfCapable.has(resource),
19566
+ // Issue #219 N7: the UDF surface is declared with the mechanism, not a boolean.
19567
+ ...ctx.udfCapable.has(resource) ? { udfFilter: "udf-marker", udfWriteShape: "merge" } : {},
19568
+ unmatchedFields: [],
19569
+ required: [],
19570
+ readOnly: [],
19571
+ queryable: [],
19572
+ picklistFields: [],
19573
+ cache: { hit: false, age: null },
19574
+ wire: 0,
19575
+ error: null
19576
+ };
19577
+ let allCached = true;
19578
+ const ages = [];
19579
+ for (const { kind, peek, outcome } of reads) {
19580
+ if (!peek.hit) {
19581
+ allCached = false;
19582
+ tally.wireUsed += 1;
19583
+ row.wire += 1;
19584
+ } else if (peek.age !== null) ages.push(peek.age);
19585
+ if (outcome.status === "rejected") {
19586
+ const error = outcome.reason;
19587
+ if (row.error === null) row.error = { code: error.code, message: error.message };
19588
+ continue;
19589
+ }
19590
+ const value = outcome.value;
19591
+ if (kind === "info") {
19592
+ row.info = value ?? null;
19593
+ } else {
19594
+ const view = value;
19595
+ if (view.rows === null) {
19596
+ if (row.error === null) row.error = { code: "INVALID_RESPONSE", message: `fieldCatalog: the ${kind} response for ${resource} was not a list` };
19597
+ continue;
19182
19598
  }
19183
- return { name: entry.name, value: entry.value };
19184
- });
19599
+ if (kind === "fields") applyFieldsFilter(view.rows, fieldsFilter, row, view.flags);
19600
+ else row.udf = view.rows;
19601
+ if (view.exposesValues) tally.anyPicklistValues = true;
19602
+ }
19185
19603
  }
19186
- if (isRecord2(value)) {
19187
- return Object.entries(value).map(([name, entryValue]) => ({ name, value: entryValue }));
19604
+ row.cache = allCached ? { hit: true, age: ages.length > 0 ? Math.max(...ages) : 0 } : { hit: false, age: null };
19605
+ const declared = await derivedFieldsFor(resource);
19606
+ if (declared.length > 0) {
19607
+ const byField = new Map(declared.map((d) => [d.field, d]));
19608
+ row.derivedFields = declared;
19609
+ for (const field of ctx.compact ? [] : row.fields ?? []) {
19610
+ const derivation = byField.get(field.name);
19611
+ if (derivation === void 0) continue;
19612
+ field.derived = {
19613
+ rule: derivation.rule,
19614
+ ...derivation.writableRoute !== void 0 ? { writableRoute: derivation.writableRoute } : {}
19615
+ };
19616
+ }
19188
19617
  }
19189
- throw new AutotaskConfigError("userDefinedFields must be an array of { name, value } entries or a name-to-value map");
19618
+ return row;
19190
19619
  }
19191
- function blindStampFor(stamp, filter) {
19192
- if (stamp === void 0) return void 0;
19193
- if (stamp.kind !== "unfiltered-blind") return stamp;
19194
- const conditions = normalizedConditions(filter);
19195
- return conditions === void 0 || conditions.length === 0 ? stamp : void 0;
19620
+ async function prepareCatalog(client, opts) {
19621
+ validateCatalogOptsShape(opts);
19622
+ const { fieldOps, udfCapable, resources: allResources } = await capabilitySets();
19623
+ const include = resolveInclude(opts);
19624
+ const targets = resolveTargets(opts, fieldOps, allResources);
19625
+ const fieldsFilter = resolveFieldsFilter(opts);
19626
+ const labels = resolveLabels(opts);
19627
+ const { compact, maxBytes } = resolveSizeOpts(opts);
19628
+ assertWithinWireCap(targets.length, include.length);
19629
+ const ctx = { client, include, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
19630
+ return { ctx, targets, compact, maxBytes };
19196
19631
  }
19197
- function decodeFileData(body) {
19198
- if (isRecord2(body)) {
19199
- const data = body.data;
19200
- if (typeof data === "string") return Buffer.from(data, "base64");
19201
- if (Array.isArray(data) && data.every((b) => typeof b === "number")) {
19202
- return Buffer.from(data);
19203
- }
19204
- }
19205
- if (typeof body === "string") return Buffer.from(body, "base64");
19206
- throw new AutotaskError(
19207
- "Expected the file envelope FileQueryResultModel { data } (or a base64 string); got a different shape",
19208
- { code: "INVALID_RESPONSE", category: "server" }
19209
- );
19632
+ async function fieldCatalogPicklists(client, resource, fields) {
19633
+ const { ctx } = await prepareCatalog(client, { resources: [resource], labels: true, fields: [...fields] });
19634
+ const holder = client[camelKey(resource)];
19635
+ const [read] = await mapReadTasks(client.http, [resource], () => readKind(ctx, resource, "fields", kindFetches(holder, resource).fields, holder, picklistsView));
19636
+ return read.outcome.status === "fulfilled" ? read.outcome.value : null;
19210
19637
  }
19211
- var DEPLURAL_EXCEPTIONS = {
19212
- tag_aliase: "tag_alias"
19213
- };
19214
- function entityNameFromPath(resourcePath) {
19215
- const segment = resourcePath.slice(resourcePath.lastIndexOf("/") + 1);
19216
- const snake = segment.replace(/([A-Z])/g, (_m, c, i) => (i > 0 ? `_` : "") + c.toLowerCase()).replace(/_{2,}/g, "_");
19217
- if (snake.endsWith("ies")) return `${snake.slice(0, -3)}y`;
19218
- if (snake.endsWith("s")) {
19219
- const stripped = snake.slice(0, -1);
19220
- return DEPLURAL_EXCEPTIONS[stripped] ?? stripped;
19638
+ async function fieldCatalog(client, opts) {
19639
+ const { ctx, targets, compact, maxBytes } = await prepareCatalog(client, opts);
19640
+ const { include, labels, fieldOps, udfCapable } = ctx;
19641
+ const cache = client.http.fieldCache;
19642
+ const zone = client.config.zone ?? "unknown";
19643
+ const rows = [];
19644
+ const tally = { wireUsed: 0, anyPicklistValues: false };
19645
+ for (const resource of targets) {
19646
+ apiEntityFor(fieldOps.get(resource));
19647
+ if (ctx.fresh) cache?.invalidate(`${resource}:`);
19221
19648
  }
19222
- return snake;
19649
+ const tasks = targets.flatMap((resource) => {
19650
+ const holder = client[camelKey(resource)];
19651
+ const fetches = kindFetches(holder, resource);
19652
+ return include.map((kind) => ({ resource, kind, fetch: fetches[kind], holder }));
19653
+ });
19654
+ const reads = await mapReadTasks(client.http, tasks, ({ resource, kind, fetch: fetch2, holder }) => readKind(ctx, resource, kind, fetch2, holder));
19655
+ for (let index = 0; index < targets.length; index += 1) {
19656
+ const start = index * include.length;
19657
+ const row = await sweepResource(ctx, targets[index], tally, reads.slice(start, start + include.length));
19658
+ if (row !== void 0) rows.push(row);
19659
+ }
19660
+ const result = {
19661
+ zone,
19662
+ label: zone,
19663
+ cached: cache !== void 0,
19664
+ labels,
19665
+ compact,
19666
+ ttlMs: cache?.ttlMs ?? null,
19667
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
19668
+ rows,
19669
+ wireUsed: tally.wireUsed,
19670
+ cap: MAX_FIELD_CATALOG_WIRE,
19671
+ truncated: false,
19672
+ counts: {
19673
+ resources: targets.length,
19674
+ fieldCapableResources: fieldOps.size,
19675
+ udfCapableResources: udfCapable.size,
19676
+ cached: rows.filter((r) => r.cache.hit === true).length
19677
+ },
19678
+ honesty: {
19679
+ picklistValues: tally.anyPicklistValues ? "partial" : "unexposed",
19680
+ note: FIELD_CATALOG_HONESTY_NOTE
19681
+ }
19682
+ };
19683
+ if (maxBytes !== void 0) applyMaxBytes(result, maxBytes);
19684
+ return result;
19223
19685
  }
19224
19686
 
19225
19687
  // src/operations/nameSnapshot.ts
@@ -20066,17 +20528,17 @@ function validateParamsBag(record, args) {
20066
20528
  }
20067
20529
  );
20068
20530
  }
20069
- var INVOKE_OPTION_KEYS = ["dryRun", "confirm", "lastModifiedDate", "maxRetries", "fresh", "verifyPersisted", "mode"];
20531
+ var INVOKE_OPTION_KEYS = ["dryRun", "confirm", "lastModifiedDate", "maxRetries", "fresh", "verifyPersisted", "expectedInventoryFacts", "mode"];
20070
20532
  function validateInvokeOptions(opts, operation) {
20071
20533
  if (opts === void 0 || opts === null) return;
20072
20534
  const unknown = Object.keys(opts).filter((k) => !INVOKE_OPTION_KEYS.includes(k));
20073
20535
  if (unknown.length === 0) return;
20074
- const suggestions = keySuggestions(unknown, ["dryRun", "confirm", "lastModifiedDate", "maxRetries", "fresh", "verifyPersisted"]);
20536
+ const suggestions = keySuggestions(unknown, ["dryRun", "confirm", "lastModifiedDate", "maxRetries", "fresh", "verifyPersisted", "expectedInventoryFacts"]);
20075
20537
  throw new AutotaskConfigError(
20076
- `invoke: "${operation}" has unknown option key(s) ${unknown.map((k) => `"${k}"`).join(", ")} \u2014 the options set is closed (valid: dryRun, confirm, lastModifiedDate, maxRetries, fresh, verifyPersisted; "mode" is internal to the mode wrappers)`,
20538
+ `invoke: "${operation}" has unknown option key(s) ${unknown.map((k) => `"${k}"`).join(", ")} \u2014 the options set is closed (valid: dryRun, confirm, lastModifiedDate, maxRetries, fresh, verifyPersisted, expectedInventoryFacts; "mode" is internal to the mode wrappers)`,
20077
20539
  {
20078
20540
  operation,
20079
- suggestedAction: suggestions.length > 0 ? `Fix the option name (${suggestions.join(", ")}).` : `Pass only dryRun / confirm / lastModifiedDate / maxRetries / fresh / verifyPersisted.`
20541
+ suggestedAction: suggestions.length > 0 ? `Fix the option name (${suggestions.join(", ")}).` : `Pass only dryRun / confirm / lastModifiedDate / maxRetries / fresh / verifyPersisted / expectedInventoryFacts.`
20080
20542
  }
20081
20543
  );
20082
20544
  }
@@ -20095,126 +20557,24 @@ function unknownKeysRefusal(raw, validKeys, subject, operation) {
20095
20557
  }
20096
20558
 
20097
20559
  // src/resources/special/inventoryLocations.ts
20098
- var fail = (message) => {
20560
+ var fail2 = (message) => {
20099
20561
  throw new AutotaskConfigError(`inventory_locations: ${message}`);
20100
20562
  };
20101
20563
  function admitInventoryLocation(value, creating) {
20102
- if (!isRecord2(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail("data must be a plain record");
20564
+ if (!isRecord2(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail2("data must be a plain record");
20103
20565
  const body = { ...value };
20104
- for (const field of Object.keys(body)) if (!["locationName", "isActive"].includes(field)) fail(`${field} is not a writable InventoryLocations field`);
20566
+ for (const field of Object.keys(body)) if (!["locationName", "isActive"].includes(field)) fail2(`${field} is not a writable InventoryLocations field`);
20105
20567
  const hasName = Object.hasOwn(body, "locationName");
20106
20568
  const hasActive = Object.hasOwn(body, "isActive");
20107
- if (creating && !hasName || hasName && (typeof body.locationName !== "string" || body.locationName.trim() === "" || body.locationName.length > 50)) fail("locationName is required and must be a nonblank string of at most 50 characters");
20108
- if (creating && !hasActive || hasActive && typeof body.isActive !== "boolean") fail("isActive must be a boolean");
20109
- if (!creating && !hasName && !hasActive) fail("update must contain locationName or isActive");
20569
+ if (creating && !hasName || hasName && (typeof body.locationName !== "string" || body.locationName.trim() === "" || body.locationName.length > 50)) fail2("locationName is required and must be a nonblank string of at most 50 characters");
20570
+ if (creating && !hasActive || hasActive && typeof body.isActive !== "boolean") fail2("isActive must be a boolean");
20571
+ if (!creating && !hasName && !hasActive) fail2("update must contain locationName or isActive");
20110
20572
  return body;
20111
20573
  }
20112
20574
  function checkInventoryLocationCurrent(value, current, id) {
20113
- if (!isRecord2(current) || !Object.hasOwn(current, "id")) fail("current record requires its own id");
20114
- if (parseIdentifier(current.id, "inventory_locations: current id") !== id) fail("current record id must match the requested id");
20115
- if (Object.hasOwn(value, "isActive") && value.isActive === false && (!Object.hasOwn(current, "isDefault") || current.isDefault !== false)) fail("inactivation requires a fresh current isDefault value explicitly false; default or unknown locations cannot be inactivated");
20116
- }
20117
-
20118
- // src/resources/special/inventoryItems.ts
20119
- var REFERENCES = ["inventoryLocationID", "productID"];
20120
- var QUANTITIES = ["quantityMinimum", "quantityMaximum", "quantityOnHand"];
20121
- var TEXT_FIELDS = ["bin", "referenceNumber"];
20122
- var MUTATION_OPTIONS = ["dryRun", "lastModifiedDate", "maxRetries", "raw", "verifyPersisted"];
20123
- function fail2(message) {
20124
- throw new AutotaskConfigError(`inventory_items: ${message}`);
20125
- }
20126
- function own(record, field) {
20127
- return Object.hasOwn(record, field) ? record[field] : void 0;
20128
- }
20129
- function int32(value, label, minimum = -2147483648) {
20130
- if (typeof value !== "number" || !Number.isInteger(value) || value < minimum || value > 2147483647) {
20131
- fail2(`${label} must be an integer between ${minimum} and 2147483647`);
20132
- }
20133
- return value;
20134
- }
20135
- function inventoryItemId(value) {
20136
- const id = parseIdentifier(value, "inventory_items: id");
20137
- if (!isAuditDecimalId(String(id))) fail2("id must fit a signed 64-bit integer");
20138
- return id;
20139
- }
20140
- function admitInventoryItem(value, creating) {
20141
- if (!isRecord2(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail2("data must be a plain record");
20142
- const body = { ...value };
20143
- const writable = [...QUANTITIES, ...TEXT_FIELDS, ...creating ? REFERENCES : []];
20144
- for (const field of Object.keys(body)) {
20145
- if (!writable.some((name) => name === field)) fail2(`${field} is not a writable InventoryItems field on ${creating ? "create" : "update"}`);
20146
- }
20147
- if (!creating && Object.keys(body).length === 0) fail2("update must contain a writable field");
20148
- if (creating) for (const field of REFERENCES) int32(own(body, field), field, 1);
20149
- for (const field of QUANTITIES) {
20150
- const nonnegative = field === "quantityMinimum" || creating && field === "quantityOnHand";
20151
- if (creating || Object.hasOwn(body, field)) int32(own(body, field), field, nonnegative ? 0 : void 0);
20152
- }
20153
- for (const field of TEXT_FIELDS) {
20154
- const text = own(body, field);
20155
- if (Object.hasOwn(body, field) && (typeof text !== "string" || text.length > 50)) fail2(`${field} must be a string of at most 50 characters`);
20156
- }
20157
- assertQuantityRange(own(body, "quantityMinimum"), own(body, "quantityMaximum"));
20158
- return body;
20159
- }
20160
- function snapshotInventoryItemOptions(value) {
20161
- if (value !== void 0 && !isRecord2(value)) fail2("options must be an object");
20162
- const options = value ?? {};
20163
- for (const key of MUTATION_OPTIONS) {
20164
- if (key in options && !Object.hasOwn(options, key)) fail2(`${key} must be an own option`);
20165
- }
20166
- const result = snapshotMutationOptions(Object.fromEntries(MUTATION_OPTIONS.map((key) => [key, own(options, key)])));
20167
- if (result.lastModifiedDate !== void 0) fail2("no documented stale timestamp is available");
20168
- if (result.raw !== void 0 && result.raw !== false) fail2("raw updates are unsupported");
20169
- if (result.maxRetries !== void 0 && (!Number.isSafeInteger(result.maxRetries) || result.maxRetries < 0)) fail2("maxRetries must be a nonnegative safe integer");
20170
- if (result.verifyPersisted !== void 0 && typeof result.verifyPersisted !== "boolean") fail2("verifyPersisted must be a boolean");
20171
- return result;
20172
- }
20173
- function assertQuantityRange(minimum, maximum) {
20174
- if (typeof minimum === "number" && typeof maximum === "number" && maximum < minimum) fail2("quantityMaximum must be at least quantityMinimum");
20175
- }
20176
- function exactItem(value, id, label) {
20177
- if (!isRecord2(value)) fail2(`${label} must be a record`);
20178
- const returned = own(value, "id");
20179
- if (typeof returned !== "string" && (typeof returned !== "number" || !Number.isSafeInteger(returned))) fail2(`${label} requires its own exact id`);
20180
- if (String(returned) !== String(id)) fail2(`${label} id must match the requested id`);
20181
- return value;
20182
- }
20183
- async function productIsSerialized(http, id, checkedBaseUrl, maxRetries) {
20184
- const operation = "products.get";
20185
- const body = await http.request({ method: "GET", path: `/V1.0/Products/${id}`, operation, maxRetries, checkedBaseUrl });
20186
- const product = exactItem(unwrapItem(body, id, operation, "product"), id, "product");
20187
- const serialized = own(product, "isSerialized");
20188
- if (typeof serialized !== "boolean") fail2("product requires a fresh boolean isSerialized fact");
20189
- return serialized;
20190
- }
20191
- async function guardInventoryItemCreate(http, data, checkedBaseUrl, maxRetries) {
20192
- const locationId = data.inventoryLocationID;
20193
- const operation = "inventory_locations.get";
20194
- const body = await http.request({ method: "GET", path: `/V1.0/InventoryLocations/${locationId}`, operation, maxRetries, checkedBaseUrl });
20195
- const location = exactItem(unwrapItem(body, locationId, operation, "inventory_location"), locationId, "inventory location");
20196
- if (own(location, "isActive") !== true) fail2("inventory location requires a fresh isActive value explicitly true");
20197
- if (await productIsSerialized(http, data.productID, checkedBaseUrl, maxRetries) && data.quantityOnHand !== 0) {
20198
- fail2("quantityOnHand must be zero when creating an item for a serialized product");
20199
- }
20200
- }
20201
- async function checkInventoryItemCurrent(http, data, current, id, checkedBaseUrl, maxRetries) {
20202
- const item = exactItem(current, id, "current record");
20203
- const minimum = own(data, "quantityMinimum");
20204
- const maximum = own(data, "quantityMaximum");
20205
- if (minimum !== void 0 || maximum !== void 0) {
20206
- assertQuantityRange(
20207
- minimum ?? int32(own(item, "quantityMinimum"), "current quantityMinimum", 0),
20208
- maximum ?? int32(own(item, "quantityMaximum"), "current quantityMaximum")
20209
- );
20210
- }
20211
- const onHand = own(data, "quantityOnHand");
20212
- if (typeof onHand !== "number") return;
20213
- const picked = int32(own(item, "quantityPicked"), "current quantityPicked");
20214
- const reserved = int32(own(item, "quantityReserved"), "current quantityReserved");
20215
- if (onHand < picked + reserved) fail2("quantityOnHand must be at least quantityPicked plus quantityReserved");
20216
- const productId = int32(own(item, "productID"), "current productID", 1);
20217
- if (await productIsSerialized(http, productId, checkedBaseUrl, maxRetries)) fail2("quantityOnHand is read-only on update for a serialized product");
20575
+ if (!isRecord2(current) || !Object.hasOwn(current, "id")) fail2("current record requires its own id");
20576
+ if (parseIdentifier(current.id, "inventory_locations: current id") !== id) fail2("current record id must match the requested id");
20577
+ if (Object.hasOwn(value, "isActive") && value.isActive === false && (!Object.hasOwn(current, "isDefault") || current.isDefault !== false)) fail2("inactivation requires a fresh current isDefault value explicitly false; default or unknown locations cannot be inactivated");
20218
20578
  }
20219
20579
 
20220
20580
  // src/resources/base/types.ts
@@ -20398,6 +20758,7 @@ var MODEL_FIELD_SETS = {
20398
20758
  "organizational_level1s": ["id", "description", "isActive", "name"],
20399
20759
  "organizational_level2s": ["id", "description", "isActive", "name"],
20400
20760
  "organizational_level_associations": ["id", "isActive", "organizationalLevel1ID", "organizationalLevel2ID"],
20761
+ "organizational_resources": ["id", "organizationalLevelAssociationID", "resourceID", "soapParentPropertyId"],
20401
20762
  "phases": ["id", "createDate", "creatorResourceID", "description", "dueDate", "estimatedHours", "externalID", "isScheduled", "lastActivityDateTime", "parentPhaseID", "phaseNumber", "projectID", "startDate", "title", "soapParentPropertyId"],
20402
20763
  "product_vendors": ["id", "isActive", "isDefault", "productID", "vendorCost", "vendorID", "vendorPartNumber", "soapParentPropertyId"],
20403
20764
  "products": ["id", "billingType", "chargeBillingCodeID", "createdByResourceID", "createdTime", "defaultVendorID", "description", "doesNotRequireProcurement", "externalProductID", "impersonatorCreatorResourceID", "internalProductID", "isActive", "isEligibleForRma", "isSerialized", "link", "manufacturerName", "manufacturerProductName", "markupRate", "msrp", "name", "periodType", "priceCostMethod", "productBillingCodeID", "productCategory", "sku", "unitCost", "unitPrice", "vendorProductNumber", "defaultInstalledProductCategoryID", "userDefinedFields"],
@@ -20415,6 +20776,7 @@ var MODEL_FIELD_SETS = {
20415
20776
  "quote_templates": ["id", "calculateTaxSeparately", "createDate", "createdBy", "currencyNegativeFormat", "currencyPositiveFormat", "dateFormat", "description", "displayTaxCategorySuperscripts", "isActive", "lastActivityBy", "lastActivityDate", "name", "numberFormat", "pageLayout", "pageNumberFormat", "showEachTaxInGroup", "showGridHeader", "showTaxCategory", "showVerticalGridLines"],
20416
20777
  "quotes": ["id", "approvalStatus", "approvalStatusChangedByResourceID", "approvalStatusChangedDate", "billToLocationID", "calculateTaxSeparately", "comment", "companyID", "contactID", "createDate", "creatorResourceID", "description", "effectiveDate", "expirationDate", "extApprovalContactResponse", "extApprovalResponseDate", "extApprovalResponseSignature", "externalQuoteNumber", "groupByID", "impersonatorCreatorResourceID", "isActive", "lastActivityDate", "lastModifiedBy", "lastPublishedByResourceID", "lastPublishedDateTime", "name", "opportunityID", "paymentTerm", "paymentType", "primaryQuote", "proposalProjectID", "purchaseOrderNumber", "quoteNumber", "quoteTemplateID", "shippingType", "shipToLocationID", "showEachTaxInGroup", "showTaxCategory", "soldToLocationID", "taxRegionID"],
20417
20778
  "resource_attachments": ["id", "attachDate", "attachedByContactID", "attachedByResourceID", "attachmentType", "contentType", "creatorType", "fileSize", "fullPath", "impersonatorCreatorResourceID", "opportunityID", "parentID", "publish", "resourceID", "title", "data", "parentType", "soapParentPropertyId", "isTaskAttachment"],
20779
+ "resource_daily_availabilities": ["id", "resourceID", "sundayAvailableHours", "mondayAvailableHours", "tuesdayAvailableHours", "wednesdayAvailableHours", "thursdayAvailableHours", "fridayAvailableHours", "saturdayAvailableHours", "weeklyBillableHoursGoal", "travelAvailability", "soapParentPropertyId"],
20418
20780
  "resource_role_queues": ["id", "queueID", "resourceID", "soapParentPropertyId"],
20419
20781
  "resource_roles": ["id", "departmentID", "isActive", "queueID", "resourceID", "roleID", "soapParentPropertyId"],
20420
20782
  "resource_skills": ["id", "resourceID", "skillDescription", "skillID", "skillLevel", "soapParentPropertyId"],
@@ -22773,6 +23135,11 @@ var MutationBase = class extends MetaBase {
22773
23135
  current = currentRecord ?? (parentId === void 0 ? await this.getGlobal(id, true, this.config.key === "knowledge_base_categories" || partialCollection !== void 0 ? opts.maxRetries : void 0, partialCollection?.checkedBaseUrl) : this.config.attachmentGet ? await this.getScopedModel(parentId, id, true) : await this.getScopedRaw(parentId, id, true));
22774
23136
  } catch (err) {
22775
23137
  if (err instanceof NotFoundError) {
23138
+ if (this.config.key === "inventory_items" && opts.expectedInventoryFacts !== void 0) {
23139
+ if (err.httpStatus === 200) inventoryFactsStale(operation);
23140
+ Object.assign(err, { notSent: true });
23141
+ throw err;
23142
+ }
22776
23143
  const reasons = EMPTY_REASON_STAMPS[this.config.key];
22777
23144
  const updateReason = reasons?.update ?? (partialCollection === void 0 ? void 0 : reasons?.get);
22778
23145
  checks.push({
@@ -24279,6 +24646,19 @@ var SIMPLE_RESOURCES = [
24279
24646
  helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
24280
24647
  opForms: { get: "global", create: "global", update: "global" }
24281
24648
  },
24649
+ {
24650
+ key: "organizational_resources",
24651
+ accessor: "organizationalResources",
24652
+ resourcePath: "/V1.0/OrganizationalResources",
24653
+ parentScopedPath: "/V1.0/OrganizationalLevelAssociations/{parentId}/Resources",
24654
+ parentPath: "/V1.0/OrganizationalLevelAssociations",
24655
+ parentField: "organizationalLevelAssociationID",
24656
+ deletable: false,
24657
+ udfCapable: false,
24658
+ ops: { query: true, queryAll: false, count: true, get: true, create: false, update: false, delete: false, getEntityInfo: true, getFieldInfo: true, getUdfInfo: true },
24659
+ helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
24660
+ opForms: { get: "global" }
24661
+ },
24282
24662
  {
24283
24663
  key: "phases",
24284
24664
  accessor: "phases",
@@ -24488,6 +24868,19 @@ var SIMPLE_RESOURCES = [
24488
24868
  helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
24489
24869
  opForms: { get: "scoped", create: "scoped", delete: "scoped" }
24490
24870
  },
24871
+ {
24872
+ key: "resource_daily_availabilities",
24873
+ accessor: "resourceDailyAvailabilities",
24874
+ resourcePath: "/V1.0/ResourceDailyAvailabilities",
24875
+ parentScopedPath: "/V1.0/Resources/{parentId}/DailyAvailabilities",
24876
+ parentPath: "/V1.0/Resources",
24877
+ parentField: "resourceID",
24878
+ deletable: false,
24879
+ udfCapable: false,
24880
+ ops: { query: true, queryAll: false, count: true, get: true, create: false, update: false, delete: false, getEntityInfo: true, getFieldInfo: true, getUdfInfo: true },
24881
+ helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
24882
+ opForms: { get: "global" }
24883
+ },
24491
24884
  {
24492
24885
  key: "resource_role_queues",
24493
24886
  accessor: "resourceRoleQueues",
@@ -25144,6 +25537,23 @@ var GenericResource = class extends BaseResource {
25144
25537
  this.requireOp("count");
25145
25538
  return this.countGlobal(params);
25146
25539
  }
25540
+ /** Read one native staff-association page; raw continuations are neither returned nor followed. */
25541
+ async listByParent(parentId) {
25542
+ if (!["organizational_resources", "resource_daily_availabilities"].includes(this.config.key)) throw new OperationNotSupportedError(this.config.key, "listByParent");
25543
+ const operation = `${this.config.key}.listByParent`;
25544
+ const parent = parseIdentifier(parentId, "parentId");
25545
+ if (!isAuditDecimalId(String(parent))) throw new AutotaskConfigError("parentId must be a non-negative signed 64-bit integer", { operation });
25546
+ const page = unwrapItems(await this.http.request({ method: "GET", path: this.scopedCollectionPath(parent), operation }), operation);
25547
+ const next = Object.hasOwn(page.pageDetails, "nextPageUrl") ? page.pageDetails.nextPageUrl : void 0;
25548
+ if (next !== null && (typeof next !== "string" || next.length === 0)) throw new AutotaskError("Expected explicit native page continuation metadata", { code: "INVALID_RESPONSE", category: "server", operation });
25549
+ const field = this.config.parentField;
25550
+ const hasInvalidParent = page.items.some((row) => {
25551
+ const value = isRecord2(row) && Object.hasOwn(row, field) ? row[field] : void 0;
25552
+ return typeof value !== "number" || !Number.isInteger(value) || value > 2147483647 || String(value) !== String(parent);
25553
+ });
25554
+ if (hasInvalidParent) throw new AutotaskError("Native page rows must bind the requested parent through the int32 model field", { code: "INVALID_RESPONSE", category: "server", operation });
25555
+ return { items: page.items, hasMore: next !== null };
25556
+ }
25147
25557
  async get(a, b = void 0, c = void 0) {
25148
25558
  this.requireOp("get");
25149
25559
  if (isIdentifier(b)) {
@@ -25162,6 +25572,7 @@ var GenericResource = class extends BaseResource {
25162
25572
  }
25163
25573
  async create(a, b = void 0, c = void 0) {
25164
25574
  this.requireOp("create");
25575
+ rejectInventoryFactsOption(isIdentifier(a) ? c : b, `${this.config.key}.create`);
25165
25576
  if (isIdentifier(a)) {
25166
25577
  if (this.config.opForms?.create === "global") throw new OperationNotSupportedError(this.config.key, "create");
25167
25578
  const parentId = this.config.key === "knowledge_base_articles" ? articleParent(a) : a;
@@ -25185,11 +25596,10 @@ var GenericResource = class extends BaseResource {
25185
25596
  }
25186
25597
  if (this.config.opForms?.create === "scoped") throw new OperationNotSupportedError(this.config.key, "create");
25187
25598
  if (this.config.key === "inventory_items") {
25188
- const body = admitInventoryItem(a, true);
25189
- const opts2 = snapshotInventoryItemOptions(b);
25599
+ const { body, opts: opts2 } = captureInventoryItemCall(a, b, true);
25190
25600
  const checkedBaseUrl = this.http.baseUrl;
25191
25601
  try {
25192
- await guardInventoryItemCreate(this.http, body, checkedBaseUrl, opts2.maxRetries);
25602
+ await guardInventoryItemCreate(this.http, body, checkedBaseUrl, opts2.maxRetries, opts2.expectedInventoryFacts);
25193
25603
  } catch (error) {
25194
25604
  if (error instanceof AutotaskError) Object.assign(error, { notSent: true });
25195
25605
  throw error;
@@ -25206,6 +25616,7 @@ var GenericResource = class extends BaseResource {
25206
25616
  }
25207
25617
  async update(a, b = void 0, c = void 0, d = void 0) {
25208
25618
  this.requireOp("update");
25619
+ rejectInventoryFactsOption(isIdentifier(b) ? d : c, `${this.config.key}.update`);
25209
25620
  if (isIdentifier(a) && isIdentifier(b)) {
25210
25621
  if (this.config.opForms?.update === "global") throw new OperationNotSupportedError(this.config.key, "update");
25211
25622
  const parentId = this.config.key === "knowledge_base_articles" ? articleParent(a) : a;
@@ -25228,16 +25639,15 @@ var GenericResource = class extends BaseResource {
25228
25639
  if (this.config.opForms?.update === "scoped") throw new OperationNotSupportedError(this.config.key, "update");
25229
25640
  if (this.config.key === "inventory_items") {
25230
25641
  const id2 = inventoryItemId(a);
25231
- const body = admitInventoryItem(b, false);
25232
- const opts2 = snapshotInventoryItemOptions(c);
25642
+ const { body, opts: opts2 } = captureInventoryItemCall(b, c, false);
25233
25643
  const checkedBaseUrl = this.http.baseUrl;
25234
- const checkCurrent = (current) => checkInventoryItemCurrent(this.http, body, current, id2, checkedBaseUrl, opts2.maxRetries);
25644
+ const checkCurrent = (current) => checkInventoryItemCurrent(this.http, body, current, id2, checkedBaseUrl, opts2.maxRetries, opts2.expectedInventoryFacts);
25235
25645
  if (opts2.dryRun === true) return this.runUpdateDryRun(id2, body, opts2, void 0, void 0, { checkCurrent, checkedBaseUrl });
25236
25646
  try {
25237
25647
  await checkCurrent(await this.getGlobal(id2, true, opts2.maxRetries, checkedBaseUrl));
25238
25648
  } catch (error) {
25239
25649
  if (error instanceof AutotaskError) Object.assign(error, { notSent: true });
25240
- throw error;
25650
+ rethrowInventoryGuardError(error, opts2.expectedInventoryFacts, "inventory_items.update");
25241
25651
  }
25242
25652
  return this.updateGlobal(id2, body, opts2, "PATCH", checkedBaseUrl);
25243
25653
  }
@@ -25271,6 +25681,7 @@ var GenericResource = class extends BaseResource {
25271
25681
  }
25272
25682
  async delete(a, b = void 0, c = void 0) {
25273
25683
  this.requireOp("delete");
25684
+ rejectInventoryFactsOption(isIdentifier(b) ? c : b, `${this.config.key}.delete`);
25274
25685
  if (isIdentifier(a) && isIdentifier(b)) {
25275
25686
  if (this.config.opForms?.delete === "global") throw new OperationNotSupportedError(this.config.key, "delete");
25276
25687
  const parentId = this.config.key === "knowledge_base_articles" ? articleParent(a) : a;
@@ -26952,7 +27363,7 @@ function dateBucketLabel(value, bucket) {
26952
27363
  var queryResourceKeysPromise = null;
26953
27364
  function queryResourceKeys() {
26954
27365
  if (queryResourceKeysPromise === null) {
26955
- queryResourceKeysPromise = chunkQXJQIZCT_cjs.loadCapabilityRecords().then((records) => {
27366
+ queryResourceKeysPromise = chunkSBHQIPCJ_cjs.loadCapabilityRecords().then((records) => {
26956
27367
  const s = /* @__PURE__ */ new Set();
26957
27368
  for (const rec of records) if (rec.operation === "query") s.add(rec.resource);
26958
27369
  return s;
@@ -27074,7 +27485,7 @@ function parseTopAndLimit(opts, problems) {
27074
27485
  return { top, limit };
27075
27486
  }
27076
27487
  async function checkFieldNames(resourceKey, conditions, opts, problems) {
27077
- const records = resourceKey === void 0 ? [] : await chunkQXJQIZCT_cjs.loadCapabilityRecords();
27488
+ const records = resourceKey === void 0 ? [] : await chunkSBHQIPCJ_cjs.loadCapabilityRecords();
27078
27489
  const record = resourceKey === void 0 ? void 0 : records.find((r) => r.resource === resourceKey && r.operation === "query");
27079
27490
  if (record === void 0) return void 0;
27080
27491
  const strings = (v) => Array.isArray(v) ? v.filter((f) => typeof f === "string" && f.trim() !== "") : [];
@@ -27263,6 +27674,13 @@ function validateFetchManyItems(items, cap, opName = "fetchByIds", capRef = `FET
27263
27674
  );
27264
27675
  continue;
27265
27676
  }
27677
+ if (hasNativeStaffCollection(resourceKey)) {
27678
+ const clientResource = `client.${camelKey(resourceKey)}`;
27679
+ problems.push(
27680
+ `${at}.resource: "${resourceKey}" is a parent-scoped child outside ${opName}; use ${clientResource}.get(id) or ${clientResource}.listByParent(parentId)`
27681
+ );
27682
+ continue;
27683
+ }
27266
27684
  const rel = RELATIONSHIP_MAP[resourceKey];
27267
27685
  const globalRead = resourceKey === "time_off_requests" || resourceKey === "knowledge_base_articles";
27268
27686
  if (rel !== void 0 && rel.parentScoped && !globalRead) {
@@ -27570,7 +27988,7 @@ async function uiLink(client, input) {
27570
27988
  var indexPromise = null;
27571
27989
  function operationIndex() {
27572
27990
  if (indexPromise === null) {
27573
- indexPromise = chunkQXJQIZCT_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
27991
+ indexPromise = chunkSBHQIPCJ_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
27574
27992
  }
27575
27993
  return indexPromise;
27576
27994
  }
@@ -31343,7 +31761,7 @@ async function wipHours(client, opts) {
31343
31761
  } else {
31344
31762
  const contractIds = positiveIds2(wipIn.map((e) => e["contractID"]));
31345
31763
  gate(chunks2(contractIds.length) + (contractIds.length > 0 ? 1 : 0), "before label reads", { contracts: contractIds.length });
31346
- const [contracts, types] = await readTasks(http, [
31764
+ const [contracts, types2] = await readTasks(http, [
31347
31765
  () => readChunks2(http, "/V1.0/Contracts", contractIds, ["contractType"]),
31348
31766
  async () => contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0
31349
31767
  ]);
@@ -31351,7 +31769,7 @@ async function wipHours(client, opts) {
31351
31769
  const bad = contractIds.filter((id) => typeof typeOf(id) !== "number");
31352
31770
  if (bad.length > 0) throw unresolved("contracts", bad);
31353
31771
  keyOfEntry = (e) => num(e["contractID"]) > 0 ? typeOf(num(e["contractID"])) : null;
31354
- for (const [id, label] of types ?? []) labels.set(id, { label });
31772
+ for (const [id, label] of types2 ?? []) labels.set(id, { label });
31355
31773
  }
31356
31774
  const approvalData = entries.some((e) => isApproved(e));
31357
31775
  const acc = () => ({ entries: 0, worked: 0, toBill: 0, approved: 0 });
@@ -31542,7 +31960,7 @@ async function nonChargeableWork(client, opts) {
31542
31960
  const contractIds = distinctIds(ncLines.map((x) => x.line["contractID"]), 1);
31543
31961
  const typed = v.groupBy === "contractType";
31544
31962
  gate(chunks3(contractIds.length) + (typed && contractIds.length > 0 ? 1 : 0) + (v.includeUnpostedTime ? 1 : 0), "before label reads", { contracts: contractIds.length });
31545
- const [contracts, types] = await readTasks(http, [
31963
+ const [contracts, types2] = await readTasks(http, [
31546
31964
  () => readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]),
31547
31965
  async () => typed && contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP11)).get("contractType") : void 0
31548
31966
  ]);
@@ -31553,7 +31971,7 @@ async function nonChargeableWork(client, opts) {
31553
31971
  if (!typed) return num(line["contractID"]);
31554
31972
  return isId(c["contractType"]) ? c["contractType"] : UNRESOLVED;
31555
31973
  };
31556
- if (typed) for (const [id, label] of types ?? []) labels.set(id, { label });
31974
+ if (typed) for (const [id, label] of types2 ?? []) labels.set(id, { label });
31557
31975
  else for (const [id, r] of contracts) labels.set(Number(id), typeof r["contractName"] === "string" ? { name: r["contractName"] } : {});
31558
31976
  }
31559
31977
  const cells = /* @__PURE__ */ new Map();
@@ -31731,8 +32149,37 @@ function bufferResult(buf) {
31731
32149
  };
31732
32150
  }
31733
32151
  var PUBLIC_INVOKE_OPTION_KEYS = INVOKE_OPTION_KEYS.filter((key) => key !== "mode");
31734
- function snapshotInvokeOptions(options, mode) {
32152
+ function snapshotInventoryInvokeOptions(options, operation, mode) {
32153
+ const { descriptors, expectedInventoryFacts: facts } = captureInventoryOptionDescriptors(options);
32154
+ if (Object.getOwnPropertySymbols(descriptors).length > 0) throw new AutotaskConfigError("inventory_items: invoke options must use string keys", { operation });
32155
+ const applyFlag = Object.hasOwn(descriptors, "dryRun") ? descriptors.dryRun : void 0;
32156
+ for (const key of PUBLIC_INVOKE_OPTION_KEYS) {
32157
+ if (key === "expectedInventoryFacts" || Object.hasOwn(descriptors, key)) continue;
32158
+ for (let owner = Object.getPrototypeOf(options); owner !== null && owner !== Object.prototype; owner = Object.getPrototypeOf(owner)) {
32159
+ const descriptor2 = Object.getOwnPropertyDescriptor(owner, key);
32160
+ if (descriptor2 !== void 0) {
32161
+ descriptors[key] = descriptor2;
32162
+ break;
32163
+ }
32164
+ }
32165
+ }
32166
+ const captured = /* @__PURE__ */ Object.create(null);
32167
+ for (const [key, descriptor2] of Object.entries(descriptors)) captured[key] = Object.hasOwn(descriptor2, "value") ? descriptor2.value : void 0;
32168
+ validateInvokeOptions(captured, operation);
32169
+ if (facts !== void 0 && Object.values(descriptors).some((descriptor2) => !Object.hasOwn(descriptor2, "value"))) throw new AutotaskConfigError("inventory_items: approved options must be data properties; accessors are unsupported", { operation });
32170
+ const applyRequested = applyFlag !== void 0 && Object.hasOwn(applyFlag, "value") && applyFlag.value === false;
32171
+ for (const [key, descriptor2] of Object.entries(descriptors)) {
32172
+ if (key === "expectedInventoryFacts" || Object.hasOwn(descriptor2, "value")) continue;
32173
+ captured[key] = descriptor2.get === void 0 ? void 0 : Reflect.apply(descriptor2.get, options, []);
32174
+ }
32175
+ captured.expectedInventoryFacts = facts;
32176
+ captured.dryRun = applyRequested || captured.dryRun !== false ? captured.dryRun : void 0;
32177
+ return Object.assign(captured, { mode });
32178
+ }
32179
+ function snapshotInvokeOptions(options, operation, mode) {
32180
+ if (operation === "inventory_items.create" || operation === "inventory_items.update") return snapshotInventoryInvokeOptions(options, operation, mode);
31735
32181
  if (!isRecord2(options)) throw new AutotaskConfigError("invoke: options must be an object");
32182
+ rejectInventoryFactsOption(options, operation);
31736
32183
  const applyFlag = Object.getOwnPropertyDescriptor(options, "dryRun");
31737
32184
  const applyRequested = applyFlag !== void 0 && Object.hasOwn(applyFlag, "value") && applyFlag.value === false;
31738
32185
  let confirmation;
@@ -31748,7 +32195,8 @@ function snapshotInvokeOptions(options, mode) {
31748
32195
  const dryRun = options.dryRun;
31749
32196
  const captured = snapshotFields(options, PUBLIC_INVOKE_OPTION_KEYS, {
31750
32197
  dryRun: applyRequested || dryRun !== false ? dryRun : void 0,
31751
- confirm
32198
+ confirm,
32199
+ expectedInventoryFacts: void 0
31752
32200
  });
31753
32201
  return Object.assign(/* @__PURE__ */ Object.create(null), captured, { mode });
31754
32202
  }
@@ -31764,6 +32212,7 @@ async function resolveRecord(operation) {
31764
32212
  }
31765
32213
  function governPreRequest(record, operation, opts) {
31766
32214
  validateInvokeOptions(opts, operation);
32215
+ if (opts.expectedInventoryFacts !== void 0) rejectInventoryFactsOption(opts, operation);
31767
32216
  const mode = opts.mode;
31768
32217
  if (mode !== void 0 && MODE_BY_EFFECT[record.effect] !== mode) {
31769
32218
  throw new AutotaskConfigError(crossModeRefusal(operation, record.effect, mode), { operation });
@@ -31887,6 +32336,7 @@ var BAG_RIDING_ARGS = {
31887
32336
  function buildMutationOpts(opts, isWrite) {
31888
32337
  const dryRun = isWrite ? opts.dryRun !== false : false;
31889
32338
  const mutationOpts = { dryRun };
32339
+ if (opts.expectedInventoryFacts !== void 0) mutationOpts.expectedInventoryFacts = opts.expectedInventoryFacts;
31890
32340
  if (isWrite && opts.lastModifiedDate !== void 0) {
31891
32341
  mutationOpts.lastModifiedDate = opts.lastModifiedDate;
31892
32342
  }
@@ -31988,6 +32438,10 @@ async function runPreRequestPass(ctx) {
31988
32438
  }
31989
32439
  async function prepareInvocation(client, operation, argsIn, opts, streaming = false) {
31990
32440
  const record = await resolveRecord(operation);
32441
+ if (operation === "inventory_items.create" || operation === "inventory_items.update") {
32442
+ governPreRequest(record, operation, opts);
32443
+ snapshotInventoryMutationOptions(opts);
32444
+ }
31991
32445
  const resolvedArgs = resolveDispatchArgs(record, argsIn);
31992
32446
  const boundedQuery = record.kind === "primitive" && record.operation === "query";
31993
32447
  const countedQuery = record.kind === "primitive" && record.operation === "count";
@@ -32029,14 +32483,16 @@ async function invokeMode(client, operation, argsIn = [], opts = {}) {
32029
32483
  return scopeNote !== void 0 && finished !== null && typeof finished === "object" ? { ...finished, scopeNote } : finished;
32030
32484
  }
32031
32485
  async function invoke(client, operation, args = [], opts = {}) {
32032
- return invokeMode(client, operation, args, snapshotInvokeOptions(opts));
32486
+ const capturedArgs = captureInventoryInvocationArgs(operation, args);
32487
+ const capturedOpts = snapshotInvokeOptions(opts, operation);
32488
+ return invokeMode(client, operation, capturedArgs(capturedOpts.expectedInventoryFacts === void 0), capturedOpts);
32033
32489
  }
32034
32490
  async function invokeRead(client, operation, args = [], opts = {}) {
32035
- return invokeMode(client, operation, args, snapshotInvokeOptions(opts, "read"));
32491
+ return invokeMode(client, operation, args, snapshotInvokeOptions(opts, operation, "read"));
32036
32492
  }
32037
32493
  async function invokeReadPages(client, operation, args, onPage, opts = {}) {
32038
32494
  if (typeof onPage !== "function") throw new AutotaskConfigError("invokeReadPages: onPage must be a function", { operation });
32039
- const prepared = await prepareInvocation(client, operation, args, snapshotInvokeOptions(opts, "read"), true);
32495
+ const prepared = await prepareInvocation(client, operation, args, snapshotInvokeOptions(opts, operation, "read"), true);
32040
32496
  prepared.pageSession.guard();
32041
32497
  const consume = prepared.method;
32042
32498
  const result = await consume.call(prepared.holder, prepared.callArgs[0], onPage);
@@ -32044,10 +32500,12 @@ async function invokeReadPages(client, operation, args, onPage, opts = {}) {
32044
32500
  return prepared.scopeNote === void 0 ? result : { ...result, scopeNote: prepared.scopeNote };
32045
32501
  }
32046
32502
  async function invokeWrite(client, operation, args = [], opts = {}) {
32047
- return invokeMode(client, operation, args, snapshotInvokeOptions(opts, "write"));
32503
+ const capturedArgs = captureInventoryInvocationArgs(operation, args);
32504
+ const capturedOpts = snapshotInvokeOptions(opts, operation, "write");
32505
+ return invokeMode(client, operation, capturedArgs(capturedOpts.expectedInventoryFacts === void 0), capturedOpts);
32048
32506
  }
32049
32507
  async function invokeDelete(client, operation, args = [], opts = {}) {
32050
- return invokeMode(client, operation, args, snapshotInvokeOptions(opts, "delete"));
32508
+ return invokeMode(client, operation, args, snapshotInvokeOptions(opts, operation, "delete"));
32051
32509
  }
32052
32510
 
32053
32511
  // src/resources/special/_shared/compositeParts.ts
@@ -32288,6 +32746,7 @@ exports.fetchByIds = fetchByIds;
32288
32746
  exports.fieldCatalog = fieldCatalog;
32289
32747
  exports.foldFlattenedOpts = foldFlattenedOpts;
32290
32748
  exports.formatVendorDetail = formatVendorDetail;
32749
+ exports.inventoryItemGuardFacts = inventoryItemGuardFacts;
32291
32750
  exports.invoke = invoke;
32292
32751
  exports.invokeDelete = invokeDelete;
32293
32752
  exports.invokeRead = invokeRead;
@@ -32314,6 +32773,7 @@ exports.queryRows = queryRows;
32314
32773
  exports.readTasks = readTasks;
32315
32774
  exports.recurringRevenue = recurringRevenue;
32316
32775
  exports.refuse = refuse2;
32776
+ exports.rejectInventoryFactsOption = rejectInventoryFactsOption;
32317
32777
  exports.relationshipMap = relationshipMap;
32318
32778
  exports.resolveAny = resolveAny;
32319
32779
  exports.resolveCompositeNames = resolveCompositeNames;