'use strict';

var chunkY362HOIZ_cjs = require('./chunk-Y362HOIZ.cjs');
var chunkLDTMSHUZ_cjs = require('./chunk-LDTMSHUZ.cjs');
var unstable = require('@osdk/api/unstable');
var client_unstable = require('@osdk/client.unstable');
var invariant = require('tiny-invariant');
var shared_client_impl = require('@osdk/shared.client.impl');
var api = require('@osdk/api');
var generatorConverters = require('@osdk/generator-converters');

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

var invariant__default = /*#__PURE__*/_interopDefault(invariant);

// src/actions/ActionValidationError.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var ActionValidationError = class extends Error {
  constructor(validation) {
    super("Validation Error: " + JSON.stringify(validation, null, 2));
    this.validation = validation;
  }
};

// src/object/AttachmentUpload.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function isAttachmentUpload(o) {
  return typeof o === "object" && o != null && "name" in o && typeof o.name === "string" && "data" in o && o.data instanceof Blob && !("fileName" in o);
}
function isAttachmentFile(o) {
  return typeof o === "object" && o instanceof Blob && "name" in o;
}
function createAttachmentUpload(data, name) {
  return {
    data,
    name
  };
}

// src/util/objectSpecifierUtils.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function createObjectSpecifierFromPrimaryKey(objectDef, primaryKey) {
  return `${objectDef.apiName}:${primaryKey}`;
}
function createObjectSpecifierFromInterfaceSpecifier(interfaceDef, interfaceSpecifier) {
  return `${interfaceSpecifier.objectTypeApiName}:${interfaceSpecifier.primaryKeyValue}`;
}
function extractPrimaryKeyFromObjectSpecifier(ObjectSpecifier) {
  return ObjectSpecifier.split(":")[1];
}

// src/createClient.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/__unstable/createBulkLinksAsyncIterFactory.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/objectSet/conjureUnionType.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function conjureUnionType(type, value) {
  return {
    type,
    [type]: value
  };
}

// src/ontology/makeConjureContext.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function makeConjureContext({
  baseUrl,
  fetch: fetchFn,
  tokenProvider
}, servicePath) {
  return {
    baseUrl,
    servicePath,
    fetchFn,
    tokenProvider
  };
}

// src/pageRequestAsAsyncIter.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function getResults(x) {
  return x.results;
}
function applyPageToken(payload, {
  pageToken
}) {
  return pageToken ? {
    ...payload,
    pageToken
  } : void 0;
}
async function* pageRequestAsAsyncIter(call, values, nextArgs, initialPayload) {
  let payload = initialPayload;
  while (payload) {
    const r = await call(payload);
    for (const q of values(r)) {
      yield q;
    }
    payload = nextArgs(payload, r);
  }
}

// src/__unstable/ConjureSupport.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/object/SimpleCache.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function createSimpleCache(map = /* @__PURE__ */ new Map(), fn) {
  function get(key) {
    const r = map.get(key);
    if (r === void 0 && fn !== void 0) {
      return set(key, fn(key));
    } else {
      return r;
    }
  }
  function set(key, value) {
    map.set(key, value);
    return value;
  }
  function remove(key) {
    return map.delete(key);
  }
  return {
    get,
    set,
    remove
  };
}
function createSimpleAsyncCache(type, fn, createCacheLocal = createSimpleCache) {
  const cache = createCacheLocal(type === "weak" ? /* @__PURE__ */ new WeakMap() : /* @__PURE__ */ new Map());
  const inProgress = createCacheLocal(type === "weak" ? /* @__PURE__ */ new WeakMap() : /* @__PURE__ */ new Map());
  const ret = {
    getOrUndefined: function getOrUndefined(key) {
      return cache.get(key);
    },
    get: async function get(key) {
      return cache.get(key) ?? inProgress.get(key) ?? ret.set(key, fn(key));
    },
    set: async function set(k, v) {
      try {
        const r = await inProgress.set(k, v);
        cache.set(k, r);
        inProgress.remove(k);
        return r;
      } catch (e) {
        inProgress.remove(k);
        throw e;
      }
    }
  };
  return ret;
}

// src/__unstable/ConjureSupport.ts
var cachedAllOntologies;
async function getOntologyVersionForRid(ctx, ontologyRid) {
  cachedAllOntologies ??= await client_unstable.loadAllOntologies(ctx, {});
  !cachedAllOntologies.ontologies[ontologyRid] ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, "ontology should be loaded") : invariant__default.default(false) : void 0;
  return cachedAllOntologies.ontologies[ontologyRid].currentOntologyVersion;
}
var strongMemoAsync = (fn) => createSimpleAsyncCache("strong", fn).get;
var weakMemoAsync = (fn) => createSimpleAsyncCache("weak", fn).get;
var MetadataClient = class {
  #client;
  #ctx;
  #logger;
  constructor(client) {
    this.#client = client;
    this.#ctx = makeConjureContext(client, "ontology-metadata/api");
    this.#client.ontologyProvider.getObjectDefinition;
    this.#logger = this.#client.logger?.child({
      mcc: true
    });
  }
  forObjectByRid = strongMemoAsync(async (rid) => {
    return Promise.resolve({
      getPropertyMapping: this.#objectPropertyMapping.bind(this, rid),
      getLinkMapping: this.#objectLinkMapping.bind(this, rid),
      getRid: () => rid,
      getApiName: async () => (await this.#getConjureObjectType(rid)).apiName
    });
  });
  forObjectByApiName = strongMemoAsync(async (objectApiName) => {
    const objectDef = await this.#client.ontologyProvider.getObjectDefinition(objectApiName);
    return this.forObjectByRid(objectDef.rid);
  });
  #objectPropertyMapping = strongMemoAsync(async (objectTypeRid) => {
    const conjureObjectType = await this.#getConjureObjectType(objectTypeRid);
    return createObjectPropertyMapping(conjureObjectType);
  });
  #objectLinkMapping = strongMemoAsync(async (objectTypeRid) => {
    const linkTypes = await client_unstable.getLinkTypesForObjectTypes(this.#ctx, {
      includeObjectTypesWithoutSearchableDatasources: true,
      loadRedacted: false,
      objectTypeBranches: {},
      objectTypeVersions: {
        [objectTypeRid]: await this.ontologyVersion("")
      }
    });
    !linkTypes.linkTypes[objectTypeRid] ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, "link type should be loaded") : invariant__default.default(false) : void 0;
    const ret = {};
    for (const l of linkTypes.linkTypes[objectTypeRid]) {
      const helper = ({
        apiName
      }, linkSide, otherObjectType) => {
        if (apiName) {
          ret[apiName] = {
            apiName,
            directedLinkTypeRid: {
              linkTypeRid: l.rid,
              linkSide
            },
            otherObjectType
          };
        }
      };
      if (l.definition.type === "oneToMany") {
        const {
          oneToMany: {
            objectTypeRidManySide,
            manyToOneLinkMetadata,
            objectTypeRidOneSide,
            oneToManyLinkMetadata
          }
        } = l.definition;
        if (objectTypeRidManySide === objectTypeRid) {
          helper(manyToOneLinkMetadata, "TARGET", objectTypeRidOneSide);
        }
        if (objectTypeRidOneSide === objectTypeRid) {
          helper(oneToManyLinkMetadata, "SOURCE", objectTypeRidManySide);
        }
      } else if (l.definition.type === "manyToMany") {
        const {
          manyToMany: {
            objectTypeRidA,
            objectTypeAToBLinkMetadata,
            objectTypeRidB,
            objectTypeBToALinkMetadata
          }
        } = l.definition;
        if (objectTypeRidA === objectTypeRid) {
          helper(objectTypeAToBLinkMetadata, "SOURCE", objectTypeRidB);
        }
        if (objectTypeRidB === objectTypeRid) {
          helper(objectTypeBToALinkMetadata, "TARGET", objectTypeRidA);
        }
      }
    }
    return ret;
  });
  #getConjureObjectType = strongMemoAsync(async (objectTypeRid) => {
    this.#logger?.debug(`getConjureObjectType(${objectTypeRid})`);
    const body = {
      datasourceTypes: [],
      objectTypes: [{
        identifier: {
          type: "objectTypeRid",
          objectTypeRid
        },
        versionReference: {
          type: "ontologyVersion",
          ontologyVersion: await this.ontologyVersion("")
        }
      }],
      linkTypes: [],
      sharedPropertyTypes: [],
      interfaceTypes: [],
      typeGroups: [],
      loadRedacted: false,
      includeObjectTypeCount: void 0,
      includeObjectTypesWithoutSearchableDatasources: true,
      includeEntityMetadata: void 0,
      actionTypes: [],
      includeTypeGroupEntitiesCount: void 0,
      entityMetadata: void 0
    };
    const entities = await client_unstable.bulkLoadOntologyEntities(this.#ctx, void 0, body);
    !entities.objectTypes[0]?.objectType ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, "object type should be loaded") : invariant__default.default(false) : void 0;
    return entities.objectTypes[0].objectType;
  });
  ontologyVersion = strongMemoAsync(async (_) => getOntologyVersionForRid(this.#ctx, await this.#client.ontologyRid));
};
var metadataCacheClient = weakMemoAsync((client) => Promise.resolve(new MetadataClient(client)));
function createObjectPropertyMapping(conjureOT) {
  !(conjureOT.primaryKeys.length === 1) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, `only one primary key supported, got ${conjureOT.primaryKeys.length}`) : invariant__default.default(false) : void 0;
  const pkRid = conjureOT.primaryKeys[0];
  const pkProperty = Object.values(conjureOT.propertyTypes).find((a) => a.rid === pkRid);
  if (!pkProperty) {
    throw new Error(`Could not find PK property by rid: ${pkRid}`);
  }
  const propertyIdToApiNameMapping = Object.fromEntries(Object.values(conjureOT.propertyTypes).map((property) => {
    return [property.id, property.apiName];
  }));
  const propertyApiNameToIdMapping = Object.fromEntries(Object.values(conjureOT.propertyTypes).map((property) => {
    return [property.apiName, property.id];
  }));
  return {
    apiName: conjureOT.apiName,
    id: conjureOT.id,
    propertyIdToApiNameMapping,
    propertyApiNameToIdMapping,
    pk: {
      rid: pkRid,
      apiName: pkProperty.apiName,
      type: pkProperty.type
    }
  };
}

