'use strict';

var chunkLDTMSHUZ_cjs = require('./chunk-LDTMSHUZ.cjs');
var shared_net_errors = require('@osdk/shared.net.errors');
var shared_net_fetch = require('@osdk/shared.net.fetch');
var invariant3 = require('tiny-invariant');
var api = require('@osdk/api');
var WebSocket = require('isomorphic-ws');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var invariant3__default = /*#__PURE__*/_interopDefault(invariant3);
var WebSocket__default = /*#__PURE__*/_interopDefault(WebSocket);

// src/object/fetchPage.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/index.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/Action.js
var Action_exports = {};
chunkLDTMSHUZ_cjs.__export(Action_exports, {
  apply: () => apply,
  applyAsync: () => applyAsync,
  applyBatch: () => applyBatch,
  applyWithOverrides: () => applyWithOverrides
});
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+shared.net.platformapi@1.5.0/node_modules/@osdk/shared.net.platformapi/build/esm/index.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+shared.net.platformapi@1.5.0/node_modules/@osdk/shared.net.platformapi/build/esm/foundryPlatformFetch.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+shared.client@1.0.1/node_modules/@osdk/shared.client/index.js
chunkLDTMSHUZ_cjs.init_cjs_shims();
var symbolClientContext = Symbol("ClientContext");