// src/__unstable/createBulkLinksAsyncIterFactory.ts
function createBulkLinksAsyncIterFactory(ctx) {
  return async function* (objs, linkTypes) {
    if (objs.length === 0) {
      return;
    }
    ctx.logger?.debug("Preparing to fetch bulk links");
    !objs.every((a) => a.$objectType === objs[0].$objectType) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false) : invariant__default.default(false) : void 0;
    const mcc = await metadataCacheClient(ctx);
    const helper = await mcc.forObjectByApiName(objs[0].$objectType);
    const [objectTypeRid, propertyMapping, fullLinkMapping] = await Promise.all([helper.getRid(), helper.getPropertyMapping(), helper.getLinkMapping()]);
    const linkMapping = Object.fromEntries(Object.entries(fullLinkMapping).filter(([apiName]) => linkTypes.includes(apiName)));
    for (const linkType of linkTypes) {
      if (linkMapping[linkType] == null) {
        throw "Unable to find link type: " + linkType;
      }
    }
    const req = {
      objectSetContext: {
        forkRid: void 0,
        objectSetFilterContext: {
          parameterOverrides: {}
        },
        ontologyBranchRid: void 0,
        owningRid: void 0,
        reportUsage: void 0,
        workstateRid: void 0
      },
      responseOptions: {
        includeObjectSetEntities: true,
        includeUsageCost: false
      },
      pageSize: 1e3,
      pageToken: void 0,
      linksRequests: [{
        directedLinkTypes: Object.values(linkMapping).map(({
          directedLinkTypeRid
        }) => directedLinkTypeRid),
        objects: conjureUnionType("objects", objs.map((o) => conjureUnionType("objectLocatorV2", {
          objectTypeRid,
          objectPrimaryKey: {
            [propertyMapping.pk.rid]: conjureUnionType(propertyMapping.pk.type.type, o.$primaryKey)
          }
        })))
      }]
    };
    const bulkLinksIter = pageRequestAsAsyncIter(client_unstable.getBulkLinksPage.bind(void 0, makeConjureContext(ctx, "object-set-service/api")), getResults, (prevReq, prevResult) => applyPageToken({
      ...prevReq,
      pageToken: prevResult.pageToken
    }, {
      pageToken: prevResult.pageToken
    }), req);
    for await (const item of bulkLinksIter) {
      const {
        objectIdentifier
      } = item;
      const obj = findObject(objectIdentifier, objs);
      for (const link of item.links) {
        const ref = link.link[link.linkSide === "SOURCE" ? "objectSideB" : "objectSideA"];
        const pk = getPrimaryKeyOrThrow(ref);
        const otherObjectApiName = await (await mcc.forObjectByRid(pk.objectTypeRid)).getApiName();
        const mappedLink = Object.values(linkMapping).find((a) => a.directedLinkTypeRid.linkTypeRid === link.link.linkTypeRid && a.directedLinkTypeRid.linkSide === link.linkSide);
        if (!mappedLink) throw new Error("Could not find link type");
        yield {
          object: obj,
          linkApiName: mappedLink.apiName,
          otherObjectApiName,
          otherObjectPk: pk.pkValue
        };
      }
    }
  };
}
function findObject(objectIdentifier, objs) {
  const {
    pkValue
  } = getPrimaryKeyOrThrow(objectIdentifier);
  const obj = objs.find((o) => o.$primaryKey === pkValue);
  if (obj == null) {
    throw new Error(`Needed to find object with pk ${pkValue}} and could not`);
  }
  return obj;
}
function getPrimaryKeyOrThrow(ref) {
  if ("type" in ref && ref.type !== "objectLocatorV2") {
    throw new Error("We do not support looking up object by rid");
  }
  const pks = Object.entries(ref.objectLocatorV2.objectPrimaryKey);
  if (pks.length !== 1) {
    throw new Error("Unable to support this request due to multiple pks");
  }
  return {
    objectTypeRid: ref.objectLocatorV2.objectTypeRid,
    pkValue: pks[0][1][pks[0][1].type]
  };
}

// src/actions/applyAction.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/util/toDataValue.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

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

// ../../node_modules/.pnpm/@osdk+foundry.mediasets@2.44.0/node_modules/@osdk/foundry.mediasets/build/esm/public/MediaSet.js
var MediaSet_exports = {};
chunkLDTMSHUZ_cjs.__export(MediaSet_exports, {
  abort: () => abort,
  calculate: () => calculate,
  commit: () => commit,
  create: () => create,
  getRidByPath: () => getRidByPath,
  info: () => info,
  read: () => read,
  readOriginal: () => readOriginal,
  reference: () => reference,
  retrieve: () => retrieve,
  upload: () => upload,
  uploadMedia: () => uploadMedia
});
chunkLDTMSHUZ_cjs.init_cjs_shims();
var _abort = [1, "/v2/mediasets/{0}/transactions/{1}/abort", 2];
function abort($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _abort, ...args);
}
var _calculate = [0, "/v2/mediasets/{0}/items/{1}/transform/imagery/thumbnail/calculate", 6];
function calculate($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _calculate, ...args);
}
var _commit = [1, "/v2/mediasets/{0}/transactions/{1}/commit", 2];
function commit($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _commit, ...args);
}
var _create = [1, "/v2/mediasets/{0}/transactions", 2];
function create($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _create, ...args);
}
var _info = [0, "/v2/mediasets/{0}/items/{1}", 6];
function info($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _info, ...args);
}
var _reference = [0, "/v2/mediasets/{0}/items/{1}/reference", 6];
function reference($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _reference, ...args);
}
var _getRidByPath = [0, "/v2/mediasets/{0}/items/getRidByPath", 2];
function getRidByPath($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _getRidByPath, ...args);
}
var _upload = [1, "/v2/mediasets/{0}/items", 3, "*/*"];
function upload($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _upload, ...args);
}
var _read = [0, "/v2/mediasets/{0}/items/{1}/content", 6, , "*/*"];
function read($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _read, ...args);
}
var _readOriginal = [0, "/v2/mediasets/{0}/items/{1}/original", 6, , "*/*"];
function readOriginal($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _readOriginal, ...args);
}
var _retrieve = [0, "/v2/mediasets/{0}/items/{1}/transform/imagery/thumbnail/retrieve", 6, , "*/*"];
function retrieve($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _retrieve, ...args);
}
var _uploadMedia = [2, "/v2/mediasets/media/upload", 7, "*/*"];
function uploadMedia($ctx, ...args) {
  return chunkY362HOIZ_cjs.foundryPlatformFetch($ctx, _uploadMedia, ...args);
}

// src/object/mediaUpload.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function isMediaReference(o) {
  return typeof o === `object` && typeof o.mimeType === "string" && "reference" in o && typeof o.reference === "object" && o.reference.type === "mediaSetViewItem" && "mediaSetViewItem" in o.reference && typeof o.reference.mediaSetViewItem === "object" && typeof o.reference.mediaSetViewItem.mediaSetRid === "string" && typeof o.reference.mediaSetViewItem.mediaSetViewRid === "string" && typeof o.reference.mediaSetViewItem.mediaItemRid === "string";
}
function isMediaUpload(o) {
  return typeof o === "object" && o != null && "fileName" in o && typeof o.fileName === "string" && "data" in o && typeof o.data === "object" && o.data instanceof Blob;
}

// src/util/interfaceUtils.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function isInterfaceActionParam(o) {
  return o != null && typeof o === "object" && "$objectType" in o && "$primaryKey" in o;
}
function isInterfaceQueryParam(o) {
  return o != null && typeof o === "object" && "$objectType" in o && "$primaryKey" in o;
}
function isInterfaceSpecifier(o) {
  return o != null && typeof o === "object" && "$objectType" in o && "$primaryKey" in o && o.$objectType !== o.$apiName;
}

// src/util/isObjectSpecifiersObject.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function isObjectSpecifiersObject(o) {
  return o && typeof o === "object" && typeof o.$apiName === "string" && o.$primaryKey != null;
}

// src/util/isOntologyObjectV2.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function isOntologyObjectV2(o) {
  return o && typeof o === "object" && typeof o.__apiName === "string" && o.__primaryKey != null;
}

// src/util/isPoint.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function isPoint(o) {
  return o && typeof o === "object" && "type" in o && o.type === "Point" && "coordinates" in o && o.coordinates.length === 2;
}

// src/util/toDataValue.ts
async function toDataValue(value, client, actionMetadata) {
  if (value == null) {
    return value;
  }
  if (Array.isArray(value) || value instanceof Set) {
    const values = Array.from(value);
    if (values.some((dataValue) => isAttachmentUpload(dataValue) || isAttachmentFile(dataValue))) {
      const converted = [];
      for (const value2 of values) {
        converted.push(await toDataValue(value2, client));
      }
      return converted;
    }
    const promiseArray = Array.from(value, async (innerValue) => await toDataValue(innerValue, client));
    return Promise.all(promiseArray);
  }
  if (isAttachmentUpload(value)) {
    const attachment = await chunkY362HOIZ_cjs.Attachment_exports.upload(client, value.data, {
      filename: value.name
    });
    return await toDataValue(attachment.rid, client);
  }
  if (isAttachmentFile(value)) {
    const attachment = await chunkY362HOIZ_cjs.Attachment_exports.upload(client, value, {
      filename: value.name
    });
    return await toDataValue(attachment.rid, client);
  }
  if (isMediaUpload(value)) {
    const mediaRef = await MediaSet_exports.uploadMedia(client, value.data, {
      filename: value.fileName,
      preview: true
    });
    return await toDataValue(mediaRef, client);
  }
  if (isOntologyObjectV2(value)) {
    return await toDataValue(value.__primaryKey, client);
  }
  if (isObjectSpecifiersObject(value)) {
    return await toDataValue(value.$primaryKey, client);
  }
  if (isPoint(value)) {
    return await toDataValue(`${value.coordinates[1]},${value.coordinates[0]}`, client);
  }
  if (chunkY362HOIZ_cjs.isWireObjectSet(value)) {
    return value;
  }
  if (chunkY362HOIZ_cjs.isObjectSet(value)) {
    return chunkY362HOIZ_cjs.getWireObjectSet(value);
  }
  if (isMediaReference(value)) {
    return value;
  }
  if (isInterfaceActionParam(value)) {
    return {
      objectTypeApiName: value.$objectType,
      primaryKeyValue: value.$primaryKey
    };
  }
  if (typeof value === "object") {
    return Object.entries(value).reduce(async (promisedAcc, [key, structValue]) => {
      const acc = await promisedAcc;
      acc[key] = await toDataValue(structValue, client);
      return acc;
    }, Promise.resolve({}));
  }
  return value;
}

// src/actions/applyAction.ts
async function applyAction(client, action, parameters, options = {}) {
  const clientWithHeaders = chunkY362HOIZ_cjs.addUserAgentAndRequestContextHeaders(chunkY362HOIZ_cjs.augmentRequestContext(client, (_) => ({
    finalMethodCall: "applyAction"
  })), action);
  if (Array.isArray(parameters)) {
    const response = await chunkY362HOIZ_cjs.Action_exports.applyBatch(clientWithHeaders, await client.ontologyRid, action.apiName, {
      requests: parameters ? await remapBatchActionParams(parameters, client, await client.ontologyProvider.getActionDefinition(action.apiName)) : [],
      options: {
        returnEdits: options?.$returnEdits ? "ALL" : "NONE"
      }
    });
    const edits = response.edits;
    return options?.$returnEdits ? edits?.type === "edits" ? remapActionResponse(response) : edits : void 0;
  } else {
    const response = await chunkY362HOIZ_cjs.Action_exports.apply(clientWithHeaders, await client.ontologyRid, action.apiName, {
      parameters: await remapActionParams(parameters, client, await client.ontologyProvider.getActionDefinition(action.apiName)),
      options: {
        mode: options?.$validateOnly ? "VALIDATE_ONLY" : "VALIDATE_AND_EXECUTE",
        returnEdits: options?.$returnEdits ? "ALL_V2_WITH_DELETIONS" : "NONE"
      }
    });
    if (options?.$validateOnly) {
      return response.validation;
    }
    if (response.validation && response.validation?.result === "INVALID") {
      const validation = response.validation;
      throw new ActionValidationError(validation);
    }
    const edits = response.edits;
    return options?.$returnEdits ? edits?.type === "edits" ? remapActionResponse(response) : edits : void 0;
  }
}
async function remapActionParams(params, client, actionMetadata) {
  if (params == null) {
    return {};
  }
  const parameterMap = {};
  for (const [key, value] of Object.entries(params)) {
    parameterMap[key] = await toDataValue(value, client);
  }
  return parameterMap;
}
async function remapBatchActionParams(params, client, actionMetadata) {
  const remappedParams = await Promise.all(params.map(async (param) => {
    return {
      parameters: await remapActionParams(param, client)
    };
  }));
  return remappedParams;
}
function remapActionResponse(response) {
  const editResponses = response?.edits;
  if (editResponses?.type === "edits") {
    const remappedActionResponse = {
      type: editResponses.type,
      deletedLinksCount: editResponses.deletedLinksCount,
      deletedObjectsCount: editResponses.deletedObjectsCount,
      addedLinks: [],
      deletedLinks: [],
      addedObjects: [],
      deletedObjects: [],
      modifiedObjects: [],
      editedObjectTypes: []
    };
    const editedObjectTypesSet = /* @__PURE__ */ new Set();
    for (const edit of editResponses.edits) {
      if (edit.type === "addLink" || edit.type === "deleteLink") {
        const osdkEdit = {
          linkTypeApiNameAtoB: edit.linkTypeApiNameAtoB,
          linkTypeApiNameBtoA: edit.linkTypeApiNameBtoA,
          aSideObject: edit.aSideObject,
          bSideObject: edit.bSideObject
        };
        edit.type === "addLink" ? remappedActionResponse.addedLinks.push(osdkEdit) : remappedActionResponse.deletedLinks?.push(osdkEdit);
        editedObjectTypesSet.add(edit.aSideObject.objectType);
        editedObjectTypesSet.add(edit.bSideObject.objectType);
      } else if (edit.type === "addObject" || edit.type === "deleteObject" || edit.type === "modifyObject") {
        const osdkEdit = {
          objectType: edit.objectType,
          primaryKey: edit.primaryKey
        };
        if (edit.type === "addObject") {
          remappedActionResponse.addedObjects.push(osdkEdit);
        } else if (edit.type === "deleteObject") {
          remappedActionResponse.deletedObjects?.push(osdkEdit);
        } else if (edit.type === "modifyObject") {
          remappedActionResponse.modifiedObjects.push(osdkEdit);
        }
        editedObjectTypesSet.add(edit.objectType);
      } else {
        if (process.env.NODE_ENV !== "production") {
          console.warn(`Unexpected edit type: ${JSON.stringify(edit)}`);
        }
      }
    }
    remappedActionResponse.editedObjectTypes = [...editedObjectTypesSet];
    return remappedActionResponse;
  }
}

// src/createMinimalClient.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

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

// src/object/convertWireToOsdkObjects/createOsdkObject.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/createGeotimeSeriesProperty.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/util/timeseriesUtils.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/util/streamutils.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var START_TOKEN = new Uint8Array([123, 34, 100, 97, 116, 97, 34, 58, 91]);
var OBJECT_OPEN_CHAR_CODE = 123;
var OBJECT_CLOSE_CHAR_CODE = 125;
async function* parseStreamedResponse(asyncIterable) {
  const utf8decoder = new TextDecoder("utf-8");
  let parsedStart = false;
  let prevChunks = [];
  let openBracesCount = 0;
  for await (const chunk of asyncIterable) {
    let i = 0;
    if (!parsedStart) {
      parsedStart = true;
      if (startsWith(chunk, START_TOKEN)) {
        i = START_TOKEN.length;
      }
    }
    for (; i < chunk.length; i++) {
      while (openBracesCount === 0 && chunk[i] !== OBJECT_OPEN_CHAR_CODE && i < chunk.length) {
        i++;
      }
      let j = i;
      for (; j < chunk.length; j++) {
        const c = chunk[j];
        if (c === OBJECT_OPEN_CHAR_CODE) {
          openBracesCount++;
        } else if (c === OBJECT_CLOSE_CHAR_CODE) {
          openBracesCount--;
          if (0 === openBracesCount) {
            yield combineAndParse(utf8decoder, prevChunks, chunk.subarray(i, j + 1));
            prevChunks = [];
            i = j;
            break;
          }
        }
      }
      if (j === chunk.length) {
        prevChunks.push(chunk.subarray(i));
        break;
      }
    }
  }
}
function startsWith(a, b) {
  if (a.length < b.length) {
    return false;
  }
  for (let i = 0; i < b.length; i++) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}
function combineAndParse(utf8decoder, prev, curr) {
  let str = "";
  for (const chunk of prev) {
    str += utf8decoder.decode(chunk, {
      stream: true
    });
  }
  str += utf8decoder.decode(curr);
  return JSON.parse(str);
}
async function* iterateReadableStream(readableStream) {
  let res = await readableStream.read();
  while (!res.done) {
    yield res.value;
    res = await readableStream.read();
  }
}

// src/util/timeseriesUtils.ts
function getTimeRange(body) {
  if ("$startTime" in body || "$endTime" in body) {
    return {
      type: "absolute",
      startTime: body.$startTime,
      endTime: body.$endTime
    };
  }
  return body.$before ? {
    type: "relative",
    startTime: {
      when: "BEFORE",
      value: body.$before,
      unit: api.TimeseriesDurationMapping[body.$unit]
    }
  } : {
    type: "relative",
    endTime: {
      when: "AFTER",
      value: body.$after,
      unit: api.TimeseriesDurationMapping[body.$unit]
    }
  };
}
async function* asyncIterPointsHelper(iterator) {
  const reader = iterator.body?.getReader();
  for await (const point of parseStreamedResponse(iterateReadableStream(reader))) {
    yield {
      time: point.time,
      value: point.value
    };
  }
}

// src/createGeotimeSeriesProperty.ts
var GeotimeSeriesPropertyImpl = class {
  #triplet;
  #client;
  constructor(client, objectApiName, primaryKey, propertyName, initialValue) {
    this.#client = client;
    this.#triplet = [objectApiName, primaryKey, propertyName];
    if (initialValue != null) {
      this.lastFetchedValue = initialValue;
    }
  }
  async getLatestValue() {
    const latestPointPromise = chunkY362HOIZ_cjs.TimeSeriesValueBankProperty_exports.getLatestValue(this.#client, await this.#client.ontologyRid, ...this.#triplet);
    latestPointPromise.then(
      (latestPoint) => this.lastFetchedValue = latestPoint,
      // eslint-disable-next-line no-console
      (err) => void console.error(err)
    );
    return latestPointPromise;
  }
  async getAllValues(query) {
    const allPoints = [];
    for await (const point of this.asyncIterValues(query)) {
      allPoints.push(point);
    }
    return allPoints;
  }
  async *asyncIterValues(query) {
    const streamPointsIterator = await chunkY362HOIZ_cjs.TimeSeriesValueBankProperty_exports.streamValues(this.#client, await this.#client.ontologyRid, ...this.#triplet, query ? {
      range: getTimeRange(query)
    } : {});
    for await (const timeseriesPoint of asyncIterPointsHelper(streamPointsIterator)) {
      yield timeseriesPoint;
    }
  }
};

// src/createMediaReferenceProperty.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var MediaReferencePropertyImpl = class {
  #mediaReference;
  #triplet;
  #client;
  constructor(args) {
    const {
      client,
      objectApiName,
      primaryKey,
      propertyName,
      mediaReference
    } = args;
    this.#client = client;
    this.#triplet = [objectApiName, primaryKey, propertyName];
    this.#mediaReference = mediaReference;
  }
  async fetchContents() {
    return chunkY362HOIZ_cjs.MediaReferenceProperty_exports.getMediaContent(this.#client, await this.#client.ontologyRid, ...this.#triplet, {
      preview: true
      // TODO: Can turn this back off when backend is no longer in beta.
    });
  }
  async fetchMetadata() {
    const r = await chunkY362HOIZ_cjs.MediaReferenceProperty_exports.getMediaMetadata(this.#client, await this.#client.ontologyRid, ...this.#triplet, {
      preview: true
      // TODO: Can turn this back off when backend is no longer in beta.
    });
    return {
      path: r.path,
      sizeBytes: Number(r.sizeBytes),
      mediaType: r.mediaType
    };
  }
  getMediaReference() {
    return this.#mediaReference;
  }
};

// src/createTimeseriesProperty.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var TimeSeriesPropertyImpl = class {
  #triplet;
  #client;
  constructor(client, objectApiName, primaryKey, propertyName) {
    this.#client = client;
    this.#triplet = [objectApiName, primaryKey, propertyName];
  }
  async getFirstPoint() {
    return chunkY362HOIZ_cjs.TimeSeriesPropertyV2_exports.getFirstPoint(this.#client, await this.#client.ontologyRid, ...this.#triplet);
  }
  async getLastPoint() {
    return chunkY362HOIZ_cjs.TimeSeriesPropertyV2_exports.getLastPoint(this.#client, await this.#client.ontologyRid, ...this.#triplet);
  }
  async getAllPoints(query) {
    const allPoints = [];
    for await (const point of this.asyncIterPoints(query)) {
      allPoints.push(point);
    }
    return allPoints;
  }
  async *asyncIterPoints(query) {
    const streamPointsIterator = await chunkY362HOIZ_cjs.TimeSeriesPropertyV2_exports.streamPoints(this.#client, await this.#client.ontologyRid, ...this.#triplet, query ? {
      range: getTimeRange(query)
    } : {});
    for await (const timeseriesPoint of asyncIterPointsHelper(streamPointsIterator)) {
      yield timeseriesPoint;
    }
  }
};

// src/object/formatting/applyPropertyFormatter.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/object/formatting/formatBoolean.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function formatBoolean(value, rule) {
  return value ? rule.valueIfTrue : rule.valueIfFalse;
}

// src/object/formatting/formatDateTime.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/object/formatting/propertyFormattingUtils.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function resolvePropertyReference(ref, objectData) {
  if (ref.type === "constant") {
    return ref.value;
  } else if (ref.type === "propertyType") {
    const value = objectData[ref.propertyApiName];
    return value != null ? String(value) : void 0;
  }
  return void 0;
}
function getBrowserLocale() {
  if (typeof navigator !== "undefined" && navigator.language != null) {
    return navigator.language;
  }
  return "en-US";
}