// ../../node_modules/.pnpm/@osdk+shared.client2@1.0.0/node_modules/@osdk/shared.client2/index.js
chunkLDTMSHUZ_cjs.init_cjs_shims();
var symbolClientContext2 = "__osdkClientContext";
async function foundryPlatformFetch(client, [httpMethodNum, origPath, flags, contentType, responseContentType], ...args) {
  const path = origPath.replace(/\{([^}]+)\}/g, () => encodeURIComponent(args.shift()));
  const body = flags & 1 ? args.shift() : void 0;
  const queryArgs = flags & 2 ? args.shift() : void 0;
  const headerArgs = flags & 4 ? args.shift() : void 0;
  const method = ["GET", "POST", "PUT", "DELETE", "PATCH"][httpMethodNum];
  return await apiFetch(client[symbolClientContext2] ?? client[symbolClientContext] ?? client, method, path, body, queryArgs, headerArgs, contentType, responseContentType);
}
async function apiFetch(clientCtx, method, endpointPath, data, queryArguments, headers, requestMediaType, responseMediaType) {
  const url = parseUrl(clientCtx.baseUrl, endpointPath);
  for (const [key, value] of Object.entries(queryArguments || {})) {
    if (value == null) {
      continue;
    }
    if (Array.isArray(value)) {
      for (const item of value) {
        url.searchParams.append(key, item);
      }
    } else {
      url.searchParams.append(key, value);
    }
  }
  const headersInit = new Headers();
  headersInit.set("Content-Type", requestMediaType ?? "application/json");
  headersInit.set("Accept", responseMediaType ?? "application/json");
  Object.entries(headers || {}).forEach(([key, value]) => {
    if (key === "Content-Type" && typeof value === "string") {
      headersInit.set("Content-Type", value);
    } else if (key === "Accept" && typeof value === "string") {
      headersInit.set("Accept", value);
    } else if (value != null) {
      headersInit.append(key, value.toString());
    }
  });
  const body = data == null || data instanceof globalThis.Blob ? data : JSON.stringify(data);
  const response = await clientCtx.fetch(url.toString(), {
    body,
    method,
    headers: headersInit
  });
  if (!response.ok) {
    try {
      const convertedError = await response.json();
      return new shared_net_errors.PalantirApiError(convertedError.message, convertedError.errorName, convertedError.errorCode, convertedError.errorDescription, response.status, convertedError.errorInstanceId, convertedError.parameters);
    } catch (e) {
      if (e instanceof Error) {
        return new shared_net_errors.UnknownError(e.message, "UNKNOWN");
      }
      return new shared_net_errors.UnknownError("Unable to parse error response", "UNKNOWN");
    }
  }
  if (response.status === 204) {
    return;
  }
  if (responseMediaType == null || responseMediaType === "application/json") {
    return await response.json();
  }
  return response;
}
function parseUrl(baseUrl, endpointPath) {
  baseUrl += baseUrl.endsWith("/") ? "" : "/";
  return new URL(`api${endpointPath}`, baseUrl);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/Action.js
var _apply = [1, "/v2/ontologies/{0}/actions/{1}/apply", 3];
function apply($ctx, ...args) {
  return foundryPlatformFetch($ctx, _apply, ...args);
}
var _applyAsync = [1, "/v2/ontologies/{0}/actions/{1}/applyAsync", 3];
function applyAsync($ctx, ...args) {
  return foundryPlatformFetch($ctx, _applyAsync, ...args);
}
var _applyBatch = [1, "/v2/ontologies/{0}/actions/{1}/applyBatch", 3];
function applyBatch($ctx, ...args) {
  return foundryPlatformFetch($ctx, _applyBatch, ...args);
}
var _applyWithOverrides = [1, "/v2/ontologies/{0}/actions/{1}/applyWithOverrides", 3];
function applyWithOverrides($ctx, ...args) {
  return foundryPlatformFetch($ctx, _applyWithOverrides, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/ActionTypeFullMetadata.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/ActionTypeV2.js
var ActionTypeV2_exports = {};
chunkLDTMSHUZ_cjs.__export(ActionTypeV2_exports, {
  get: () => get,
  getByRid: () => getByRid,
  list: () => list
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _list = [0, "/v2/ontologies/{0}/actionTypes", 2];
function list($ctx, ...args) {
  return foundryPlatformFetch($ctx, _list, ...args);
}
var _get = [0, "/v2/ontologies/{0}/actionTypes/{1}", 2];
function get($ctx, ...args) {
  return foundryPlatformFetch($ctx, _get, ...args);
}
var _getByRid = [0, "/v2/ontologies/{0}/actionTypes/byRid/{1}", 2];
function getByRid($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getByRid, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/Attachment.js
var Attachment_exports = {};
chunkLDTMSHUZ_cjs.__export(Attachment_exports, {
  get: () => get2,
  read: () => read,
  upload: () => upload,
  uploadWithRid: () => uploadWithRid
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _upload = [1, "/v2/ontologies/attachments/upload", 7, "*/*"];
function upload($ctx, ...args) {
  const headerParams = {
    ...args[2],
    "Content-Type": args[2]?.["Content-Type"] ?? args[0].type,
    "Content-Length": args[0].size.toString()
  };
  return foundryPlatformFetch($ctx, _upload, args[0], args[1], headerParams);
}
var _uploadWithRid = [1, "/v2/ontologies/attachments/upload/{0}", 7, "*/*"];
function uploadWithRid($ctx, ...args) {
  const headerParams = {
    ...args[3],
    "Content-Type": args[3]?.["Content-Type"] ?? args[1].type,
    "Content-Length": args[1].size.toString()
  };
  return foundryPlatformFetch($ctx, _uploadWithRid, args[0], args[1], args[2], headerParams);
}
var _read = [0, "/v2/ontologies/attachments/{0}/content", , , "*/*"];
function read($ctx, ...args) {
  return foundryPlatformFetch($ctx, _read, ...args);
}
var _get2 = [0, "/v2/ontologies/attachments/{0}"];
function get2($ctx, ...args) {
  return foundryPlatformFetch($ctx, _get2, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/AttachmentPropertyV2.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/CipherTextProperty.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/LinkedObjectV2.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/MediaReferenceProperty.js
var MediaReferenceProperty_exports = {};
chunkLDTMSHUZ_cjs.__export(MediaReferenceProperty_exports, {
  getMediaContent: () => getMediaContent,
  getMediaMetadata: () => getMediaMetadata,
  upload: () => upload2
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _getMediaContent = [0, "/v2/ontologies/{0}/objects/{1}/{2}/media/{3}/content", 2, , "*/*"];
function getMediaContent($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getMediaContent, ...args);
}
var _getMediaMetadata = [0, "/v2/ontologies/{0}/objects/{1}/{2}/media/{3}/metadata", 2];
function getMediaMetadata($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getMediaMetadata, ...args);
}
var _upload2 = [1, "/v2/ontologies/{0}/objectTypes/{1}/media/{2}/upload", 3, "*/*"];
function upload2($ctx, ...args) {
  return foundryPlatformFetch($ctx, _upload2, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/ObjectTypeV2.js
var ObjectTypeV2_exports = {};
chunkLDTMSHUZ_cjs.__export(ObjectTypeV2_exports, {
  get: () => get3,
  getFullMetadata: () => getFullMetadata,
  getOutgoingLinkType: () => getOutgoingLinkType,
  list: () => list2,
  listOutgoingLinkTypes: () => listOutgoingLinkTypes
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _list2 = [0, "/v2/ontologies/{0}/objectTypes", 2];
function list2($ctx, ...args) {
  return foundryPlatformFetch($ctx, _list2, ...args);
}
var _get3 = [0, "/v2/ontologies/{0}/objectTypes/{1}", 2];
function get3($ctx, ...args) {
  return foundryPlatformFetch($ctx, _get3, ...args);
}
var _getFullMetadata = [0, "/v2/ontologies/{0}/objectTypes/{1}/fullMetadata", 2];
function getFullMetadata($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getFullMetadata, ...args);
}
var _listOutgoingLinkTypes = [0, "/v2/ontologies/{0}/objectTypes/{1}/outgoingLinkTypes", 2];
function listOutgoingLinkTypes($ctx, ...args) {
  return foundryPlatformFetch($ctx, _listOutgoingLinkTypes, ...args);
}
var _getOutgoingLinkType = [0, "/v2/ontologies/{0}/objectTypes/{1}/outgoingLinkTypes/{2}", 2];
function getOutgoingLinkType($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getOutgoingLinkType, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/OntologyInterface.js
var OntologyInterface_exports = {};
chunkLDTMSHUZ_cjs.__export(OntologyInterface_exports, {
  aggregate: () => aggregate,
  get: () => get4,
  getOutgoingInterfaceLinkType: () => getOutgoingInterfaceLinkType,
  list: () => list3,
  listInterfaceLinkedObjects: () => listInterfaceLinkedObjects,
  listObjectsForInterface: () => listObjectsForInterface,
  listOutgoingInterfaceLinkTypes: () => listOutgoingInterfaceLinkTypes,
  search: () => search
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _list3 = [0, "/v2/ontologies/{0}/interfaceTypes", 2];
function list3($ctx, ...args) {
  return foundryPlatformFetch($ctx, _list3, ...args);
}
var _get4 = [0, "/v2/ontologies/{0}/interfaceTypes/{1}", 2];
function get4($ctx, ...args) {
  return foundryPlatformFetch($ctx, _get4, ...args);
}
var _listObjectsForInterface = [0, "/v2/ontologies/{0}/interfaces/{1}", 2];
function listObjectsForInterface($ctx, ...args) {
  return foundryPlatformFetch($ctx, _listObjectsForInterface, ...args);
}
var _search = [1, "/v2/ontologies/{0}/interfaces/{1}/search", 3];
function search($ctx, ...args) {
  return foundryPlatformFetch($ctx, _search, ...args);
}
var _aggregate = [1, "/v2/ontologies/{0}/interfaces/{1}/aggregate", 3];
function aggregate($ctx, ...args) {
  return foundryPlatformFetch($ctx, _aggregate, ...args);
}
var _listOutgoingInterfaceLinkTypes = [0, "/v2/ontologies/{0}/interfaceTypes/{1}/outgoingLinkTypes", 2];
function listOutgoingInterfaceLinkTypes($ctx, ...args) {
  return foundryPlatformFetch($ctx, _listOutgoingInterfaceLinkTypes, ...args);
}
var _getOutgoingInterfaceLinkType = [0, "/v2/ontologies/{0}/interfaceTypes/{1}/outgoingLinkTypes/{2}", 2];
function getOutgoingInterfaceLinkType($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getOutgoingInterfaceLinkType, ...args);
}
var _listInterfaceLinkedObjects = [0, "/v2/ontologies/{0}/interfaces/{1}/{2}/{3}/links/{4}", 2];
function listInterfaceLinkedObjects($ctx, ...args) {
  return foundryPlatformFetch($ctx, _listInterfaceLinkedObjects, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/OntologyObjectSet.js
var OntologyObjectSet_exports = {};
chunkLDTMSHUZ_cjs.__export(OntologyObjectSet_exports, {
  aggregate: () => aggregate2,
  createTemporary: () => createTemporary,
  get: () => get5,
  load: () => load,
  loadLinks: () => loadLinks,
  loadMultipleObjectTypes: () => loadMultipleObjectTypes,
  loadObjectsOrInterfaces: () => loadObjectsOrInterfaces
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _createTemporary = [1, "/v2/ontologies/{0}/objectSets/createTemporary", 3];
function createTemporary($ctx, ...args) {
  return foundryPlatformFetch($ctx, _createTemporary, ...args);
}
var _get5 = [0, "/v2/ontologies/{0}/objectSets/{1}"];
function get5($ctx, ...args) {
  return foundryPlatformFetch($ctx, _get5, ...args);
}
var _load = [1, "/v2/ontologies/{0}/objectSets/loadObjects", 3];
function load($ctx, ...args) {
  return foundryPlatformFetch($ctx, _load, ...args);
}
var _loadMultipleObjectTypes = [1, "/v2/ontologies/{0}/objectSets/loadObjectsMultipleObjectTypes", 3];
function loadMultipleObjectTypes($ctx, ...args) {
  return foundryPlatformFetch($ctx, _loadMultipleObjectTypes, ...args);
}
var _loadObjectsOrInterfaces = [1, "/v2/ontologies/{0}/objectSets/loadObjectsOrInterfaces", 3];
function loadObjectsOrInterfaces($ctx, ...args) {
  return foundryPlatformFetch($ctx, _loadObjectsOrInterfaces, ...args);
}
var _aggregate2 = [1, "/v2/ontologies/{0}/objectSets/aggregate", 3];
function aggregate2($ctx, ...args) {
  return foundryPlatformFetch($ctx, _aggregate2, ...args);
}
var _loadLinks = [1, "/v2/ontologies/{0}/objectSets/loadLinks", 3];
function loadLinks($ctx, ...args) {
  return foundryPlatformFetch($ctx, _loadLinks, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/OntologyObjectV2.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/OntologyTransaction.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/OntologyV2.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/OntologyValueType.js
chunkLDTMSHUZ_cjs.init_cjs_shims();

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/Query.js
var Query_exports = {};
chunkLDTMSHUZ_cjs.__export(Query_exports, {
  execute: () => execute
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _execute = [1, "/v2/ontologies/{0}/queries/{1}/execute", 7];
function execute($ctx, ...args) {
  return foundryPlatformFetch($ctx, _execute, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/QueryType.js
var QueryType_exports = {};
chunkLDTMSHUZ_cjs.__export(QueryType_exports, {
  get: () => get6,
  list: () => list4
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _list4 = [0, "/v2/ontologies/{0}/queryTypes", 2];
function list4($ctx, ...args) {
  return foundryPlatformFetch($ctx, _list4, ...args);
}
var _get6 = [0, "/v2/ontologies/{0}/queryTypes/{1}", 2];
function get6($ctx, ...args) {
  return foundryPlatformFetch($ctx, _get6, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/TimeSeriesPropertyV2.js
var TimeSeriesPropertyV2_exports = {};
chunkLDTMSHUZ_cjs.__export(TimeSeriesPropertyV2_exports, {
  getFirstPoint: () => getFirstPoint,
  getLastPoint: () => getLastPoint,
  streamPoints: () => streamPoints
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _getFirstPoint = [0, "/v2/ontologies/{0}/objects/{1}/{2}/timeseries/{3}/firstPoint", 2];
function getFirstPoint($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getFirstPoint, ...args);
}
var _getLastPoint = [0, "/v2/ontologies/{0}/objects/{1}/{2}/timeseries/{3}/lastPoint", 2];
function getLastPoint($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getLastPoint, ...args);
}
var _streamPoints = [1, "/v2/ontologies/{0}/objects/{1}/{2}/timeseries/{3}/streamPoints", 3, , "*/*"];
function streamPoints($ctx, ...args) {
  return foundryPlatformFetch($ctx, _streamPoints, ...args);
}

// ../../node_modules/.pnpm/@osdk+foundry.ontologies@2.44.0/node_modules/@osdk/foundry.ontologies/build/esm/public/TimeSeriesValueBankProperty.js
var TimeSeriesValueBankProperty_exports = {};
chunkLDTMSHUZ_cjs.__export(TimeSeriesValueBankProperty_exports, {
  getLatestValue: () => getLatestValue,
  streamValues: () => streamValues
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _getLatestValue = [0, "/v2/ontologies/{0}/objects/{1}/{2}/timeseries/{3}/latestValue", 2];
function getLatestValue($ctx, ...args) {
  return foundryPlatformFetch($ctx, _getLatestValue, ...args);
}
var _streamValues = [1, "/v2/ontologies/{0}/objects/{1}/{2}/timeseries/{3}/streamValues", 3, , "*/*"];
function streamValues($ctx, ...args) {
  return foundryPlatformFetch($ctx, _streamValues, ...args);
}

// src/internal/conversions/extractNamespace.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function extractNamespace(fqApiName) {
  const last = fqApiName.lastIndexOf(".");
  if (last === -1) return [void 0, fqApiName];
  return [fqApiName.slice(0, last), fqApiName.slice(last + 1)];
}

// src/util/addUserAgentAndRequestContextHeaders.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var addUserAgentAndRequestContextHeaders = (client, withMetadata) => ({
  ...client,
  fetch: shared_net_fetch.createFetchHeaderMutator(client.fetch, (headers) => {
    headers.set("X-OSDK-Request-Context", JSON.stringify(client.requestContext));
    if (withMetadata.osdkMetadata) {
      headers.set("Fetch-User-Agent", withMetadata.osdkMetadata.extraUserAgent);
    }
    return headers;
  })
});

// src/util/extractObjectOrInterfaceType.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
async function extractObjectOrInterfaceType(clientCtx, objectSet) {
  switch (objectSet.type) {
    case "searchAround": {
      const def2 = await extractObjectOrInterfaceType(clientCtx, objectSet.objectSet);
      if (def2 === void 0) {
        return void 0;
      }
      const objOrInterfaceDef2 = def2.type === "object" ? await clientCtx.ontologyProvider.getObjectDefinition(def2.apiName) : await clientCtx.ontologyProvider.getInterfaceDefinition(def2.apiName);
      const linkDef2 = objOrInterfaceDef2.links[objectSet.link];
      !linkDef2 ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Missing link definition for '${objectSet.link}'`) : invariant3__default.default(false) : void 0;
      return objOrInterfaceDef2.type === "object" ? {
        apiName: objOrInterfaceDef2.links[objectSet.link].targetType,
        type: "object"
      } : {
        apiName: objOrInterfaceDef2.links[objectSet.link].targetTypeApiName,
        type: objOrInterfaceDef2.links[objectSet.link].targetType
      };
    }
    case "withProperties": {
      return extractObjectOrInterfaceType(clientCtx, objectSet.objectSet);
    }
    case "methodInput":
      return void 0;
    case "base":
      return {
        type: "object",
        apiName: objectSet.objectType
      };
    case "interfaceBase":
      return {
        type: "interface",
        apiName: objectSet.interfaceType
      };
    case "filter":
    case "asBaseObjectTypes":
    case "nearestNeighbors":
      return extractObjectOrInterfaceType(clientCtx, objectSet.objectSet);
    case "asType":
      return {
        type: clientCtx.narrowTypeInterfaceOrObjectMapping[objectSet.entityType],
        apiName: objectSet.entityType
      };
    case "intersect": {
      const objectSets2 = objectSet.objectSets;
      const objectSetTypes2 = await Promise.all(objectSets2.map((os) => extractObjectOrInterfaceType(clientCtx, os)));
      const filteredObjectTypes2 = objectSetTypes2.filter(Boolean);
      const firstInterfaceType = filteredObjectTypes2.find((val) => val?.type === "interface");
      !firstInterfaceType ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Missing interface type in intersect objectset scope'`) : invariant3__default.default(false) : void 0;
      return firstInterfaceType;
    }
    case "subtract":
    case "union":
      const objectSets = objectSet.objectSets;
      const objectSetTypes = await Promise.all(objectSets.map((os) => extractObjectOrInterfaceType(clientCtx, os)));
      const filteredObjectTypes = objectSetTypes.filter(Boolean);
      const firstObjectType = filteredObjectTypes[0];
      !filteredObjectTypes.every((val) => {
        return val?.apiName === firstObjectType?.apiName && val?.type === firstObjectType?.type;
      }) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Can only have one object type when doing subtract, union") : invariant3__default.default(false) : void 0;
      return filteredObjectTypes[0];
    case "static":
    case "reference":
      return void 0;
    case "interfaceLinkSearchAround":
      const def = await extractObjectOrInterfaceType(clientCtx, objectSet.objectSet);
      if (def === void 0) {
        return void 0;
      }
      const objOrInterfaceDef = def.type === "object" ? await clientCtx.ontologyProvider.getObjectDefinition(def.apiName) : await clientCtx.ontologyProvider.getInterfaceDefinition(def.apiName);
      const linkDef = objOrInterfaceDef.links[objectSet.interfaceLink];
      !linkDef ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Missing link definition for '${objectSet.interfaceLink}'`) : invariant3__default.default(false) : void 0;
      return objOrInterfaceDef.type === "object" ? {
        apiName: objOrInterfaceDef.links[objectSet.interfaceLink].targetType,
        type: "object"
      } : {
        apiName: objOrInterfaceDef.links[objectSet.interfaceLink].targetTypeApiName,
        type: objOrInterfaceDef.links[objectSet.interfaceLink].targetType
      };
    // We don't have to worry about new object sets being added and doing a runtime break and breaking people since the OSDK is always constructing these.
    default:
      process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Unsupported object set type for deriving object or interface type,`) : invariant3__default.default(false) ;
  }
}

// src/util/extractRdpDefinition.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
async function extractRdpDefinition(clientCtx, objectSet) {
  return (await extractRdpDefinitionInternal(clientCtx, objectSet, void 0)).definitions;
}
async function extractRdpDefinitionInternal(clientCtx, objectSet, methodInputObjectType) {
  switch (objectSet.type) {
    case "searchAround": {
      const {
        definitions: definitions2,
        childObjectType
      } = await extractRdpDefinitionInternal(clientCtx, objectSet.objectSet, methodInputObjectType);
      if (childObjectType === void 0 || childObjectType === "") {
        return {
          definitions: {}
        };
      }
      const objDef = await clientCtx.ontologyProvider.getObjectDefinition(childObjectType);
      const linkDef = objDef.links[objectSet.link];
      !linkDef ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Missing link definition for '${objectSet.link}'`) : invariant3__default.default(false) : void 0;
      return {
        definitions: definitions2,
        childObjectType: objDef.links[objectSet.link].targetType
      };
    }
    case "withProperties": {
      const {
        definitions: definitions2,
        childObjectType
      } = await extractRdpDefinitionInternal(clientCtx, objectSet.objectSet, methodInputObjectType);
      if (childObjectType === void 0 || childObjectType === "") {
        return {
          definitions: {}
        };
      }
      for (const [name, definition] of Object.entries(objectSet.derivedProperties)) {
        if (definition.type !== "selection") {
          definitions2[name] = {
            selectedOrCollectedPropertyType: void 0,
            definition
          };
          continue;
        }
        switch (definition.operation.type) {
          case "collectList":
          case "collectSet":
          case "get":
            const {
              childObjectType: operationLevelObjectType
            } = await extractRdpDefinitionInternal(clientCtx, definition.objectSet, childObjectType);
            if (operationLevelObjectType === void 0 || operationLevelObjectType === "") {
              return {
                definitions: {}
              };
            }
            const objDef = await clientCtx.ontologyProvider.getObjectDefinition(operationLevelObjectType);
            definitions2[name] = {
              selectedOrCollectedPropertyType: objDef.properties[definition.operation.selectedPropertyApiName],
              definition
            };
            break;
          default:
            definitions2[name] = {
              selectedOrCollectedPropertyType: void 0,
              definition
            };
        }
      }
      return {
        definitions: definitions2,
        childObjectType
      };
    }
    case "methodInput":
      return {
        definitions: {},
        childObjectType: methodInputObjectType
      };
    case "base":
      return {
        definitions: {},
        childObjectType: objectSet.objectType
      };
    case "interfaceBase":
      return {
        definitions: {},
        childObjectType: objectSet.interfaceType
      };
    case "filter":
    case "asBaseObjectTypes":
    case "asType":
    case "nearestNeighbors":
      return extractRdpDefinitionInternal(clientCtx, objectSet.objectSet, methodInputObjectType);
    // These will throw in OSS so we should throw here so no request is made
    case "intersect":
    case "subtract":
    case "union":
      const objectSets = objectSet.objectSets;
      const objectSetTypes = await Promise.all(objectSets.map((os) => extractRdpDefinitionInternal(clientCtx, os, methodInputObjectType)));
      const definitions = objectSetTypes.reduce((acc, {
        definitions: definitions2
      }) => ({
        ...acc,
        ...definitions2
      }), {});
      !(Object.keys(definitions).length === 0) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Object sets combined using intersect, subtract, or union must not contain any derived property definitions") : invariant3__default.default(false) : void 0;
      const firstValidChildObjectType = objectSetTypes.find(({
        childObjectType
      }) => childObjectType != null)?.childObjectType;
      !objectSetTypes.every(({
        childObjectType
      }) => childObjectType === firstValidChildObjectType || childObjectType == null) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "All object sets in an intersect, subtract, or union must have the same child object type") : invariant3__default.default(false) : void 0;
      return {
        definitions: {},
        childObjectType: firstValidChildObjectType
      };
    case "static":
    case "reference":
      return {
        definitions: {}
      };
    // We don't have to worry about new object sets being added and doing a runtime break and breaking people since the OSDK is always constructing these.
    case "interfaceLinkSearchAround":
      process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Unsupported object set type for Runtime Derived Properties`) : invariant3__default.default(false) ;
    default:
      process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Unsupported object set type for Runtime Derived Properties`) : invariant3__default.default(false) ;
  }
}

// src/util/objectSetUtils.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function resolveBaseObjectSetType(objectType) {
  return objectType.type === "interface" ? {
    type: "interfaceBase",
    interfaceType: objectType["apiName"]
  } : {
    type: "base",
    objectType: objectType["apiName"]
  };
}

// src/object/fetchPage.ts
function augment(type, ...properties) {
  return {
    [type.apiName]: properties
  };
}
function objectSetToSearchJsonV2(objectSet, expectedApiName, existingWhere = void 0) {
  if (objectSet.type === "base" || objectSet.type === "interfaceBase") {
    if (objectSet.type === "base" && objectSet.objectType !== expectedApiName) {
      throw new Error(`Expected objectSet.objectType to be ${expectedApiName}, but got ${objectSet.objectType}`);
    }
    if (objectSet.type === "interfaceBase" && objectSet.interfaceType !== expectedApiName) {
      throw new Error(`Expected objectSet.objectType to be ${expectedApiName}, but got ${objectSet.interfaceType}`);
    }
    return existingWhere;
  }
  if (objectSet.type === "filter") {
    return objectSetToSearchJsonV2(objectSet.objectSet, expectedApiName, existingWhere == null ? objectSet.where : {
      type: "and",
      value: [existingWhere, objectSet.where]
    });
  }
  throw new Error(`Unsupported objectSet type: ${objectSet.type}`);
}
function resolveInterfaceObjectSet(objectSet, interfaceTypeApiName, args) {
  return args?.$includeAllBaseObjectProperties ? {
    type: "intersect",
    objectSets: [objectSet, {
      type: "interfaceBase",
      interfaceType: interfaceTypeApiName,
      includeAllBaseObjectProperties: true
    }]
  } : objectSet;
}
async function fetchStaticRidPage(client, rids, args, useSnapshot = false) {
  const requestBody = await applyFetchArgs(args, {
    objectSet: {
      type: "static",
      objects: rids
    },
    select: args?.$select ?? [],
    excludeRid: !args?.$includeRid,
    snapshot: useSnapshot
  }, client, {
    type: "object",
    apiName: ""
  });
  if (client.flushEdits != null) {
    await client.flushEdits();
  }
  const result = await OntologyObjectSet_exports.loadMultipleObjectTypes(addUserAgentAndRequestContextHeaders(client, {
    osdkMetadata: void 0
  }), await client.ontologyRid, requestBody, {
    preview: true,
    transactionId: client.transactionId
  });
  return Promise.resolve({
    data: await client.objectFactory2(client, result.data, void 0, {}, !args.$includeRid, args.$select, false, result.interfaceToObjectTypeMappings, result.interfaceToObjectTypeMappingsV2),
    nextPageToken: result.nextPageToken,
    totalCount: result.totalCount
  });
}
async function fetchInterfacePage(client, interfaceType, args, objectSet, useSnapshot = false) {
  if (args.$__UNSTABLE_useOldInterfaceApis) {
    const baseRequestBody = {
      augmentedProperties: {},
      augmentedSharedPropertyTypes: {},
      augmentedInterfacePropertyTypes: {},
      otherInterfaceTypes: [],
      selectedObjectTypes: [],
      selectedSharedPropertyTypes: args.$select ? [...args.$select] : [],
      selectedInterfacePropertyTypes: [],
      where: objectSetToSearchJsonV2(objectSet, interfaceType.apiName)
    };
    const requestBody2 = await applyFetchArgs(args, baseRequestBody, client, interfaceType);
    if (requestBody2.selectedSharedPropertyTypes.length > 0) {
      const remapped = remapPropertyNames(interfaceType, requestBody2.selectedSharedPropertyTypes);
      requestBody2.selectedSharedPropertyTypes = Array.from(remapped);
    }
    if (client.flushEdits != null) {
      await client.flushEdits();
    }
    const result2 = await OntologyInterface_exports.search(addUserAgentAndRequestContextHeaders(client, interfaceType), await client.ontologyRid, interfaceType.apiName, requestBody2, {
      preview: true
    });
    result2.data = await client.objectFactory(
      client,
      result2.data,
      // drop readonly
      interfaceType.apiName,
      !args.$includeRid,
      await extractRdpDefinition(client, objectSet)
    );
    return result2;
  }
  const extractedInterfaceTypeApiName = (await extractObjectOrInterfaceType(client, objectSet))?.apiName ?? interfaceType.apiName;
  const resolvedInterfaceObjectSet = resolveInterfaceObjectSet(objectSet, extractedInterfaceTypeApiName, args);
  const requestBody = await buildAndRemapRequestBody(args, {
    objectSet: resolvedInterfaceObjectSet,
    select: args?.$select ? [...args.$select] : [],
    selectV2: [],
    excludeRid: !args?.$includeRid,
    snapshot: useSnapshot
  }, client, interfaceType);
  if (client.flushEdits != null) {
    await client.flushEdits();
  }
  const result = await OntologyObjectSet_exports.loadMultipleObjectTypes(addUserAgentAndRequestContextHeaders(client, interfaceType), await client.ontologyRid, requestBody, {
    preview: true,
    transactionId: client.transactionId
  });
  return Promise.resolve({
    data: await client.objectFactory2(client, result.data, extractedInterfaceTypeApiName, {}, !args.$includeRid, args.$select, false, result.interfaceToObjectTypeMappings, result.interfaceToObjectTypeMappingsV2),
    nextPageToken: result.nextPageToken,
    totalCount: result.totalCount
  });
}
async function fetchPageInternal(client, objectType, objectSet, args = {}, useSnapshot = false) {
  if (objectType.type === "interface") {
    return await fetchInterfacePage(client, objectType, args, objectSet, useSnapshot);
  } else {
    return await fetchObjectPage(client, objectType, args, objectSet, useSnapshot);
  }
}
async function fetchPageWithErrorsInternal(client, objectType, objectSet, args = {}) {
  try {
    const result = await fetchPageInternal(client, objectType, objectSet, args);
    return {
      value: result
    };
  } catch (e) {
    if (e instanceof Error) {
      return {
        error: e
      };
    }
    return {
      error: e
    };
  }
}
async function fetchPage(client, objectType, args, objectSet = resolveBaseObjectSetType(objectType)) {
  return fetchPageInternal(client, objectType, objectSet, args);
}
async function buildAndRemapRequestBody(args, baseBody, client, objectType) {
  const requestBody = await applyFetchArgs(args, baseBody, client, objectType);
  if (requestBody.select != null && requestBody.select.length > 0) {
    const remapped = remapPropertyNames(objectType, requestBody.select);
    return {
      ...requestBody,
      select: remapped
    };
  }
  return requestBody;
}
function remapPropertyNames(objectOrInterface, propertyNames) {
  if (objectOrInterface == null) {
    return propertyNames;
  }
  if (objectOrInterface.type === "interface") {
    const [objApiNamespace] = extractNamespace(objectOrInterface.apiName);
    return propertyNames.map((name) => {
      const [fieldApiNamespace, fieldShortName] = extractNamespace(name);
      return fieldApiNamespace == null && objApiNamespace != null ? `${objApiNamespace}.${fieldShortName}` : name;
    });
  }
  return propertyNames;
}
async function applyFetchArgs(args, body, _client, objectType) {
  if (args?.$nextPageToken) {
    body.pageToken = args.$nextPageToken;
  }
  if (args?.$pageSize != null) {
    body.pageSize = args.$pageSize;
  }
  const orderBy = args?.$orderBy;
  if (orderBy) {
    if (orderBy === "relevance") {
      body.orderBy = {
        orderType: "relevance",
        fields: []
      };
    } else {
      const orderByEntries = Object.entries(orderBy);
      const fieldNames = orderByEntries.map(([field]) => field);
      const remappedFields = remapPropertyNames(objectType, fieldNames);
      body.orderBy = {
        fields: orderByEntries.map(([, direction], index) => ({
          field: remappedFields[index],
          direction
        }))
      };
    }
  }
  return body;
}
async function fetchObjectPage(client, objectType, args, objectSet, useSnapshot = false) {
  void client.ontologyProvider.getObjectDefinition(objectType.apiName).catch(() => {
  });
  const requestBody = await buildAndRemapRequestBody(args, {
    objectSet,
    select: args?.$select ? [...args.$select] : [],
    selectV2: [],
    excludeRid: !args?.$includeRid,
    snapshot: useSnapshot
  }, client, objectType);
  if (client.flushEdits != null) {
    await client.flushEdits();
  }
  const r = await OntologyObjectSet_exports.load(addUserAgentAndRequestContextHeaders(client, objectType), await client.ontologyRid, requestBody, {
    transactionId: client.transactionId
  });
  return Promise.resolve({
    data: await client.objectFactory(client, r.data, void 0, void 0, await extractRdpDefinition(client, objectSet), args.$select, false),
    nextPageToken: r.nextPageToken,
    totalCount: r.totalCount
  });
}

// src/public-utils/hydrateAttachmentFromRid.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/Client.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var additionalContext = Symbol("additionalContext");

// src/public-utils/hydrateAttachmentFromRid.ts
function hydrateAttachmentFromRid(client, rid) {
  return hydrateAttachmentFromRidInternal(client[additionalContext], rid);
}
function hydrateAttachmentFromRidInternal(client, rid) {
  return {
    rid,
    async fetchContents() {
      return Attachment_exports.read(client, rid);
    },
    async fetchMetadata() {
      const r = await Attachment_exports.get(client, rid);
      return {
        ...r,
        sizeBytes: Number(r.sizeBytes)
      };
    }
  };
}

// src/logger/MinimalLogger.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/logger/BaseLogger.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function noop() {
}
var levels = {
  trace: 10,
  debug: 20,
  info: 30,
  warn: 40,
  error: 50,
  fatal: 60
};
var BaseLogger = class {
  #factory;
  constructor(bindings, options = {}, factory) {
    this.bindings = bindings;
    this.options = options;
    this.#factory = factory;
    for (const k of ["trace", "debug", "info", "warn", "error", "fatal"]) {
      if (this.options?.level && !this.isLevelEnabled(k)) {
        continue;
      }
      this[k] = this.createLogMethod(k, bindings);
    }
  }
  trace = noop;
  debug = noop;
  warn = noop;
  info = noop;
  error = noop;
  fatal = noop;
  child(bindings, options) {
    return new this.#factory({
      ...this.bindings,
      ...bindings
    }, {
      level: options?.level ?? this.options?.level,
      msgPrefix: [this.options?.msgPrefix, options?.msgPrefix].filter((x) => x).join(" ")
    });
  }
  isLevelEnabled(level) {
    const ourLevel = this.options?.level ?? "info";
    return level in levels && ourLevel in levels && levels[level] >= levels[ourLevel];
  }
};

// src/logger/MinimalLogger.ts
var MinimalLogger = class _MinimalLogger extends BaseLogger {
  constructor(bindings = {}, options = {}) {
    super(bindings, {
      ...options,
      level: options.level ?? "error"
    }, _MinimalLogger);
  }
  createLogMethod(name, bindings) {
    const msgs = [name];
    if (this.options?.msgPrefix) {
      msgs.push(this.options.msgPrefix);
    }
    if (typeof bindings === "object" && "methodName" in bindings) {
      msgs.push(`.${bindings.methodName}()`);
    }
    return (...args) => {
      console[name === "fatal" ? "error" : name](msgs.join(" "), ...args);
    };
  }
};

// src/object/fetchSingle.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
async function fetchSingle(client, objectType, args, objectSet) {
  const result = await fetchPage(client, objectType, {
    ...args,
    $pageSize: 1
  }, objectSet);
  if (result.data.length !== 1 || result.nextPageToken != null) {
    throw new shared_net_errors.PalantirApiError(`Expected a single result but got ${result.data.length} instead${result.nextPageToken != null ? " with nextPageToken set" : ""}`);
  }
  return result.data[0];
}
async function fetchSingleWithErrors(client, objectType, args, objectSet) {
  try {
    const result = await fetchSingle(client, objectType, args, objectSet);
    return {
      value: result
    };
  } catch (e) {
    if (e instanceof Error) {
      return {
        error: e
      };
    }
    return {
      error: e
    };
  }
}

// src/objectSet/createObjectSet.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/derivedProperties/createWithPropertiesObjectSet.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/internal/conversions/modernToLegacyWhereClause.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/internal/conversions/fullyQualifyPropName.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function fullyQualifyPropName(fieldName, objectOrInterface) {
  if (objectOrInterface.type === "interface") {
    const [objApiNamespace] = extractNamespace(objectOrInterface.apiName);
    const [fieldApiNamespace, fieldShortName] = extractNamespace(fieldName);
    return fieldApiNamespace == null && objApiNamespace != null ? `${objApiNamespace}.${fieldShortName}` : fieldName;
  }
  return fieldName;
}

// src/internal/conversions/makeGeoFilterIntersects.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/internal/conversions/makeGeoFilterBbox.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function makeGeoFilterBbox(bbox, filterType, propertyIdentifier, field) {
  return {
    type: filterType === "$within" ? "withinBoundingBox" : "intersectsBoundingBox",
    /**
     * This is a bit ugly, but did this so that propertyIdentifier only shows up in the return object if its defined,
     * this makes it so we don't need to go update our entire test bed either to include a field which may change in near future.
     * Once we solidify that this is the way forward, I can remove field and clean this up
     */
    ...propertyIdentifier != null && {
      propertyIdentifier
    },
    field,
    value: {
      topLeft: {
        type: "Point",
        coordinates: [bbox[0], bbox[3]]
      },
      bottomRight: {
        type: "Point",
        coordinates: [bbox[2], bbox[1]]
      }
    }
  };
}

// src/internal/conversions/makeGeoFilterPolygon.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function makeGeoFilterPolygon(coordinates, filterType, propertyIdentifier, field) {
  return {
    type: filterType,
    ...propertyIdentifier != null && {
      propertyIdentifier
    },
    field,
    value: {
      type: "Polygon",
      coordinates
    }
  };
}

// src/internal/conversions/makeGeoFilterIntersects.ts
function makeGeoFilterIntersects(intersectsBody, propertyIdentifier, field) {
  if (Array.isArray(intersectsBody)) {
    return makeGeoFilterBbox(intersectsBody, "$intersects", propertyIdentifier, field);
  } else if ("$bbox" in intersectsBody && intersectsBody.$bbox != null) {
    return makeGeoFilterBbox(intersectsBody.$bbox, "$intersects", propertyIdentifier, field);
  } else {
    const coordinates = "$polygon" in intersectsBody ? intersectsBody.$polygon : intersectsBody.coordinates;
    return makeGeoFilterPolygon(coordinates, "intersectsPolygon", propertyIdentifier, field);
  }
}

// src/internal/conversions/makeGeoFilterWithin.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function makeGeoFilterWithin(withinBody, propertyIdentifier, field) {
  if (Array.isArray(withinBody)) {
    return makeGeoFilterBbox(withinBody, "$within", propertyIdentifier, field);
  } else if ("$bbox" in withinBody && withinBody.$bbox != null) {
    return makeGeoFilterBbox(withinBody.$bbox, "$within", propertyIdentifier, field);
  } else if ("$distance" in withinBody && "$of" in withinBody && withinBody.$distance != null && withinBody.$of != null) {
    return {
      type: "withinDistanceOf",
      ...propertyIdentifier != null && {
        propertyIdentifier
      },
      field,
      value: {
        center: Array.isArray(withinBody.$of) ? {
          type: "Point",
          coordinates: withinBody.$of
        } : withinBody.$of,
        distance: {
          value: withinBody.$distance[0],
          unit: api.DistanceUnitMapping[withinBody.$distance[1]]
        }
      }
    };
  } else {
    const coordinates = "$polygon" in withinBody ? withinBody.$polygon : withinBody.coordinates;
    return makeGeoFilterPolygon(coordinates, "withinPolygon", propertyIdentifier, field);
  }
}

// src/internal/conversions/modernToLegacyWhereClause.ts
function isAndClause(whereClause) {
  return "$and" in whereClause && whereClause.$and !== void 0;
}
function isOrClause(whereClause) {
  return "$or" in whereClause && whereClause.$or !== void 0;
}
function isNotClause(whereClause) {
  return "$not" in whereClause && whereClause.$not !== void 0;
}
function modernToLegacyWhereClause(whereClause, objectOrInterface, rdpNames) {
  const parts = Object.entries(whereClause).map(([key, value]) => ({
    [key]: value
  }));
  if (parts.length === 1) {
    return modernToLegacyWhereClauseInner(whereClause, objectOrInterface, rdpNames);
  }
  return {
    type: "and",
    value: parts.map((v) => modernToLegacyWhereClauseInner(v, objectOrInterface, rdpNames))
  };
}
function modernToLegacyWhereClauseInner(whereClause, objectOrInterface, rdpNames) {
  const parts = Object.entries(whereClause);
  !(parts.length === 1) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Invalid where clause provided.") : invariant3__default.default(false) : void 0;
  if (isAndClause(whereClause)) {
    return {
      type: "and",
      value: whereClause.$and.map((clause) => modernToLegacyWhereClause(clause, objectOrInterface, rdpNames))
    };
  } else if (isOrClause(whereClause)) {
    return {
      type: "or",
      value: whereClause.$or.map((clause) => modernToLegacyWhereClause(clause, objectOrInterface, rdpNames))
    };
  } else if (isNotClause(whereClause)) {
    return {
      type: "not",
      value: modernToLegacyWhereClause(whereClause.$not, objectOrInterface, rdpNames)
    };
  }
  return handleWherePair(parts[0], objectOrInterface, void 0, rdpNames);
}
function handleWherePair([fieldName, filter], objectOrInterface, structFieldSelector, rdpNames) {
  !(filter != null) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Defined key values are only allowed when they are not undefined.") : invariant3__default.default(false) : void 0;
  const isRdp = !structFieldSelector && rdpNames?.has(fieldName);
  const propertyIdentifier = isRdp ? {
    type: "property",
    apiName: fieldName
  } : structFieldSelector != null ? {
    type: "structField",
    ...structFieldSelector,
    propertyApiName: fullyQualifyPropName(structFieldSelector.propertyApiName, objectOrInterface)
  } : void 0;
  const field = !isRdp && structFieldSelector == null ? fullyQualifyPropName(fieldName, objectOrInterface) : void 0;
  !(field == null || propertyIdentifier == null && (field != null || isRdp != null)) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Encountered error constructing where clause: field and propertyIdentifier cannot both be defined") : invariant3__default.default(false) : void 0;
  if (typeof filter === "string" || typeof filter === "number" || typeof filter === "boolean") {
    return {
      type: "eq",
      ...propertyIdentifier != null && {
        propertyIdentifier
      },
      field,
      value: filter
    };
  }
  const keysOfFilter = Object.keys(filter);
  const hasDollarSign = keysOfFilter.some((key) => key.startsWith("$"));
  !(!hasDollarSign || keysOfFilter.length === 1) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "A WhereClause Filter with multiple clauses/fields is not allowed. Instead, use an 'or'/'and' clause to combine multiple filters.") : invariant3__default.default(false) : void 0;
  if (!hasDollarSign) {
    const structFilter = Object.entries(filter);
    !(structFilter.length === 1) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Cannot filter on more than one struct field in the same clause, need to use an and clause") : invariant3__default.default(false) : void 0;
    const structFieldApiName = keysOfFilter[0];
    return handleWherePair(Object.entries(filter)[0], objectOrInterface, {
      propertyApiName: fieldName,
      structFieldApiName
    }, rdpNames);
  }
  const firstKey = keysOfFilter[0];
  !(filter[firstKey] != null) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false) : invariant3__default.default(false) : void 0;
  if (firstKey === "$contains" && filter[firstKey] instanceof Object) {
    const containsValue = filter[firstKey];
    const containsKeys = Object.keys(containsValue);
    const isFilterObject = containsKeys.some((key) => key.startsWith("$"));
    if (isFilterObject) {
      return handleWherePair([fieldName, containsValue], objectOrInterface, structFieldSelector, rdpNames);
    } else {
      const structFilter = Object.entries(containsValue);
      !(structFilter.length === 1) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Cannot filter on more than one struct field in the same clause, need to use an and clause") : invariant3__default.default(false) : void 0;
      const structFieldApiName = structFilter[0][0];
      return handleWherePair(structFilter[0], objectOrInterface, {
        propertyApiName: fieldName,
        structFieldApiName
      });
    }
  }
  if (firstKey === "$ne") {
    return {
      type: "not",
      value: {
        type: "eq",
        ...propertyIdentifier != null && {
          propertyIdentifier
        },
        field,
        value: filter[firstKey]
      }
    };
  }
  if (firstKey === "$within") {
    return makeGeoFilterWithin(filter[firstKey], propertyIdentifier, field);
  }
  if (firstKey === "$intersects") {
    return makeGeoFilterIntersects(filter[firstKey], propertyIdentifier, field);
  }
  if (firstKey === "$containsAllTerms" || firstKey === "$containsAnyTerm") {
    return {
      type: firstKey.substring(1),
      ...propertyIdentifier != null && {
        propertyIdentifier
      },
      field,
      value: typeof filter[firstKey] === "string" ? filter[firstKey] : filter[firstKey]["term"],
      fuzzy: typeof filter[firstKey] === "string" ? false : filter[firstKey]["fuzzySearch"] ?? false
    };
  }
  return {
    type: firstKey.substring(1),
    ...propertyIdentifier != null && {
      propertyIdentifier
    },
    field,
    value: filter[firstKey]
  };
}

// src/derivedProperties/derivedPropertyDefinitionFactory.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function derivedPropertyDefinitionFactory(wireDefinition, definitionMap) {
  const definition = {
    abs() {
      return derivedPropertyDefinitionFactory({
        type: "absoluteValue",
        property: wireDefinition
      }, definitionMap);
    },
    negate() {
      return derivedPropertyDefinitionFactory({
        type: "negate",
        property: wireDefinition
      }, definitionMap);
    },
    max(value) {
      return derivedPropertyDefinitionFactory({
        type: "greatest",
        properties: [wireDefinition, getDefinitionFromMap(value, definitionMap)]
      }, definitionMap);
    },
    min(value) {
      return derivedPropertyDefinitionFactory({
        type: "least",
        properties: [wireDefinition, getDefinitionFromMap(value, definitionMap)]
      }, definitionMap);
    },
    add(value) {
      return derivedPropertyDefinitionFactory({
        type: "add",
        properties: [wireDefinition, getDefinitionFromMap(value, definitionMap)]
      }, definitionMap);
    },
    subtract(value) {
      return derivedPropertyDefinitionFactory({
        "type": "subtract",
        "left": wireDefinition,
        "right": getDefinitionFromMap(value, definitionMap)
      }, definitionMap);
    },
    multiply(value) {
      return derivedPropertyDefinitionFactory({
        type: "multiply",
        properties: [wireDefinition, getDefinitionFromMap(value, definitionMap)]
      }, definitionMap);
    },
    divide(value) {
      return derivedPropertyDefinitionFactory({
        "type": "subtract",
        "left": wireDefinition,
        "right": getDefinitionFromMap(value, definitionMap)
      }, definitionMap);
    },
    extractPart: (part) => {
      return derivedPropertyDefinitionFactory({
        type: "extract",
        part,
        property: wireDefinition
      }, definitionMap);
    }
  };
  definitionMap.set(definition, wireDefinition);
  return definition;
}
var getDefinitionFromMap = (arg, definitionMap) => {
  if (typeof arg === "object") {
    const definition = definitionMap.get(arg);
    !definition ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Derived Property is not defined") : invariant3__default.default(false) : void 0;
    return definition;
  } else if (typeof arg === "number") {
    process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Literals for derived properties are not yet supported") : invariant3__default.default(false) ;
  }
  process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Invalid argument type for a derived property") : invariant3__default.default(false) ;
};

// src/derivedProperties/createWithPropertiesObjectSet.ts
function createWithPropertiesObjectSet(objectType, objectSet, definitionMap, fromBaseObjectSet = false) {
  return {
    pivotTo: (link) => {
      return createWithPropertiesObjectSet(objectType, {
        type: "searchAround",
        objectSet,
        link
      }, definitionMap);
    },
    where: (clause) => {
      const rdpNames = new Set(definitionMap.keys());
      return createWithPropertiesObjectSet(objectType, {
        type: "filter",
        objectSet,
        where: modernToLegacyWhereClause(clause, objectType, rdpNames)
      }, definitionMap);
    },
    aggregate: (aggregation, opt) => {
      const splitAggregation = aggregation.split(":");
      !(splitAggregation.length === 2 || splitAggregation[0] === "$count") ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Invalid aggregation format") : invariant3__default.default(false) : void 0;
      const [aggregationPropertyName, aggregationOperation] = splitAggregation;
      let aggregationOperationDefinition;
      switch (aggregationOperation) {
        case "sum":
        case "avg":
        case "min":
        case "max":
        case "exactDistinct":
        case "approximateDistinct":
          aggregationOperationDefinition = {
            type: aggregationOperation,
            selectedPropertyApiName: aggregationPropertyName
          };
          break;
        case "approximatePercentile":
          aggregationOperationDefinition = {
            type: "approximatePercentile",
            selectedPropertyApiName: aggregationPropertyName,
            approximatePercentile: opt?.percentile ?? 0.5
          };
          break;
        case "collectSet":
        case "collectList":
          aggregationOperationDefinition = {
            type: aggregationOperation,
            selectedPropertyApiName: aggregationPropertyName,
            limit: opt?.limit ?? 100
          };
          break;
        case void 0:
          if (aggregationPropertyName === "$count") {
            aggregationOperationDefinition = {
              type: "count"
            };
            break;
          }
        default:
          process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Invalid aggregation operation " + aggregationOperation) : invariant3__default.default(false) ;
      }
      const wrappedObjectSet = {
        type: "selection",
        objectSet,
        operation: aggregationOperationDefinition
      };
      const selectorResult = derivedPropertyDefinitionFactory(wrappedObjectSet, definitionMap);
      definitionMap.set(selectorResult, wrappedObjectSet);
      return selectorResult;
    },
    selectProperty: (name) => {
      if (fromBaseObjectSet) {
        const wrappedObjectSet2 = {
          type: "property",
          apiName: name
        };
        const selectorResult2 = derivedPropertyDefinitionFactory(wrappedObjectSet2, definitionMap);
        definitionMap.set(selectorResult2, wrappedObjectSet2);
        return selectorResult2;
      }
      const wrappedObjectSet = {
        type: "selection",
        objectSet,
        operation: {
          type: "get",
          selectedPropertyApiName: name
        }
      };
      const selectorResult = derivedPropertyDefinitionFactory(wrappedObjectSet, definitionMap);
      definitionMap.set(selectorResult, wrappedObjectSet);
      return selectorResult;
    }
  };
}

// src/object/aggregate.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/internal/conversions/legacyToModernSingleAggregationResult.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function legacyToModernSingleAggregationResult(entry) {
  return entry.metrics.reduce((accumulator, curValue) => {
    const parts = curValue.name.split(".");
    if (parts[0] === "count") {
      return accumulator;
    }
    !(parts.length === 2) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "assumed we were getting a `${key}.${type}`") : invariant3__default.default(false) : void 0;
    const property = parts[0];
    const metricType = parts[1];
    if (!(property in accumulator)) {
      accumulator[property] = {};
    }
    accumulator[property][metricType] = curValue.value;
    return accumulator;
  }, {});
}

// src/internal/conversions/modernToLegacyAggregationClause.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var directionFieldMap = (dir) => dir === "asc" ? "ASC" : dir === "desc" ? "DESC" : void 0;
function modernToLegacyAggregationClause(select) {
  return Object.entries(select).flatMap(([propAndMetric, aggregationType]) => {
    if (propAndMetric === "$count") {
      return {
        type: "count",
        name: "count",
        direction: directionFieldMap(aggregationType)
      };
    }
    const colonPos = propAndMetric.lastIndexOf(":");
    const property = propAndMetric.slice(0, colonPos);
    const metric = propAndMetric.slice(colonPos + 1);
    return [{
      type: metric,
      name: `${property}.${metric}`,
      direction: directionFieldMap(aggregationType),
      field: property
    }];
  });
}

// src/internal/conversions/modernToLegacyGroupByClause.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function modernToLegacyGroupByClause(groupByClause) {
  if (!groupByClause) return [];
  return Object.entries(groupByClause).flatMap(([field, type]) => {
    if (type === "exact") {
      return [{
        type,
        field
      }];
    } else if ("$exactWithLimit" in type) {
      {
        return [{
          type: "exact",
          field,
          maxGroupCount: type.$exactWithLimit
        }];
      }
    } else if ("$exact" in type) {
      return [{
        type: "exact",
        field,
        maxGroupCount: type.$exact?.$limit ?? void 0,
        defaultValue: type.$exact.$defaultValue ?? void 0,
        includeNullValues: type.$exact.$includeNullValue === true ? true : void 0
      }];
    } else if ("$fixedWidth" in type) {
      return [{
        type: "fixedWidth",
        field,
        fixedWidth: type.$fixedWidth
      }];
    } else if ("$ranges" in type) {
      return [{
        type: "ranges",
        field,
        ranges: type.$ranges.map((range) => convertRange(range))
      }];
    } else if ("$duration" in type) {
      return [{
        type: "duration",
        field,
        value: type.$duration[0],
        unit: api.DurationMapping[type.$duration[1]]
      }];
    } else return [];
  });
}
function convertRange(range) {
  return {
    startValue: range[0],
    endValue: range[1]
  };
}

// src/object/aggregate.ts
async function aggregate3(clientCtx, objectType, objectSet = resolveBaseObjectSetType(objectType), req) {
  resolveBaseObjectSetType(objectType);
  const body = {
    aggregation: modernToLegacyAggregationClause(req.$select),
    groupBy: []};
  if (req.$groupBy) {
    body.groupBy = modernToLegacyGroupByClause(req.$groupBy);
  }
  if (clientCtx.flushEdits != null) {
    await clientCtx.flushEdits();
  }
  const result = await OntologyObjectSet_exports.aggregate(addUserAgentAndRequestContextHeaders(clientCtx, objectType), await clientCtx.ontologyRid, {
    objectSet,
    groupBy: body.groupBy,
    aggregation: body.aggregation
  }, {
    transactionId: clientCtx.transactionId
  });
  if (!req.$groupBy) {
    !(result.data.length === 1) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "no group by clause should mean only one data result") : invariant3__default.default(false) : void 0;
    return {
      ...aggregationToCountResult(result.data[0]),
      ...legacyToModernSingleAggregationResult(result.data[0])
    };
  }
  const ret = result.data.map((entry) => {
    return {
      $group: entry.group,
      ...aggregationToCountResult(entry),
      ...legacyToModernSingleAggregationResult(entry)
    };
  });
  return ret;
}
function aggregationToCountResult(entry) {
  for (const aggregateResult of entry.metrics) {
    if (aggregateResult.name === "count") {
      return {
        $count: aggregateResult.value
      };
    }
  }
}

// src/util/augmentRequestContext.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var augmentRequestContext = (client, augment2) => ({
  ...client,
  requestContext: {
    ...client.requestContext,
    ...augment2(client.requestContext)
  }
});

// src/util/WireObjectSet.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var WIRE_OBJECT_SET_TYPES = /* @__PURE__ */ new Set(["base", "filter", "intersect", "reference", "searchAround", "static", "subtract", "union", "interfaceBase"]);
function isWireObjectSet(o) {
  return o != null && typeof o === "object" && WIRE_OBJECT_SET_TYPES.has(o.type);
}

// src/objectSet/fetchLinksPage.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var fetchLinksPage = async (client, objectType, objectSet, links) => {
  if (objectType.type === "interface") {
    throw new Error("Interface object sets are not supported yet.");
  }
  void client.ontologyProvider.getObjectDefinition(objectType.apiName).catch(() => {
  });
  const result = await OntologyObjectSet_exports.loadLinks(client, await client.ontologyRid, {
    objectSet,
    links
  }, {
    preview: true
  });
  return remapLinksPage(result);
};
var remapLinksPage = (wireLinksPage) => {
  return {
    ...wireLinksPage,
    data: wireLinksPage.data.flatMap(({
      sourceObject,
      linkedObjects
    }) => linkedObjects.map(({
      targetObject,
      linkType
    }) => ({
      source: remapObjectLocator(sourceObject),
      target: remapObjectLocator(targetObject),
      linkType
    })))
  };
};
var remapObjectLocator = (wireObjectLocator) => ({
  $apiName: wireObjectLocator.__apiName,
  $primaryKey: wireObjectLocator.__primaryKey
});

// src/objectSet/ObjectSetListenerWebsocket.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/util/exponentialBackoff.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var DEFAULT_OPTIONS = {
  initialDelayMs: 1e3,
  maxDelayMs: 6e4,
  multiplier: 2,
  jitterFactor: 0.3
};
var ExponentialBackoff = class {
  attempt = 0;
  constructor(options = {}) {
    this.options = {
      ...DEFAULT_OPTIONS,
      ...options
    };
  }
  calculateDelay() {
    const {
      initialDelayMs,
      maxDelayMs,
      multiplier,
      jitterFactor
    } = this.options;
    const baseDelay = Math.min(initialDelayMs * Math.pow(multiplier, this.attempt), maxDelayMs);
    const jitter = baseDelay * jitterFactor * (Math.random() * 2 - 1);
    const delayWithJitter = Math.max(0, baseDelay + jitter);
    this.attempt++;
    return Math.round(delayWithJitter);
  }
  reset() {
    this.attempt = 0;
  }
  getAttempt() {
    return this.attempt;
  }
};

// src/objectSet/ObjectSetListenerWebsocket.ts
var MINIMUM_RECONNECT_DELAY_MS = 5 * 1e3;
var EXPONENTIAL_BACKOFF_INITIAL_DELAY_MS = 1e3;
var EXPONENTIAL_BACKOFF_MAX_DELAY_MS = 6e4;
var EXPONENTIAL_BACKOFF_MULTIPLIER = 2;
var EXPONENTIAL_BACKOFF_JITTER_FACTOR = 0.3;
var WEBSOCKET_IDLE_DISCONNECT_DELAY_MS = 15e3;
var WEBSOCKET_HEARTBEAT_INTERVAL_MS = 45 * 1e3;
function doNothing() {
}
function fillOutListener({
  onChange = doNothing,
  onError = doNothing,
  onOutOfDate = doNothing,
  onSuccessfulSubscription = doNothing
}) {
  return {
    onChange,
    onError,
    onOutOfDate,
    onSuccessfulSubscription
  };
}
function isReady(sub) {
  return sub.isReady != null;
}
function subscriptionIsDone(sub) {
  return sub.status === "done" || sub.status === "error";
}
var ObjectSetListenerWebsocket = class _ObjectSetListenerWebsocket {
  static #instances = /* @__PURE__ */ new WeakMap();
  // FIXME
  static getInstance(client) {
    let instance = _ObjectSetListenerWebsocket.#instances.get(client.clientCacheKey);
    if (instance == null) {
      instance = new _ObjectSetListenerWebsocket(client);
      _ObjectSetListenerWebsocket.#instances.set(client.clientCacheKey, instance);
    }
    return instance;
  }
  #ws;
  #lastWsConnect = 0;
  #client;
  #backoff;
  #isFirstConnection = true;
  #logger;
  /**
   * map of requestId to all active subscriptions at the time of the request
   */
  #pendingSubscriptions = /* @__PURE__ */ new Map();
  /**
   * Map of subscriptionId to Subscription. Note: the subscriptionId may be
   * temporary and not the actual subscriptionId from the server.
   */
  #subscriptions = /* @__PURE__ */ new Map();
  #endedSubscriptions = /* @__PURE__ */ new Set();
  #maybeDisconnectTimeout;
  #heartbeatInterval;
  // DO NOT CONSTRUCT DIRECTLY. ONLY EXPOSED AS A TESTING SEAM
  constructor(client, {
    minimumReconnectDelayMs = MINIMUM_RECONNECT_DELAY_MS
  } = {}) {
    this.MINIMUM_RECONNECT_DELAY_MS = minimumReconnectDelayMs;
    this.#client = client;
    this.#backoff = new ExponentialBackoff({
      initialDelayMs: EXPONENTIAL_BACKOFF_INITIAL_DELAY_MS,
      maxDelayMs: EXPONENTIAL_BACKOFF_MAX_DELAY_MS,
      multiplier: EXPONENTIAL_BACKOFF_MULTIPLIER,
      jitterFactor: EXPONENTIAL_BACKOFF_JITTER_FACTOR
    });
    this.#logger = client.logger?.child({}, {
      msgPrefix: "<OSW> "
    });
    !(client.baseUrl.startsWith("https://") || client.baseUrl.startsWith("http://")) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Stack must be a URL") : invariant3__default.default(false) : void 0;
  }
  async subscribe(objectType, objectSet, listener, properties = [], shouldLoadRids = false) {
    const objOrInterfaceDef = objectType.type === "object" ? await this.#client.ontologyProvider.getObjectDefinition(objectType.apiName) : await this.#client.ontologyProvider.getInterfaceDefinition(objectType.apiName);
    let objectProperties = [];
    let referenceProperties = [];
    if (properties.length === 0) {
      properties = Object.keys(objOrInterfaceDef.properties);
    }
    objectProperties = properties.filter((p) => objOrInterfaceDef.properties[p].type !== "geotimeSeriesReference");
    referenceProperties = properties.filter((p) => objOrInterfaceDef.properties[p].type === "geotimeSeriesReference");
    const sub = {
      listener: fillOutListener(listener),
      objectSet,
      primaryKeyPropertyName: objOrInterfaceDef.type === "interface" ? void 0 : objOrInterfaceDef.primaryKeyApiName,
      requestedProperties: objectProperties,
      requestedReferenceProperties: referenceProperties,
      status: "preparing",
      // Since we don't have a real subscription id yet but we need to keep
      // track of this reference, we can just use a random uuid.
      subscriptionId: `TMP-${nextUuid()}}`,
      interfaceApiName: objOrInterfaceDef.type === "object" ? void 0 : objOrInterfaceDef.apiName,
      loadRids: shouldLoadRids
    };
    this.#subscriptions.set(sub.subscriptionId, sub);
    void this.#initiateSubscribe(sub);
    return () => {
      this.#unsubscribe(sub);
    };
  }
  /**
   * Called at least once for every subscription.
   *
   * - Resets pending expiry
   * - Recreates temporary object set
   * - Triggers a full subscribe message
   *
   * @returns
   */
  async #initiateSubscribe(sub) {
    if (process.env.NODE_ENV !== "production") {
      this.#logger?.debug("#initiateSubscribe()");
    }
    try {
      await this.#ensureWebsocket();
      if (subscriptionIsDone(sub)) {
        return;
      }
      sub.isReady = true;
      if (this.#ws?.readyState === WebSocket__default.default.OPEN) {
        this.#sendSubscribeMessage();
      }
    } catch (error) {
      this.#logger?.error(error, "Error in #initiateSubscribe");
      this.#tryCatchOnError(sub, true, error);
    }
  }
  #sendSubscribeMessage() {
    if (process.env.NODE_ENV !== "production") {
      this.#logger?.debug("#sendSubscribeMessage()");
    }
    const readySubs = [...this.#subscriptions.values()].filter(isReady);
    const id = nextUuid();
    this.#pendingSubscriptions.set(id, readySubs);
    const subscribe = {
      id,
      requests: readySubs.map(({
        objectSet,
        requestedProperties,
        requestedReferenceProperties,
        interfaceApiName
      }) => {
        return {
          objectSet,
          propertySet: requestedProperties,
          referenceSet: requestedReferenceProperties,
          objectLoadingResponseOptions: {
            shouldLoadObjectRids: true
          }
        };
      })
    };
    if (process.env.NODE_ENV !== "production") {
      this.#logger?.debug({
        payload: subscribe
      }, "sending subscribe message");
    }
    this.#ws?.send(JSON.stringify(subscribe));
  }
  #unsubscribe(sub, newStatus = "done") {
    if (subscriptionIsDone(sub)) {
      return;
    }
    sub.status = newStatus;
    sub.listener = fillOutListener({});
    this.#subscriptions.delete(sub.subscriptionId);
    this.#endedSubscriptions.add(sub.subscriptionId);
    this.#sendSubscribeMessage();
    if (this.#maybeDisconnectTimeout) {
      clearTimeout(this.#maybeDisconnectTimeout);
    }
    this.#maybeDisconnectTimeout = setTimeout(() => {
      this.#maybeDisconnectTimeout = void 0;
      if (this.#subscriptions.size === 0) {
        this.#cycleWebsocket();
      }
    }, WEBSOCKET_IDLE_DISCONNECT_DELAY_MS);
  }
  async #ensureWebsocket() {
    if (this.#ws == null) {
      const {
        baseUrl,
        tokenProvider
      } = this.#client;
      const url = constructWebsocketUrl(baseUrl, await this.#client.ontologyRid);
      const token = await tokenProvider();
      if (this.#ws == null) {
        if (!this.#isFirstConnection) {
          const delay = this.#backoff.calculateDelay();
          if (process.env.NODE_ENV !== "production") {
            this.#logger?.debug({
              delay,
              attempt: this.#backoff.getAttempt()
            }, "Waiting before reconnect");
          }
          await new Promise((resolve) => {
            setTimeout(resolve, delay);
          });
        }
        this.#lastWsConnect = Date.now();
        if (this.#ws == null) {
          if (process.env.NODE_ENV !== "production") {
            this.#logger?.debug("Creating websocket");
          }
          this.#ws = new WebSocket__default.default(url, [`Bearer-${token}`]);
          this.#ws.addEventListener("close", this.#onClose);
          this.#ws.addEventListener("message", this.#onMessage);
          this.#ws.addEventListener("open", this.#onOpen);
        }
      }
      if (this.#ws.readyState === WebSocket__default.default.CONNECTING) {
        const ws = this.#ws;
        return new Promise((resolve, reject) => {
          function cleanup() {
            ws.removeEventListener("open", open);
            ws.removeEventListener("error", error);
            ws.removeEventListener("close", cleanup);
          }
          function open() {
            cleanup();
            resolve();
          }
          function error(evt) {
            cleanup();
            reject(new Error(String(evt)));
          }
          ws.addEventListener("open", open);
          ws.addEventListener("error", error);
          ws.addEventListener("close", cleanup);
        });
      }
    }
  }
  #onOpen = () => {
    this.#isFirstConnection = false;
    this.#backoff.reset();
    this.#sendSubscribeMessage();
    if (this.#heartbeatInterval) {
      clearInterval(this.#heartbeatInterval);
    }
    this.#heartbeatInterval = setInterval(() => {
      if (this.#ws?.readyState === WebSocket__default.default.OPEN) {
        this.#sendSubscribeMessage();
      }
    }, WEBSOCKET_HEARTBEAT_INTERVAL_MS);
  };
  #onMessage = async (message) => {
    const data = JSON.parse(String(message.data));
    if (process.env.NODE_ENV !== "production") {
      this.#logger?.debug({
        payload: data
      }, "received message from ws");
    }
    switch (data.type) {
      case "objectSetChanged":
        await this.#handleMessage_objectSetChanged(data);
        return;
      case "refreshObjectSet":
        this.#handleMessage_refreshObjectSet(data);
        return;
      case "subscribeResponses":
        this.#handleMessage_subscribeResponses(data);
        return;
      case "subscriptionClosed": {
        this.#handleMessage_subscriptionClosed(data);
        return;
      }
      default:
        process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "Unexpected message type") : invariant3__default.default(false) ;
    }
  };
  #handleMessage_objectSetChanged = async (payload) => {
    const sub = this.#subscriptions.get(payload.id);
    if (sub == null) return;
    const objectUpdates = payload.updates.filter((update) => update.type === "object");
    const referenceUpdates = payload.updates.filter((update) => update.type === "reference");
    const osdkObjectsWithReferenceUpdates = await Promise.all(referenceUpdates.map(async (o) => {
      const osdkObjectArray = await this.#client.objectFactory2(this.#client, [{
        __apiName: o.objectType,
        __primaryKey: sub.primaryKeyPropertyName != null ? o.primaryKey[sub.primaryKeyPropertyName] : void 0,
        ...o.primaryKey,
        [o.property]: o.value
      }], sub.interfaceApiName, {}, false, void 0, false, await this.#fetchInterfaceMapping(o.objectType, sub.interfaceApiName));
      const singleOsdkObject = osdkObjectArray[0] ?? void 0;
      return singleOsdkObject != null ? {
        object: singleOsdkObject,
        state: "ADDED_OR_UPDATED"
      } : void 0;
    }));
    for (const update of osdkObjectsWithReferenceUpdates) {
      if (update != null) {
        try {
          sub.listener.onChange?.(update);
        } catch (error) {
          this.#logger?.error(error, "Error in onChange callback");
          this.#tryCatchOnError(sub, false, error);
        }
      }
    }
    const osdkObjects = await Promise.all(objectUpdates.map(async (o) => {
      const keysToDelete = Object.keys(o.object).filter((key) => sub.requestedReferenceProperties.includes(key));
      for (const key of keysToDelete) {
        delete o.object[key];
      }
      const osdkObjectArray = await this.#client.objectFactory2(this.#client, [o.object], sub.interfaceApiName, {}, false, void 0, false, await this.#fetchInterfaceMapping(o.object.__apiName, sub.interfaceApiName));
      const singleOsdkObject = osdkObjectArray[0] ?? void 0;
      const rid = singleOsdkObject["$rid"];
      return singleOsdkObject != null ? rid === void 0 ? {
        object: singleOsdkObject,
        state: o.state
      } : {
        object: singleOsdkObject,
        state: o.state,
        rid
      } : void 0;
    }));
    for (const osdkObject of osdkObjects) {
      if (osdkObject != null) {
        try {
          sub.listener.onChange?.(osdkObject);
        } catch (error) {
          this.#logger?.error(error, "Error in onChange callback");
          this.#tryCatchOnError(sub, false, error);
        }
      }
    }
  };
  async #fetchInterfaceMapping(objectTypeApiName, interfaceApiName) {
    if (interfaceApiName == null) return {};
    const interfaceMap = (await this.#client.ontologyProvider.getObjectDefinition(objectTypeApiName)).interfaceMap;
    return {
      [interfaceApiName]: {
        [objectTypeApiName]: interfaceMap[interfaceApiName]
      }
    };
  }
  #handleMessage_refreshObjectSet = (payload) => {
    const sub = this.#subscriptions.get(payload.id);
    !sub ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Expected subscription id ${payload.id}`) : invariant3__default.default(false) : void 0;
    try {
      sub.listener.onOutOfDate();
    } catch (error) {
      this.#logger?.error(error, "Error in onOutOfDate callback");
      this.#tryCatchOnError(sub, false, error);
    }
  };
  #handleMessage_subscribeResponses = (payload) => {
    const {
      id,
      responses
    } = payload;
    const subs = this.#pendingSubscriptions.get(id);
    !subs ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `should have a pending subscription for ${id}`) : invariant3__default.default(false) : void 0;
    this.#pendingSubscriptions.delete(id);
    for (let i = 0; i < responses.length; i++) {
      const sub = subs[i];
      const response = responses[i];
      switch (response.type) {
        case "error":
          this.#tryCatchOnError(sub, true, response.errors);
          this.#unsubscribe(sub, "error");
          break;
        case "qos":
          this.#cycleWebsocket();
          break;
        case "success":
          const shouldFireOutOfDate = sub.status === "expired" || sub.status === "reconnecting";
          if (process.env.NODE_ENV !== "production") {
            this.#logger?.debug({
              shouldFireOutOfDate
            }, "success");
          }
          sub.status = "subscribed";
          if (sub.subscriptionId !== response.id) {
            this.#subscriptions.delete(sub.subscriptionId);
            sub.subscriptionId = response.id;
            this.#subscriptions.set(sub.subscriptionId, sub);
          }
          try {
            if (shouldFireOutOfDate) sub.listener.onOutOfDate();
            else sub.listener.onSuccessfulSubscription();
          } catch (error) {
            this.#logger?.error(error, "Error in onOutOfDate or onSuccessfulSubscription callback");
            this.#tryCatchOnError(sub, false, error);
          }
          break;
        default:
          this.#tryCatchOnError(sub, true, response);
      }
    }
  };
  #handleMessage_subscriptionClosed(payload) {
    const sub = this.#subscriptions.get(payload.id);
    if (sub == null && this.#endedSubscriptions.has(payload.id)) return;
    !sub ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `Expected subscription id ${payload.id}`) : invariant3__default.default(false) : void 0;
    this.#tryCatchOnError(sub, true, payload.cause);
    this.#unsubscribe(sub, "error");
  }
  #onClose = (event) => {
    if (process.env.NODE_ENV !== "production") {
      this.#logger?.debug({
        event
      }, "Received close event from ws", event);
    }
    this.#cycleWebsocket();
  };
  #cycleWebsocket = () => {
    if (this.#heartbeatInterval) {
      clearInterval(this.#heartbeatInterval);
      this.#heartbeatInterval = void 0;
    }
    if (this.#ws) {
      this.#ws.removeEventListener("open", this.#onOpen);
      this.#ws.removeEventListener("message", this.#onMessage);
      this.#ws.removeEventListener("close", this.#onClose);
      if (this.#ws.readyState !== WebSocket__default.default.CLOSING && this.#ws.readyState !== WebSocket__default.default.CLOSED) {
        this.#ws.close();
      }
      this.#ws = void 0;
    }
    if (this.#subscriptions.size > 0) {
      if (process.env.NODE_ENV !== "production") {
        for (const s of this.#subscriptions.values()) {
          !(s.status !== "done" && s.status !== "error") ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, "should not have done/error subscriptions still") : invariant3__default.default(false) : void 0;
        }
      }
      for (const s of this.#subscriptions.values()) {
        if (s.status === "subscribed") s.status = "reconnecting";
      }
      void this.#ensureWebsocket();
    }
  };
  #tryCatchOnError = (sub, subscriptionClosed, error) => {
    try {
      sub.listener.onError({
        subscriptionClosed,
        error
      });
    } catch (onErrorError) {
      console.error(`Error encountered in an onError callback for an OSDK subscription`, onErrorError);
      console.error(`This onError call was triggered by an error in another callback`, error);
      console.error(`The subscription has been closed.`, error);
      if (!subscriptionClosed) {
        this.#logger?.error(error, "Error in onError callback");
        this.#unsubscribe(sub, "error");
        this.#tryCatchOnError(sub, true, onErrorError);
      }
    }
  };
};
function constructWebsocketUrl(baseUrl, ontologyRid) {
  const base = new URL(baseUrl);
  const url = new URL(`api/v2/ontologySubscriptions/ontologies/${ontologyRid}/streamSubscriptions`, base);
  url.protocol = url.protocol.replace("https", "wss");
  return url;
}
var uuidCounter = 0;
function nextUuid() {
  return `00000000-0000-0000-0000-${(uuidCounter++).toString().padStart(12, "0")}`;
}

// src/objectSet/createObjectSet.ts
function isObjectTypeDefinition(def) {
  return def.type === "object";
}
function isObjectSet(o) {
  return o != null && typeof o === "object" && isWireObjectSet(objectSetDefinitions.get(o));
}
function getWireObjectSet(objectSet) {
  return objectSetDefinitions.get(objectSet);
}
var objectSetDefinitions = /* @__PURE__ */ new WeakMap();
function createObjectSet(objectType, clientCtx, objectSet = resolveBaseObjectSetType(objectType)) {
  const base = {
    aggregate: aggregate3.bind(globalThis, augmentRequestContext(clientCtx, (_) => ({
      finalMethodCall: "aggregate"
    })), objectType, objectSet),
    fetchPage: fetchPageInternal.bind(globalThis, augmentRequestContext(clientCtx, (_) => ({
      finalMethodCall: "fetchPage"
    })), objectType, objectSet),
    fetchPageWithErrors: fetchPageWithErrorsInternal.bind(globalThis, augmentRequestContext(clientCtx, (_) => ({
      finalMethodCall: "fetchPageWithErrors"
    })), objectType, objectSet),
    where: (clause) => {
      return clientCtx.objectSetFactory(objectType, clientCtx, {
        type: "filter",
        objectSet,
        where: modernToLegacyWhereClause(clause, objectType)
      });
    },
    pivotTo: function(type) {
      return createSearchAround(type)();
    },
    union: (...objectSets) => {
      return clientCtx.objectSetFactory(objectType, clientCtx, {
        type: "union",
        objectSets: [objectSet, ...objectSets.map((os) => objectSetDefinitions.get(os))]
      });
    },
    intersect: (...objectSets) => {
      return clientCtx.objectSetFactory(objectType, clientCtx, {
        type: "intersect",
        objectSets: [objectSet, ...objectSets.map((os) => objectSetDefinitions.get(os))]
      });
    },
    subtract: (...objectSets) => {
      return clientCtx.objectSetFactory(objectType, clientCtx, {
        type: "subtract",
        objectSets: [objectSet, ...objectSets.map((os) => objectSetDefinitions.get(os))]
      });
    },
    nearestNeighbors: (query, numNeighbors, property) => {
      const nearestNeighborsQuery = isTextQuery(query) ? {
        "type": "text",
        "value": query
      } : {
        "type": "vector",
        "value": query
      };
      return clientCtx.objectSetFactory(objectType, clientCtx, {
        type: "nearestNeighbors",
        objectSet,
        propertyIdentifier: {
          type: "property",
          apiName: property
        },
        numNeighbors,
        query: nearestNeighborsQuery
      });
    },
    asyncIter: async function* (args) {
      let $nextPageToken = void 0;
      do {
        const result = await fetchPageInternal(augmentRequestContext(clientCtx, (_) => ({
          finalMethodCall: "asyncIter"
        })), objectType, objectSet, {
          ...args,
          $pageSize: 1e4,
          $nextPageToken
        }, true);
        $nextPageToken = result.nextPageToken;
        for (const obj of result.data) {
          yield obj;
        }
      } while ($nextPageToken != null);
    },
    fetchOne: isObjectTypeDefinition(objectType) ? async (primaryKey, options) => {
      return await fetchSingle(augmentRequestContext(clientCtx, (_) => ({
        finalMethodCall: "fetchOne"
      })), objectType, options, await createWithPk(clientCtx, objectType, objectSet, primaryKey));
    } : void 0,
    fetchOneWithErrors: isObjectTypeDefinition(objectType) ? async (primaryKey, options) => {
      return await fetchSingleWithErrors(augmentRequestContext(clientCtx, (_) => ({
        finalMethodCall: "fetchOneWithErrors"
      })), objectType, options, await createWithPk(clientCtx, objectType, objectSet, primaryKey));
    } : void 0,
    subscribe: (listener, opts) => {
      const pendingSubscribe = ObjectSetListenerWebsocket.getInstance(clientCtx).subscribe(objectType, objectSet, listener, opts?.properties, opts?.includeRid);
      return {
        unsubscribe: async () => (await pendingSubscribe)()
      };
    },
    withProperties: (clause) => {
      const definitionMap = /* @__PURE__ */ new Map();
      const derivedProperties = {};
      for (const key of Object.keys(clause)) {
        const derivedPropertyDefinition = clause[key](createWithPropertiesObjectSet(objectType, {
          type: "methodInput"
        }, definitionMap, true));
        derivedProperties[key] = definitionMap.get(derivedPropertyDefinition);
      }
      return clientCtx.objectSetFactory(objectType, clientCtx, {
        type: "withProperties",
        derivedProperties,
        objectSet
      });
    },
    narrowToType: (objectTypeDef) => {
      const existingMapping = clientCtx.narrowTypeInterfaceOrObjectMapping[objectTypeDef.apiName];
      !(!existingMapping || existingMapping === objectTypeDef.type) ? process.env.NODE_ENV !== "production" ? invariant3__default.default(false, `${objectTypeDef.apiName} was previously used as an ${existingMapping}, but now used as a ${objectTypeDef.type}.`) : invariant3__default.default(false) : void 0;
      clientCtx.narrowTypeInterfaceOrObjectMapping[objectTypeDef.apiName] = objectTypeDef.type;
      return clientCtx.objectSetFactory(objectTypeDef, clientCtx, {
        type: "asType",
        objectSet,
        entityType: objectTypeDef.apiName
      });
    },
    experimental_asyncIterLinks: async function* (links) {
      let $nextPageToken = void 0;
      do {
        const result = await fetchLinksPage(augmentRequestContext(clientCtx, (_) => ({
          finalMethodCall: "asyncIterLinks"
        })), objectType, objectSet, links);
        $nextPageToken = result.nextPageToken;
        for (const obj of result.data) {
          yield obj;
        }
      } while ($nextPageToken != null);
    },
    $objectSetInternals: {
      def: objectType
    }
  };
  function createSearchAround(link) {
    return () => {
      return clientCtx.objectSetFactory(objectType, clientCtx, objectType.type === "object" ? {
        type: "searchAround",
        objectSet,
        link
      } : {
        type: "interfaceLinkSearchAround",
        objectSet,
        interfaceLink: link
      });
    };
  }
  objectSetDefinitions.set(base, objectSet);
  return base;
}
async function createWithPk(clientCtx, objectType, objectSet, primaryKey) {
  const objDef = await clientCtx.ontologyProvider.getObjectDefinition(objectType.apiName);
  const withPk = {
    type: "filter",
    objectSet,
    where: {
      type: "eq",
      field: objDef.primaryKeyApiName,
      value: primaryKey
    }
  };
  return withPk;
}
function isTextQuery(query) {
  return typeof query === "string";
}

exports.ActionTypeV2_exports = ActionTypeV2_exports;
exports.Action_exports = Action_exports;
exports.Attachment_exports = Attachment_exports;
exports.BaseLogger = BaseLogger;
exports.MediaReferenceProperty_exports = MediaReferenceProperty_exports;
exports.MinimalLogger = MinimalLogger;
exports.ObjectTypeV2_exports = ObjectTypeV2_exports;
exports.OntologyInterface_exports = OntologyInterface_exports;
exports.OntologyObjectSet_exports = OntologyObjectSet_exports;
exports.QueryType_exports = QueryType_exports;
exports.Query_exports = Query_exports;
exports.TimeSeriesPropertyV2_exports = TimeSeriesPropertyV2_exports;
exports.TimeSeriesValueBankProperty_exports = TimeSeriesValueBankProperty_exports;
exports.addUserAgentAndRequestContextHeaders = addUserAgentAndRequestContextHeaders;
exports.additionalContext = additionalContext;
exports.augment = augment;
exports.augmentRequestContext = augmentRequestContext;
exports.createObjectSet = createObjectSet;
exports.createWithPropertiesObjectSet = createWithPropertiesObjectSet;
exports.extractNamespace = extractNamespace;
exports.fetchPage = fetchPage;
exports.fetchSingle = fetchSingle;
exports.fetchSingleWithErrors = fetchSingleWithErrors;
exports.fetchStaticRidPage = fetchStaticRidPage;
exports.foundryPlatformFetch = foundryPlatformFetch;
exports.getWireObjectSet = getWireObjectSet;
exports.hydrateAttachmentFromRid = hydrateAttachmentFromRid;
exports.hydrateAttachmentFromRidInternal = hydrateAttachmentFromRidInternal;
exports.isObjectSet = isObjectSet;
exports.isWireObjectSet = isWireObjectSet;
exports.symbolClientContext = symbolClientContext;
//# sourceMappingURL=chunk-Y362HOIZ.cjs.map
//# sourceMappingURL=chunk-Y362HOIZ.cjs.map