// src/object/formatting/formatDateTime.ts
function formatDateTime(value, format, timezone, objectData, locale, userTimezoneOverride) {
  const date = value instanceof Date ? value : new Date(value);
  if (isNaN(date.getTime())) {
    return void 0;
  }
  const resolvedTimezone = resolveTimezone(timezone, objectData, userTimezoneOverride);
  switch (format.type) {
    case "localizedFormat":
      return formatLocalized(date, format, locale, resolvedTimezone);
    case "stringFormat":
      return void 0;
    default:
      return void 0;
  }
}
var INVALID_DATE_STRING = "Invalid date or timezone";
function formatLocalized(date, format, locale, timezone) {
  if (format.format === "DATE_FORMAT_ISO_INSTANT") {
    return date.toISOString();
  }
  if (format.format === "DATE_FORMAT_RELATIVE_TO_NOW") {
    return formatRelativeToNow(date, locale, timezone);
  }
  const options = getLocalizedFormatOptions(format.format);
  try {
    return new Intl.DateTimeFormat(locale, timezone ? {
      ...options,
      timeZone: timezone
    } : options).format(date);
  } catch (_e) {
    return INVALID_DATE_STRING;
  }
}
function getLocalizedFormatOptions(format) {
  switch (format) {
    case "DATE_FORMAT_DATE":
      return FORMAT_DATE;
    case "DATE_FORMAT_YEAR_AND_MONTH":
      return FORMAT_YEAR_AND_MONTH;
    case "DATE_FORMAT_DATE_TIME":
      return FORMAT_DATE_TIME;
    case "DATE_FORMAT_DATE_TIME_SHORT":
      return FORMAT_DATE_TIME_SHORT;
    case "DATE_FORMAT_TIME":
      return FORMAT_TIME;
    default:
      return {};
  }
}
var FORMAT_DATE = {
  day: "numeric",
  month: "short",
  weekday: "short",
  year: "numeric"
};
var FORMAT_YEAR_AND_MONTH = {
  month: "short",
  year: "numeric"
};
var FORMAT_DATE_TIME = {
  day: "numeric",
  month: "short",
  weekday: "short",
  year: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric"
};
var FORMAT_DATE_TIME_SHORT = {
  day: "numeric",
  month: "short",
  year: "numeric",
  hour: "numeric",
  minute: "numeric"
};
var FORMAT_TIME = {
  hour: "numeric",
  minute: "numeric",
  second: "numeric"
};
var DATE_TIME_SHORT_WITH_WEEKDAY = {
  day: "numeric",
  month: "short",
  weekday: "short",
  year: "numeric",
  hour: "numeric",
  minute: "numeric"
};
function resolveTimezone(timezone, objectData, userTimezoneOverride) {
  if (userTimezoneOverride != null) {
    return userTimezoneOverride;
  }
  if (timezone == null) {
    return void 0;
  }
  switch (timezone.type) {
    case "user":
      return void 0;
    case "static":
      return resolvePropertyReference(timezone.zoneId, objectData);
    default:
      return void 0;
  }
}
var SECOND_MS = 1e3;
var MINUTE_MS = 60 * SECOND_MS;
var HOUR_MS = 60 * MINUTE_MS;
var DAY_MS = 24 * HOUR_MS;
function formatRelativeToNow(date, locale, timezone) {
  const now = Date.now();
  const diff = date.valueOf() - now;
  const absDiff = Math.abs(diff);
  if (absDiff >= DAY_MS) {
    const dtf = new Intl.DateTimeFormat(locale, {
      ...DATE_TIME_SHORT_WITH_WEEKDAY,
      timeZone: timezone
    });
    return dtf.format(date);
  }
  const rtf = new Intl.RelativeTimeFormat(locale, {
    numeric: "auto"
  });
  const units = [["hour", HOUR_MS], ["minute", MINUTE_MS], ["second", SECOND_MS]];
  for (const [unit, ms] of units) {
    if (absDiff >= ms) {
      return rtf.format(Math.floor(diff / ms), unit);
    }
  }
  return rtf.format(0, "second");
}

// src/object/formatting/formatNumber.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function formatNumber(value, numberType, objectData, locale) {
  switch (numberType.type) {
    case "standard":
      return formatStandardNumber(value, numberType.baseFormatOptions, locale);
    case "fixedValues":
      return numberType.values[value];
    case "currency":
      return formatCurrency(value, numberType, objectData, locale);
    case "standardUnit":
      return formatStandardUnit(value, numberType, objectData, locale);
    case "customUnit":
      return formatCustomUnit(value, numberType, objectData, locale);
    case "affix":
      return formatAffix(value, numberType, objectData, locale);
    case "duration":
      return void 0;
    case "scale":
      return formatScale(value, numberType, locale);
    case "ratio":
      return formatRatio(value, numberType, locale);
    default:
      return void 0;
  }
}
function formatStandardNumber(value, options, locale) {
  return formatNumberWithAffixes(value, options, locale);
}
function formatCurrency(value, rule, objectData, locale) {
  const currencyCode = resolvePropertyReference(rule.currencyCode, objectData);
  if (currencyCode == null) {
    return formatStandardNumber(value, rule.baseFormatOptions, locale);
  }
  const options = {
    ...convertToIntlOptions(rule.baseFormatOptions),
    style: "currency",
    currency: currencyCode,
    currencyDisplay: rule.style === "COMPACT" ? "narrowSymbol" : "symbol"
  };
  return formatWithIntl(value, options, locale);
}
function formatStandardUnit(value, rule, objectData, locale) {
  const unit = resolvePropertyReference(rule.unit, objectData);
  if (unit == null) {
    return formatStandardNumber(value, rule.baseFormatOptions, locale);
  }
  const options = {
    ...convertToIntlOptions(rule.baseFormatOptions),
    style: "unit",
    unit
  };
  try {
    return formatWithIntl(value, options, locale);
  } catch (error) {
    const suffix = ` ${unit}`;
    return formatNumberWithAffixes(value, rule.baseFormatOptions, locale, "", suffix);
  }
}
function formatCustomUnit(value, rule, objectData, locale) {
  const unit = resolvePropertyReference(rule.unit, objectData);
  const suffix = unit != null ? ` ${unit}` : "";
  return formatNumberWithAffixes(value, rule.baseFormatOptions, locale, "", suffix);
}
function formatAffix(value, rule, objectData, locale) {
  const prefix = rule.affix.prefix != null ? resolvePropertyReference(rule.affix.prefix, objectData) ?? "" : "";
  const suffix = rule.affix.postfix != null ? resolvePropertyReference(rule.affix.postfix, objectData) ?? "" : "";
  return formatNumberWithAffixes(value, rule.baseFormatOptions, locale, prefix, suffix);
}
function getScaleDivisor(scaleType) {
  switch (scaleType) {
    case "THOUSANDS":
      return 1e3;
    case "MILLIONS":
      return 1e6;
    case "BILLIONS":
      return 1e9;
    default:
      throw new Error(`Unknown scale type: ${scaleType}`);
  }
}
function getLocalizedCompactSuffix(scaleDivisor, locale) {
  const compactFormatter = new Intl.NumberFormat(locale, {
    notation: "compact",
    compactDisplay: "short"
  });
  const parts = compactFormatter.formatToParts(scaleDivisor);
  const compactPart = parts.find((p) => p.type === "compact");
  return compactPart?.value ?? "";
}
function formatScale(value, rule, locale) {
  const scaleDivisor = getScaleDivisor(rule.scaleType);
  const scaledValue = value / scaleDivisor;
  const suffix = getLocalizedCompactSuffix(scaleDivisor, locale);
  return formatNumberWithAffixes(scaledValue, rule.baseFormatOptions, locale, "", suffix);
}
function getRatioScaledValue(value, ratioType) {
  switch (ratioType) {
    case "PERCENTAGE":
      return value * 100;
    case "PER_MILLE":
      return value * 1e3;
    case "BASIS_POINTS":
      return value * 1e4;
    default:
      throw new Error(`Unknown ratio type: ${ratioType}`);
  }
}
function formatRatio(value, rule, locale) {
  if (rule.ratioType === "PERCENTAGE") {
    const options = {
      ...convertToIntlOptions(rule.baseFormatOptions),
      style: "percent"
    };
    return formatWithIntl(value, options, locale);
  }
  const scaledValue = getRatioScaledValue(value, rule.ratioType);
  let suffix;
  switch (rule.ratioType) {
    case "PER_MILLE":
      suffix = "\u2030";
      break;
    case "BASIS_POINTS":
      suffix = " bps";
      break;
    default:
      rule.ratioType;
      throw new Error(`Unknown ratio type: ${rule.ratioType}`);
  }
  return formatNumberWithAffixes(scaledValue, rule.baseFormatOptions, locale, "", suffix);
}
function mapNotation(notation) {
  switch (notation) {
    case "STANDARD":
      return "standard";
    case "SCIENTIFIC":
      return "scientific";
    case "ENGINEERING":
      return "engineering";
    case "COMPACT":
      return "compact";
  }
}
function mapRoundingMode(mode) {
  switch (mode) {
    case "CEIL":
      return "ceil";
    case "FLOOR":
      return "floor";
    case "ROUND_CLOSEST":
      return "halfExpand";
    default:
      return void 0;
  }
}
function convertToIntlOptions(options) {
  return {
    useGrouping: options.useGrouping,
    minimumIntegerDigits: options.minimumIntegerDigits,
    minimumFractionDigits: options.minimumFractionDigits,
    maximumFractionDigits: options.maximumFractionDigits,
    minimumSignificantDigits: options.minimumSignificantDigits,
    maximumSignificantDigits: options.maximumSignificantDigits,
    notation: options.notation ? mapNotation(options.notation) : void 0,
    roundingMode: options.roundingMode ? mapRoundingMode(options.roundingMode) : void 0,
    convertNegativeToParenthesis: options.convertNegativeToParenthesis
  };
}
function maybeConvertNegativeToParenthesis(formatted, value, shouldConvert) {
  if (shouldConvert && value < 0) {
    return formatted.replace(/^-/, "(") + ")";
  }
  return formatted;
}
function formatWithIntl(value, options, locale) {
  const formatter = new Intl.NumberFormat(locale, options);
  const formatted = formatter.format(value);
  return maybeConvertNegativeToParenthesis(formatted, value, options.convertNegativeToParenthesis ?? false);
}
function formatNumberWithAffixes(value, baseOptions, locale, prefix, suffix) {
  const intlOptions = convertToIntlOptions(baseOptions);
  const formatted = formatWithIntl(value, intlOptions, locale);
  return `${prefix || ""}${formatted}${suffix || ""}`;
}

// src/object/formatting/applyPropertyFormatter.ts
function applyPropertyFormatter(propertyValue, propertyDefinition, objectData, options = {}) {
  if (propertyDefinition?.valueFormatting == null || propertyValue == null) {
    return void 0;
  }
  return formatPropertyValue(propertyValue, propertyDefinition.valueFormatting, objectData, options);
}
function formatPropertyValue(value, rule, objectData, options) {
  switch (rule.type) {
    case "boolean":
      if (typeof value !== "boolean") {
        return void 0;
      }
      return formatBoolean(value, rule);
    case "number":
      if (typeof value !== "number") {
        return void 0;
      }
      return formatNumber(value, rule.numberType, objectData, options.locale ?? getBrowserLocale());
    case "date":
    case "timestamp":
      if (typeof value !== "string") {
        return void 0;
      }
      return formatDateTime(new Date(value), rule.format, rule.type === "timestamp" ? rule.displayTimezone : void 0, objectData, options.locale ?? getBrowserLocale(), options.timezoneId);
    default:
      return void 0;
  }
}

// src/object/convertWireToOsdkObjects/getDollarAs.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/ontology/OntologyProvider.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var InterfaceDefinitions = Symbol("InterfaceDefinitions" );

// src/object/convertWireToOsdkObjects/createOsdkInterface.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/object/convertWireToOsdkObjects/getDollarLink.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/object/convertWireToOsdkObjects/InternalSymbols.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var UnderlyingOsdkObject = Symbol("Underlying Object" );
var ObjectDefRef = Symbol("ObjectDefinition" );
var InterfaceDefRef = Symbol("InterfaceDefinition" );
var ClientRef = Symbol("ClientRef" );

// src/object/convertWireToOsdkObjects/getDollarLink.ts
function get$link(holder) {
  const client = holder[ClientRef];
  const objDef = holder[ObjectDefRef];
  const rawObj = holder[UnderlyingOsdkObject];
  return Object.freeze(Object.fromEntries(Object.keys(objDef.links).map((linkName) => {
    const linkDef = objDef.links[linkName];
    const objectSet = client.objectSetFactory(objDef, client).where({
      [objDef.primaryKeyApiName]: rawObj.$primaryKey
    }).pivotTo(linkName);
    const value = !linkDef.multiplicity ? {
      fetchOne: (options) => chunkY362HOIZ_cjs.fetchSingle(client, objDef, options ?? {}, chunkY362HOIZ_cjs.getWireObjectSet(objectSet)),
      fetchOneWithErrors: (options) => chunkY362HOIZ_cjs.fetchSingleWithErrors(client, objDef, options ?? {}, chunkY362HOIZ_cjs.getWireObjectSet(objectSet))
    } : objectSet;
    return [linkName, value];
  })));
}
function get$linkForInterface(holder) {
  const client = holder[UnderlyingOsdkObject][ClientRef];
  const objDef = holder[UnderlyingOsdkObject][ObjectDefRef];
  const interfaceDef = holder[InterfaceDefRef];
  const rawObj = holder[UnderlyingOsdkObject];
  return Object.freeze(Object.fromEntries(Object.keys(interfaceDef.links).map((linkName) => {
    const linkDef = interfaceDef.links[linkName];
    const objectSet = client.objectSetFactory(interfaceDef, client).intersect(client.objectSetFactory(objDef, client).where({
      [objDef.primaryKeyApiName]: rawObj.$primaryKey
    })).pivotTo(linkName);
    const value = !linkDef.multiplicity ? {
      fetchOne: (options) => chunkY362HOIZ_cjs.fetchSingle(client, objDef, options ?? {}, chunkY362HOIZ_cjs.getWireObjectSet(objectSet)),
      fetchOneWithErrors: (options) => chunkY362HOIZ_cjs.fetchSingleWithErrors(client, objDef, options ?? {}, chunkY362HOIZ_cjs.getWireObjectSet(objectSet))
    } : objectSet;
    return [linkName, value];
  })));
}

// src/object/convertWireToOsdkObjects/createOsdkInterface.ts
function createOsdkInterface(underlying, interfaceDef) {
  const [objApiNamespace] = chunkY362HOIZ_cjs.extractNamespace(interfaceDef.apiName);
  return Object.freeze(Object.defineProperties({}, {
    // first to minimize hidden classes
    [UnderlyingOsdkObject]: {
      value: underlying
    },
    "$apiName": {
      value: interfaceDef.apiName,
      enumerable: true
    },
    "$as": {
      value: underlying.$as,
      enumerable: false
    },
    "$objectType": {
      value: underlying.$objectType,
      enumerable: "$objectType" in underlying
    },
    "$primaryKey": {
      value: underlying.$primaryKey,
      enumerable: "$primaryKey" in underlying
    },
    "$objectSpecifier": {
      value: underlying.$objectSpecifier,
      enumerable: "$objectSpecifier" in underlying
    },
    "$title": {
      value: underlying.$title,
      enumerable: "$title" in underlying
    },
    "$rid": {
      value: underlying.$rid,
      enumerable: "$rid" in underlying
    },
    "$clone": {
      value: clone,
      enumerable: false
    },
    "$__EXPERIMENTAL__NOT_SUPPORTED_YET__metadata": {
      value: {
        "ObjectMetadata": underlying[ObjectDefRef],
        "InterfaceMetadata": interfaceDef
      },
      enumerable: false
    },
    "$__EXPERIMENTAL__NOT_SUPPORTED_YET__getFormattedValue": {
      value: underlying.$__EXPERIMENTAL__NOT_SUPPORTED_YET__getFormattedValue,
      enumerable: false
    },
    "$link": {
      get: function() {
        return get$linkForInterface(this);
      }
    },
    [InterfaceDefRef]: {
      value: interfaceDef
    },
    ...Object.fromEntries(Object.keys(interfaceDef.properties).map((p) => {
      const objDef = underlying[ObjectDefRef];
      const [apiNamespace, apiName] = chunkY362HOIZ_cjs.extractNamespace(p);
      const targetPropName = objDef.interfaceMap[interfaceDef.apiName][p];
      return [apiNamespace === objApiNamespace ? apiName : p, {
        enumerable: targetPropName in underlying,
        value: underlying[targetPropName]
      }];
    }))
  }));
  function clone(update) {
    if (update == null) {
      return underlying.$clone().$as(interfaceDef);
    }
    for (const key of Object.keys(update)) {
      if (!(key in interfaceDef.properties)) {
        throw new Error(`Invalid property ${key} for interface ${interfaceDef.apiName}`);
      }
    }
    const remappedProps = Object.fromEntries(Object.keys(update).map((p) => mapProperty(p, update[p])).filter((x) => x != null));
    return underlying.$clone(remappedProps).$as(interfaceDef);
  }
  function mapProperty(propertyName, value) {
    const objDef = underlying[ObjectDefRef];
    const targetPropName = objDef.interfaceMap[interfaceDef.apiName][propertyName];
    if (targetPropName == null) {
      throw new Error(`Cannot clone interface with ${propertyName} as property is not implemented by the underlying object type ${objDef.apiName}`);
    }
    return [targetPropName, value];
  }
}

// src/object/convertWireToOsdkObjects/getDollarAs.ts
var get$as = createSimpleCache(/* @__PURE__ */ new WeakMap(), $asFactory).get;
var osdkObjectToInterfaceView = createSimpleCache(/* @__PURE__ */ new WeakMap(), () => /* @__PURE__ */ new Map());
function $asFactory(objDef) {
  return function $as(targetMinDef) {
    let targetInterfaceApiName;
    if (typeof targetMinDef === "string") {
      if (targetMinDef === objDef.apiName) {
        return this[UnderlyingOsdkObject];
      }
      if (objDef.interfaceMap?.[targetMinDef] == null) {
        throw new Error(`Object does not implement interface '${targetMinDef}'.`);
      }
      targetInterfaceApiName = targetMinDef;
    } else if (targetMinDef.apiName === objDef.apiName) {
      return this[UnderlyingOsdkObject];
    } else {
      if (targetMinDef.type === "object") {
        throw new Error(`'${targetMinDef.apiName}' is not an interface nor is it '${objDef.apiName}', which is the object type.`);
      }
      targetInterfaceApiName = targetMinDef.apiName;
    }
    const def = objDef[InterfaceDefinitions][targetInterfaceApiName];
    if (!def) {
      throw new Error(`Object does not implement interface '${targetInterfaceApiName}'.`);
    }
    const underlying = this[UnderlyingOsdkObject];
    const existing = osdkObjectToInterfaceView.get(underlying).get(targetInterfaceApiName)?.deref();
    if (existing) return existing;
    const osdkInterface = createOsdkInterface(underlying, def.def);
    osdkObjectToInterfaceView.get(underlying).set(targetInterfaceApiName, new WeakRef(osdkInterface));
    return osdkInterface;
  };
}

// src/object/convertWireToOsdkObjects/createOsdkObject.ts
var specialPropertyTypes = /* @__PURE__ */ new Set(["attachment", "geotimeSeriesReference", "mediaReference", "numericTimeseries", "stringTimeseries", "sensorTimeseries"]);
var basePropDefs = {
  "$as": {
    get: function() {
      return get$as(this[ObjectDefRef]);
    }
  },
  "$link": {
    get: function() {
      return get$link(this);
    }
  },
  "$clone": {
    value: function(update) {
      const rawObj = this[UnderlyingOsdkObject];
      const def = this[ObjectDefRef];
      if (update == null) {
        return createOsdkObject(this[ClientRef], def, {
          ...rawObj
        });
      }
      if (def.primaryKeyApiName in update && rawObj[def.primaryKeyApiName] !== update[def.primaryKeyApiName]) {
        throw new Error(`Cannot update ${def.apiName} object with differing primary key values `);
      }
      if (def.titleProperty in update && !("$title" in update)) {
        update.$title = update[def.titleProperty];
      }
      const newObject = {
        ...this[UnderlyingOsdkObject],
        ...update
      };
      return createOsdkObject(this[ClientRef], this[ObjectDefRef], newObject);
    }
  },
  "$objectSpecifier": {
    get: function() {
      const rawObj = this[UnderlyingOsdkObject];
      return createObjectSpecifierFromPrimaryKey(this[ObjectDefRef], rawObj.$primaryKey);
    },
    enumerable: true
  },
  "$__EXPERIMENTAL__NOT_SUPPORTED_YET__metadata": {
    get: function() {
      return {
        ObjectMetadata: this[ObjectDefRef]
      };
    },
    enumerable: false
  },
  "$__EXPERIMENTAL__NOT_SUPPORTED_YET__getFormattedValue": {
    value: function(propertyApiName, options) {
      const rawObj = this[UnderlyingOsdkObject];
      const def = this[ObjectDefRef];
      const propertyValue = rawObj[propertyApiName];
      return applyPropertyFormatter(propertyValue, def.properties[propertyApiName], rawObj, options);
    },
    enumerable: false
  }
};
function createOsdkObject(client, objectDef, simpleOsdkProperties, derivedPropertyTypeByName = {}) {
  const rawObj = simpleOsdkProperties;
  Object.defineProperties(rawObj, {
    [UnderlyingOsdkObject]: {
      enumerable: false,
      value: simpleOsdkProperties
    },
    [ObjectDefRef]: {
      value: objectDef,
      enumerable: false
    },
    // TODO: Potentially update when GA metadata field
    [ClientRef]: {
      value: client,
      enumerable: false
    },
    ...basePropDefs
  });
  for (const propKey of Object.keys(rawObj)) {
    if (propKey in objectDef.properties && typeof objectDef.properties[propKey].type === "string" && specialPropertyTypes.has(objectDef.properties[propKey].type)) {
      rawObj[propKey] = createSpecialProperty(client, objectDef, rawObj, propKey);
    } else if (propKey in derivedPropertyTypeByName) {
      rawObj[propKey] = modifyRdpProperties(client, derivedPropertyTypeByName, rawObj[propKey], propKey);
    }
  }
  return Object.freeze(rawObj);
}
function modifyRdpProperties(client, derivedPropertyTypeByName, rawValue, propKey) {
  if (derivedPropertyTypeByName[propKey].definition.type === "selection" && derivedPropertyTypeByName[propKey].definition.operation.type === "count") {
    const num = Number(rawValue);
    !Number.isSafeInteger(num) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, "Count aggregation for derived property " + propKey + " returned a value larger than safe integer.") : invariant__default.default(false) : void 0;
    return num;
  } else if (derivedPropertyTypeByName[propKey].selectedOrCollectedPropertyType != null && typeof derivedPropertyTypeByName[propKey].selectedOrCollectedPropertyType.type === "string" && specialPropertyTypes.has(derivedPropertyTypeByName[propKey].selectedOrCollectedPropertyType.type)) {
    switch (derivedPropertyTypeByName[propKey].selectedOrCollectedPropertyType?.type) {
      case "attachment":
        if (Array.isArray(rawValue)) {
          return rawValue.map((a) => chunkY362HOIZ_cjs.hydrateAttachmentFromRidInternal(client, a.rid));
        } else {
          return chunkY362HOIZ_cjs.hydrateAttachmentFromRidInternal(client, rawValue.rid);
        }
      default:
        process.env.NODE_ENV !== "production" ? invariant__default.default(false, "Derived property aggregations for Timeseries and Media are not supported") : invariant__default.default(false) ;
    }
  }
  return rawValue;
}
function createSpecialProperty(client, objectDef, rawObject, p) {
  const rawValue = rawObject[p];
  const propDef = objectDef.properties[p];
  if (process.env.NODE_ENV !== "production") {
    !(propDef != null && typeof propDef.type === "string" && specialPropertyTypes.has(propDef.type)) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false) : invariant__default.default(false) : void 0;
  }
  if (propDef.type === "attachment") {
    if (Array.isArray(rawValue)) {
      return rawValue.map((a) => chunkY362HOIZ_cjs.hydrateAttachmentFromRidInternal(client, a.rid));
    }
    return chunkY362HOIZ_cjs.hydrateAttachmentFromRidInternal(client, rawValue.rid);
  }
  if (propDef.type === "numericTimeseries" || propDef.type === "stringTimeseries" || propDef.type === "sensorTimeseries") {
    return new TimeSeriesPropertyImpl(client, objectDef.apiName, rawObject[objectDef.primaryKeyApiName], p);
  }
  if (propDef.type === "geotimeSeriesReference") {
    return new GeotimeSeriesPropertyImpl(client, objectDef.apiName, rawObject[objectDef.primaryKeyApiName], p, rawValue.type === "geotimeSeriesValue" ? {
      time: rawValue.timestamp,
      value: {
        type: "Point",
        coordinates: rawValue.position
      }
    } : void 0);
  }
  if (propDef.type === "mediaReference") {
    return new MediaReferencePropertyImpl({
      client,
      objectApiName: objectDef.apiName,
      primaryKey: rawObject[objectDef.primaryKeyApiName],
      propertyName: p,
      mediaReference: rawValue
    });
  }
}

// src/object/convertWireToOsdkObjects.ts
async function convertWireToOsdkObjects(client, objects, interfaceApiName, forceRemoveRid = false, derivedPropertyTypesByName, selectedProps, strictNonNull = false) {
  fixObjectPropertiesInPlace(objects, forceRemoveRid);
  const ifaceDef = interfaceApiName ? await client.ontologyProvider.getInterfaceDefinition(interfaceApiName) : void 0;
  const ifaceSelected = ifaceDef ? selectedProps ?? Object.keys(ifaceDef.properties) : void 0;
  const ret = [];
  for (const rawObj of objects) {
    const objectDef = await client.ontologyProvider.getObjectDefinition(rawObj.$apiName);
    !objectDef ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, `Missing definition for '${rawObj.$apiName}'`) : invariant__default.default(false) : void 0;
    let objProps;
    let conforming = true;
    if (ifaceDef && ifaceSelected) {
      invariantInterfacesAsViews(objectDef, ifaceDef.apiName, client);
      conforming &&= isConforming(client, ifaceDef, rawObj, ifaceSelected);
      reframeAsObjectInPlace(objectDef, ifaceDef.apiName, rawObj);
      objProps = convertInterfacePropNamesToObjectPropNames(objectDef, ifaceDef.apiName, ifaceSelected);
    } else {
      objProps = selectedProps ?? Object.keys(objectDef.properties);
    }
    conforming &&= isConforming(client, objectDef, rawObj, objProps);
    if (strictNonNull === "throw" && !conforming) {
      throw new Error("Unable to safely convert objects as some non nullable properties are null");
    } else if (strictNonNull === "drop" && !conforming) {
      continue;
    }
    let osdkObject = createOsdkObject(client, objectDef, rawObj, derivedPropertyTypesByName);
    if (interfaceApiName) osdkObject = osdkObject.$as(interfaceApiName);
    ret.push(osdkObject);
  }
  return ret;
}
async function convertWireToOsdkObjects2(client, objects, interfaceApiName, derivedPropertyTypeByName, forceRemoveRid = false, selectedProps, strictNonNull = false, interfaceToObjectTypeMappings = {}, interfaceToObjectTypeMappingsV2 = {}) {
  fixObjectPropertiesInPlace(objects, forceRemoveRid);
  const effectiveMappings = Object.keys(interfaceToObjectTypeMappingsV2).length > 0 ? convertInterfaceToObjectTypeMappingsV2ToV1(interfaceToObjectTypeMappingsV2) : interfaceToObjectTypeMappings;
  const isInterfaceScoped = Object.keys(effectiveMappings).length > 0;
  const ret = [];
  for (const rawObj of objects) {
    const objectDef = await client.ontologyProvider.getObjectDefinition(rawObj.$apiName);
    !objectDef ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, `Missing definition for '${rawObj.$apiName}'`) : invariant__default.default(false) : void 0;
    const interfaceToObjMapping = interfaceApiName && isInterfaceScoped ? effectiveMappings[interfaceApiName][rawObj.$apiName] : void 0;
    const ifaceSelected = interfaceApiName && interfaceToObjMapping ? selectedProps ? Object.keys(interfaceToObjMapping).filter((val) => {
      selectedProps?.includes(interfaceToObjMapping[val]);
    }) : [...Object.values(interfaceToObjMapping), objectDef.primaryKeyApiName] : void 0;
    let objProps;
    let conforming = true;
    if (interfaceApiName && ifaceSelected) {
      invariantInterfacesAsViews(objectDef, interfaceApiName, client);
      objProps = ifaceSelected;
    } else {
      objProps = selectedProps ?? Object.keys(objectDef.properties);
    }
    conforming &&= isConforming(client, objectDef, rawObj, objProps);
    if (strictNonNull === "throw" && !conforming) {
      throw new Error("Unable to safely convert objects as some non nullable properties are null");
    } else if (strictNonNull === "drop" && !conforming) {
      continue;
    }
    let osdkObject = createOsdkObject(client, objectDef, rawObj, derivedPropertyTypeByName);
    if (interfaceApiName && isInterfaceScoped) osdkObject = osdkObject.$as(interfaceApiName);
    ret.push(osdkObject);
  }
  return ret;
}
function convertInterfacePropNamesToObjectPropNames(objectDef, interfaceApiName, ifacePropsToMap) {
  return ifacePropsToMap.map((ifaceProp) => objectDef.interfaceMap[interfaceApiName][ifaceProp]);
}
function reframeAsObjectInPlace(objectDef, interfaceApiName, rawObj) {
  const newProps = {};
  for (const [sptProp, regularProp] of Object.entries(objectDef.interfaceMap[interfaceApiName])) {
    if (sptProp in rawObj) {
      const value = rawObj[sptProp];
      delete rawObj[sptProp];
      if (value !== void 0) {
        newProps[regularProp] = value;
      }
    }
  }
  Object.assign(rawObj, newProps);
  if (!(objectDef.primaryKeyApiName in rawObj)) {
    rawObj[objectDef.primaryKeyApiName] = rawObj.$primaryKey;
  }
}
function isConforming(client, def, obj, propsToCheck) {
  for (const propName of propsToCheck) {
    if (propName in def.properties && def.properties[propName].nullable === false && obj[propName] == null) {
      if (process.env.NODE_ENV !== "production") {
        client.logger?.debug({
          obj: {
            $apiName: obj["$apiName"],
            $objectType: obj["$objectType"],
            $primaryKey: obj["$primaryKey"]
          }
        }, `Found object that does not conform to its definition. Expected ${def.apiName}'s ${propName} to not be null.`);
      }
      return false;
    }
  }
  return true;
}
function invariantInterfacesAsViews(objectDef, interfaceApiName, client) {
  if (objectDef.interfaceMap?.[interfaceApiName] == null) {
    const warning = "Interfaces are only supported 'as views' but your metadata object is missing the correct information. This suggests your interfaces have not been migrated to the newer version yet and you cannot use this version of the SDK.";
    if (client.logger) {
      client.logger.warn(warning);
    } else {
      console.error(`WARNING! ${warning}`);
    }
    throw new Error(warning);
  }
}
function fixObjectPropertiesInPlace(objs, forceRemoveRid) {
  for (const obj of objs) {
    if (forceRemoveRid) {
      delete obj.__rid;
    }
    if (obj.__rid) {
      obj.$rid = obj.__rid;
      delete obj.__rid;
    }
    if (obj.__score) {
      obj.$score = obj.__score;
      delete obj.__score;
    }
    obj.$apiName ??= obj.__apiName;
    obj.$objectType = obj.$apiName;
    obj.$primaryKey ??= obj.__primaryKey;
    obj.$title ??= obj.__title;
    delete obj.__apiName;
    delete obj.__primaryKey;
    delete obj.__title;
  }
}
function convertInterfaceToObjectTypeMappingsV2ToV1(mappingsV2) {
  return Object.fromEntries(Object.entries(mappingsV2).map(([interfaceApiName, objectTypeMappingsV2]) => [interfaceApiName, Object.fromEntries(Object.entries(objectTypeMappingsV2).map(([objectTypeName, propertyMappings]) => [objectTypeName, Object.fromEntries(Object.entries(propertyMappings).filter(([, impl]) => impl.type === "localPropertyImplementation").map(([interfaceProp, impl]) => [interfaceProp, impl.propertyApiName]))]))]));
}

// src/ontology/StandardOntologyProvider.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/object/Cache.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function createClientCache(fn) {
  const cache = /* @__PURE__ */ new WeakMap();
  function get(client, key) {
    if (cache.get(client.clientCacheKey) == null) {
      cache.set(client.clientCacheKey, /* @__PURE__ */ new Map());
    }
    const r = cache.get(client.clientCacheKey).get(key);
    if (r === void 0 && fn !== void 0) {
      return set(client, key, fn(client, key));
    } else {
      return r;
    }
  }
  function set(client, key, value) {
    if (cache.get(client.clientCacheKey) == null) {
      cache.set(client.clientCacheKey, /* @__PURE__ */ new Map());
    }
    cache.get(client.clientCacheKey).set(key, value);
    return value;
  }
  function remove(client, key) {
    if (cache.get(client.clientCacheKey) == null) return false;
    return cache.get(client.clientCacheKey).delete(key);
  }
  return {
    get,
    set,
    remove
  };
}
function createAsyncClientCache(fn, createCacheLocal = createClientCache) {
  const cache = createCacheLocal();
  const inProgress = createCacheLocal();
  const ret = {
    getOrUndefined: function getOrUndefined(client, key) {
      return cache.get(client, key);
    },
    get: async function get(client, key) {
      return cache.get(client, key) ?? inProgress.get(client, key) ?? ret.set(client, key, fn(client, key));
    },
    set: async function set(client, k, v) {
      try {
        const r = await inProgress.set(client, k, v);
        cache.set(client, k, r);
        inProgress.remove(client, k);
        return r;
      } catch (e) {
        inProgress.remove(client, k);
        throw e;
      }
    }
  };
  return ret;
}

// src/util/deepFreeze.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
function deepFreeze(obj) {
  Object.getOwnPropertyNames(obj).forEach((name) => {
    const prop = obj[name];
    if (typeof prop === "object" && prop != null && !Object.isFrozen(prop)) {
      deepFreeze(prop);
    }
  });
  return Object.freeze(obj);
}

// src/ontology/loadActionMetadata.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
async function loadActionMetadata(client, actionType) {
  const r = await chunkY362HOIZ_cjs.ActionTypeV2_exports.get(client, await client.ontologyRid, actionType);
  return generatorConverters.wireActionTypeV2ToSdkActionMetadata(r);
}

// src/ontology/loadFullObjectMetadata.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
async function loadFullObjectMetadata(client, objectType) {
  const full = await chunkY362HOIZ_cjs.ObjectTypeV2_exports.getFullMetadata(client, await client.ontologyRid, objectType, {
    preview: true
  });
  const ret = generatorConverters.wireObjectTypeFullMetadataToSdkObjectMetadata(full, true);
  return {
    ...ret
  };
}

// src/ontology/loadInterfaceMetadata.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
async function loadInterfaceMetadata(client, objectType) {
  const r = await chunkY362HOIZ_cjs.OntologyInterface_exports.get(client, await client.ontologyRid, objectType, {
    preview: true
  });
  return generatorConverters.__UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition(r, true);
}

// src/ontology/loadQueryMetadata.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
async function loadQueryMetadata(client, queryTypeApiNameAndVersion) {
  const [apiName, version] = queryTypeApiNameAndVersion.split(":");
  const r = await chunkY362HOIZ_cjs.QueryType_exports.get(client, await client.ontologyRid, apiName, {
    version
  });
  return generatorConverters.wireQueryTypeV2ToSdkQueryMetadata(r);
}

// src/ontology/StandardOntologyProvider.ts
var createStandardOntologyProviderFactory = (client) => {
  return (client2) => {
    async function loadObject(client3, key) {
      const objectDef = await loadFullObjectMetadata(client3, key);
      const interfaceDefs = Object.fromEntries((await Promise.all(objectDef.implements?.map((i) => ret.getInterfaceDefinition(i)) ?? [])).map((i) => [i.apiName, {
        def: i,
        handler: void 0
      }]));
      const fullObjectDef = {
        ...objectDef,
        [InterfaceDefinitions]: interfaceDefs
      };
      return deepFreeze(fullObjectDef);
    }
    async function loadInterface(client3, key) {
      return deepFreeze(await loadInterfaceMetadata(client3, key));
    }
    async function loadQuery(client3, key) {
      return loadQueryMetadata(client3, key);
    }
    async function loadAction(client3, key) {
      const r = await loadActionMetadata(client3, key);
      return r;
    }
    function makeGetter(fn) {
      const cache = createAsyncClientCache((client3, key) => fn(client3, key, false));
      return async (apiName) => {
        return await cache.get(client2, apiName);
      };
    }
    function makeQueryGetter(client3, fn) {
      const queryCache = createAsyncClientCache((client4, key) => {
        return fn(client4, key);
      });
      return async (apiName, version) => {
        const key = version ? `${apiName}:${version}` : apiName;
        return await queryCache.get(client3, key);
      };
    }
    const ret = {
      getObjectDefinition: makeGetter(loadObject),
      getInterfaceDefinition: makeGetter(loadInterface),
      getActionDefinition: makeGetter(loadAction),
      getQueryDefinition: makeQueryGetter(client2, loadQuery)
    };
    return ret;
  };
};

// src/util/UserAgent.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var USER_AGENT = `osdk-client/${"2.7.0-rc.15"}`;
var OBSERVABLE_USER_AGENT = `osdk-observable-client/${"2.7.0-rc.15"}`;

// src/createMinimalClient.ts
function createMinimalClient(metadata, baseUrl, tokenProvider, options = {}, fetchFn = global.fetch, objectSetFactory = chunkY362HOIZ_cjs.createObjectSet, createOntologyProviderFactory = createStandardOntologyProviderFactory) {
  if (process.env.NODE_ENV !== "production") {
    try {
      new URL(baseUrl);
    } catch (e) {
      const hint = !baseUrl.startsWith("http://") || !baseUrl.startsWith("https://") ? ". Did you forget to add 'http://' or 'https://'?" : "";
      throw new Error(`Invalid stack URL: ${baseUrl}${hint}`);
    }
  }
  const processedBaseUrl = new URL(baseUrl);
  processedBaseUrl.pathname += processedBaseUrl.pathname.endsWith("/") ? "" : "/";
  const minimalClient = {
    ...shared_client_impl.createSharedClientContext(processedBaseUrl.toString(), tokenProvider, USER_AGENT, fetchFn),
    objectSetFactory,
    objectFactory: convertWireToOsdkObjects,
    objectFactory2: convertWireToOsdkObjects2,
    ontologyRid: metadata.ontologyRid,
    logger: options.logger,
    transactionId: options.transactionId,
    clientCacheKey: {},
    requestContext: {},
    narrowTypeInterfaceOrObjectMapping: {}
  };
  return Object.freeze(Object.assign(minimalClient, {
    ontologyProvider: createOntologyProviderFactory(options)(minimalClient)
  }));
}

// src/fetchMetadata.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
var fetchMetadataInternal = async (client, definition) => {
  if (definition.type === "object") {
    const {
      [InterfaceDefinitions]: interfaceDefs,
      ...objectTypeDef
    } = await client.ontologyProvider.getObjectDefinition(definition.apiName);
    return objectTypeDef;
  } else if (definition.type === "interface") {
    return client.ontologyProvider.getInterfaceDefinition(definition.apiName);
  } else if (definition.type === "action") {
    return client.ontologyProvider.getActionDefinition(definition.apiName);
  } else if (definition.type === "query") {
    return client.ontologyProvider.getQueryDefinition(definition.apiName, definition.isFixedVersion ? definition.version : void 0);
  } else {
    throw new Error("Not implemented for given definition");
  }
};

// src/queries/applyQuery.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();

// src/util/toDataValueQueries.ts
chunkLDTMSHUZ_cjs.init_cjs_shims();
async function toDataValueQueries(value, client, desiredType) {
  if (value == null) {
    return value;
  }
  if (Array.isArray(value) && desiredType.type === "array") {
    const values = Array.from(value);
    if (values.some((dataValue) => isAttachmentUpload(dataValue) || isAttachmentFile(dataValue))) {
      const converted = [];
      for (const value2 of values) {
        converted.push(await toDataValueQueries(value2, client, desiredType));
      }
      return converted;
    }
    const promiseArray = Array.from(value, async (innerValue) => await toDataValueQueries(innerValue, client, desiredType.array));
    return Promise.all(promiseArray);
  }
  switch (desiredType.type) {
    case "attachment": {
      if (isAttachmentUpload(value)) {
        const attachment = await chunkY362HOIZ_cjs.Attachment_exports.upload(client, value.data, {
          filename: value.name
        });
        return attachment.rid;
      }
      if (isAttachmentFile(value)) {
        const attachment = await chunkY362HOIZ_cjs.Attachment_exports.upload(client, value, {
          filename: value.name
        });
        return attachment.rid;
      }
      return value;
    }
    case "twoDimensionalAggregation": {
      return {
        groups: value
      };
    }
    case "threeDimensionalAggregation": {
      return {
        groups: value
      };
    }
    case "set": {
      if (value instanceof Set) {
        const promiseArray = Array.from(value, async (innerValue) => await toDataValueQueries(innerValue, client, desiredType["set"]));
        return Promise.all(promiseArray);
      }
      break;
    }
    case "object": {
      if (isObjectSpecifiersObject(value)) {
        return value.$primaryKey;
      }
      break;
    }
    case "interface": {
      if (isInterfaceSpecifier(value) || isInterfaceQueryParam(value)) {
        return {
          objectTypeApiName: value.$objectType,
          primaryKeyValue: value.$primaryKey
        };
      }
    }
    case "objectSet":
    case "interfaceObjectSet": {
      if (chunkY362HOIZ_cjs.isWireObjectSet(value)) {
        return value;
      }
      if (chunkY362HOIZ_cjs.isObjectSet(value)) {
        return chunkY362HOIZ_cjs.getWireObjectSet(value);
      }
      break;
    }
    case "map": {
      if (typeof value === "object") {
        const entrySet = [];
        for (const [key, mapValue] of Object.entries(value)) {
          entrySet.push({
            key: desiredType.keyType.type === "object" ? extractPrimaryKeyFromObjectSpecifier(key) : await toDataValueQueries(key, client, desiredType.keyType),
            value: await toDataValueQueries(mapValue, client, desiredType.valueType)
          });
        }
        return entrySet;
      }
      break;
    }
    case "struct": {
      if (typeof value === "object") {
        const structMap = {};
        for (const [key, structValue] of Object.entries(value)) {
          structMap[key] = await toDataValueQueries(structValue, client, desiredType["struct"][key]);
        }
        return structMap;
      }
    }
    case "boolean":
    case "date":
    case "double":
    case "float":
    case "integer":
    case "long":
    case "string":
    case "timestamp":
      return value;
  }
  return value;
}

// src/queries/applyQuery.ts
async function applyQuery(client, query, params) {
  const qd = client.ontologyProvider.getQueryDefinition(query.apiName, query.isFixedVersion ? query.version : void 0);
  if (client.flushEdits != null) {
    await client.flushEdits();
  }
  const response = await chunkY362HOIZ_cjs.Query_exports.execute(chunkY362HOIZ_cjs.addUserAgentAndRequestContextHeaders(chunkY362HOIZ_cjs.augmentRequestContext(client, (_) => ({
    finalMethodCall: "applyQuery"
  })), query), await client.ontologyRid, query.apiName, {
    parameters: params ? await remapQueryParams(params, client, (await qd).parameters) : {}
  }, {
    version: query.isFixedVersion ? query.version : void 0,
    transactionId: client.transactionId
  });
  const objectOutputDefs = await getRequiredDefinitions((await qd).output, client);
  const remappedResponse = await remapQueryResponse(client, (await qd).output, response.value, objectOutputDefs);
  return remappedResponse;
}
async function remapQueryParams(params, client, paramTypes) {
  const parameterMap = {};
  for (const [key, value] of Object.entries(params)) {
    parameterMap[key] = await toDataValueQueries(value, client, paramTypes[key]);
  }
  return parameterMap;
}
async function remapQueryResponse(client, responseDataType, responseValue, definitions) {
  if (responseValue == null) {
    if (responseDataType.nullable) {
      return void 0;
    } else {
      throw new Error("Got null response when nullable was not allowed");
    }
  }
  switch (responseDataType.type) {
    case "union": {
      throw new Error("Union return types are not yet supported");
    }
    case "array": {
      for (let i = 0; i < responseValue.length; i++) {
        responseValue[i] = await remapQueryResponse(client, responseDataType.array, responseValue[i], definitions);
      }
      return responseValue;
    }
    case "set": {
      for (let i = 0; i < responseValue.length; i++) {
        responseValue[i] = await remapQueryResponse(client, responseDataType.set, responseValue[i], definitions);
      }
      return responseValue;
    }
    case "attachment": {
      return chunkY362HOIZ_cjs.hydrateAttachmentFromRidInternal(client, responseValue);
    }
    case "object": {
      const def = definitions.get(responseDataType.object);
      if (!def || def.type !== "object") {
        throw new Error(`Missing definition for ${responseDataType.object}`);
      }
      return createQueryObjectResponse(responseValue, def);
    }
    case "interface": {
      const def = definitions.get(responseDataType.interface);
      if (!def || def.type !== "interface") {
        throw new Error(`Missing definition for ${responseDataType.interface}`);
      }
      return createQueryInterfaceResponse(responseValue, def);
    }
    case "objectSet": {
      const def = definitions.get(responseDataType.objectSet);
      if (!def) {
        throw new Error(`Missing definition for ${responseDataType.objectSet}`);
      }
      if (typeof responseValue === "string") {
        return chunkY362HOIZ_cjs.createObjectSet(def, client, {
          type: "intersect",
          objectSets: [{
            type: "base",
            objectType: responseDataType.objectSet
          }, {
            type: "reference",
            reference: responseValue
          }]
        });
      }
      return chunkY362HOIZ_cjs.createObjectSet(def, client, responseValue);
    }
    case "struct": {
      for (const [key, subtype] of Object.entries(responseDataType.struct)) {
        if (requiresConversion(subtype)) {
          responseValue[key] = await remapQueryResponse(client, subtype, responseValue[key], definitions);
        }
      }
      return responseValue;
    }
    case "map": {
      const map = {};
      !Array.isArray(responseValue) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, "Expected array entry") : invariant__default.default(false) : void 0;
      for (const entry of responseValue) {
        !(entry.key != null) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, "Expected key") : invariant__default.default(false) : void 0;
        !(entry.value != null) ? process.env.NODE_ENV !== "production" ? invariant__default.default(false, "Expected value") : invariant__default.default(false) : void 0;
        const key = responseDataType.keyType.type === "object" ? getObjectSpecifier(entry.key, responseDataType.keyType.object, definitions) : entry.key;
        const value = await remapQueryResponse(client, responseDataType.valueType, entry.value, definitions);
        map[key] = value;
      }
      return map;
    }
    case "twoDimensionalAggregation": {
      const result = [];
      for (const {
        key,
        value
      } of responseValue.groups) {
        result.push({
          key,
          value
        });
      }
      return result;
    }
    case "threeDimensionalAggregation": {
      const result = [];
      for (const {
        key,
        groups
      } of responseValue.groups) {
        const subResult = [];
        for (const {
          key: subKey,
          value
        } of groups) {
          subResult.push({
            key: subKey,
            value
          });
        }
        result.push({
          key,
          groups: subResult
        });
      }
      return result;
    }
  }
  return responseValue;
}
async function getRequiredDefinitions(dataType, client) {
  const result = /* @__PURE__ */ new Map();
  switch (dataType.type) {
    case "objectSet": {
      const objectDef = await client.ontologyProvider.getObjectDefinition(dataType.objectSet);
      result.set(dataType.objectSet, objectDef);
      break;
    }
    case "interfaceObjectSet": {
      const interfaceDef = await client.ontologyProvider.getInterfaceDefinition(dataType.objectSet);
      result.set(dataType.objectSet, interfaceDef);
      break;
    }
    case "object": {
      const objectDef = await client.ontologyProvider.getObjectDefinition(dataType.object);
      result.set(dataType.object, objectDef);
      break;
    }
    case "interface": {
      const interfaceDef = await client.ontologyProvider.getInterfaceDefinition(dataType.interface);
      result.set(dataType.interface, interfaceDef);
      break;
    }
    case "set": {
      return getRequiredDefinitions(dataType.set, client);
    }
    case "array": {
      return getRequiredDefinitions(dataType.array, client);
    }
    case "map": {
      const types = [dataType.keyType, dataType.valueType];
      const allDefs = await Promise.all(types.map((value) => getRequiredDefinitions(value, client)));
      for (const defs of allDefs) {
        for (const [type, objectDef] of defs) {
          result.set(type, objectDef);
        }
      }
      break;
    }
    case "struct": {
      const structValues = Object.values(dataType.struct);
      const allDefs = await Promise.all(structValues.map((value) => getRequiredDefinitions(value, client)));
      for (const defs of allDefs) {
        for (const [type, objectDef] of defs) {
          result.set(type, objectDef);
        }
      }
      break;
    }
  }
  return result;
}
function requiresConversion(dataType) {
  switch (dataType.type) {
    case "boolean":
    case "date":
    case "double":
    case "float":
    case "integer":
    case "long":
    case "string":
    case "timestamp":
      return false;
    case "union":
      return true;
    case "struct":
      return Object.values(dataType.struct).some(requiresConversion);
    case "set":
      return requiresConversion(dataType.set);
    case "attachment":
    case "objectSet":
    case "twoDimensionalAggregation":
    case "threeDimensionalAggregation":
    case "object":
      return true;
    default:
      return false;
  }
}
function getObjectSpecifier(primaryKey, objectTypeApiName, definitions) {
  const def = definitions.get(objectTypeApiName);
  if (!def || def.type !== "object") {
    throw new Error(`Missing definition for ${objectTypeApiName}`);
  }
  return createObjectSpecifierFromPrimaryKey(def, primaryKey);
}
function createQueryObjectResponse(primaryKey, objectDef) {
  return {
    $apiName: objectDef.apiName,
    $title: void 0,
    $objectType: objectDef.apiName,
    $primaryKey: primaryKey,
    $objectSpecifier: createObjectSpecifierFromPrimaryKey(objectDef, primaryKey)
  };
}
function createQueryInterfaceResponse(interfaceSpecifier, interfaceDef) {
  return {
    $apiName: interfaceDef.apiName,
    $title: void 0,
    $objectType: interfaceSpecifier.objectTypeApiName,
    $primaryKey: interfaceSpecifier.primaryKeyValue,
    $objectSpecifier: createObjectSpecifierFromInterfaceSpecifier(interfaceDef, interfaceSpecifier)
  };
}

// src/createClient.ts
var ActionInvoker = class {
  constructor(clientCtx, actionDef) {
    this.applyAction = applyAction.bind(void 0, clientCtx, actionDef);
    this.batchApplyAction = applyAction.bind(void 0, clientCtx, actionDef);
  }
};
var QueryInvoker = class {
  constructor(clientCtx, queryDef) {
    this.executeFunction = applyQuery.bind(void 0, clientCtx, queryDef);
  }
};
function createClientInternal(objectSetFactory, transactionRid, flushEdits, baseUrl, ontologyRid, tokenProvider, options = void 0, fetchFn = fetch) {
  if (typeof ontologyRid === "string") {
    if (!ontologyRid.startsWith("ri.")) {
      throw new Error("Invalid ontology RID");
    }
  } else {
    ontologyRid.then((ontologyRid2) => {
      if (!ontologyRid2.startsWith("ri.")) {
        throw new Error("Invalid ontology RID");
      }
    });
  }
  const clientCtx = createMinimalClient({
    ontologyRid
  }, baseUrl, tokenProvider, {
    ...options,
    logger: options?.logger ?? new chunkY362HOIZ_cjs.MinimalLogger(),
    transactionId: transactionRid,
    flushEdits
  }, fetchFn, objectSetFactory);
  return createClientFromContext(clientCtx);
}
function createClientFromContext(clientCtx) {
  function clientFn(o) {
    if (o.type === "object" || o.type === "interface") {
      return clientCtx.objectSetFactory(o, clientCtx);
    } else if (o.type === "action") {
      return new ActionInvoker(clientCtx, o);
    } else if (o.type === "query") {
      return new QueryInvoker(clientCtx, o);
    } else if (o.type === "experiment") {
      switch (o.name) {
        case unstable.__EXPERIMENTAL__NOT_SUPPORTED_YET__getBulkLinks.name:
          return {
            getBulkLinks: createBulkLinksAsyncIterFactory(clientCtx)
          };
        case unstable.__EXPERIMENTAL__NOT_SUPPORTED_YET__fetchOneByRid.name:
          return {
            fetchOneByRid: async (objectType, rid, options) => {
              return await chunkY362HOIZ_cjs.fetchSingle(clientCtx, objectType, options, createWithRid([rid]));
            }
          };
        case unstable.__EXPERIMENTAL__NOT_SUPPORTED_YET__createMediaReference.name:
          return {
            createMediaReference: async (args) => {
              const {
                data,
                fileName,
                objectType,
                propertyType
              } = args;
              return await chunkY362HOIZ_cjs.MediaReferenceProperty_exports.upload(clientCtx, await clientCtx.ontologyRid, objectType.apiName, propertyType, data, {
                mediaItemPath: fileName,
                preview: true
              });
            }
          };
        case unstable.__EXPERIMENTAL__NOT_SUPPORTED_YET__fetchPageByRid.name:
          return {
            fetchPageByRid: async (objectOrInterfaceType, rids, options = {}) => {
              return await chunkY362HOIZ_cjs.fetchPage(clientCtx, objectOrInterfaceType, options, createWithRid(rids));
            },
            fetchPageByRidNoType: async (rids, options) => {
              return await chunkY362HOIZ_cjs.fetchStaticRidPage(clientCtx, rids, options ?? {});
            }
          };
      }
      throw new Error("not implemented");
    } else {
      throw new Error("not implemented");
    }
  }
  const fetchMetadata = fetchMetadataInternal.bind(void 0, clientCtx);
  const symbolClientContext2 = "__osdkClientContext";
  const client = Object.defineProperties(clientFn, {
    [chunkY362HOIZ_cjs.symbolClientContext]: {
      value: clientCtx
    },
    [symbolClientContext2]: {
      value: clientCtx
    },
    [chunkY362HOIZ_cjs.additionalContext]: {
      value: clientCtx
    },
    fetchMetadata: {
      value: fetchMetadata
    }
  });
  return client;
}
var createClient = createClientInternal.bind(void 0, chunkY362HOIZ_cjs.createObjectSet, void 0, void 0);
var createClientWithTransaction = (transactionRid, flushEdits, ...args) => createClientInternal(chunkY362HOIZ_cjs.createObjectSet, transactionRid, flushEdits, ...args);
function createWithRid(rids) {
  const withRid = {
    type: "static",
    "objects": rids
  };
  return withRid;
}

exports.ActionValidationError = ActionValidationError;
exports.ClientRef = ClientRef;
exports.OBSERVABLE_USER_AGENT = OBSERVABLE_USER_AGENT;
exports.ObjectDefRef = ObjectDefRef;
exports.USER_AGENT = USER_AGENT;
exports.UnderlyingOsdkObject = UnderlyingOsdkObject;
exports.applyQuery = applyQuery;
exports.createAttachmentUpload = createAttachmentUpload;
exports.createClient = createClient;
exports.createClientFromContext = createClientFromContext;
exports.createClientWithTransaction = createClientWithTransaction;
exports.createObjectSpecifierFromPrimaryKey = createObjectSpecifierFromPrimaryKey;
exports.createOsdkObject = createOsdkObject;
exports.extractPrimaryKeyFromObjectSpecifier = extractPrimaryKeyFromObjectSpecifier;
exports.isObjectSpecifiersObject = isObjectSpecifiersObject;
//# sourceMappingURL=chunk-CDUYWOVQ.cjs.map
//# sourceMappingURL=chunk-CDUYWOVQ.cjs.map